repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Gaea-iOS/FoundationExtension | String+Input.swift | 1 | 1179 | //
// String+Input.swift
// Pods
//
// Created by 王小涛 on 2017/9/2.
//
//
import Foundation
extension Optional where Wrapped == String {
var isEmptyOrInvisibleString: Bool {
switch self {
case .none:
return false
case let .some(value):
return value.isEmptyOrInvisibleString
}
}
var isValidPhone: Bool {
switch self {
case .none:
return false
case let .some(value):
return value.isValidPhone
}
}
}
extension String {
var isValidPhone: Bool {
let regular = try! NSRegularExpression(pattern: "^1\\d{10}$")
return regular.numberOfMatches(in: self, range: NSMakeRange(0, length)) > 0
}
}
extension Optional where Wrapped == String {
var string: String {
switch self {
case .none:
return ""
case let .some(value):
return value
}
}
}
extension Optional where Wrapped == Int {
var int: Int {
switch self {
case .none:
return 0
case let .some(value):
return value
}
}
}
| mit | 9e79af19d49aded1de2fb83824547ebb | 17.919355 | 83 | 0.526854 | 4.376866 | false | false | false | false |
gzios/swift | Advanced/LearnSwift/LearnSwift/CanChoose/CanChooseDemo.swift | 1 | 785 | //
// CanChooseDemo.swift
// LearnSwift
//
// Created by Tim on 2018/8/22.
// Copyright © 2018年 郭振涛. All rights reserved.
//
import Cocoa
class CanChooseDemo: NSObject {
override init() {
super.init()
tsetCanChoose()
}
func tsetCanChoose() {
var array = ["one","two","three"]
}
}
///枚举
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
extension Collection where Element:Equatable{
func index(of element: Element) -> Optional<Index> {
var idx = startIndex
while idx != endIndex {
if self[idx] == element{
return .some(idx)
}
formIndex(after: &idx)
}
return .none
}
}
| apache-2.0 | f4b020fc7d01950578aa710504360e7a | 16.155556 | 56 | 0.518135 | 3.958974 | false | false | false | false |
lieonCX/Uber | UberRider/UberRider/ViewModel/Chat/ContactViewModel.swift | 1 | 4363 | //
// ContactViewModel.swift
// UberRider
//
// Created by lieon on 2017/3/31.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import Foundation
import UIKit
import FirebaseDatabase
import ObjectMapper
class ContactViewModel {
var currentUserID: String = ""
lazy var contacts: [Contact] = [Contact]()
func getContacts(finishCallback: @escaping () -> Void) {
DBProvider.shared.usersRef.child(UserInfo.shared.uid).child(Constants.data).child(Constants.contacts).observe(.value, with: { snapshot in
guard let contacts = snapshot.value as? [String: Any] else { return }
self.contacts.removeAll()
contacts.forEach({ (key: String, value: Any) in
guard let value = value as? [String: Any], let model = Mapper<Contact>().map(JSON: value) else { return }
self.contacts.append(model)
})
finishCallback()
})
}
func addConact(email: String, callback: @escaping (_ message: String) -> Void) {
var data: [String: Any] = [String: Any]()
if !email.isValidEmail() {
callback("Please enter a valid email")
return
}
let group = DispatchGroup()
group.enter()
var isSame = false
DBProvider.shared.usersRef.child(UserInfo.shared.uid).child(Constants.data).observeSingleEvent(of: .value, with: { snapshot in
guard let dataJson = snapshot.value as? [String: Any] else { return }
if let contactsJson = dataJson[Constants.contacts] as? [String: Any] {
for (_, value) in contactsJson {
if let value = value as? [String: String], let friendEmail = value[Constants.email], email == friendEmail {
isSame = true
break
}
}
}
group.leave()
if isSame {
callback("repeat add")
}
})
group.notify(queue: .main) {
if isSame {
return
}
data[Constants.email] = email
var emailArray: [String] = [String]()
DBProvider.shared.usersRef.observeSingleEvent(of: .value, with: { snapshot in
guard let users = snapshot.value as? [String: Any] else { return }
for (key, _) in users {
group.enter()
DBProvider.shared.usersRef.child(key).child(Constants.data).child(Constants.email).observe(.value, with: { dataSnapshot in
if let value = dataSnapshot.value as? String {
emailArray.append(value)
} else {
callback("do not get it")
}
group.leave()
})
}
group.notify(queue: DispatchQueue.main, execute: {
if !emailArray.contains(email) {
callback("fail:\(email) do not exist")
} else {
DBProvider.shared.usersRef.observeSingleEvent(of: .value, with: {
snapshot in
guard let users = snapshot.value as? [String: Any] else { return }
for (key, value) in users {
if let value = value as? [String: Any], let dataJson = value[Constants.data] as? [String: Any], let currentEmail = dataJson[Constants.email] as? String {
if currentEmail == email {
data[Constants.id] = key
DBProvider.shared.usersRef.child(UserInfo.shared.uid).child(Constants.data).child(Constants.contacts).childByAutoId().setValue(data, withCompletionBlock: { (error, _) in
if let error = error {
callback("The email:\(email) add failedly:\(error.localizedDescription)")
} else {
callback("Add Success")
}
})
}
}
}
})
}
})
})
}
}
}
| mit | 13d61c9cb8b8eddc16831ccb6a0f36ac | 41.745098 | 205 | 0.494954 | 5.011494 | false | false | false | false |
LYM-mg/MGDYZB | MGDYZB简单封装版/MGDYZB/Class/Home/ViewModel/SearchViewModel.swift | 1 | 3527 | //
// SearchViewModel.swift
// MGDYZB
//
// Created by i-Techsys.com on 17/4/10.
// Copyright © 2017年 ming. All rights reserved.
//
import UIKit
class SearchViewModel: BaseViewModel {
lazy var keyword: String = ""
lazy var offset: Int = 0
/*
http://capi.douyucdn.cn/api/v1/searchNew/%E9%98%BF%E7%8B%B8/1?limit=20&client_sys=ios&offset=0
http://capi.douyucdn.cn/api/v1/searchNew/666/1?limit=20&client_sys=ios&offset=0
*/
func searchDataWithKeyword(_ finishCallback: @escaping () -> ()) {
let urlStr = "http://capi.douyucdn.cn/api/v1/searchNew/\(keyword)/1"
let parameters: [String: Any] = ["limit": 20,"client_sys": "ios","offset": offset]
NetWorkTools.requestData1(.get, urlString: urlStr, parameters: parameters) { (result) in
// 1.对界面进行处理
guard let resultDict = result as? [String: Any] else { return }
guard let dataDict = resultDict["data"] as? [String: Any] else { return }
guard let dataArray = dataDict["room"] as? [[String: Any]] else { return }
// 2.判断是否分组数据
// 2.1.创建组
let group = AnchorGroup()
// 2.2.遍历dataArray的所有的字典
for dict in dataArray {
group.anchors.append(AnchorModel(dict: dict))
}
// 2.3.将group,添加到anchorGroups
self.anchorGroups.append(group)
// 3.完成回调
finishCallback()
}
}
}
//"room_id": "522424",
//"room_src": "https://rpic.douyucdn.cn/a1704/11/08/522424_170411082238.jpg",
//"vertical_src": "https://rpic.douyucdn.cn/a1704/11/08/522424_170411082238.jpg",
//"isVertical": 0,
//"cate_id": "1",
//"room_name": "LCS 季后赛4月10日赛事重播",
//"show_status": "1",
//"subject": "",
//"show_time": "1485141294",
//"owner_uid": "34223270",
//"specific_catalog": "lcs",
//"specific_status": "1",
//"vod_quality": "0",
//"nickname": "Riot丶LCS",
//"online": 4515,
//"child_id": "37",
//"avatar": "https://apic.douyucdn.cn/upload/avanew/face/201612/22/11/cd342c0703b2a9a6efa038eb51ef94ac_big.jpg",
//"avatar_mid": "https://apic.douyucdn.cn/upload/avanew/face/201612/22/11/cd342c0703b2a9a6efa038eb51ef94ac_middle.jpg",
//"avatar_small": "https://apic.douyucdn.cn/upload/avanew/face/201612/22/11/cd342c0703b2a9a6efa038eb51ef94ac_small.jpg",
//"jumpUrl": "",
//"icon_data": {
// "status": 5,
// "icon_url": "",
// "icon_width": 0,
// "icon_height": 0
//},
//"url": "/lcs",
//"game_url": "/directory/game/LOL",
//"game_name": "英雄联盟",
//"rid": "522424",
//"oid": "34223270",
//"n": "LCS 季后赛4月10日赛事重播",
//"lt": "1491821346",
//"uc": "4393",
//"ls": "1",
//"on": "Riot丶LCS",
//"fans": "106134",
//"ranktype": 0
//
//
//"room_id": "522424",
//"room_src": "https://rpic.douyucdn.cn/a1704/11/08/522424_170411082238.jpg",
//"vertical_src": "https://rpic.douyucdn.cn/a1704/11/08/522424_170411082238.jpg",
//"isVertical": 0,
//"cate_id": "1",
//"room_name": "LCS 季后赛4月10日赛事重播",
//"status": "1",
//"show_status": "1",
//"subject": "",
//"show_time": "1485141294",
//"owner_uid": "34223270",
//"specific_catalog": "lcs",
//"specific_status": "1",
//"vod_quality": "0",
//"nickname": "Riot丶LCS",
//"online": 4515,
//"url": "/lcs",
//"game_url": "/directory/game/LOL",
//"game_name": "英雄联盟",
//"jumpUrl": "",
//"fans": "106134",
//"ranktype": 0
| mit | bc4d8cedeffe0ad985bfa0888e39a73e | 30.009174 | 120 | 0.583728 | 2.791082 | false | false | false | false |
Adorkable/StoryboardKit | StoryboardKit/StoryboardFileParser.swift | 1 | 2570 | //
// StoryboardFileParser.swift
// StoryboardKit
//
// Created by Ian on 5/3/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import Foundation
import SWXMLHash
/**
* Interface for implementing a Version Specific Storyboard File Parser
*/
protocol StoryboardFileVersionedParser {
static func supports(root : XMLIndexer) -> Bool
static func parse(indexer : XMLIndexer, applicationInfo : ApplicationInfo) throws -> StoryboardFileParser.ParseResult
}
/**
* Parses storyboard files
*/
public class StoryboardFileParser: NSObject {
/**
* Result value after parsing a Storyboard file
*/
public typealias ParseResult = (StoryboardInstanceInfo?, [String]?)
/**
Main parsing function
- parameter applicationInfo: The applicationInfo instance you wish to fill
- parameter pathFileName: The path to the Storyboard file
- returns: A StoryboardInstanceInfo that represents the parsed Storyboard file and/or an error, and/or any verbose feedback, any of which non-nil or nil depending on the parsing results
*/
public class func parse(applicationInfo : ApplicationInfo, pathFileName : String) throws -> ParseResult {
var result : ParseResult
if NSFileManager.defaultManager().fileExistsAtPath(pathFileName) {
if let data = NSData(contentsOfFile: pathFileName)
{
let indexer = SWXMLHash.parse(data)
result = try self.parseXML(indexer, applicationInfo: applicationInfo)
} else
{
throw NSError(domain: "Unable to open Storyboard file \(pathFileName)", code: 0, userInfo: nil)
}
} else
{
throw NSError(domain: "Unable to find Storyboard file \(pathFileName)", code: 0, userInfo: nil)
}
return result
}
internal static let versionedParserClasses : [StoryboardFileVersionedParser.Type] = [StoryboardFile3_0Parser.self]
internal class func parseXML(indexer : XMLIndexer, applicationInfo : ApplicationInfo) throws -> ParseResult {
var result : ParseResult
// TODO: fix to use versionsedParserClasses
if StoryboardFile3_0Parser.supports(indexer)
{
result = try StoryboardFile3_0Parser.parse(indexer, applicationInfo: applicationInfo)
} else
{
throw NSError(domain: "Unsupported Storyboard file format version: \(version)", code: 0, userInfo: nil)
}
return result
}
}
| mit | 48aae9cc619163c36465e9fa3be288d3 | 33.266667 | 189 | 0.658755 | 4.942308 | false | false | false | false |
benlangmuir/swift | test/Incremental/Dependencies/reference-dependencies-members-fine.swift | 14 | 3517 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-swift-frontend -typecheck -primary-file %t/main.swift %S/../Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - > %t.swiftdeps
// RUN: %target-swift-frontend -typecheck -primary-file %t/main.swift %S/../Inputs/reference-dependencies-members-helper.swift -emit-reference-dependencies-path - > %t-2.swiftdeps
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t-2.swiftdeps %t-2-processed.swiftdeps
// RUN: diff %t-processed.swiftdeps %t-2-processed.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-NOMINAL-2 %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-MEMBER %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=PROVIDES-MEMBER-NEGATIVE %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-NOMINAL %s < %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=DEPENDS-MEMBER %s < %t-processed.swiftdeps
// PROVIDES-NOMINAL-DAG: nominal implementation 4main4BaseC '' true
// PROVIDES-NOMINAL-DAG: nominal interface 4main4BaseC '' true
class Base {
// PROVIDES-MEMBER-DAG: potentialMember implementation 4main4BaseC '' true
// PROVIDES-MEMBER-DAG: potentialMember interface 4main4BaseC '' true
// PROVIDES-MEMBER-NEGATIVE-NOT: member {{.*}} 4main4BaseC {{[^']]+}} true
func foo() {}
}
// PROVIDES-NOMINAL-DAG: nominal implementation 4main3SubC '' true
// PROVIDES-NOMINAL-DAG: nominal interface 4main3SubC '' true
// DEPENDS-NOMINAL-DAG: nominal interface 4main9OtherBaseC '' false
class Sub : OtherBase {
// PROVIDES-MEMBER-DAG: potentialMember implementation 4main3SubC '' true
// PROVIDES-MEMBER-NEGATIVE-NOT: {{potentialM|m}}}}ember implementation 4main3SubC {{.+}} true
// DEPENDS-MEMBER-DAG: potentialMember interface 4main9OtherBaseC '' false
// DEPENDS-MEMBER-DAG: member interface 4main9OtherBaseC foo false
// DEPENDS-MEMBER-DAG: member interface 4main9OtherBaseC init false
func foo() {}
}
// PROVIDES-NOMINAL-DAG: nominal implementation 4main9SomeProtoP '' true
// PROVIDES-NOMINAL-DAG: nominal interface 4main9SomeProtoP '' true
// PROVIDES-MEMBER-DAG: potentialMember interface 4main9SomeProtoP '' true
protocol SomeProto {}
// PROVIDES-NOMINAL-DAG: nominal implementation 4main10OtherClassC '' true
// PROVIDES-NOMINAL-2-DAG: nominal interface 4main10OtherClassC '' true
// PROVIDES-MEMBER-DAG: potentialMember interface 4main10OtherClassC '' true
// DEPENDS-MEMBER-DAG: potentialMember interface 4main10OtherClassC '' true
extension OtherClass : SomeProto {}
// PROVIDES-NOMINAL-DAG: nominal implementation 4main11OtherStructV '' true
// PROVIDES-NOMINAL-DAG: nominal interface 4main11OtherStructV '' true
extension OtherStruct {
// PROVIDES-MEMBER-DAG: potentialMember interface 4main11OtherStructV '' true
// PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV foo true
// PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV bar true
// PROVIDES-MEMBER-DAG: member interface 4main11OtherStructV baz true
// DEPENDS-MEMBER-DAG: potentialMember interface 4main11OtherStructV '' true
func foo() {}
var bar: () { return () }
private func baz() {}
}
| apache-2.0 | e8798ae2e87d2ab40219d9bd34d091a5 | 52.287879 | 179 | 0.744384 | 3.622039 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/CompilerProtocols.swift | 3 | 41116 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Intrinsic protocols shared with the compiler
//===----------------------------------------------------------------------===//
/// A type that can be converted to and from an associated raw value.
///
/// With a `RawRepresentable` type, you can switch back and forth between a
/// custom type and an associated `RawValue` type without losing the value of
/// the original `RawRepresentable` type. Using the raw value of a conforming
/// type streamlines interoperation with Objective-C and legacy APIs and
/// simplifies conformance to other protocols, such as `Equatable`,
/// `Comparable`, and `Hashable`.
///
/// The `RawRepresentable` protocol is seen mainly in two categories of types:
/// enumerations with raw value types and option sets.
///
/// Enumerations with Raw Values
/// ============================
///
/// For any enumeration with a string, integer, or floating-point raw type, the
/// Swift compiler automatically adds `RawRepresentable` conformance. When
/// defining your own custom enumeration, you give it a raw type by specifying
/// the raw type as the first item in the enumeration's type inheritance list.
/// You can also use literals to specify values for one or more cases.
///
/// For example, the `Counter` enumeration defined here has an `Int` raw value
/// type and gives the first case a raw value of `1`:
///
/// enum Counter: Int {
/// case one = 1, two, three, four, five
/// }
///
/// You can create a `Counter` instance from an integer value between 1 and 5
/// by using the `init?(rawValue:)` initializer declared in the
/// `RawRepresentable` protocol. This initializer is failable because although
/// every case of the `Counter` type has a corresponding `Int` value, there
/// are many `Int` values that *don't* correspond to a case of `Counter`.
///
/// for i in 3...6 {
/// print(Counter(rawValue: i))
/// }
/// // Prints "Optional(Counter.three)"
/// // Prints "Optional(Counter.four)"
/// // Prints "Optional(Counter.five)"
/// // Prints "nil"
///
/// Option Sets
/// ===========
///
/// Option sets all conform to `RawRepresentable` by inheritance using the
/// `OptionSet` protocol. Whether using an option set or creating your own,
/// you use the raw value of an option set instance to store the instance's
/// bitfield. The raw value must therefore be of a type that conforms to the
/// `FixedWidthInteger` protocol, such as `UInt8` or `Int`. For example, the
/// `Direction` type defines an option set for the four directions you can
/// move in a game.
///
/// struct Directions: OptionSet {
/// let rawValue: UInt8
///
/// static let up = Directions(rawValue: 1 << 0)
/// static let down = Directions(rawValue: 1 << 1)
/// static let left = Directions(rawValue: 1 << 2)
/// static let right = Directions(rawValue: 1 << 3)
/// }
///
/// Unlike enumerations, option sets provide a nonfailable `init(rawValue:)`
/// initializer to convert from a raw value, because option sets don't have an
/// enumerated list of all possible cases. Option set values have
/// a one-to-one correspondence with their associated raw values.
///
/// In the case of the `Directions` option set, an instance can contain zero,
/// one, or more of the four defined directions. This example declares a
/// constant with three currently allowed moves. The raw value of the
/// `allowedMoves` instance is the result of the bitwise OR of its three
/// members' raw values:
///
/// let allowedMoves: Directions = [.up, .down, .left]
/// print(allowedMoves.rawValue)
/// // Prints "7"
///
/// Option sets use bitwise operations on their associated raw values to
/// implement their mathematical set operations. For example, the `contains()`
/// method on `allowedMoves` performs a bitwise AND operation to check whether
/// the option set contains an element.
///
/// print(allowedMoves.contains(.right))
/// // Prints "false"
/// print(allowedMoves.rawValue & Directions.right.rawValue)
/// // Prints "0"
public protocol RawRepresentable<RawValue> {
/// The raw type that can be used to represent all values of the conforming
/// type.
///
/// Every distinct value of the conforming type has a corresponding unique
/// value of the `RawValue` type, but there may be values of the `RawValue`
/// type that don't have a corresponding value of the conforming type.
associatedtype RawValue
/// Creates a new instance with the specified raw value.
///
/// If there is no value of the type that corresponds with the specified raw
/// value, this initializer returns `nil`. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// print(PaperSize(rawValue: "Legal"))
/// // Prints "Optional("PaperSize.Legal")"
///
/// print(PaperSize(rawValue: "Tabloid"))
/// // Prints "nil"
///
/// - Parameter rawValue: The raw value to use for the new instance.
init?(rawValue: RawValue)
/// The corresponding value of the raw type.
///
/// A new instance initialized with `rawValue` will be equivalent to this
/// instance. For example:
///
/// enum PaperSize: String {
/// case A4, A5, Letter, Legal
/// }
///
/// let selectedSize = PaperSize.Letter
/// print(selectedSize.rawValue)
/// // Prints "Letter"
///
/// print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
/// // Prints "true"
var rawValue: RawValue { get }
}
/// Returns a Boolean value indicating whether the two arguments are equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func == <T: RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue: Equatable {
return lhs.rawValue == rhs.rawValue
}
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func != <T: RawRepresentable>(lhs: T, rhs: T) -> Bool
where T.RawValue: Equatable {
return lhs.rawValue != rhs.rawValue
}
// This overload is needed for ambiguity resolution against the
// implementation of != for T: Equatable
/// Returns a Boolean value indicating whether the two arguments are not equal.
///
/// - Parameters:
/// - lhs: A raw-representable instance.
/// - rhs: A second raw-representable instance.
@inlinable // trivial-implementation
public func != <T: Equatable>(lhs: T, rhs: T) -> Bool
where T: RawRepresentable, T.RawValue: Equatable {
return lhs.rawValue != rhs.rawValue
}
// Ensure that any RawRepresentable types that conform to Hashable without
// providing explicit implementations get hashing that's consistent with the ==
// definition above. (Compiler-synthesized hashing is based on stored properties
// rather than rawValue; the difference is subtle, but it can be fatal.)
extension RawRepresentable where RawValue: Hashable, Self: Hashable {
@inlinable // trivial
public var hashValue: Int {
// Note: in Swift 5.5 and below, this used to return `rawValue.hashValue`.
// The current definition matches the default `hashValue` implementation,
// so that RawRepresentable types don't need to implement both `hashValue`
// and `hash(into:)` to customize their hashing.
_hashValue(for: self)
}
@inlinable // trivial
public func hash(into hasher: inout Hasher) {
hasher.combine(rawValue)
}
@inlinable // trivial
public func _rawHashValue(seed: Int) -> Int {
// In 5.0, this used to return rawValue._rawHashValue(seed: seed). This was
// slightly faster, but it interfered with conforming types' ability to
// customize their hashing. The current definition is equivalent to the
// default implementation; however, we need to keep the definition to remain
// ABI compatible with code compiled on 5.0.
//
// Note that unless a type provides a custom hash(into:) implementation,
// this new version returns the same values as the original 5.0 definition,
// so code that used to work in 5.0 remains working whether or not the
// original definition was inlined.
//
// See https://bugs.swift.org/browse/SR-10734
var hasher = Hasher(_seed: seed)
self.hash(into: &hasher)
return hasher._finalize()
}
}
/// A type that provides a collection of all of its values.
///
/// Types that conform to the `CaseIterable` protocol are typically
/// enumerations without associated values. When using a `CaseIterable` type,
/// you can access a collection of all of the type's cases by using the type's
/// `allCases` property.
///
/// For example, the `CompassDirection` enumeration declared in this example
/// conforms to `CaseIterable`. You access the number of cases and the cases
/// themselves through `CompassDirection.allCases`.
///
/// enum CompassDirection: CaseIterable {
/// case north, south, east, west
/// }
///
/// print("There are \(CompassDirection.allCases.count) directions.")
/// // Prints "There are 4 directions."
/// let caseList = CompassDirection.allCases
/// .map({ "\($0)" })
/// .joined(separator: ", ")
/// // caseList == "north, south, east, west"
///
/// Conforming to the CaseIterable Protocol
/// =======================================
///
/// The compiler can automatically provide an implementation of the
/// `CaseIterable` requirements for any enumeration without associated values
/// or `@available` attributes on its cases. The synthesized `allCases`
/// collection provides the cases in order of their declaration.
///
/// You can take advantage of this compiler support when defining your own
/// custom enumeration by declaring conformance to `CaseIterable` in the
/// enumeration's original declaration. The `CompassDirection` example above
/// demonstrates this automatic implementation.
public protocol CaseIterable {
/// A type that can represent a collection of all values of this type.
associatedtype AllCases: Collection = [Self]
where AllCases.Element == Self
/// A collection of all values of this type.
static var allCases: AllCases { get }
}
/// A type that can be initialized using the nil literal, `nil`.
///
/// `nil` has a specific meaning in Swift---the absence of a value. Only the
/// `Optional` type conforms to `ExpressibleByNilLiteral`.
/// `ExpressibleByNilLiteral` conformance for types that use `nil` for other
/// purposes is discouraged.
public protocol ExpressibleByNilLiteral {
/// Creates an instance initialized with `nil`.
init(nilLiteral: ())
}
public protocol _ExpressibleByBuiltinIntegerLiteral {
init(_builtinIntegerLiteral value: Builtin.IntLiteral)
}
/// A type that can be initialized with an integer literal.
///
/// The standard library integer and floating-point types, such as `Int` and
/// `Double`, conform to the `ExpressibleByIntegerLiteral` protocol. You can
/// initialize a variable or constant of any of these types by assigning an
/// integer literal.
///
/// // Type inferred as 'Int'
/// let cookieCount = 12
///
/// // An array of 'Int'
/// let chipsPerCookie = [21, 22, 25, 23, 24, 19]
///
/// // A floating-point value initialized using an integer literal
/// let redPercentage: Double = 1
/// // redPercentage == 1.0
///
/// Conforming to ExpressibleByIntegerLiteral
/// =========================================
///
/// To add `ExpressibleByIntegerLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByIntegerLiteral {
/// A type that represents an integer literal.
///
/// The standard library integer and floating-point types are all valid types
/// for `IntegerLiteralType`.
associatedtype IntegerLiteralType: _ExpressibleByBuiltinIntegerLiteral
/// Creates an instance initialized to the specified integer value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an integer literal. For example:
///
/// let x = 23
///
/// In this example, the assignment to the `x` constant calls this integer
/// literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(integerLiteral value: IntegerLiteralType)
}
public protocol _ExpressibleByBuiltinFloatLiteral {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
/// A type that can be initialized with a floating-point literal.
///
/// The standard library floating-point types---`Float`, `Double`, and
/// `Float80` where available---all conform to the `ExpressibleByFloatLiteral`
/// protocol. You can initialize a variable or constant of any of these types
/// by assigning a floating-point literal.
///
/// // Type inferred as 'Double'
/// let threshold = 6.0
///
/// // An array of 'Double'
/// let measurements = [2.2, 4.1, 3.65, 4.2, 9.1]
///
/// Conforming to ExpressibleByFloatLiteral
/// =======================================
///
/// To add `ExpressibleByFloatLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByFloatLiteral {
/// A type that represents a floating-point literal.
///
/// Valid types for `FloatLiteralType` are `Float`, `Double`, and `Float80`
/// where available.
associatedtype FloatLiteralType: _ExpressibleByBuiltinFloatLiteral
/// Creates an instance initialized to the specified floating-point value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a floating-point literal. For example:
///
/// let x = 21.5
///
/// In this example, the assignment to the `x` constant calls this
/// floating-point literal initializer behind the scenes.
///
/// - Parameter value: The value to create.
init(floatLiteral value: FloatLiteralType)
}
public protocol _ExpressibleByBuiltinBooleanLiteral {
init(_builtinBooleanLiteral value: Builtin.Int1)
}
/// A type that can be initialized with the Boolean literals `true` and
/// `false`.
///
/// `Bool`, `DarwinBoolean`, `ObjCBool`, and `WindowsBool` are treated as
/// Boolean values. Expanding this set to include types that represent more than
/// simple Boolean values is discouraged.
///
/// To add `ExpressibleByBooleanLiteral` conformance to your custom type,
/// implement the `init(booleanLiteral:)` initializer that creates an instance
/// of your type with the given Boolean value.
public protocol ExpressibleByBooleanLiteral {
/// A type that represents a Boolean literal, such as `Bool`.
associatedtype BooleanLiteralType: _ExpressibleByBuiltinBooleanLiteral
/// Creates an instance initialized to the given Boolean value.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using one of the Boolean literals `true` and `false`. For
/// example:
///
/// let twasBrillig = true
///
/// In this example, the assignment to the `twasBrillig` constant calls this
/// Boolean literal initializer behind the scenes.
///
/// - Parameter value: The value of the new instance.
init(booleanLiteral value: BooleanLiteralType)
}
public protocol _ExpressibleByBuiltinUnicodeScalarLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32)
}
/// A type that can be initialized with a string literal containing a single
/// Unicode scalar value.
///
/// The `String`, `StaticString`, `Character`, and `Unicode.Scalar` types all
/// conform to the `ExpressibleByUnicodeScalarLiteral` protocol. You can
/// initialize a variable of any of these types using a string literal that
/// holds a single Unicode scalar.
///
/// let ñ: Unicode.Scalar = "ñ"
/// print(ñ)
/// // Prints "ñ"
///
/// Conforming to ExpressibleByUnicodeScalarLiteral
/// ===============================================
///
/// To add `ExpressibleByUnicodeScalarLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByUnicodeScalarLiteral {
/// A type that represents a Unicode scalar literal.
///
/// Valid types for `UnicodeScalarLiteralType` are `Unicode.Scalar`,
/// `Character`, `String`, and `StaticString`.
associatedtype UnicodeScalarLiteralType: _ExpressibleByBuiltinUnicodeScalarLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(unicodeScalarLiteral value: UnicodeScalarLiteralType)
}
public protocol _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
: _ExpressibleByBuiltinUnicodeScalarLiteral {
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal containing a single
/// extended grapheme cluster.
///
/// An *extended grapheme cluster* is a group of one or more Unicode scalar
/// values that approximates a single user-perceived character. Many
/// individual characters, such as "é", "김", and "🇮🇳", can be made up of
/// multiple Unicode scalar values. These code points are combined by
/// Unicode's boundary algorithms into extended grapheme clusters.
///
/// The `String`, `StaticString`, and `Character` types conform to the
/// `ExpressibleByExtendedGraphemeClusterLiteral` protocol. You can initialize
/// a variable or constant of any of these types using a string literal that
/// holds a single character.
///
/// let snowflake: Character = "❄︎"
/// print(snowflake)
/// // Prints "❄︎"
///
/// Conforming to ExpressibleByExtendedGraphemeClusterLiteral
/// =========================================================
///
/// To add `ExpressibleByExtendedGraphemeClusterLiteral` conformance to your
/// custom type, implement the required initializer.
public protocol ExpressibleByExtendedGraphemeClusterLiteral
: ExpressibleByUnicodeScalarLiteral {
/// A type that represents an extended grapheme cluster literal.
///
/// Valid types for `ExtendedGraphemeClusterLiteralType` are `Character`,
/// `String`, and `StaticString`.
associatedtype ExtendedGraphemeClusterLiteralType
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral
/// Creates an instance initialized to the given value.
///
/// - Parameter value: The value of the new instance.
init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType)
}
extension ExpressibleByExtendedGraphemeClusterLiteral
where ExtendedGraphemeClusterLiteralType == UnicodeScalarLiteralType {
@_transparent
public init(unicodeScalarLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(extendedGraphemeClusterLiteral: value)
}
}
public protocol _ExpressibleByBuiltinStringLiteral
: _ExpressibleByBuiltinExtendedGraphemeClusterLiteral {
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1)
}
/// A type that can be initialized with a string literal.
///
/// The `String` and `StaticString` types conform to the
/// `ExpressibleByStringLiteral` protocol. You can initialize a variable or
/// constant of either of these types using a string literal of any length.
///
/// let picnicGuest = "Deserving porcupine"
///
/// Conforming to ExpressibleByStringLiteral
/// ========================================
///
/// To add `ExpressibleByStringLiteral` conformance to your custom type,
/// implement the required initializer.
public protocol ExpressibleByStringLiteral
: ExpressibleByExtendedGraphemeClusterLiteral {
/// A type that represents a string literal.
///
/// Valid types for `StringLiteralType` are `String` and `StaticString`.
associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral
/// Creates an instance initialized to the given string value.
///
/// - Parameter value: The value of the new instance.
init(stringLiteral value: StringLiteralType)
}
extension ExpressibleByStringLiteral
where StringLiteralType == ExtendedGraphemeClusterLiteralType {
@_transparent
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
}
/// A type that can be initialized using an array literal.
///
/// An array literal is a simple way of expressing a list of values. Simply
/// surround a comma-separated list of values, instances, or literals with
/// square brackets to create an array literal. You can use an array literal
/// anywhere an instance of an `ExpressibleByArrayLiteral` type is expected: as
/// a value assigned to a variable or constant, as a parameter to a method or
/// initializer, or even as the subject of a nonmutating operation like
/// `map(_:)` or `filter(_:)`.
///
/// Arrays, sets, and option sets all conform to `ExpressibleByArrayLiteral`,
/// and your own custom types can as well. Here's an example of creating a set
/// and an array using array literals:
///
/// let employeesSet: Set<String> = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesSet)
/// // Prints "["Amir", "Dave", "Jihye", "Alessia"]"
///
/// let employeesArray: [String] = ["Amir", "Jihye", "Dave", "Alessia", "Dave"]
/// print(employeesArray)
/// // Prints "["Amir", "Jihye", "Dave", "Alessia", "Dave"]"
///
/// The `Set` and `Array` types each handle array literals in their own way to
/// create new instances. In this case, the newly created set drops the
/// duplicate value ("Dave") and doesn't maintain the order of the array
/// literal's elements. The new array, on the other hand, matches the order
/// and number of elements provided.
///
/// - Note: An array literal is not the same as an `Array` instance. You can't
/// initialize a type that conforms to `ExpressibleByArrayLiteral` simply by
/// assigning an existing array.
///
/// let anotherSet: Set = employeesArray
/// // error: cannot convert value of type '[String]' to specified type 'Set'
///
/// Type Inference of Array Literals
/// ================================
///
/// Whenever possible, Swift's compiler infers the full intended type of your
/// array literal. Because `Array` is the default type for an array literal,
/// without writing any other code, you can declare an array with a particular
/// element type by providing one or more values.
///
/// In this example, the compiler infers the full type of each array literal.
///
/// let integers = [1, 2, 3]
/// // 'integers' has type '[Int]'
///
/// let strings = ["a", "b", "c"]
/// // 'strings' has type '[String]'
///
/// An empty array literal alone doesn't provide enough information for the
/// compiler to infer the intended type of the `Array` instance. When using an
/// empty array literal, specify the type of the variable or constant.
///
/// var emptyArray: [Bool] = []
/// // 'emptyArray' has type '[Bool]'
///
/// Because many functions and initializers fully specify the types of their
/// parameters, you can often use an array literal with or without elements as
/// a parameter. For example, the `sum(_:)` function shown here takes an `Int`
/// array as a parameter:
///
/// func sum(values: [Int]) -> Int {
/// return values.reduce(0, +)
/// }
///
/// let sumOfFour = sum([5, 10, 15, 20])
/// // 'sumOfFour' == 50
///
/// let sumOfNone = sum([])
/// // 'sumOfNone' == 0
///
/// When you call a function that does not fully specify its parameters' types,
/// use the type-cast operator (`as`) to specify the type of an array literal.
/// For example, the `log(name:value:)` function shown here has an
/// unconstrained generic `value` parameter.
///
/// func log<T>(name name: String, value: T) {
/// print("\(name): \(value)")
/// }
///
/// log(name: "Four integers", value: [5, 10, 15, 20])
/// // Prints "Four integers: [5, 10, 15, 20]"
///
/// log(name: "Zero integers", value: [] as [Int])
/// // Prints "Zero integers: []"
///
/// Conforming to ExpressibleByArrayLiteral
/// =======================================
///
/// Add the capability to be initialized with an array literal to your own
/// custom types by declaring an `init(arrayLiteral:)` initializer. The
/// following example shows the array literal initializer for a hypothetical
/// `OrderedSet` type, which has setlike semantics but maintains the order of
/// its elements.
///
/// struct OrderedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
/// }
///
/// extension OrderedSet: ExpressibleByArrayLiteral {
/// init(arrayLiteral: Element...) {
/// self.init()
/// for element in arrayLiteral {
/// self.append(element)
/// }
/// }
/// }
public protocol ExpressibleByArrayLiteral {
/// The type of the elements of an array literal.
associatedtype ArrayLiteralElement
/// Creates an instance initialized with the given elements.
init(arrayLiteral elements: ArrayLiteralElement...)
}
/// A type that can be initialized using a dictionary literal.
///
/// A dictionary literal is a simple way of writing a list of key-value pairs.
/// You write each key-value pair with a colon (`:`) separating the key and
/// the value. The dictionary literal is made up of one or more key-value
/// pairs, separated by commas and surrounded with square brackets.
///
/// To declare a dictionary, assign a dictionary literal to a variable or
/// constant:
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana",
/// "JP": "Japan", "US": "United States"]
/// // 'countryCodes' has type [String: String]
///
/// print(countryCodes["BR"]!)
/// // Prints "Brazil"
///
/// When the context provides enough type information, you can use a special
/// form of the dictionary literal, square brackets surrounding a single
/// colon, to initialize an empty dictionary.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.count)
/// // Prints "0"
///
/// - Note:
/// A dictionary literal is *not* the same as an instance of `Dictionary`.
/// You can't initialize a type that conforms to `ExpressibleByDictionaryLiteral`
/// simply by assigning an instance of `Dictionary`, `KeyValuePairs`, or similar.
///
/// Conforming to the ExpressibleByDictionaryLiteral Protocol
/// =========================================================
///
/// To add the capability to be initialized with a dictionary literal to your
/// own custom types, declare an `init(dictionaryLiteral:)` initializer. The
/// following example shows the dictionary literal initializer for a
/// hypothetical `CountedSet` type, which uses setlike semantics while keeping
/// track of the count for duplicate elements:
///
/// struct CountedSet<Element: Hashable>: Collection, SetAlgebra {
/// // implementation details
///
/// /// Updates the count stored in the set for the given element,
/// /// adding the element if necessary.
/// ///
/// /// - Parameter n: The new count for `element`. `n` must be greater
/// /// than or equal to zero.
/// /// - Parameter element: The element to set the new count on.
/// mutating func updateCount(_ n: Int, for element: Element)
/// }
///
/// extension CountedSet: ExpressibleByDictionaryLiteral {
/// init(dictionaryLiteral elements: (Element, Int)...) {
/// self.init()
/// for (element, count) in elements {
/// self.updateCount(count, for: element)
/// }
/// }
/// }
public protocol ExpressibleByDictionaryLiteral {
/// The key type of a dictionary literal.
associatedtype Key
/// The value type of a dictionary literal.
associatedtype Value
/// Creates an instance initialized with the given key-value pairs.
init(dictionaryLiteral elements: (Key, Value)...)
}
/// A type that can be initialized by string interpolation with a string
/// literal that includes expressions.
///
/// Use string interpolation to include one or more expressions in a string
/// literal, wrapped in a set of parentheses and prefixed by a backslash. For
/// example:
///
/// let price = 2
/// let number = 3
/// let message = "One cookie: $\(price), \(number) cookies: $\(price * number)."
/// print(message)
/// // Prints "One cookie: $2, 3 cookies: $6."
///
/// Extending the Default Interpolation Behavior
/// ============================================
///
/// Add new interpolation behavior to existing types by extending
/// `DefaultStringInterpolation`, the type that implements interpolation for
/// types like `String` and `Substring`, to add an overload of
/// `appendInterpolation(_:)` with their new behavior.
///
/// For more information, see the `DefaultStringInterpolation` and
/// `StringInterpolationProtocol` documentation.
///
/// Creating a Type That Supports the Default String Interpolation
/// ==============================================================
///
/// To create a new type that supports string literals and interpolation, but
/// that doesn't need any custom behavior, conform the type to
/// `ExpressibleByStringInterpolation` and implement the
/// `init(stringLiteral: String)` initializer declared by the
/// `ExpressibleByStringLiteral` protocol. Swift will automatically use
/// `DefaultStringInterpolation` as the interpolation type and provide an
/// implementation for `init(stringInterpolation:)` that passes the
/// interpolated literal's contents to `init(stringLiteral:)`, so you don't
/// need to implement anything specific to this protocol.
///
/// Creating a Type That Supports Custom String Interpolation
/// =========================================================
///
/// If you want a conforming type to differentiate between literal and
/// interpolated segments, restrict the types that can be interpolated,
/// support different interpolators from the ones on `String`, or avoid
/// constructing a `String` containing the data, the type must specify a custom
/// `StringInterpolation` associated type. This type must conform to
/// `StringInterpolationProtocol` and have a matching `StringLiteralType`.
///
/// For more information, see the `StringInterpolationProtocol` documentation.
public protocol ExpressibleByStringInterpolation
: ExpressibleByStringLiteral {
/// The type each segment of a string literal containing interpolations
/// should be appended to.
///
/// The `StringLiteralType` of an interpolation type must match the
/// `StringLiteralType` of the conforming type.
associatedtype StringInterpolation: StringInterpolationProtocol
= DefaultStringInterpolation
where StringInterpolation.StringLiteralType == StringLiteralType
/// Creates an instance from a string interpolation.
///
/// Most `StringInterpolation` types will store information about the
/// literals and interpolations appended to them in one or more properties.
/// `init(stringInterpolation:)` should use these properties to initialize
/// the instance.
///
/// - Parameter stringInterpolation: An instance of `StringInterpolation`
/// which has had each segment of the string literal appended
/// to it.
init(stringInterpolation: StringInterpolation)
}
extension ExpressibleByStringInterpolation
where StringInterpolation == DefaultStringInterpolation {
/// Creates a new instance from an interpolated string literal.
///
/// Don't call this initializer directly. It's used by the compiler when
/// you create a string using string interpolation. Instead, use string
/// interpolation to create a new string by including values, literals,
/// variables, or expressions enclosed in parentheses, prefixed by a
/// backslash (`\(`...`)`).
///
/// let price = 2
/// let number = 3
/// let message = """
/// If one cookie costs \(price) dollars, \
/// \(number) cookies cost \(price * number) dollars.
/// """
/// // message == "If one cookie costs 2 dollars, 3 cookies cost 6 dollars."
public init(stringInterpolation: DefaultStringInterpolation) {
self.init(stringLiteral: stringInterpolation.make())
}
}
/// Represents the contents of a string literal with interpolations while it's
/// being built up.
///
/// Each `ExpressibleByStringInterpolation` type has an associated
/// `StringInterpolation` type which conforms to `StringInterpolationProtocol`.
/// Swift converts an expression like `"The time is \(time)." as MyString` into
/// a series of statements similar to:
///
/// var interpolation = MyString.StringInterpolation(literalCapacity: 13,
/// interpolationCount: 1)
///
/// interpolation.appendLiteral("The time is ")
/// interpolation.appendInterpolation(time)
/// interpolation.appendLiteral(".")
///
/// MyString(stringInterpolation: interpolation)
///
/// The `StringInterpolation` type is responsible for collecting the segments
/// passed to its `appendLiteral(_:)` and `appendInterpolation` methods and
/// assembling them into a whole, converting as necessary. Once all of the
/// segments are appended, the interpolation is passed to an
/// `init(stringInterpolation:)` initializer on the type being created, which
/// must extract the accumulated data from the `StringInterpolation`.
///
/// In simple cases, you can use `DefaultStringInterpolation` as the
/// interpolation type for types that conform to the
/// `ExpressibleByStringLiteral` protocol. To use the default interpolation,
/// conform a type to `ExpressibleByStringInterpolation` and implement
/// `init(stringLiteral: String)`. Values in interpolations are converted to
/// strings, and then passed to that initializer just like any other string
/// literal.
///
/// Handling String Interpolations
/// ==============================
///
/// With a custom interpolation type, each interpolated segment is translated
/// into a call to a special `appendInterpolation` method. The contents of
/// the interpolation's parentheses are treated as the call's argument list.
/// That argument list can include multiple arguments and argument labels.
///
/// The following examples show how string interpolations are translated into
/// calls to `appendInterpolation`:
///
/// - `\(x)` translates to `appendInterpolation(x)`
/// - `\(x, y)` translates to `appendInterpolation(x, y)`
/// - `\(foo: x)` translates to `appendInterpolation(foo: x)`
/// - `\(x, foo: y)` translates to `appendInterpolation(x, foo: y)`
///
/// The `appendInterpolation` methods in your custom type must be mutating
/// instance methods that return `Void`. This code shows a custom interpolation
/// type's declaration of an `appendInterpolation` method that provides special
/// validation for user input:
///
/// extension MyString.StringInterpolation {
/// mutating func appendInterpolation(validating input: String) {
/// // Perform validation of `input` and store for later use
/// }
/// }
///
/// To use this interpolation method, create a string literal with an
/// interpolation using the `validating` parameter label.
///
/// let userInput = readLine() ?? ""
/// let myString = "The user typed '\(validating: userInput)'." as MyString
///
/// `appendInterpolation` methods support virtually all features of methods:
/// they can have any number of parameters, can specify labels for any or all
/// of their parameters, can provide default values, can have variadic
/// parameters, and can have parameters with generic types. Most importantly,
/// they can be overloaded, so a type that conforms to
/// `StringInterpolationProtocol` can provide several different
/// `appendInterpolation` methods with different behaviors. An
/// `appendInterpolation` method can also throw; when a user writes a literal
/// with one of these interpolations, they must mark the string literal with
/// `try` or one of its variants.
public protocol StringInterpolationProtocol {
/// The type that should be used for literal segments.
associatedtype StringLiteralType: _ExpressibleByBuiltinStringLiteral
/// Creates an empty instance ready to be filled with string literal content.
///
/// Don't call this initializer directly. Instead, initialize a variable or
/// constant using a string literal with interpolated expressions.
///
/// Swift passes this initializer a pair of arguments specifying the size of
/// the literal segments and the number of interpolated segments. Use this
/// information to estimate the amount of storage you will need.
///
/// - Parameter literalCapacity: The approximate size of all literal segments
/// combined. This is meant to be passed to `String.reserveCapacity(_:)`;
/// it may be slightly larger or smaller than the sum of the counts of each
/// literal segment.
/// - Parameter interpolationCount: The number of interpolations which will be
/// appended. Use this value to estimate how much additional capacity will
/// be needed for the interpolated segments.
init(literalCapacity: Int, interpolationCount: Int)
/// Appends a literal segment to the interpolation.
///
/// Don't call this method directly. Instead, initialize a variable or
/// constant using a string literal with interpolated expressions.
///
/// Interpolated expressions don't pass through this method; instead, Swift
/// selects an overload of `appendInterpolation`. For more information, see
/// the top-level `StringInterpolationProtocol` documentation.
///
/// - Parameter literal: A string literal containing the characters
/// that appear next in the string literal.
mutating func appendLiteral(_ literal: StringLiteralType)
// Informal requirement: Any desired appendInterpolation overloads, e.g.:
//
// mutating func appendInterpolation<T>(_: T)
// mutating func appendInterpolation(_: Int, radix: Int)
// mutating func appendInterpolation<T: Encodable>(json: T) throws
}
/// A type that can be initialized using a color literal (e.g.
/// `#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)`).
public protocol _ExpressibleByColorLiteral {
/// Creates an instance initialized with the given properties of a color
/// literal.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a color literal.
init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float)
}
/// A type that can be initialized using an image literal (e.g.
/// `#imageLiteral(resourceName: "hi.png")`).
public protocol _ExpressibleByImageLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using an image literal.
init(imageLiteralResourceName path: String)
}
/// A type that can be initialized using a file reference literal (e.g.
/// `#fileLiteral(resourceName: "resource.txt")`).
public protocol _ExpressibleByFileReferenceLiteral {
/// Creates an instance initialized with the given resource name.
///
/// Do not call this initializer directly. Instead, initialize a variable or
/// constant using a file reference literal.
init(fileReferenceLiteralResourceName path: String)
}
/// A container is destructor safe if whether it may store to memory on
/// destruction only depends on its type parameters destructors.
/// For example, whether `Array<Element>` may store to memory on destruction
/// depends only on `Element`.
/// If `Element` is an `Int` we know the `Array<Int>` does not store to memory
/// during destruction. If `Element` is an arbitrary class
/// `Array<MemoryUnsafeDestructorClass>` then the compiler will deduce may
/// store to memory on destruction because `MemoryUnsafeDestructorClass`'s
/// destructor may store to memory on destruction.
/// If in this example during `Array`'s destructor we would call a method on any
/// type parameter - say `Element.extraCleanup()` - that could store to memory,
/// then Array would no longer be a _DestructorSafeContainer.
public protocol _DestructorSafeContainer {
}
| apache-2.0 | 19f0dbaec91e09622dd79cae46cdf85e | 41.191992 | 85 | 0.687432 | 4.749769 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application | Chula Expo 2017/Chula Expo 2017/AppDelegate.swift | 1 | 14378 | //
// AppDelegate.swift
// Chula Expo 2017
//
// Created by Pakpoom on 12/25/2559 BE.
// Copyright © 2559 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
import CoreData
import FBSDKLoginKit
import Alamofire
import Siren
import Fabric
import Answers
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SirenDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
print("...")
print(urls[urls.count-1] as URL)
Fabric.with([Answers.self])
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
NSTimeZone.default = TimeZone(secondsFromGMT: 25200)!
let siren = Siren.sharedInstance
siren.delegate = self
siren.alertType = .force
siren.checkVersion(checkType: .immediately)
application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil))
return true
}
func sirenLatestVersionInstalled() {
let fetchUserData = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
let requestDeleteUserData = NSBatchDeleteRequest(fetchRequest: fetchUserData)
let fetchReservedData = NSFetchRequest<NSFetchRequestResult>(entityName: "ReservedActivity")
let requestDeleteReservedActivity = NSBatchDeleteRequest(fetchRequest: fetchReservedData)
do {
try managedObjectContext.execute(requestDeleteUserData)
try managedObjectContext.execute(requestDeleteReservedActivity)
} catch let error {
print(error)
}
if EntityHistory.getLanguage(inManageobjectcontext: managedObjectContext) == nil {
_ = EntityHistory.addHistory(forEntityName: "LANGUAGE-TH", inManageobjectcontext: managedObjectContext)
do {
try managedObjectContext.save()
} catch {
print("error")
}
}
APIController.downloadHightlightActivities(inManageobjectcontext: self.managedObjectContext) { (success) in
if success {
APIController.downloadStageActivities(inManageobjectcontext: self.managedObjectContext, completion: nil)
}
}
APIController.downloadZone(inManageobjectcontext: self.managedObjectContext)
APIController.downloadFacility(inManageobjectcontext: self.managedObjectContext)
}
func sirenDidShowUpdateDialog(alertType: SirenAlertType) {
self.managedObjectContext.performAndWait {
let fetchActivityData = NSFetchRequest<NSFetchRequestResult>(entityName: "ActivityData")
let requestDeleteActivityData = NSBatchDeleteRequest(fetchRequest: fetchActivityData)
let fetchEntityHistory = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityHistory")
let requestDeleteEntitiyHistory = NSBatchDeleteRequest(fetchRequest: fetchEntityHistory)
let fetchFacilityData = NSFetchRequest<NSFetchRequestResult>(entityName: "FacilityData")
let requestDeleteFacilityData = NSBatchDeleteRequest(fetchRequest: fetchFacilityData)
let fetchFavoritedData = NSFetchRequest<NSFetchRequestResult>(entityName: "FavoritedActivity")
let requestDeleteFavoritedActivity = NSBatchDeleteRequest(fetchRequest: fetchFavoritedData)
let fetchHighlighActivity = NSFetchRequest<NSFetchRequestResult>(entityName: "HighlightActivity")
let requestDeleteHighlightActivity = NSBatchDeleteRequest(fetchRequest: fetchHighlighActivity)
let fetchImageData = NSFetchRequest<NSFetchRequestResult>(entityName: "ImageData")
let requestDeleteImageData = NSBatchDeleteRequest(fetchRequest: fetchImageData)
let fetchNearbyActivity = NSFetchRequest<NSFetchRequestResult>(entityName: "NearbyActivity")
let requestDeleteNearbyActivity = NSBatchDeleteRequest(fetchRequest: fetchNearbyActivity)
let fetchPlaceData = NSFetchRequest<NSFetchRequestResult>(entityName: "PlaceData")
let requestDeletePlaceData = NSBatchDeleteRequest(fetchRequest: fetchPlaceData)
let fetchRecommendActivity = NSFetchRequest<NSFetchRequestResult>(entityName: "RecommendActivity")
let requestDeleteRecommendActivity = NSBatchDeleteRequest(fetchRequest: fetchRecommendActivity)
let fetchReservedData = NSFetchRequest<NSFetchRequestResult>(entityName: "ReservedActivity")
let requestDeleteReservedActivity = NSBatchDeleteRequest(fetchRequest: fetchReservedData)
let fetchRoomData = NSFetchRequest<NSFetchRequestResult>(entityName: "RoomData")
let requestDeleteRoomData = NSBatchDeleteRequest(fetchRequest: fetchRoomData)
let fetchRoundData = NSFetchRequest<NSFetchRequestResult>(entityName: "RoundData")
let requestDeleteRoundData = NSBatchDeleteRequest(fetchRequest: fetchRoundData)
let fetchStageActivity = NSFetchRequest<NSFetchRequestResult>(entityName: "StageActivity")
let requestDeleteStageActivity = NSBatchDeleteRequest(fetchRequest: fetchStageActivity)
let fetchTagData = NSFetchRequest<NSFetchRequestResult>(entityName: "TagData")
let requestDeleteTagData = NSBatchDeleteRequest(fetchRequest: fetchTagData)
let fetchVideoData = NSFetchRequest<NSFetchRequestResult>(entityName: "VideoData")
let requestDeleteVideoData = NSBatchDeleteRequest(fetchRequest: fetchVideoData)
let fetchZoneData = NSFetchRequest<NSFetchRequestResult>(entityName: "ZoneData")
let requestDeleteZoneData = NSBatchDeleteRequest(fetchRequest: fetchZoneData)
let fetchUserData = NSFetchRequest<NSFetchRequestResult>(entityName: "UserData")
let requestDeleteUserData = NSBatchDeleteRequest(fetchRequest: fetchUserData)
do {
try self.managedObjectContext.execute(requestDeleteActivityData)
try self.managedObjectContext.execute(requestDeleteEntitiyHistory)
try self.managedObjectContext.execute(requestDeleteFacilityData)
try self.managedObjectContext.execute(requestDeleteFavoritedActivity)
try self.managedObjectContext.execute(requestDeleteHighlightActivity)
try self.managedObjectContext.execute(requestDeleteImageData)
try self.managedObjectContext.execute(requestDeleteNearbyActivity)
try self.managedObjectContext.execute(requestDeletePlaceData)
try self.managedObjectContext.execute(requestDeleteRecommendActivity)
try self.managedObjectContext.execute(requestDeleteReservedActivity)
try self.managedObjectContext.execute(requestDeleteRoomData)
try self.managedObjectContext.execute(requestDeleteRoundData)
try self.managedObjectContext.execute(requestDeleteStageActivity)
try self.managedObjectContext.execute(requestDeleteTagData)
try self.managedObjectContext.execute(requestDeleteVideoData)
try self.managedObjectContext.execute(requestDeleteZoneData)
try self.managedObjectContext.execute(requestDeleteUserData)
} catch let error {
print(error)
}
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
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.
FBSDKAppEvents.activateApp()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
// abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 2b264ac3a39611a69adebfdad51d0ce4 | 50.715827 | 291 | 0.687348 | 6.33348 | false | false | false | false |
YoonBongKim/NotificationExampleForiOS | LocalNotificationsExample/AppDelegate.swift | 1 | 10608 | //
// AppDelegate.swift
// LocalNotificationsExample
//
// Created by KimYoonBong on 2015. 5. 29..
// Copyright (c) 2015년 KimYoonBong. All rights reserved.
//
import UIKit
import Parse
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// For Parse
Parse.setApplicationId("Ob0oAUGLasjHk0mGd4KMQPpGHFwLajvXARtYetSF", clientKey: "VTpcD7Gs8BqzE9V2CVMnWaDZCMwabomqgOp3a9eA")
// For iOS8
if NSProcessInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion(majorVersion: 8, minorVersion: 0, patchVersion: 0)) {
let types = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
// MARK: - Actions and Category for Local Notification
let localAction1 = UIMutableUserNotificationAction()
localAction1.activationMode = UIUserNotificationActivationMode.Foreground
localAction1.title = "Action1"
localAction1.identifier = "ACTION1"
localAction1.destructive = false
localAction1.authenticationRequired = false
let localAction2 = UIMutableUserNotificationAction()
localAction2.activationMode = .Background
localAction2.title = "Action2"
localAction2.identifier = "ACTION2"
localAction2.destructive = false
localAction2.authenticationRequired = false
let localCategory = UIMutableUserNotificationCategory()
localCategory.identifier = "CATEGORY1"
localCategory.setActions([localAction1, localAction2], forContext: UIUserNotificationActionContext.Default)
// MARK: - Actions and Category for Remote Notification
let remoteAction1 = UIMutableUserNotificationAction()
remoteAction1.activationMode = UIUserNotificationActivationMode.Foreground
remoteAction1.title = "Action3"
remoteAction1.identifier = "ACTION3"
remoteAction1.destructive = false
remoteAction1.authenticationRequired = false
let remoteAction2 = UIMutableUserNotificationAction()
remoteAction2.activationMode = .Background
remoteAction2.title = "Action4"
remoteAction2.identifier = "ACTION4"
remoteAction2.destructive = false
remoteAction2.authenticationRequired = false
let remoteCategory = UIMutableUserNotificationCategory()
remoteCategory.identifier = "CATEGORY2"
remoteCategory.setActions([remoteAction1, remoteAction2], forContext: UIUserNotificationActionContext.Default)
var categorySet = Set<UIMutableUserNotificationCategory>()
categorySet.insert(localCategory)
categorySet.insert(remoteCategory)
let settings = UIUserNotificationSettings(forTypes: types, categories: categorySet)
application.registerUserNotificationSettings(settings)
}
if let options = launchOptions {
if let notification = options[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
if let body = notification.alertBody {
showAlert(application.applicationState, message:body)
}
}
}
application.applicationIconBadgeNumber = 0
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if notification.category == "CATEGORY1" {
if let id = identifier {
switch id {
case "ACTION1":
let alertView = UIAlertView(title: "LOCAL NOTIFICATION", message: "You chose ACTION1! Right?!", delegate: nil, cancelButtonTitle: "Right!")
alertView.show()
break
case "ACTION2":
NSNotificationCenter.defaultCenter().postNotificationName("LNSilentRemoteNotification", object: nil)
break
default:
break
}
}
}
completionHandler()
}
/*
{ "alert" : "HELLO?!", "category" : "CATEGORY2", }
*/
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [NSObject : AnyObject], completionHandler: () -> Void) {
if let info = userInfo["aps"] as? Dictionary<String, AnyObject> {
if let category = info["category"] as? String {
if category == "CATEGORY2" {
if let id = identifier {
switch id {
case "ACTION3":
let alertView = UIAlertView(title: "REMOTE NOTIFICATION", message: "You chose ACTION3! Right?!", delegate: nil, cancelButtonTitle: "Right!")
alertView.show()
break
case "ACTION4":
NSNotificationCenter.defaultCenter().postNotificationName("LNSilentRemoteNotification", object: nil)
break
default:
break
}
}
}
}
}
completionHandler()
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
println("\(notification)")
notification.applicationIconBadgeNumber = 0
if let body = notification.alertBody {
showAlert(application.applicationState, message: body)
}
}
func showAlert(state: UIApplicationState, message: String) {
var text: String = ""
switch state {
case .Active:
text = "Active "
break
case .Inactive:
text = "Inactive "
break
case .Background:
text = "Background "
break
default:
text = "FirstRun "
break
}
text += "Notification"
let alertView = UIAlertView(title: text, message: message, delegate: nil, cancelButtonTitle: "Okay")
alertView.show()
NSNotificationCenter.defaultCenter().postNotificationName("LNReloadNotification", object: nil)
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
println("device token : \(deviceToken)")
let parsePushInstallation = PFInstallation.currentInstallation()
parsePushInstallation.setDeviceTokenFromData(deviceToken)
parsePushInstallation.channels = ["global"]
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
println("error :\(error.localizedDescription)")
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
println("\(userInfo)")
if let info = userInfo["aps"] as? Dictionary<String, AnyObject> {
if let silent = info["content-available"] as? Bool {
println("\(silent)")
NSNotificationCenter.defaultCenter().postNotificationName("LNSilentRemoteNotification", object: nil)
completionHandler(UIBackgroundFetchResult.NewData)
}
else {
PFPush.handlePush(userInfo)
completionHandler(UIBackgroundFetchResult.NoData)
}
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 36e68434cc977aa14a1c7e3206c90813 | 39.174242 | 285 | 0.604281 | 6.253538 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/BaseApplicationBridge.swift | 1 | 3248 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Base application for Application purposes
Auto-generated implementation of IBaseApplication specification.
*/
public class BaseApplicationBridge : IBaseApplication {
/**
Group of API.
*/
private var apiGroup : IAdaptiveRPGroup? = nil
/**
Default constructor.
*/
public init() {
self.apiGroup = IAdaptiveRPGroup.Application
}
/**
Return the API group for the given interface.
*/
public final func getAPIGroup() -> IAdaptiveRPGroup? {
return self.apiGroup!
}
/**
Return the API version for the given interface.
*/
public final func getAPIVersion() -> String? {
return "v2.2.15"
}
/**
Invokes the given method specified in the API request object.
@param request APIRequest object containing method name and parameters.
@return APIResponse with status code, message and JSON response or a JSON null string for void functions. Status code 200 is OK, all others are HTTP standard error conditions.
*/
public func invoke(request : APIRequest) -> APIResponse? {
let response : APIResponse = APIResponse()
var responseCode : Int32 = 200
var responseMessage : String = "OK"
let responseJSON : String? = "null"
switch request.getMethodName()! {
default:
// 404 - response null.
responseCode = 404
responseMessage = "BaseApplicationBridge does not provide the function '\(request.getMethodName()!)' Please check your client-side API version; should be API version >= v2.2.15."
}
response.setResponse(responseJSON!)
response.setStatusCode(responseCode)
response.setStatusMessage(responseMessage)
return response
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 0687ea3bf790f21743ad851dd79615b7 | 33.531915 | 194 | 0.613062 | 5.063963 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/RequestJoinChatModalController.swift | 1 | 5419 | //
// RequestJoinGroupModalController.swift
// Telegram
//
// Created by Mikhail Filimonov on 01.10.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
private final class Arguments {
let context: AccountContext
init(context: AccountContext) {
self.context = context
}
}
private struct State : Equatable {
let flags: ExternalJoiningChatState.Invite.Flags
let title: String
let about: String?
let photoRepresentation: TelegramMediaImageRepresentation?
let participantsCount: Int32
let isChannelOrMegagroup: Bool
}
private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] {
var entries:[InputDataEntry] = []
var sectionId:Int32 = 0
var index: Int32 = 0
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
// entries
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("value"), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in
return RequestJoinChatRowItem(initialSize, stableId: stableId, context: arguments.context, photo: state.photoRepresentation, title: state.title, about: state.about, participantsCount: Int(state.participantsCount), isChannelOrMegagroup: state.isChannelOrMegagroup, viewType: .singleItem)
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
entries.append(.custom(sectionId: sectionId, index: index, value: .none, identifier: .init("about"), equatable: InputDataEquatable(state), comparable: nil, item: { initialSize, stableId in
return GeneralBlockTextRowItem(initialSize, stableId: stableId, viewType: .singleItem, text: state.flags.isChannel ? strings().requestJoinDescChannel : strings().requestJoinDescGroup, font: .normal(.text), color: theme.colors.grayText)
}))
index += 1
entries.append(.sectionId(sectionId, type: .normal))
sectionId += 1
return entries
}
func RequestJoinChatModalController(context: AccountContext, joinhash: String, invite: ExternalJoiningChatState, interaction:@escaping(Peer)->Void) -> InputDataModalController {
switch invite {
case let .invite(state):
let actionsDisposable = DisposableSet()
let initialState = State(flags: state.flags, title: state.title, about: state.about, photoRepresentation: state.photoRepresentation, participantsCount: state.participantsCount, isChannelOrMegagroup: state.flags.isChannel && state.flags.isBroadcast)
var close:(()->Void)? = nil
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((State) -> State) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
let arguments = Arguments(context: context)
let signal = statePromise.get() |> deliverOnPrepareQueue |> map { state in
return InputDataSignalValue(entries: entries(state, arguments: arguments))
}
let controller = InputDataController(dataSignal: signal, title: state.title)
controller.onDeinit = {
actionsDisposable.dispose()
}
let modalInteractions = ModalInteractions(acceptTitle: strings().requestJoinButton, accept: { [weak controller] in
_ = controller?.returnKeyAction()
}, drawBorder: true, height: 50, singleButton: true)
let modalController = InputDataModalController(controller, modalInteractions: modalInteractions)
controller.leftModalHeader = ModalHeaderData(image: theme.icons.modalClose, handler: { [weak modalController] in
modalController?.close()
})
close = { [weak modalController] in
modalController?.modal?.close()
}
controller.afterTransaction = { controller in
}
controller.returnKeyInvocation = { _, _ in
close?()
_ = showModalProgress(signal: context.engine.peers.joinChatInteractively(with: joinhash), for: context.window).start(next: { peer in
if let peer = peer?._asPeer() {
interaction(peer)
}
}, error: { error in
let text: String
switch error {
case .generic:
text = strings().unknownError
case .tooMuchJoined:
showInactiveChannels(context: context, source: .join)
return
case .tooMuchUsers:
text = strings().groupUsersTooMuchError
case .requestSent:
let navigation = context.bindings.rootNavigation()
navigation.controller.show(toaster: .init(text: strings().requestJoinSent))
return
case .flood:
text = strings().joinLinkFloodError
}
alert(for: context.window, info: text)
})
return .default
}
return modalController
default:
fatalError("I thought it's impossible.")
}
}
| gpl-2.0 | 9da0e4bd91a16dc00b0e2a4afa0aac99 | 36.365517 | 294 | 0.634182 | 5.063551 | false | false | false | false |
skylib/SnapImagePicker | SnapImagePicker/ImagePicker/View/ImageGridView.swift | 1 | 981 | import UIKit
class ImageGridView: UIView {
static let LineWidth = CGFloat(2.0)
static let LineColor = UIColor.black
override func draw(_ rect: CGRect) {
let oneThirdWidth = rect.size.width / 3
let oneThirdHeight = rect.size.height / 3
ImageGridView.LineColor.set()
for i in 1...2 {
drawStraightLineFrom(CGPoint(x: 0, y: oneThirdHeight * CGFloat(i)),
to: CGPoint(x: rect.size.width, y: oneThirdHeight * CGFloat(i))).stroke()
drawStraightLineFrom(CGPoint(x: oneThirdWidth * CGFloat(i), y: 0),
to: CGPoint(x: oneThirdWidth * CGFloat(i), y: rect.size.height)).stroke()
}
}
func drawStraightLineFrom(_ from: CGPoint, to: CGPoint) -> UIBezierPath {
let path = UIBezierPath()
path.move(to: from)
path.addLine(to: to)
path.lineWidth = ImageGridView.LineWidth
return path
}
}
| bsd-3-clause | 05a4774d3250a19240ea138ae5e8c78d | 35.333333 | 106 | 0.58002 | 4.104603 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIKitExtensions/UIView+QMUI.swift | 1 | 22090 | //
// UIView+QMUI.swift
// QMUI.swift
//
// Created by xnxin on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
struct QMUIBorderViewPosition: OptionSet {
let rawValue: Int
init(rawValue: Int) {
self.rawValue = rawValue
}
static let none = QMUIBorderViewPosition(rawValue: 0)
static let top = QMUIBorderViewPosition(rawValue: 1 << 0)
static let left = QMUIBorderViewPosition(rawValue: 1 << 1)
static let bottom = QMUIBorderViewPosition(rawValue: 1 << 2)
static let right = QMUIBorderViewPosition(rawValue: 1 << 3)
}
extension UIView: SelfAware {
private static let _onceToken = UUID().uuidString
static func awake() {
DispatchQueue.once(token: _onceToken) {
let clazz = UIView.self
if #available(iOS 11, *) {
ReplaceMethod(clazz, #selector(safeAreaInsetsDidChange), #selector(qmui_safeAreaInsetsDidChange))
}
var selector = #selector((UIView.convert(_:to:)) as (UIView) -> (CGPoint, UIView?) -> CGPoint)
var qmui_selector = #selector((UIView.qmui_convert(_:to:)) as (UIView) -> (CGPoint, UIView?) -> CGPoint)
ReplaceMethod(clazz, selector, qmui_selector)
selector = #selector((UIView.convert(_:from:)) as (UIView) -> (CGPoint, UIView?) -> CGPoint)
qmui_selector = #selector((UIView.qmui_convert(_:from:)) as (UIView) -> (CGPoint, UIView?) -> CGPoint)
ReplaceMethod(clazz, selector, qmui_selector)
selector = #selector((UIView.convert(_:to:)) as (UIView) -> (CGRect, UIView?) -> CGRect)
qmui_selector = #selector((UIView.qmui_convert(rect:to:)) as (UIView) -> (CGRect, UIView?) -> CGRect)
ReplaceMethod(clazz, selector, qmui_selector)
selector = #selector((UIView.convert(_:from:)) as (UIView) -> (CGRect, UIView?) -> CGRect)
qmui_selector = #selector((UIView.qmui_convert(rect:from:)) as (UIView) -> (CGRect, UIView?) -> CGRect)
ReplaceMethod(clazz, selector, qmui_selector)
ReplaceMethod(clazz, #selector(layoutSubviews), #selector(qmui_debug_layoutSubviews))
ReplaceMethod(clazz, #selector(addSubview(_:)), #selector(qmui_debug_addSubview(_:)))
ReplaceMethod(clazz, #selector(becomeFirstResponder), #selector(qmui_debug_becomeFirstResponder))
ReplaceMethod(clazz, #selector(layoutSublayers(of:)), #selector(qmui_layoutSublayers(of:)))
}
}
@objc open func qmui_safeAreaInsetsDidChange() {
qmui_safeAreaInsetsDidChange()
qmui_safeAreaInsetsBeforeChange = qmui_safeAreaInsets
}
@objc open func qmui_convert(_ point: CGPoint, to view: UIView?) -> CGPoint {
alertConvertValue(view)
return qmui_convert(point, to: view)
}
@objc open func qmui_convert(_ point: CGPoint, from view: UIView?) -> CGPoint {
alertConvertValue(view)
return qmui_convert(point, from: view)
}
@objc open func qmui_convert(rect: CGRect, to view: UIView?) -> CGRect {
alertConvertValue(view)
return qmui_convert(rect: rect, to: view)
}
@objc open func qmui_convert(rect: CGRect, from view: UIView?) -> CGRect {
alertConvertValue(view)
return qmui_convert(rect: rect, from: view)
}
@objc func qmui_debug_layoutSubviews() {
qmui_debug_layoutSubviews()
if qmui_shouldShowDebugColor {
qmui_hasDebugColor = true
backgroundColor = debugColor()
renderColor(subviews)
}
}
}
extension UIView {
fileprivate struct Keys {
static var safeAreaInsetsBeforeChange = "safeAreaInsetsBeforeChange"
static var borderPosition = "borderPosition"
static var borderWidth = "borderWidth"
static var borderColor = "borderColor"
static var dashPhase = "dashPhase"
static var dashPattern = "dashPattern"
static var borderLayer = "borderLayer"
static var needsDifferentDebugColor = "needsDifferentDebugColor"
static var shouldShowDebugColor = "shouldShowDebugColor"
static var hasDebugColor = "hasDebugColor"
}
/**
* 相当于 initWithFrame:CGRectMake(0, 0, size.width, size.height)
*/
convenience init(size: CGSize) {
self.init(frame: size.rect)
}
/// 在 iOS 11 及之后的版本,此属性将返回系统已有的 self.safeAreaInsets。在之前的版本此属性返回 UIEdgeInsetsZero
var qmui_safeAreaInsets: UIEdgeInsets {
if #available(iOS 11.0, *) {
return safeAreaInsets
}
return UIEdgeInsets.zero
}
/// 为了在 safeAreaInsetsDidChange 里得知变化前的 safeAreaInsets 值,增加了这个属性,注意这个属性仅在 `safeAreaInsetsDidChange` 的 super 调用前才有效。
/// https://github.com/QMUI/QMUI_iOS/issues/253
var qmui_safeAreaInsetsBeforeChange: UIEdgeInsets {
get {
return (objc_getAssociatedObject(self, &Keys.safeAreaInsetsBeforeChange) as? UIEdgeInsets) ?? UIEdgeInsets.zero
}
set {
objc_setAssociatedObject(self, &Keys.safeAreaInsetsBeforeChange, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func qmui_removeAllSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
static func qmui_animate(with animated: Bool, duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((_ finish: Bool) -> Void)?) {
if animated {
UIView.animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
} else {
animations()
if let notNilCompletion = completion {
notNilCompletion(true)
}
}
}
static func qmui_animate(with animated: Bool, duration: TimeInterval, animations: @escaping () -> Void, completion: ((_ finish: Bool) -> Void)?) {
if animated {
UIView.animate(withDuration: duration, animations: animations, completion: completion)
} else {
animations()
if let notNilCompletion = completion {
notNilCompletion(true)
}
}
}
static func qmui_animate(with animated: Bool, duration: TimeInterval, animations: @escaping () -> Void) {
if animated {
UIView.animate(withDuration: duration, animations: animations)
} else {
animations()
}
}
private func hasSharedAncestorView(_ view: UIView?) -> Bool {
if let view = view {
var sharedAncestorView: UIView? = self
while sharedAncestorView != nil && !view.isDescendant(of: sharedAncestorView!) {
sharedAncestorView = sharedAncestorView?.superview
}
if sharedAncestorView != nil {
return true
}
}
return true
}
private func isUIKitPrivateView() -> Bool {
// 系统有些东西本身也存在不合理,但我们不关心这种,所以过滤掉
if self is UIWindow {
return true
}
var isPrivate = false
let classString = String(describing: type(of: self))
let array = ["LayoutContainer", "NavigationItemButton", "NavigationItemView", "SelectionGrabber", "InputViewContent"]
for string in array {
if classString.hasPrefix("UI") || classString.hasPrefix("_UI") && classString.contains(string) {
isPrivate = true
break
}
}
return isPrivate
}
private func alertConvertValue(_ view:UIView?) {
if IS_DEBUG && isUIKitPrivateView() && !hasSharedAncestorView(view) {
print("进行坐标系转换运算的 \(self) 和 \(String(describing: view)) 不存在共同的父 view,可能导致运算结果不准确(特别是在横屏状态下)")
}
}
}
// MARK: - QMUI_Runtime
extension UIView {
/**
* 判断当前类是否有重写某个指定的 UIView 的方法
* @param selector 要判断的方法
* @return YES 表示当前类重写了指定的方法,NO 表示没有重写,使用的是 UIView 默认的实现
*/
func qmui_hasOverrideUIKitMethod(_ selector: Selector) -> Bool {
// 排序依照 Xcode Interface Builder 里的控件排序,但保证子类在父类前面
var viewSuperclasses = [
UILabel.self,
UIButton.self,
UISegmentedControl.self,
UITextField.self,
UISlider.self,
UISwitch.self,
UIActivityIndicatorView.self,
UIProgressView.self,
UIPageControl.self,
UIStepper.self,
UITableView.self,
UITableViewCell.self,
UIImageView.self,
UICollectionView.self,
UICollectionViewCell.self,
UICollectionReusableView.self,
UITextView.self,
UIScrollView.self,
UIDatePicker.self,
UIPickerView.self,
UIWebView.self,
UIWindow.self,
UINavigationBar.self,
UIToolbar.self,
UITabBar.self,
UISearchBar.self,
UIControl.self,
UIView.self,
]
if #available(iOS 9.0, *) {
viewSuperclasses.append(UIStackView.self)
}
for aClass in viewSuperclasses {
if qmui_hasOverrideMethod(selector: selector, of: aClass) {
return true
}
}
return false
}
}
// MARK: - QMUI_Debug
/**
* Debug UIView 的时候用,对某个 view 的 subviews 都添加一个半透明的背景色,方面查看 view 的布局情况
*/
extension UIView {
/// 是否需要添加debug背景色,默认NO
var qmui_shouldShowDebugColor: Bool {
set {
objc_setAssociatedObject(self, &Keys.shouldShowDebugColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if newValue {
setNeedsLayout()
}
}
get {
return (objc_getAssociatedObject(self, &Keys.shouldShowDebugColor) as? Bool) ?? false
}
}
/// 是否每个view的背景色随机,如果不随机则统一使用半透明红色,默认NO
var qmui_needsDifferentDebugColor: Bool {
set {
objc_setAssociatedObject(self, &Keys.needsDifferentDebugColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
if newValue {
setNeedsLayout()
}
}
get {
return (objc_getAssociatedObject(self, &Keys.needsDifferentDebugColor) as? Bool) ?? false
}
}
/// 标记一个view是否已经被添加了debug背景色,外部一般不使用
private(set) var qmui_hasDebugColor: Bool {
set {
objc_setAssociatedObject(self, &Keys.hasDebugColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return (objc_getAssociatedObject(self, &Keys.hasDebugColor) as? Bool) ?? false
}
}
private func renderColor(_ subviews: [UIView]) {
subviews.forEach {
if #available(iOS 9.0, *) {
if let view = $0 as? UIStackView {
view.renderColor(view.arrangedSubviews)
}
}
$0.qmui_hasDebugColor = true
$0.qmui_shouldShowDebugColor = self.qmui_shouldShowDebugColor
$0.qmui_needsDifferentDebugColor = self.qmui_needsDifferentDebugColor
$0.backgroundColor = self.debugColor()
}
}
private func debugColor() -> UIColor {
if !qmui_needsDifferentDebugColor {
return UIColorTestRed
} else {
return UIColor.qmui_randomColor.withAlphaComponent(0.8)
}
}
@objc func qmui_debug_addSubview(_ view: UIView) {
assert(view != self, "把自己作为 subview 添加到自己身上!\n\(Thread.callStackSymbols)")
self.qmui_debug_addSubview(view)
}
@objc func qmui_debug_becomeFirstResponder() -> Bool {
if IS_SIMULATOR && !(self is UIWindow) && window != nil && !window!.isKeyWindow {
QMUISymbolicUIViewBecomeFirstResponderWithoutKeyWindow()
}
return qmui_debug_becomeFirstResponder()
}
private func QMUISymbolicUIViewBecomeFirstResponderWithoutKeyWindow() {
print("尝试让一个处于非 keyWindow 上的 \(self) becomeFirstResponder,可能导致界面显示异常,请添加 '\(#function)' 的 Symbolic Breakpoint 以捕捉此类信息\n\(Thread.callStackSymbols)")
}
}
// MARK: - QMUI_Border
/**
* UIView (QMUI_Border) 为 UIView 方便地显示某几个方向上的边框。
*
* 系统的默认实现里,要为 UIView 加边框一般是通过 view.layer 来实现,view.layer 会给四条边都加上边框,如果你只想为其中某几条加上边框就很麻烦,于是 UIView (QMUI_Border) 提供了 qmui_borderPosition 来解决这个问题。
* @warning 注意如果你需要为 UIView 四条边都加上边框,请使用系统默认的 view.layer 来实现,而不要用 UIView (QMUI_Border),会浪费资源,这也是为什么 QMUIBorderViewPosition 不提供一个 QMUIBorderViewPositionAll 枚举值的原因。
*/
extension UIView {
/// 设置边框类型,支持组合,例如:`borderType = QMUIBorderViewTypeTop|QMUIBorderViewTypeBottom`
var qmui_borderPosition: QMUIBorderViewPosition {
set {
objc_setAssociatedObject(self, &Keys.borderPosition, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
setNeedsLayout()
}
get {
let position = objc_getAssociatedObject(self, &Keys.borderPosition) as? QMUIBorderViewPosition
return position ?? QMUIBorderViewPosition.none
}
}
/// 边框的大小,默认为PixelOne
@IBInspectable
var qmui_borderWidth: CGFloat {
set {
objc_setAssociatedObject(self, &Keys.borderWidth, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
setNeedsLayout()
}
get {
let borderWidth = objc_getAssociatedObject(self, &Keys.borderWidth) as? CGFloat
return borderWidth ?? PixelOne
}
}
/// 边框的颜色,默认为UIColorSeparator
@IBInspectable
var qmui_borderColor: UIColor {
set {
objc_setAssociatedObject(self, &Keys.borderColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
setNeedsLayout()
}
get {
return (objc_getAssociatedObject(self, &Keys.borderColor) as? UIColor) ?? UIColorSeparator
}
}
/// 虚线 : dashPhase默认是0,且当dashPattern设置了才有效
var qmui_dashPhase: CGFloat {
set {
objc_setAssociatedObject(self, &Keys.dashPhase, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
setNeedsLayout()
}
get {
return (objc_getAssociatedObject(self, &Keys.dashPhase) as? CGFloat) ?? 0
}
}
var qmui_dashPattern: [NSNumber]? {
set {
objc_setAssociatedObject(self, &Keys.dashPattern, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
setNeedsLayout()
}
get {
return objc_getAssociatedObject(self, &Keys.dashPattern) as? [NSNumber]
}
}
/// border的layer
private(set) var qmui_borderLayer: CAShapeLayer? {
set {
objc_setAssociatedObject(self, &Keys.borderLayer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &Keys.borderLayer) as? CAShapeLayer
}
}
@objc func qmui_layoutSublayers(of layer: CALayer) {
qmui_layoutSublayers(of: layer)
if (qmui_borderLayer == nil && qmui_borderPosition == .none) || (qmui_borderLayer == nil && qmui_borderWidth == 0) {
return
}
if qmui_borderLayer != nil && qmui_borderPosition == .none && qmui_borderLayer!.path == nil {
return
}
if qmui_borderLayer != nil && qmui_borderWidth == 0 && qmui_borderLayer!.lineWidth == 0 {
return
}
if qmui_borderLayer == nil {
qmui_borderLayer = CAShapeLayer()
qmui_borderLayer!.qmui_removeDefaultAnimations()
layer.addSublayer(qmui_borderLayer!)
}
qmui_borderLayer!.frame = bounds
let borderWidth = qmui_borderWidth
qmui_borderLayer!.lineWidth = borderWidth
qmui_borderLayer!.strokeColor = qmui_borderColor.cgColor
qmui_borderLayer!.lineDashPhase = qmui_dashPhase
if qmui_dashPattern != nil {
qmui_borderLayer!.lineDashPattern = qmui_dashPattern
}
var path: UIBezierPath?
if qmui_borderPosition != .none {
path = UIBezierPath()
}
if qmui_borderPosition.contains(QMUIBorderViewPosition.top) {
path?.move(to: CGPoint(x: 0, y: borderWidth / 2))
path?.addLine(to: CGPoint(x: bounds.width, y: borderWidth / 2))
}
if qmui_borderPosition.contains(QMUIBorderViewPosition.left) {
path?.move(to: CGPoint(x: borderWidth / 2, y: 0))
path?.addLine(to: CGPoint(x: borderWidth / 2, y: bounds.height - 0))
}
if qmui_borderPosition.contains(QMUIBorderViewPosition.bottom) {
path?.move(to: CGPoint(x: 0, y: bounds.height - borderWidth / 2))
path?.addLine(to: CGPoint(x: bounds.width, y: bounds.height - borderWidth / 2))
}
if qmui_borderPosition.contains(QMUIBorderViewPosition.right) {
path?.move(to: CGPoint(x: bounds.width - borderWidth / 2, y: 0))
path?.addLine(to: CGPoint(x: bounds.width - borderWidth / 2, y: bounds.height))
}
qmui_borderLayer!.path = path?.cgPath
}
}
// MARK: - QMUI_Layout
/**
* 对 view.frame 操作的简便封装,注意 view 与 view 之间互相计算时,需要保证处于同一个坐标系内。
* siwft 虽然支持 view.frame.minY 等属性,调用已经很方便,但是 view.frame.minY 都是只读
*/
extension UIView {
/// 等价于 CGRectGetMinY(frame)
var qmui_top: CGFloat {
get {
return frame.minY
}
set {
frame = frame.setY(newValue)
}
}
/// 等价于 CGRectGetMinX(frame)
var qmui_left: CGFloat {
get {
return frame.minX
}
set {
frame = frame.setX(newValue)
}
}
/// 等价于 CGRectGetMaxY(frame)
var qmui_bottom: CGFloat {
get {
return frame.maxY
}
set {
frame = frame.setY(newValue - frame.height)
}
}
/// 等价于 CGRectGetMaxX(frame)
var qmui_right: CGFloat {
get {
return frame.maxX
}
set {
frame = frame.setX(newValue - frame.width)
}
}
var qmui_width: CGFloat {
get {
return frame.width
}
set {
frame = frame.setWidth(newValue)
}
}
var qmui_height: CGFloat {
get {
return frame.height
}
set {
frame = frame.setHeight(newValue)
}
}
/// 保持其他三个边缘的位置不变的情况下,将顶边缘拓展到某个指定的位置,注意高度会跟随变化。
var qmui_extendToTop: CGFloat {
get {
return qmui_top
}
set {
qmui_height = qmui_bottom - qmui_extendToTop
qmui_top = qmui_extendToTop
}
}
/// 保持其他三个边缘的位置不变的情况下,将左边缘拓展到某个指定的位置,注意宽度会跟随变化。
var qmui_extendToLeft: CGFloat {
get {
return qmui_left
}
set {
qmui_width = qmui_right - qmui_extendToLeft
qmui_left = qmui_extendToLeft
}
}
/// 保持其他三个边缘的位置不变的情况下,将底边缘拓展到某个指定的位置,注意高度会跟随变化。
var qmui_extendToBottom: CGFloat {
get {
return qmui_bottom
}
set {
qmui_height = qmui_extendToBottom - qmui_top
qmui_bottom = qmui_extendToBottom
}
}
/// 保持其他三个边缘的位置不变的情况下,将右边缘拓展到某个指定的位置,注意宽度会跟随变化。
var qmui_extendToRight: CGFloat {
get {
return qmui_right
}
set {
qmui_width = qmui_extendToRight - qmui_left
qmui_right = qmui_extendToRight
}
}
/**
* 获取当前view在superview内的水平居中时的minX
*/
var qmui_minXWhenCenterInSuperview: CGFloat {
return superview?.bounds.width.center(frame.width) ?? 0
}
/**
* 获取当前view在superview内的垂直居中时的minY
*/
var qmui_minYWhenCenterInSuperview: CGFloat {
return superview?.bounds.height.center(frame.height) ?? 0
}
}
// MARK: - QMUI_Snapshotting
/**
* 方便地将某个 UIView 截图并转成一个 UIImage,注意如果这个 UIView 本身做了 transform,也不会在截图上反映出来,截图始终都是原始 UIView 的截图。
*/
extension UIView {
var qmui_snapshotLayerImage: UIImage? {
return UIImage.qmui_image(view: self)
}
func qmui_snapshotImage(_ afterScreenUpdates: Bool) -> UIImage? {
return UIImage.qmui_image(view: self, afterScreenUpdates: afterScreenUpdates)
}
}
| mit | f6e1956bb9dcaf84c10f22b13ea9b541 | 32.107317 | 205 | 0.596533 | 4.337665 | false | false | false | false |
steelwheels/KiwiScript | KiwiLibrary/Source/Graphics/KLSize.swift | 1 | 1193 | /**
* @file KLSize.swift
* @brief Define KLSize class
* @par Copyright
* Copyright (C) 2021 Steel Wheels Project
*/
import CoconutData
import KiwiEngine
import JavaScriptCore
import Foundation
public extension CGSize
{
static func isSize(scriptValue val: JSValue) -> Bool {
if let dict = val.toDictionary() as? Dictionary<String, Any> {
if let _ = dict["width"] as? NSNumber,
let _ = dict["height"] as? NSNumber {
return true
} else {
return false
}
} else {
return false
}
}
static func fromJSValue(scriptValue val: JSValue) -> CGSize? {
if let dict = val.toDictionary() as? Dictionary<String, Any> {
if let wnum = dict["width"] as? NSNumber,
let hnum = dict["height"] as? NSNumber {
return CGSize(width: wnum.doubleValue, height: hnum.doubleValue)
}
}
return nil
}
func toJSValue(context ctxt: KEContext) -> JSValue {
let wnum = NSNumber(floatLiteral: Double(self.width))
let hnum = NSNumber(floatLiteral: Double(self.height))
let result: Dictionary<String, NSObject> = [
"class" : NSString(string: CGSize.ClassName),
"width" : wnum,
"height" : hnum
]
return JSValue(object: result, in: ctxt)
}
}
| lgpl-2.1 | 77b0eca57ce8dd950e5704c6bdc03495 | 23.346939 | 68 | 0.667225 | 3.304709 | false | false | false | false |
plushcube/Learning | Algorithms/Data Structures Course/week1_1.swift | 1 | 2780 | import Foundation
struct Params {
let count: Int
let numbers: [Int]
}
enum InputError: Error {
case wrongCount
case wrongNumbers
}
extension InputError: CustomStringConvertible {
var description: String {
switch self {
case .wrongCount: return "Wrong count"
case .wrongNumbers: return "Wrong numbers"
}
}
}
extension Params: CustomStringConvertible {
var description: String {
let string = numbers.reduce("") { result, value in result + "\(value) " }
return "\(count)\n\(string)"
}
}
func generateParams(max: Int) -> Params {
let count = 2 + Int(arc4random()) % (max - 2)
let numbers = (0 ..< count).map { _ in Int(arc4random()) % 100000 }
return Params(count: count, numbers: numbers)
}
func getArguments() throws -> Params {
guard let countString = readLine(strippingNewline: true), let count = Int(countString) else {
throw InputError.wrongCount
}
guard let numbersString = readLine(strippingNewline: true) else {
throw InputError.wrongNumbers
}
let separated = numbersString.components(separatedBy: " ")
guard separated.count == count else {
throw InputError.wrongNumbers
}
let numbers = separated.map({ Int($0)! })
return Params(count: count, numbers: numbers)
}
func maxPairwiseProduct(_ params: Params) -> Int {
var result = 0
for i in 0 ..< params.count {
for j in 0 ..< params.count where i != j {
let product = params.numbers[i] * params.numbers[j]
result = max(result, product)
}
}
return result
}
func maxPairwiseProductFast(_ params: Params) -> Int {
var maxIndex1 = -1
for index in 0 ..< params.count {
if maxIndex1 == -1 || params.numbers[index] > params.numbers[maxIndex1] {
maxIndex1 = index
}
}
var maxIndex2 = -1
for index in 0 ..< params.count where index != maxIndex1 {
if maxIndex2 == -1 || params.numbers[index] > params.numbers[maxIndex2] {
maxIndex2 = index
}
}
guard maxIndex1 != -1, maxIndex2 != -1 else { return 0 }
return params.numbers[maxIndex1] * params.numbers[maxIndex2]
}
while true {
let params = generateParams(max: 10)
print("\(params)")
let result1 = maxPairwiseProduct(params)
let result2 = maxPairwiseProductFast(params)
if result1 != result2 {
print("Wrong answer: \(result1) \(result2)")
break
} else {
print("OK")
}
}
//let params = generateParams(max: 10000)
//print("\(params)")
//print("\(maxPairwiseProductFast(params))")
//do {
// let params = try getArguments()
// print("\(maxPairwiseProductFast(params))")
//} catch(let error) {
// print("\(error)")
//}
| mit | ee757076027033b7f820078a70057c39 | 25.730769 | 97 | 0.614748 | 3.888112 | false | false | false | false |
atrick/swift | test/stdlib/FlatMapDeprecation.swift | 7 | 1504 | // RUN: %target-typecheck-verify-swift -swift-version 4
func flatMapOnSequence<
S : Sequence
>(xs: S, f: (S.Element) -> S.Element?) {
_ = xs.flatMap(f) // expected-warning {{'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value}} expected-note {{compactMap}}
}
func flatMapOnLazySequence<
S : LazySequenceProtocol
>(xs: S, f: (S.Element) -> S.Element?) {
_ = xs.flatMap(f) // expected-warning {{'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value}} expected-note {{compactMap}}
}
func flatMapOnLazyCollection<
C : LazyCollectionProtocol
>(xs: C, f: (C.Element) -> C.Element?) {
_ = xs.flatMap(f) // expected-warning {{'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value}} expected-note {{compactMap}}
}
func flatMapOnLazyBidirectionalCollection<
C : LazyCollectionProtocol & BidirectionalCollection
>(xs: C, f: (C.Element) -> C.Element?)
where C.Elements : BidirectionalCollection {
_ = xs.flatMap(f) // expected-warning {{'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value}} expected-note {{compactMap}}
}
func flatMapOnCollectionOfStrings<
C : Collection
>(xs: C, f: (C.Element) -> String?) {
_ = xs.flatMap(f) // expected-warning {{'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value}} expected-note {{compactMap}}
}
| apache-2.0 | 6cef7c601bbe1e6d92cfea36fdb6073a | 46 | 176 | 0.71609 | 3.947507 | false | false | false | false |
optimizely/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/MixpanelType.swift | 1 | 6615 | //
// MixpanelType.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/19/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
/// Property keys must be String objects and the supported value types need to conform to MixpanelType.
/// MixpanelType can be either String, Int, UInt, Double, Float, Bool, [MixpanelType], [String: MixpanelType], Date, URL, or NSNull.
public protocol MixpanelType: Any {
/**
Checks if this object has nested object types that Mixpanel supports.
*/
func isValidNestedType() -> Bool
func equals(rhs: MixpanelType) -> Bool
}
extension String: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is String {
return self == rhs as! String
}
return false
}
}
extension NSNumber: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is NSNumber {
return self.isEqual(rhs)
}
return false
}
}
extension Int: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is Int {
return self == rhs as! Int
}
return false
}
}
extension UInt: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is UInt {
return self == rhs as! UInt
}
return false
}
}
extension Double: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is Double {
return self == rhs as! Double
}
return false
}
}
extension Float: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is Float {
return self == rhs as! Float
}
return false
}
}
extension Bool: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is Bool {
return self == rhs as! Bool
}
return false
}
}
extension Date: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is Date {
return self == rhs as! Date
}
return false
}
}
extension URL: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is URL {
return self == rhs as! URL
}
return false
}
}
extension NSNull: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
Will always return true.
*/
public func isValidNestedType() -> Bool { return true }
public func equals(rhs: MixpanelType) -> Bool {
if rhs is NSNull {
return true
}
return false
}
}
extension Array: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
*/
public func isValidNestedType() -> Bool {
for element in self {
guard let _ = element as? MixpanelType else {
return false
}
}
return true
}
public func equals(rhs: MixpanelType) -> Bool {
if rhs is [MixpanelType] {
let rhs = rhs as! [MixpanelType]
if self.count != rhs.count {
return false
}
if !isValidNestedType() {
return false
}
let lhs = self as! [MixpanelType]
for (i, val) in lhs.enumerated() {
if !val.equals(rhs: rhs[i]) {
return false
}
}
return true
}
return false
}
}
extension Dictionary: MixpanelType {
/**
Checks if this object has nested object types that Mixpanel supports.
*/
public func isValidNestedType() -> Bool {
for (key, value) in self {
guard let _ = key as? String, let _ = value as? MixpanelType else {
return false
}
}
return true
}
public func equals(rhs: MixpanelType) -> Bool {
if rhs is [String: MixpanelType] {
let rhs = rhs as! [String: MixpanelType]
if self.keys.count != rhs.keys.count {
return false
}
if !isValidNestedType() {
return false
}
for (key, val) in self as! [String: MixpanelType] {
guard let rVal = rhs[key] else {
return false
}
if !val.equals(rhs: rVal) {
return false
}
}
return true
}
return false
}
}
func assertPropertyTypes(_ properties: Properties?) {
if let properties = properties {
for (_, v) in properties {
MPAssert(v.isValidNestedType(),
"Property values must be of valid type (MixpanelType). Got \(type(of: v))")
}
}
}
| apache-2.0 | e8319d1e719566d7672fd625f06e6eef | 25.142292 | 132 | 0.559117 | 4.950599 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/AnimationSelectionTableViewCell.swift | 3 | 2980 | //
// AnimationSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/26/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import SwiftEntryKit
class AnimationSelectionTableViewCell: SelectionTableViewCell {
enum Action: String {
case entrance
case exit
case pop
var isOut: Bool {
return Set([.exit, .pop]).contains(self)
}
}
var action: Action = .entrance
var animation: EKAttributes.Animation {
set {
switch action {
case .entrance:
attributesWrapper.attributes.entranceAnimation = newValue
case .exit:
attributesWrapper.attributes.exitAnimation = newValue
case .pop:
attributesWrapper.attributes.popBehavior = EKAttributes.PopBehavior.animated(animation: newValue)
}
}
get {
switch action {
case .entrance:
return attributesWrapper.attributes.entranceAnimation
case .exit:
return attributesWrapper.attributes.exitAnimation
case .pop:
if case EKAttributes.PopBehavior.animated(animation: let animation) = attributesWrapper.attributes.popBehavior {
return animation
} else {
fatalError()
}
}
}
}
func configure(attributesWrapper: EntryAttributeWrapper, action: Action) {
self.action = action
configure(attributesWrapper: attributesWrapper)
}
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "\(action.rawValue.capitalized) Animation"
descriptionValue = "Describes the \(action.rawValue) animation of the entry"
insertSegments(by: ["Translate", "Scale", "Fade"])
selectSegment()
}
private func selectSegment() {
if animation.containsTranslation {
segmentedControl.selectedSegmentIndex = 0
} else if animation.containsScale {
segmentedControl.selectedSegmentIndex = 1
} else if animation.containsFade {
segmentedControl.selectedSegmentIndex = 2
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
animation = .translation
case 1 where action.isOut:
animation = .init(scale: .init(from: 1, to: 0, duration: 0.3))
case 1:
animation = .init(scale: .init(from: 0, to: 1, duration: 0.3))
case 2 where action.isOut:
animation = .init(fade: .init(from: 1, to: 0, duration: 0.3))
case 2:
animation = .init(fade: .init(from: 0, to: 1, duration: 0.3))
default:
break
}
}
}
| apache-2.0 | 0accf1f3175de59cf2c6d160ecc1d419 | 31.747253 | 128 | 0.588926 | 5.016835 | false | false | false | false |
Sajjon/Zeus | Pods/SwiftyBeaver/sources/FileDestination.swift | 1 | 4096 | //
// FileDestination.swift
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger on 05.12.15.
// Copyright © 2015 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
public class FileDestination: BaseDestination {
public var logFileURL: URL?
override public var defaultHashValue: Int {return 2}
let fileManager = FileManager.default
var fileHandle: FileHandle? = nil
public override init() {
// platform-dependent logfile directory default
var baseURL: URL?
if OS == "OSX" {
if let url = fileManager.urls(for:.cachesDirectory, in: .userDomainMask).first {
baseURL = url
// try to use ~/Library/Caches/APP NAME instead of ~/Library/Caches
if let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as? String {
do {
if let appURL = baseURL?.appendingPathComponent(appName, isDirectory: true) {
try fileManager.createDirectory(at: appURL,
withIntermediateDirectories: true, attributes: nil)
baseURL = appURL
}
} catch let error as NSError {
print("Warning! Could not create folder /Library/Caches/\(appName). \(error)")
}
}
}
} else {
// iOS, watchOS, etc. are using the caches directory
if let url = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first {
baseURL = url
}
}
if let baseURL = baseURL {
logFileURL = baseURL.appendingPathComponent("swiftybeaver.log", isDirectory: false)
}
super.init()
// bash font color, first value is intensity, second is color
// see http://bit.ly/1Otu3Zr & for syntax http://bit.ly/1Tp6Fw9
// uses the 256-color table from http://bit.ly/1W1qJuH
reset = "\u{001b}[0m"
escape = "\u{001b}[38;5;"
levelColor.Verbose = "251m"
levelColor.Debug = "35m"
levelColor.Info = "38m"
levelColor.Warning = "178m"
levelColor.Error = "197m"
}
// append to file. uses full base class functionality
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
path: String, function: String, line: Int) -> String? {
let formattedString = super.send(level, msg: msg, thread: thread, path: path, function: function, line: line)
if let str = formattedString {
let _ = saveToFile(str: str)
}
return formattedString
}
deinit {
// close file handle if set
if let fileHandle = fileHandle {
fileHandle.closeFile()
}
}
/// appends a string as line to a file.
/// returns boolean about success
func saveToFile(str: String) -> Bool {
guard let url = logFileURL else { return false }
do {
if fileManager.fileExists(atPath: url.path) == false {
// create file if not existing
let line = str + "\n"
try line.write(to: url as URL, atomically: true, encoding: String.Encoding.utf8)
} else {
// append to end of file
if fileHandle == nil {
// initial setting of file handle
fileHandle = try FileHandle(forWritingTo: url as URL)
}
if let fileHandle = fileHandle {
fileHandle.seekToEndOfFile()
let line = str + "\n"
let data = line.data(using: String.Encoding.utf8)!
fileHandle.write(data)
}
}
return true
} catch let error {
print("SwiftyBeaver File Destination could not write to file \(url). \(error)")
return false
}
}
}
| apache-2.0 | 25606398113d7babd0ffdd6f0ae9e97f | 36.227273 | 117 | 0.546276 | 4.886635 | false | false | false | false |
eduresende/ios-nd-swift-syntax-swift-3 | Lesson3/L3_Exercises_withSolutions.playground/Contents.swift | 1 | 4204 | //: # Lesson 3 Exercises - Collections
import UIKit
//: ## Array initialization
//: ### Exercise 1
//: 1a) Initialize the array, cuteAnimals. It should be of type CuddlyCreature. Type your answer below.
// Solution
var cuteAnimals = [CuddlyCreature]()
//: 1b) Initialize an array of 5 bools using array literal syntax.
// Solution
var boolArray = [true, false, false, true, true]
//: ## Array operations: count, insert, append, remove, retrieveWithSubscript
//: ### Exercise 2
//: Print out the number of spaniels in the array below.
var spaniels = ["American Cocker", "Cavalier King Charles", "English Springer", "French", "Irish Water","Papillon", "Picardy","Russian", "French", "Welsh Springer"]
// Solution
print(spaniels.count)
//: ### Exercise 3
//: Insert "indigo" into the array below so that its index is after "blue" and before "violet".
var colors = ["red", "orange", "yellow", "green", "blue", "violet"]
// Solution
colors.insert("indigo", at: 5)
//: ### Exercise 4
//: Insert "English Cocker" into the spaniels array so that its index is before "English Springer".
// Solution
spaniels.insert("English Cocker", at: 2)
//: ### Exercise 5
//: Append "Barcelona" to the end of the olympicHosts array.
var olympicHosts = ["London", "Beijing","Athens", "Sydney", "Atlanta"]
// Solution
olympicHosts.append("Barcelona")
//: ### Exercise 6
//: Remove "Lyla" and "Daniel" from the waitingList array and add them to the end of the admitted array.
var admitted = ["Jennifer", "Vijay", "James"]
var waitingList = ["Lyla", "Daniel", "Isabel", "Eric"]
// Solution
var name = waitingList.remove(at: 0)
admitted.append(name)
//: ### Exercise 7
//: Using subscript syntax, print out the 2nd and 3rd names from the admitted array.
// Solution
print("second: \(admitted[1]), third: \(admitted[2])")
//: ## Dictionary initialization
//: ### Exercise 8
//: a) Initialize an empty dictionary which holds Strings as keys and Bools as values.
// Solution
var dictionary = [String: Bool]()
//: b) Initialize a dictionary using array literal syntax. The keys should be the Strings: "Anchovies", "Coconut", "Cilantro", "Liver" and each value should be a Bool representing whether you like the food or not.
// Solution
var polarizingFoods = ["Anchovies":true, "Coconut":true, "Cilantro":true, "Liver": false]
//: ## Dictionary operations: count, insert, remove, update, retrieve with subscript
//: ### Exercise 9
//: Insert an entry for George H.W. Bush to the dictionary below.
var presidentialPetsDict = ["Barack Obama":"Bo", "Bill Clinton": "Socks", "George Bush": "Miss Beazley", "Ronald Reagan": "Lucky"]
//desired output
// ["Barack Obama":"Bo", "George Bush": "Miss Beazley","Bill Clinton": "Socks", "George H. W. Bush": "Millie", "Ronald Reagan": "Lucky"]
// Solution
presidentialPetsDict["George H. W. Bush"] = "Millie"
print(presidentialPetsDict)
//: ### Exercise 10
//: Remove the entry for "George Bush" and replace it with an entry for "George W. Bush".
// Solution
var oldValue = presidentialPetsDict.removeValue(forKey: "George Bush")
presidentialPetsDict["George W. Bush"] = oldValue
//: ### Exercise 11
//: We've initialized a new dictionary of presidentialDogs with the entries from presidentialPets. Update the entry for Bill Clinton by replacing "Socks" the cat with "Buddy" the dog.
var presidentialDogs = presidentialPetsDict
// Solution
presidentialDogs["Bill Clinton"] = "Buddy"
//: ### Exercise 12
//: Use subscript syntax to fill in the print statement below and produce the following string: "Michele Obama walks Bo every morning." You'll need to retrieve a value from the presidentialDogs dictionary and unwrap it using if let.
//print("Michele Obama walks \() every morning.")
// Solution
if let dog = presidentialDogs["Barack Obama"] {
print("Michele Obama walks \(dog) every morning.")
} else {
print("No value found")
}
//: ### Exercise 13
// How many studio albums did Led Zeppelin release?
var studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
// Solution
studioAlbums.count
| mit | 40aac787be40ca3db879dd17f76984e4 | 40.215686 | 232 | 0.708611 | 3.45156 | false | false | false | false |
euronautic/cosmos | code/data_structures/linked_list/linked_list/linked_list.swift | 3 | 1264 | //
// linked_list.swift
//
// Created by Kajornsak Peerapathananont on 10/14/2560 BE.
// Copyright © 2560 Kajornsak Peerapathananont. All rights reserved.
//
import Foundation
//: Playground - noun: a place where people can play
public struct Node<T>{
private var data : T?
private var next : [Node<T>?] = []
init() {
self.data = nil
}
init(data : T){
self.data = data
}
func getData()->T? {
return self.data
}
func getNext()->Node<T>?{
return self.next[0]
}
mutating func setNext(next : Node<T>?){
self.next = [next]
}
}
public struct LinkedList<T>{
private var head : Node<T>?
init() {
self.head = nil
}
init(head : Node<T>?) {
self.head = head
}
func size() -> Int {
if var current_node = head{
var len = 1
while let next = current_node.getNext(){
current_node = next
len += 1
}
return len
}
return 0
}
mutating func insert(data : T){
var node : Node<T> = Node<T>(data: data)
node.setNext(next : self.head)
self.head = node
}
}
| gpl-3.0 | 5128417c17a2411fd6dd784a4c0b9b6f | 16.788732 | 69 | 0.492478 | 3.792793 | false | false | false | false |
N26-OpenSource/bob | Sources/Bob/Commands/Align Version/RegexMatcher.swift | 1 | 2246 | /*
* Copyright (c) 2017 N26 GmbH.
*
* This file is part of Bob.
*
* Bob 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.
*
* Bob 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 Bob. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
public class RegexMatcher {
private var text: String
public init(text: String) {
self.text = text
}
/// Returns groups matching a regex
///
/// - Parameters:
/// - regexString: Regex to match
public func matches(stringMatching regexString: String) -> [String] {
var ranges = [Range<String.Index>]()
var range: Range<String.Index>? = Range<String.Index>(uncheckedBounds: (lower: text.startIndex, upper: text.endIndex))
while range != nil {
let newRange = text.range(of: regexString, options: .regularExpression, range: range)
if let `newRange` = newRange {
ranges.append(newRange)
range = Range<String.Index>(uncheckedBounds: (lower: newRange.upperBound, upper: text.endIndex))
} else {
range = nil
}
}
var matches = [String]()
ranges.forEach {
matches.append(String(text[$0]))
}
return matches
}
/// Replaces group matching regex with a replacement
///
/// - Parameters:
/// - regexString: Regex to match
/// - replacement: Replacement string
public func replace(stringMatching regexString: String, with replacement: String) {
self.text = self.text.replacingOccurrences(of: regexString, with: replacement, options: .regularExpression)
}
public var result: String {
return self.text
}
}
| gpl-3.0 | fc29b588ea959d17c1cc97e3272e0be6 | 31.550725 | 126 | 0.620214 | 4.519115 | false | false | false | false |
swiftix/swift.old | stdlib/public/core/Sequence.swift | 1 | 22606 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
/// Encapsulates iteration state and interface for iteration over a
/// *sequence*.
///
/// - Note: While it is safe to copy a *generator*, advancing one
/// copy may invalidate the others.
///
/// Any code that uses multiple generators (or `for`...`in` loops)
/// over a single *sequence* should have static knowledge that the
/// specific *sequence* is multi-pass, either because its concrete
/// type is known or because it is constrained to `CollectionType`.
/// Also, the generators must be obtained by distinct calls to the
/// *sequence's* `generate()` method, rather than by copying.
public protocol GeneratorType {
/// The type of element generated by `self`.
typealias Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`. Specific implementations of this protocol
/// are encouraged to respond to violations of this requirement by
/// calling `preconditionFailure("...")`.
@warn_unused_result
mutating func next() -> Element?
}
/// A type that can be iterated with a `for`...`in` loop.
///
/// `SequenceType` makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. To
/// ensure non-destructive iteration, constrain your *sequence* to
/// `CollectionType`.
///
/// As a consequence, it is not possible to run multiple `for` loops
/// on a sequence to "resume" iteration:
///
/// for element in sequence {
/// if ... some condition { break }
/// }
///
/// for element in sequence {
/// // Not guaranteed to continue from the next element.
/// }
///
/// `SequenceType` makes no requirement about the behavior in that
/// case. It is not correct to assume that a sequence will either be
/// "consumable" and will resume iteration, or that a sequence is a
/// collection and will restart iteration from the first element.
/// A conforming sequence that is not a collection is allowed to
/// produce an arbitrary sequence of elements from the second generator.
public protocol SequenceType {
/// A type that provides the *sequence*'s iteration interface and
/// encapsulates its iteration state.
typealias Generator : GeneratorType
// FIXME: should be constrained to SequenceType
// (<rdar://problem/20715009> Implement recursive protocol
// constraints)
/// A type that represents a subsequence of some of the elements.
typealias SubSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
@warn_unused_result
func generate() -> Generator
/// Return a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
@warn_unused_result
func underestimateCount() -> Int
/// Return an `Array` containing the results of mapping `transform`
/// over `self`.
///
/// - Complexity: O(N).
@warn_unused_result
func map<T>(
@noescape transform: (Generator.Element) throws -> T
) rethrows -> [T]
/// Return an `Array` containing the elements of `self`,
/// in order, that satisfy the predicate `includeElement`.
@warn_unused_result
func filter(
@noescape includeElement: (Generator.Element) throws -> Bool
) rethrows -> [Generator.Element]
/// Call `body` on each element in `self` in the same order as a
/// *for-in loop.*
///
/// sequence.forEach {
/// // body code
/// }
///
/// is similar to:
///
/// for element in sequence {
/// // body code
/// }
///
/// - Note: You cannot use the `break` or `continue` statement to exit the
/// current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
/// exit from the current call to `body`, not any outer scope, and won't
/// skip subsequent calls.
///
/// - Complexity: O(`self.count`)
func forEach(@noescape body: (Generator.Element) throws -> Void) rethrows
/// Returns a subsequence containing all but the first `n` elements.
///
/// - Requires: `n >= 0`
/// - Complexity: O(`n`)
@warn_unused_result
func dropFirst(n: Int) -> SubSequence
/// Returns a subsequence containing all but the last `n` elements.
///
/// - Requires: `self` is a finite sequence.
/// - Requires: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
func dropLast(n: Int) -> SubSequence
/// Returns a subsequence, up to `maxLength` in length, containing the
/// initial elements.
///
/// If `maxLength` exceeds `self.count`, the result contains all
/// the elements of `self`.
///
/// - Requires: `maxLength >= 0`
@warn_unused_result
func prefix(maxLength: Int) -> SubSequence
/// Returns a slice, up to `maxLength` in length, containing the
/// final elements of `s`.
///
/// If `maxLength` exceeds `s.count`, the result contains all
/// the elements of `s`.
///
/// - Requires: `self` is a finite sequence.
/// - Requires: `maxLength >= 0`
@warn_unused_result
func suffix(maxLength: Int) -> SubSequence
/// Returns the maximal `SubSequence`s of `self`, in order, that
/// don't contain elements satisfying the predicate `isSeparator`.
///
/// - Parameter maxSplit: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplit + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing the remaining elements.
/// The default value is `Int.max`.
///
/// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// satisfying `isSeparator`.
/// The default value is `false`.
///
/// - Requires: `maxSplit >= 0`
@warn_unused_result
func split(maxSplit: Int, allowEmptySlices: Bool,
@noescape isSeparator: (Generator.Element) throws -> Bool
) rethrows -> [SubSequence]
@warn_unused_result
func _customContainsEquatableElement(
element: Generator.Element
) -> Bool?
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
func _preprocessingPass<R>(preprocess: (Self)->R) -> R?
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Generator.Element>
/// Copy a Sequence into an array, returning one past the last
/// element initialized.
func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>)
-> UnsafeMutablePointer<Generator.Element>
}
/// A default generate() function for `GeneratorType` instances that
/// are declared to conform to `SequenceType`
extension SequenceType
where Self.Generator == Self, Self : GeneratorType {
public func generate() -> Self {
return self
}
}
/// A sequence that lazily consumes and drops `n` elements from an underlying
/// `Base` generator before possibly returning the first available element.
///
/// The underlying generator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already dropped from the underlying sequence.
internal class _DropFirstSequence<Base : GeneratorType>
: SequenceType, GeneratorType {
internal var generator: Base
internal let limit: Int
internal var dropped: Int
internal init(_ generator: Base, limit: Int, dropped: Int = 0) {
self.generator = generator
self.limit = limit
self.dropped = dropped
}
internal func generate() -> _DropFirstSequence<Base> {
return self
}
internal func next() -> Base.Element? {
while dropped < limit {
if generator.next() == nil {
dropped = limit
return nil
}
++dropped
}
return generator.next()
}
}
/// A sequence that only consumes up to `n` elements from an underlying
/// `Base` generator.
///
/// The underlying generator's sequence may be infinite.
///
/// This is a class - we require reference semantics to keep track
/// of how many elements we've already taken from the underlying sequence.
internal class _PrefixSequence<Base : GeneratorType> : SequenceType, GeneratorType {
internal let maxLength: Int
internal var generator: Base
internal var taken: Int
internal init(_ generator: Base, maxLength: Int, taken: Int = 0) {
self.generator = generator
self.maxLength = maxLength
self.taken = taken
}
internal func generate() -> _PrefixSequence<Base> {
return self
}
internal func next() -> Base.Element? {
if taken >= maxLength { return nil }
++taken
if let next = generator.next() {
return next
}
taken = maxLength
return nil
}
}
//===----------------------------------------------------------------------===//
// Default implementations for SequenceType
//===----------------------------------------------------------------------===//
extension SequenceType {
/// Return an `Array` containing the results of mapping `transform`
/// over `self`.
///
/// - Complexity: O(N).
@warn_unused_result
public func map<T>(
@noescape transform: (Generator.Element) throws -> T
) rethrows -> [T] {
let initialCapacity = underestimateCount()
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<T>(
initialCapacity: initialCapacity)
var generator = generate()
// FIXME: Type checker doesn't allow a `rethrows` function to catch and
// throw an error. It'd be nice to separate the success and failure cleanup
// paths more cleanly than this.
// Ensure the buffer is left in a destructible state.
var finished = false
defer {
if !finished {
_ = builder.finish()
}
}
// Add elements up to the initial capacity without checking for regrowth.
for _ in 0..<initialCapacity {
builder.addWithExistingCapacity(try transform(generator.next()!))
}
// Add remaining elements, if any.
while let element = generator.next() {
builder.add(try transform(element))
}
let buffer = builder.finish()
finished = true
return Array(buffer)
}
/// Return an `Array` containing the elements of `self`,
/// in order, that satisfy the predicate `includeElement`.
@warn_unused_result
public func filter(
@noescape includeElement: (Generator.Element) throws -> Bool
) rethrows -> [Generator.Element] {
var builder =
_UnsafePartiallyInitializedContiguousArrayBuffer<Generator.Element>(
initialCapacity: 0)
var generator = generate()
// FIXME: Type checker doesn't allow a `rethrows` function to catch and
// throw an error. It'd be nice to separate the success and failure cleanup
// paths more cleanly than this.
// Ensure the buffer is left in a destructible state.
var finished = false
defer {
if !finished {
_ = builder.finish()
}
}
while let element = generator.next() {
if try includeElement(element) {
builder.add(element)
}
}
let buffer = builder.finish()
finished = true
return Array(buffer)
}
/// Returns a subsequence containing all but the first `n` elements.
///
/// - Requires: `n >= 0`
/// - Complexity: O(`n`)
@warn_unused_result
public func dropFirst(n: Int) -> AnySequence<Generator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
// If this is already a _DropFirstSequence, we need to fold in
// the current drop count and drop limit so no data is lost.
//
// i.e. [1,2,3,4].dropFirst(1).dropFirst(1) should be equivalent to
// [1,2,3,4].dropFirst(2).
// FIXME: <rdar://problem/21885675> Use method dispatch to fold
// _PrefixSequence and _DropFirstSequence counts
if let any = self as? AnySequence<Generator.Element>,
let box = any._box as? _SequenceBox<_DropFirstSequence<Generator>> {
let base = box._base
let folded = _DropFirstSequence(base.generator, limit: base.limit + n,
dropped: base.dropped)
return AnySequence(folded)
}
return AnySequence(_DropFirstSequence(generate(), limit: n))
}
/// Returns a subsequence containing all but the last `n` elements.
///
/// - Requires: `self` is a finite collection.
/// - Requires: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
public func dropLast(n: Int) -> AnySequence<Generator.Element> {
_precondition(n >= 0, "Can't drop a negative number of elements from a sequence")
if n == 0 { return AnySequence(self) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements from this sequence in a holding tank, a ring buffer
// of size <= n. If more elements keep coming in, pull them out of the
// holding tank into the result, an `Array`. This saves
// `n` * sizeof(Generator.Element) of memory, because slices keep the entire
// memory of an `Array` alive.
var result: [Generator.Element] = []
var ringBuffer: [Generator.Element] = []
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < n {
ringBuffer.append(element)
} else {
result.append(ringBuffer[i])
ringBuffer[i] = element
i = i.successor() % n
}
}
return AnySequence(result)
}
@warn_unused_result
public func prefix(maxLength: Int) -> AnySequence<Generator.Element> {
_precondition(maxLength >= 0, "Can't take a prefix of negative length from a sequence")
if maxLength == 0 {
return AnySequence(EmptyCollection<Generator.Element>())
}
// FIXME: <rdar://problem/21885675> Use method dispatch to fold
// _PrefixSequence and _DropFirstSequence counts
if let any = self as? AnySequence<Generator.Element>,
let box = any._box as? _SequenceBox<_PrefixSequence<Generator>> {
let base = box._base
let folded = _PrefixSequence(
base.generator,
maxLength: min(base.maxLength, maxLength),
taken: base.taken)
return AnySequence(folded)
}
return AnySequence(_PrefixSequence(generate(), maxLength: maxLength))
}
@warn_unused_result
public func suffix(maxLength: Int) -> AnySequence<Generator.Element> {
_precondition(maxLength >= 0, "Can't take a suffix of negative length from a sequence")
if maxLength == 0 { return AnySequence([]) }
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
// Put incoming elements into a ring buffer to save space. Once all
// elements are consumed, reorder the ring buffer into an `Array`
// and return it. This saves memory for sequences particularly longer
// than `maxLength`.
var ringBuffer: [Generator.Element] = []
ringBuffer.reserveCapacity(min(maxLength, underestimateCount()))
var i = ringBuffer.startIndex
for element in self {
if ringBuffer.count < maxLength {
ringBuffer.append(element)
} else {
ringBuffer[i] = element
i = i.successor() % maxLength
}
}
if i != ringBuffer.startIndex {
return AnySequence(
[ringBuffer[i..<ringBuffer.endIndex], ringBuffer[0..<i]].flatten())
}
return AnySequence(ringBuffer)
}
/// Returns the maximal `SubSequence`s of `self`, in order, that
/// don't contain elements satisfying the predicate `isSeparator`.
///
/// - Parameter maxSplit: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplit + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing the remaining elements.
/// The default value is `Int.max`.
///
/// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// satisfying `isSeparator`.
/// The default value is `false`.
///
/// - Requires: `maxSplit >= 0`
@warn_unused_result
public func split(
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false,
@noescape isSeparator: (Generator.Element) throws -> Bool
) rethrows -> [AnySequence<Generator.Element>] {
_precondition(maxSplit >= 0, "Must take zero or more splits")
var result: [AnySequence<Generator.Element>] = []
var subSequence: [Generator.Element] = []
func appendSubsequence() -> Bool {
if subSequence.isEmpty && !allowEmptySlices {
return false
}
result.append(AnySequence(subSequence))
subSequence = []
return true
}
if maxSplit == 0 {
// We aren't really splitting the sequence. Convert `self` into an
// `Array` using a fast entry point.
subSequence = Array(self)
appendSubsequence()
return result
}
var hitEnd = false
var generator = self.generate()
while true {
guard let element = generator.next() else {
hitEnd = true
break
}
if try isSeparator(element) {
if !appendSubsequence() {
continue
}
if result.count == maxSplit {
break
}
} else {
subSequence.append(element)
}
}
if !hitEnd {
while let element = generator.next() {
subSequence.append(element)
}
}
appendSubsequence()
return result
}
/// Return a value less than or equal to the number of elements in
/// `self`, **nondestructively**.
///
/// - Complexity: O(N).
@warn_unused_result
public func underestimateCount() -> Int {
return 0
}
public func _preprocessingPass<R>(preprocess: (Self)->R) -> R? {
return nil
}
@warn_unused_result
public func _customContainsEquatableElement(
element: Generator.Element
) -> Bool? {
return nil
}
}
extension SequenceType {
/// Call `body` on each element in `self` in the same order as a
/// *for-in loop.*
///
/// sequence.forEach {
/// // body code
/// }
///
/// is similar to:
///
/// for element in sequence {
/// // body code
/// }
///
/// - Note: You cannot use the `break` or `continue` statement to exit the
/// current call of the `body` closure or skip subsequent calls.
/// - Note: Using the `return` statement in the `body` closure will only
/// exit from the current call to `body`, not any outer scope, and won't
/// skip subsequent calls.
///
/// - Complexity: O(`self.count`)
public func forEach(
@noescape body: (Generator.Element) throws -> Void
) rethrows {
for element in self {
try body(element)
}
}
}
extension SequenceType where Generator.Element : Equatable {
/// Returns the maximal `SubSequence`s of `self`, in order, around elements
/// equatable to `separator`.
///
/// - Parameter maxSplit: The maximum number of `SubSequence`s to
/// return, minus 1.
/// If `maxSplit + 1` `SubSequence`s are returned, the last one is
/// a suffix of `self` containing the remaining elements.
/// The default value is `Int.max`.
///
/// - Parameter allowEmptySubsequences: If `true`, an empty `SubSequence`
/// is produced in the result for each pair of consecutive elements
/// satisfying `isSeparator`.
/// The default value is `false`.
///
/// - Requires: `maxSplit >= 0`
@warn_unused_result
public func split(
separator: Generator.Element,
maxSplit: Int = Int.max,
allowEmptySlices: Bool = false
) -> [AnySequence<Generator.Element>] {
return split(maxSplit, allowEmptySlices: allowEmptySlices,
isSeparator: { $0 == separator })
}
}
extension SequenceType {
/// Returns a subsequence containing all but the first element.
///
/// - Requires: `n >= 0`
/// - Complexity: O(`n`)
@warn_unused_result
public func dropFirst() -> SubSequence { return dropFirst(1) }
/// Returns a subsequence containing all but the last element.
///
/// - Requires: `self` is a finite sequence.
/// - Requires: `n >= 0`
/// - Complexity: O(`self.count`)
@warn_unused_result
public func dropLast() -> SubSequence { return dropLast(1) }
}
/// Return an underestimate of the number of elements in the given
/// sequence, without consuming the sequence. For Sequences that are
/// actually Collections, this will return `x.count`.
@available(*, unavailable, message="call the 'underestimateCount()' method on the sequence")
public func underestimateCount<T : SequenceType>(x: T) -> Int {
fatalError("unavailable function can't be called")
}
extension SequenceType {
public func _initializeTo(ptr: UnsafeMutablePointer<Generator.Element>)
-> UnsafeMutablePointer<Generator.Element> {
var p = UnsafeMutablePointer<Generator.Element>(ptr)
for x in GeneratorSequence(self.generate()) {
p++.initialize(x)
}
return p
}
}
// Pending <rdar://problem/14011860> and <rdar://problem/14396120>,
// pass a GeneratorType through GeneratorSequence to give it "SequenceType-ness"
/// A sequence built around a generator of type `G`.
///
/// Useful mostly to recover the ability to use `for`...`in`,
/// given just a generator `g`:
///
/// for x in GeneratorSequence(g) { ... }
public struct GeneratorSequence<
Base : GeneratorType
> : GeneratorType, SequenceType {
@available(*, unavailable, renamed="Base")
public typealias G = Base
/// Construct an instance whose generator is a copy of `base`.
public init(_ base: Base) {
_base = base
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> Base.Element? {
return _base.next()
}
internal var _base: Base
}
| apache-2.0 | ba36cc008cc6c2e744f1452b582be5b6 | 32.195301 | 92 | 0.646819 | 4.283873 | false | false | false | false |
luongtsu/MHCalendar | MHCalendar/MHCalendar.swift | 1 | 11234 | //
// MHCalendar.swift
// MHCalendarDemo
//
// Created by Luong Minh Hiep on 9/12/17.
// Copyright © 2017 Luong Minh Hiep. All rights reserved.
//
import UIKit
protocol MHCalendarResponsible: class {
func didSelectDate(date: Date)
func didSelectDates(dates: [Date])
func didSelectAnotherMonth(isNextMonth: Bool)
}
class MHCalendar: UINibView {
@IBOutlet weak var headerView: MHCalendarHeaderView!
@IBOutlet weak var collectionView: UICollectionView!
weak var mhCalendarObserver : MHCalendarResponsible? = nil {
didSet {
didSetObserver()
}
}
// Appearance
var dayDisabledTintColor: UIColor = UIColor.lightGray
var weekdayTintColor: UIColor = UIColor.darkGray
var weekendTintColor: UIColor = UIColor.red
var todayTintColor: UIColor = UIColor.brown
var dateSelectionColor: UIColor = UIColor.blue
var monthTitleColor: UIColor = UIColor.brown {
didSet {
headerView.updateMonthTitleColor(monthTitleColor)
}
}
var monthBackgroundColor: UIColor = UIColor.clear {
didSet {
headerView.backgroundColor = monthBackgroundColor
}
}
// Other config
var selectedDates = [Date]()
var startDate: Date = Date(year: 2017, month: 1, day: 1)
var endDate: Date = Date(year: 2057, month: 1, day: 1)
var displayingDate: Date! = Date() {
didSet {
displayingYear = displayingDate.year()
displayingMonth = displayingDate.month()
firstDayOfThisMonth = Date(year: displayingYear, month: displayingMonth, day: 1)
updateCalendarView()
}
}
var hightlightsToday: Bool = true
var hideDaysFromOtherMonth: Bool = false
var selectEnabled: Bool = true
var multiSelectEnabled: Bool = true
// Helper params
fileprivate var displayingYear: Int = 2000
fileprivate var displayingMonth: Int = 1
fileprivate var firstDayOfThisMonth: Date! = Date()
fileprivate var lastSelectedIndex: IndexPath?
override func awakeFromNib() {
super.awakeFromNib()
MHCollectionViewCell.register(to: collectionView)
MHCollectionViewCell.register(to: collectionView)
collectionView.backgroundColor = UIColor.clear
}
private func didSetObserver() {
headerView.observer = self
/// set the gesture here
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGestureRight))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeGestureLeft))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.addGestureRecognizer(swipeLeft)
}
@objc private func respondToSwipeGestureRight() {
moveToAnotherMonth(isNextMonth: false)
}
@objc private func respondToSwipeGestureLeft() {
moveToAnotherMonth(isNextMonth: true)
}
private func updateCalendarView() {
collectionView.reloadData()
headerView.currentMonthLabel.text = displayingDate.monthYearInfo()
}
}
extension MHCalendar: MHCalendarHeaderViewResponsible {
func moveToAnotherMonth(isNextMonth: Bool) {
if isNextMonth {
if displayingDate.year() == endDate.year() && displayingDate.month() == endDate.month() {
return // reach the limit
}
displayingDate = displayingDate.dateByAddingMonths(1)
headerView.leftButton.isHidden = false
if displayingDate.year() == endDate.year() && displayingDate.month() == endDate.month() {
headerView.rightButton.isHidden = true
}
}
if !isNextMonth {
if displayingDate.year() == startDate.year() && displayingDate.month() == startDate.month() {
return // reach the limit
}
displayingDate = displayingDate.dateByAddingMonths(-1)
headerView.rightButton.isHidden = false
if displayingDate.year() == startDate.year() && displayingDate.month() == startDate.month() {
headerView.leftButton.isHidden = true
}
}
mhCalendarObserver?.didSelectAnotherMonth(isNextMonth: isNextMonth)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension MHCalendar: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
let rect = UIScreen.main.bounds
let screenWidth = rect.size.width - 27
return CGSize(width: screenWidth/7, height: screenWidth/7)
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
return UIEdgeInsetsMake(5, 0, 5, 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension MHCalendar: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let firstDayOfThisMonth = Date(year: displayingYear, month: displayingMonth, day: 1)
let addingPrefixDaysWithMonth = firstDayOfThisMonth.numberOfDaysInMonth() + firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday
let addingSuffixDays = addingPrefixDaysWithMonth % 7
var totalNumber = addingPrefixDaysWithMonth
if addingSuffixDays != 0 {
totalNumber = totalNumber + (7 - addingSuffixDays)
}
return totalNumber
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = MHCollectionViewCell.dequeue(from: collectionView, indexPath: indexPath) else {
assertionFailure("Need config MHCollectionViewCell")
return UICollectionViewCell()
}
let prefixDays = firstDayOfThisMonth.weekday() - Calendar.current.firstWeekday
if indexPath.row >= prefixDays {
cell.isCellSelectable = true
let currentDate = firstDayOfThisMonth.dateByAddingDays(indexPath.row-prefixDays)
let nextMonthFirstDay = firstDayOfThisMonth.dateByAddingDays(firstDayOfThisMonth.numberOfDaysInMonth()-1)
cell.currentDate = currentDate
cell.titleLabel.text = "\(currentDate.day())"
print("\(currentDate) \(currentDate.isSaturday()) \(currentDate.isSunday())")
if selectedDates.filter({ $0.isDateSameDay(currentDate)}).count > 0 && (firstDayOfThisMonth.month() == currentDate.month()) {
cell.selectedForLabelColor(dateSelectionColor)
} else {
cell.deSelectedForLabelColor(weekdayTintColor)
if cell.currentDate.isSaturday() || cell.currentDate.isSunday() {
cell.titleLabel.textColor = weekendTintColor
}
if (currentDate > nextMonthFirstDay) {
cell.isCellSelectable = false
if hideDaysFromOtherMonth {
cell.titleLabel.textColor = UIColor.clear
} else {
cell.titleLabel.textColor = self.dayDisabledTintColor
}
}
if currentDate.isToday() && hightlightsToday {
cell.setTodayCellColor(todayTintColor)
}
if Calendar.current.startOfDay(for: cell.currentDate as Date) < Calendar.current.startOfDay(for: startDate) {
cell.isCellSelectable = false
cell.titleLabel.textColor = self.dayDisabledTintColor
}
}
} else {
cell.deSelectedForLabelColor(weekdayTintColor)
cell.isCellSelectable = false
let previousDay = firstDayOfThisMonth.dateByAddingDays(-( prefixDays - indexPath.row))
cell.currentDate = previousDay
cell.titleLabel.text = "\(previousDay.day())"
if hideDaysFromOtherMonth {
cell.titleLabel.textColor = UIColor.clear
} else {
cell.titleLabel.textColor = self.dayDisabledTintColor
}
}
cell.backgroundColor = UIColor.clear
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard selectEnabled else {
return
}
let cell = collectionView.cellForItem(at: indexPath) as! MHCollectionViewCell
if !multiSelectEnabled && cell.isCellSelectable! {
if let `lastSelectedIndex` = lastSelectedIndex {
let lastSelectedCell = collectionView.cellForItem(at: lastSelectedIndex) as! MHCollectionViewCell
updateUnselectedCell(cell: lastSelectedCell)
selectedDates.removeAll()
}
mhCalendarObserver?.didSelectDate(date: cell.currentDate)
cell.selectedForLabelColor(dateSelectionColor)
selectedDates.append(cell.currentDate)
lastSelectedIndex = indexPath
return
}
if cell.isCellSelectable! {
if selectedDates.filter({ $0.isDateSameDay(cell.currentDate)
}).count == 0 {
selectedDates.append(cell.currentDate)
cell.selectedForLabelColor(dateSelectionColor)
if cell.currentDate.isToday() {
cell.setTodayCellColor(dateSelectionColor)
}
}
else {
selectedDates = selectedDates.filter(){
return !($0.isDateSameDay(cell.currentDate))
}
updateUnselectedCell(cell: cell)
}
}
}
private func updateUnselectedCell(cell: MHCollectionViewCell) {
if cell.currentDate.isSaturday() || cell.currentDate.isSunday() {
cell.deSelectedForLabelColor(weekendTintColor)
}
else {
cell.deSelectedForLabelColor(weekdayTintColor)
}
if cell.currentDate.isToday() && hightlightsToday{
cell.setTodayCellColor(todayTintColor)
}
}
}
| mit | eb46b43667985e426e227aeb1799ea67 | 37.601375 | 175 | 0.634381 | 5.509073 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Model/NewModel/NewEvent.swift | 1 | 2592 | //
// Copyright © 2018 Ingresse. All rights reserved.
//
public struct NewEvent: Decodable, Equatable {
public var categories: [Category] = []
public var companyId: Int = -1
public var createdAt: String = ""
public var desc: String = ""
public var id: Int = -1
public var place: Place?
public var poster: Poster?
public var producerId: Int = -1
public var sessions: [Session] = []
public var slug: String = ""
public var status: Status?
public var title: String = ""
public var attributes: SearchEventAttributes?
public var updatedAt: String = ""
enum CodingKeys: String, CodingKey {
case source = "_source"
}
enum EventCodingKeys: String, CodingKey {
case categories
case companyId
case createdAt
case desc = "description"
case id
case place
case poster
case producerId
case sessions
case slug
case status
case title
case attributes
case updatedAt
}
public struct Session: Codable, Equatable {
public var dateTime: String = ""
public var id: Int = -1
public var status: String = ""
}
public struct Status: Codable, Equatable {
public var id: Int = -1
public var name: String = ""
}
public init(from decoder: Decoder) throws {
guard
let source = try? decoder.container(keyedBy: CodingKeys.self),
let container = try? source.nestedContainer(keyedBy: EventCodingKeys.self, forKey: .source)
else { return }
companyId = container.decodeKey(.companyId, ofType: Int.self)
createdAt = container.decodeKey(.createdAt, ofType: String.self)
desc = container.decodeKey(.desc, ofType: String.self)
id = container.decodeKey(.id, ofType: Int.self)
producerId = container.decodeKey(.producerId, ofType: Int.self)
slug = container.decodeKey(.slug, ofType: String.self)
title = container.decodeKey(.title, ofType: String.self)
updatedAt = container.decodeKey(.updatedAt, ofType: String.self)
categories = container.decodeKey(.categories, ofType: [Category].self)
sessions = container.decodeKey(.sessions, ofType: [Session].self)
place = container.safeDecodeKey(.place, to: Place.self)
poster = container.safeDecodeKey(.poster, to: Poster.self)
status = container.safeDecodeKey(.status, to: Status.self)
attributes = container.safeDecodeKey(.attributes, to: SearchEventAttributes.self)
}
}
| mit | 5acf773abecae5134f567bad67fd3819 | 32.649351 | 103 | 0.636434 | 4.537653 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingRstStreamState.swift | 1 | 1439 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// A protocol that provides implementation for sending RST_STREAM frames, for those states that
/// can validly send such frames.
///
/// This protocol should only be conformed to by states for the HTTP/2 connection state machine.
protocol SendingRstStreamState: HasFlowControlWindows {
var streamState: ConnectionStreamState { get set }
}
extension SendingRstStreamState {
/// Called to send a RST_STREAM frame.
mutating func sendRstStream(streamID: HTTP2StreamID, reason: HTTP2ErrorCode) -> StateMachineResultWithEffect {
let result = self.streamState.locallyResetStreamState(streamID: streamID) {
$0.sendRstStream(reason: reason)
}
return StateMachineResultWithEffect(result,
inboundFlowControlWindow: self.inboundFlowControlWindow,
outboundFlowControlWindow: self.outboundFlowControlWindow)
}
}
| apache-2.0 | 43526f80aa0cd39e699fe35d11450ade | 42.606061 | 114 | 0.627519 | 5.139286 | false | false | false | false |
ivlevAstef/DITranquillity | Tests/DITranquillityTest/DITranquillityTests_MoreParameters.swift | 1 | 9625 | //
// DITranquillityTests_MoreParameters.swift
// DITranquillity-iOS
//
// Created by Alexander Ivlev on 17/05/2018.
// Copyright © 2018 Alexander Ivlev. All rights reserved.
//
import XCTest
import DITranquillity
private class A1 {}
private class A2 {}
private class A3 {}
private class A4 {}
private class A5 {}
private class A6 {}
private class A7 {}
private class A8 {}
private class A9 {}
private class A10 {}
private class A11 {}
private class A12 {}
private class A13 {}
private class A14 {}
private class A15 {}
private class A16 {}
/// with one parameters have more tests
private class RegTest {
init() {}
init(a1: A1, a2: A2) {}
init(a1: A1, a2: A2, a3: A3) {}
init(a1: A1, a2: A2, a3: A3, a4: A4) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15) {}
init(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15, a16: A16) {}
}
private class MethodTest {
init() {}
func method(a1: A1, a2: A2) {}
func method(a1: A1, a2: A2, a3: A3) {}
func method(a1: A1, a2: A2, a3: A3, a4: A4) {}
func method(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) {}
func method(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) {}
func method(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) {}
func method(a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) {}
}
/// with one parameters have more tests
private class RegArgTest {
init() {}
init(arg1: Int, a1: A1) {}
init(arg1: Int, a1: A1, a2: A2) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14) {}
init(arg1: Int, a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9, a10: A10, a11: A11, a12: A12, a13: A13, a14: A14, a15: A15) {}
}
class DITranquillityTests_MoreParameters: XCTestCase {
override func setUp() {
super.setUp()
}
private func registerAllClasses(in container: DIContainer) {
container.register(A1.init)
container.register(A2.init)
container.register(A3.init)
container.register(A4.init)
container.register(A5.init)
container.register(A6.init)
container.register(A7.init)
container.register(A8.init)
container.register(A9.init)
container.register(A10.init)
container.register(A11.init)
container.register(A12.init)
container.register(A13.init)
container.register(A14.init)
container.register(A15.init)
container.register(A16.init)
}
private func testRegisterUse(_ regClosure: (_: DIContainer) -> ()) {
let container = DIContainer()
registerAllClasses(in: container)
regClosure(container)
let test: RegTest? = *container
XCTAssertNotNil(test)
}
private func testMethodUse(_ methodClosure: (_: DIComponentBuilder<MethodTest>) -> ()) {
let container = DIContainer()
registerAllClasses(in: container)
methodClosure(container.register(MethodTest.init))
let test: MethodTest? = *container
XCTAssertNotNil(test)
}
private func testArgsRegisterUse(_ regClosure: (_: DIContainer) -> ()) {
let container = DIContainer()
registerAllClasses(in: container)
regClosure(container)
let testWithoutArg: RegArgTest? = container.resolve()
XCTAssertNil(testWithoutArg)
let test: RegArgTest? = container.resolve(args: 10)
XCTAssertNotNil(test)
}
func test01() {
testRegisterUse { $0.register(RegTest.init(a1:a2:)) }
}
func test02() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:)) }
}
func test03() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:)) }
}
func test04() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:)) }
}
func test05() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:)) }
}
func test06() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:)) }
}
func test07() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:)) }
}
func test08() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:)) }
}
func test09() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:)) }
}
func test10() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:)) }
}
func test11() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:)) }
}
func test12() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:)) }
}
func test13() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:)) }
}
func test14() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:)) }
}
func test15() {
testRegisterUse { $0.register(RegTest.init(a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:a16:)) }
}
func testMethod01() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2) } }
}
func testMethod02() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3) } }
}
func testMethod03() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3, a4: $4) } }
}
func testMethod04() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3, a4: $4, a5: $5) } }
}
func testMethod05() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3, a4: $4, a5: $5, a6: $6) } }
}
func testMethod06() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3, a4: $4, a5: $5, a6: $6, a7: $7) } }
}
func testMethod07() {
testMethodUse { $0.injection { $0.method(a1: $1, a2: $2, a3: $3, a4: $4, a5: $5, a6: $6, a7: $7, a8: $8) } }
}
func testArg00() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:)) { arg($0) } }
}
func testArg01() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:)) { arg($0) } }
}
func testArg02() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:)) { arg($0) } }
}
func testArg03() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:)) { arg($0) } }
}
func testArg04() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:)) { arg($0) } }
}
func testArg05() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:)) { arg($0) } }
}
func testArg06() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:)) { arg($0) } }
}
func testArg07() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:)) { arg($0) } }
}
func testArg08() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:)) { arg($0) } }
}
func testArg09() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:)) { arg($0) } }
}
func testArg10() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:)) { arg($0) } }
}
func testArg11() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:)) { arg($0) } }
}
func testArg12() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:)) { arg($0) } }
}
func testArg13() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:)) { arg($0) } }
}
func testArg14() {
testArgsRegisterUse { $0.register(RegArgTest.init(arg1:a1:a2:a3:a4:a5:a6:a7:a8:a9:a10:a11:a12:a13:a14:a15:)) { arg($0) } }
}
}
| mit | 1f936f0f9c5142c59ba1f8942870c2ed | 36.889764 | 154 | 0.60318 | 2.087183 | false | true | false | false |
austinzheng/swift | test/Constraints/generic_construction_deduction.swift | 66 | 665 | // RUN: %target-typecheck-verify-swift
struct A<T> {
// Can deduce from this constructor
init(x:T) { }
// Can't from this one
init(x:Int, y:Int) { }
static func bort(_ x: T) -> T { return x }
}
var a = A(x: 0)
var a1 : A<Int> = a
var b = A(x: "zero")
var b1 : A<String> = b
class C<T> {
init(x:T) { }
}
var c = C(x: 0)
var c1 : C<Int> = c
var d = C(x: "zero")
var d1 : C<String> = d
var x : Int = A.bort(0)
var y : String = A.bort("zero")
func foo(_ a: A<String>) { }
// Deduce A<String> from context
foo(A(x: 0, y: 0))
// Specifying only some of the generic arguments.
struct B { }
struct X<T,U> {
init(a:U) {}
}
var q = X<B,Int>(a: x)
| apache-2.0 | 87a00d0172d5b5f1d6ff9ea4afeb0d06 | 14.113636 | 49 | 0.550376 | 2.239057 | false | false | false | false |
hiddenviewer/Swiftris | Swiftris/Game/View/GameScore.swift | 1 | 3939 | //
// GameScore.swift
// Swiftris
//
// Created by Sungbae Kim on 2015. 7. 4..
// Copyright (c) 2015년 1minute2life. All rights reserved.
//
import UIKit
class GameScore: UIView {
var gameLevel = 0
var lineClearCount = 0
var gameScore = 0
fileprivate var levelLabel = UILabel()
fileprivate var lineClearLabel = UILabel()
fileprivate var scoreLabel = UILabel()
fileprivate var scores = [0, 10, 30, 60, 100]
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(red:0.21, green:0.21, blue:0.21, alpha:1.0)
self.levelLabel.translatesAutoresizingMaskIntoConstraints = false
self.levelLabel.textColor = UIColor.white
self.levelLabel.text = "Level: \(self.gameLevel)"
self.levelLabel.font = Swiftris.GameFont(20)
self.levelLabel.adjustsFontSizeToFitWidth = true
self.levelLabel.minimumScaleFactor = 0.9
self.addSubview(self.levelLabel)
self.lineClearLabel.translatesAutoresizingMaskIntoConstraints = false
self.lineClearLabel.textColor = UIColor.white
self.lineClearLabel.text = "Lines: \(self.lineClearCount)"
self.lineClearLabel.font = Swiftris.GameFont(20)
self.lineClearLabel.adjustsFontSizeToFitWidth = true
self.lineClearLabel.minimumScaleFactor = 0.9
self.addSubview(self.lineClearLabel)
self.scoreLabel = UILabel(frame: CGRect.zero)
self.scoreLabel.translatesAutoresizingMaskIntoConstraints = false
self.scoreLabel.textColor = UIColor.white
self.scoreLabel.text = "Score: \(self.gameScore)"
self.scoreLabel.font = Swiftris.GameFont(20)
self.scoreLabel.adjustsFontSizeToFitWidth = true
self.scoreLabel.minimumScaleFactor = 0.9
self.addSubview(self.scoreLabel)
let views = [
"level": self.levelLabel,
"lineClear": self.lineClearLabel,
"score": self.scoreLabel,
"selfView": self
] as [String : Any]
self.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "H:|-[level(80)]-10-[lineClear(>=90)]-10-[score(lineClear)]-|",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: views)
)
self.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "[selfView]-(<=0)-[level]",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: views)
)
NotificationCenter.default.addObserver(self,
selector: #selector(GameScore.lineClear(_:)),
name: NSNotification.Name(rawValue: Swiftris.LineClearNotification),
object: nil)
}
@objc func lineClear(_ noti:Notification) {
if let userInfo = noti.userInfo as? [String:NSNumber] {
if let lineCount = userInfo["lineCount"] {
self.lineClearCount += lineCount.intValue
self.gameScore += self.scores[lineCount.intValue]
self.update()
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func clear() {
self.gameLevel = 0
self.lineClearCount = 0
self.gameScore = 0
self.update()
}
func update() {
self.levelLabel.text = "Level: \(self.gameLevel)"
self.lineClearLabel.text = "Lines: \(self.lineClearCount)"
self.scoreLabel.text = "Score: \(self.gameScore)"
}
}
| mit | 67b9b0ac66fb8f99dca05c6f7cb8a30a | 34.468468 | 125 | 0.589535 | 4.830675 | false | false | false | false |
lanjing99/RxSwiftDemo | 16-testing-with-rxtests/final/Testing/TestingTests/TestingViewModel.swift | 1 | 3276 | /*
* Copyright (c) 2014-2016 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.
*
* 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 XCTest
import RxSwift
import RxTest
@testable import Testing
class TestingViewModel : XCTestCase {
var viewModel: ViewModel!
var scheduler: ConcurrentDispatchQueueScheduler!
override func setUp() {
super.setUp()
viewModel = ViewModel()
scheduler = ConcurrentDispatchQueueScheduler(qos: .default)
}
func testColorIsRedWhenHexStringIsFF0000_async() {
let disposeBag = DisposeBag()
// 1
let expect = expectation(description: #function)
// 2
let expectedColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
// 3
var result: UIColor!
// 1
viewModel.color.asObservable()
.skip(1)
.subscribe(onNext: {
// 2
result = $0
expect.fulfill()
})
.addDisposableTo(disposeBag)
// 3
viewModel.hexString.value = "#ff0000"
// 4
waitForExpectations(timeout: 1.0) { error in
guard error == nil else {
XCTFail(error!.localizedDescription)
return
}
// 5
XCTAssertEqual(expectedColor, result)
}
}
func testColorIsRedWhenHexStringIsFF0000() {
// 1
let colorObservable = viewModel.color.asObservable().subscribeOn(scheduler)
// 2
viewModel.hexString.value = "#ff0000"
// 3
do {
guard let result = try colorObservable.toBlocking(timeout: 1.0).first() else { return }
XCTAssertEqual(result, .red)
} catch {
print(error)
}
}
func testRgbIs010WhenHexStringIs00FF00() {
// 1
let rgbObservable = viewModel.rgb.asObservable().subscribeOn(scheduler)
// 2
viewModel.hexString.value = "#00ff00"
// 3
let result = try! rgbObservable.toBlocking().first()!
XCTAssertEqual(0 * 255, result.0)
XCTAssertEqual(1 * 255, result.1)
XCTAssertEqual(0 * 255, result.2)
}
func testColorNameIsRayWenderlichGreenWhenHexStringIs006636() {
// 1
let colorNameObservable = viewModel.colorName.asObservable().subscribeOn(scheduler)
// 2
viewModel.hexString.value = "#006636"
// 3
XCTAssertEqual("rayWenderlichGreen", try! colorNameObservable.toBlocking().first()!)
}
}
| mit | 9c83f07f21a757d27dc532963b3d617e | 25 | 93 | 0.684371 | 4.339073 | false | true | false | false |
mussegam/OpenWeatherMap | OpenWeatherMap/ViewControllers/ReportViewController.swift | 1 | 5760 | //
// ReportViewController.swift
// OpenWeatherMap
//
// Created by Javi Dolcet Figueras on 01/03/15.
// Copyright (c) 2015 Teanamics. All rights reserved.
//
import UIKit
import MapKit
class ReportViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak private var tempField: UITextField!
@IBOutlet weak private var humidField: UITextField!
@IBOutlet weak private var rainField: UITextField!
@IBOutlet weak private var locationMap: MKMapView!
@IBOutlet weak private var mapWidth: NSLayoutConstraint!
let locationManager = CLLocationManager();
let cartoDB_API = "88a4a6d71419e6fe522a6302c8e9ace7004d8953";
override func viewDidLoad() {
super.viewDidLoad()
tempField.attributedPlaceholder = NSAttributedString(string:"Temperature (ºC)", attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
rainField.attributedPlaceholder = NSAttributedString(string:"Air humidity (%)", attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
humidField.attributedPlaceholder = NSAttributedString(string:"Soil humidity (%)", attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
self.addPadding(tempField)
self.addPadding(rainField)
self.addPadding(humidField)
let toolbarTemp = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
let toolbarRain = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
let toolbarHumid = UIToolbar(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 44))
let flexSpace = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace, target:nil, action:nil)
let toRainButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target: self, action: "toRainfall")
let toHumidButton = UIBarButtonItem(title: "Next", style: UIBarButtonItemStyle.Plain, target:self, action: "toHumidity")
let doneButton = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.Done, target:self, action: "dismissKeyboard")
toolbarTemp.items = [flexSpace, toRainButton]
toolbarRain.items = [flexSpace, toHumidButton]
toolbarHumid.items = [flexSpace, doneButton]
tempField.inputAccessoryView = toolbarTemp
rainField.inputAccessoryView = toolbarRain
humidField.inputAccessoryView = toolbarHumid
if (CLLocationManager.locationServicesEnabled()) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
mapWidth.constant = UIScreen.mainScreen().bounds.width - 40
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func sendReport() {
let temp = (tempField.text as NSString).floatValue
let humidity = (humidField.text as NSString).floatValue
let rainfall = (rainField.text as NSString).floatValue
let urlString = "http://ygneo.cartodb.com/api/v2/sql?q=UPDATE iot_demo_1 SET temperatur=\(temp), humidity=\(humidity), rainfall=\(rainfall) WHERE id_rec='25061:0:0:7:127:1'&api_key=\(cartoDB_API)"
let url = NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!);
let request = NSURLRequest(URL: url!);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {
(response: NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var title = "Report sent"
var message = "Your weather report was sent successfully!"
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) -> Void in
})
if let anError = error {
title = "Error sending report"
message = "There was an error sending your weather report. Please, try again in a few minutes";
}
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert);
alert.addAction(action);
[self .presentViewController(alert, animated: true, completion: { () -> Void in
})];
}
}
// MARK: Private methods
private func addPadding(textField: UITextField) {
textField.leftViewMode = UITextFieldViewMode.Always;
textField.leftView = UIView(frame:CGRect(x:0, y:0, width:10, height:10));
}
func toRainfall() {
rainField.becomeFirstResponder()
}
func toHumidity() {
humidField.becomeFirstResponder()
}
func dismissKeyboard() {
self.view.endEditing(true);
self.sendReport()
}
// MARK: Location manager delegate
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if ((error) != nil) {
print(error)
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as! CLLocation
var coord = locationObj.coordinate
locationMap.setRegion(MKCoordinateRegionMake(coord, MKCoordinateSpanMake(0.01, 0.01)), animated: true)
if (locationObj.horizontalAccuracy < 50) {
locationManager.stopUpdatingLocation()
}
}
}
| mit | 0a191789cef1366ebc96ed067cf1ead7 | 42.961832 | 204 | 0.676506 | 5.042907 | false | false | false | false |
zhxnlai/ZLSwipeableViewSwift | ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/CustomDirectionDemoViewController.swift | 1 | 1040 | //
// CustomDirectionDemoViewController.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 5/25/15.
// Copyright (c) 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
class CustomDirectionDemoViewController: ZLSwipeableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let segmentControl = UISegmentedControl(items: [" ", "←", "↑", "→", "↓", "↔︎", "↕︎", "☩"])
segmentControl.selectedSegmentIndex = 5
navigationItem.titleView = segmentControl
segmentControl.addTarget(self, action: #selector(segmentedControlFired), for: .valueChanged)
}
// MARK: - Actions
@objc func segmentedControlFired(control: AnyObject?) {
if let control = control as? UISegmentedControl {
let directions: [ZLSwipeableViewDirection] = [.None, .Left, .Up, .Right, .Down, .Horizontal, .Vertical, .All]
self.swipeableView.allowedDirection = directions[control.selectedSegmentIndex]
}
}
}
| mit | 5c1e03b29278162523a94908378838b9 | 30.9375 | 121 | 0.658513 | 4.624434 | false | false | false | false |
kckd/ClassicAppExporter | classicexp-mac/ClassicListExporter/SwiftCompression.swift | 1 | 8557 | ///
/// SwiftDataCompression
///
/// libcompression wrapper as an extension for the `Data` type
/// (ZLIB, LZFSE, LZMA, LZ4, deflate, RFC-1950, RFC-1951)
///
/// Created by Markus Wanke, 2016/12/05
///
///
/// Apache License, Version 2.0
///
/// Copyright 2016, Markus Wanke
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
import Foundation
import Compression
extension Data
{
/// Compresses the data.
/// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type
/// - returns: compressed data
public func compress(withAlgorithm algo: CompressionAlgorithm) -> Data?
{
return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in
let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: algo.lowLevelType)
return perform(config, source: sourcePtr, sourceSize: count)
}
}
/// Decompresses the data.
/// - parameter withAlgorithm: Compression algorithm to use. See the `CompressionAlgorithm` type
/// - returns: decompressed data
public func decompress(withAlgorithm algo: CompressionAlgorithm) -> Data?
{
return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in
let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: algo.lowLevelType)
return perform(config, source: sourcePtr, sourceSize: count)
}
}
/// Please consider the [libcompression documentation](https://developer.apple.com/reference/compression/1665429-data_compression)
/// for further details. Short info:
/// ZLIB : Fast with a very solid compression rate. There is a reason it is used everywhere.
/// LZFSE : Apples proprietary compression algorithm. Claims to compress as good as ZLIB but 2 to 3 times faster.
/// LZMA : Horribly slow. Compression as well as decompression. Normally you will regret choosing LZMA.
/// LZ4 : Fast, but depending on the data the compression rate can be really bad. Which is often the case.
public enum CompressionAlgorithm
{
case ZLIB
case LZFSE
case LZMA
case LZ4
}
/// Compresses the data using the zlib deflate algorithm.
/// - returns: raw deflated data according to [RFC-1951](https://tools.ietf.org/html/rfc1951).
/// - note: Fixed at compression level 5 (best trade off between speed and time)
public func deflate() -> Data?
{
return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in
let config = (operation: COMPRESSION_STREAM_ENCODE, algorithm: COMPRESSION_ZLIB)
return perform(config, source: sourcePtr, sourceSize: count)
}
}
/// Deompresses the data using the zlib deflate algorithm. Self is expected to be a raw deflate
/// stream according to [RFC-1951](https://tools.ietf.org/html/rfc1951).
/// - returns: uncompressed data
public func inflate() -> Data?
{
return self.withUnsafeBytes { (sourcePtr: UnsafePointer<UInt8>) -> Data? in
let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB)
return perform(config, source: sourcePtr, sourceSize: count)
}
}
/// Compresses the data using the zlib deflate algorithm.
/// - returns: zlib deflated data according to [RFC-1950](https://tools.ietf.org/html/rfc1950)
/// - note: Fixed at compression level 5 (best trade off between speed and time)
public func zip() -> Data?
{
var res = Data(bytes: [0x78, 0x5e])
guard let deflated = self.deflate() else { return nil }
res.append(deflated)
var adler = self.adler32().bigEndian
res.append(Data(bytes: &adler, count: MemoryLayout<UInt32>.size))
return res
}
/// Deompresses the data using the zlib deflate algorithm. Self is expected to be a zlib deflate
/// stream according to [RFC-1950](https://tools.ietf.org/html/rfc1950).
/// - parameter skipCheckSumValidation: skip the adler32 checksum validation. default: true
/// - returns: uncompressed data
public func unzip(skipCheckSumValidation: Bool = true) -> Data?
{
// 2 byte header + 4 byte adler32 checksum
let overhead = 6
guard count > overhead else { return nil }
let header: UInt16 = withUnsafeBytes { (ptr: UnsafePointer<UInt16>) -> UInt16 in
return ptr.pointee.bigEndian
}
// check for the deflate stream bit
guard header >> 8 & 0b1111 == 0b1000 else { return nil }
// check the header checksum
guard header % 31 == 0 else { return nil }
let cresult: Data? = withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> Data? in
let source = ptr.advanced(by: 2)
let config = (operation: COMPRESSION_STREAM_DECODE, algorithm: COMPRESSION_ZLIB)
return perform(config, source: source, sourceSize: count - overhead)
}
guard let inflated = cresult else { return nil }
if skipCheckSumValidation { return inflated }
let cksum: UInt32 = withUnsafeBytes { (bytePtr: UnsafePointer<UInt8>) -> UInt32 in
let last = bytePtr.advanced(by: count - 4)
return last.withMemoryRebound(to: UInt32.self, capacity: 1) { (intPtr) -> UInt32 in
return intPtr.pointee.bigEndian
}
}
return cksum == inflated.adler32() ? inflated : nil
}
/// Rudimentary implementation of the adler32 checksum.
/// - returns: adler32 checksum (4 byte)
public func adler32() -> UInt32
{
var s1: UInt32 = 1
var s2: UInt32 = 0
let prime: UInt32 = 65521
for byte in self {
s1 += UInt32(byte)
if s1 >= prime { s1 = s1 % prime }
s2 += s1
if s2 >= prime { s2 = s2 % prime }
}
return (s2 << 16) | s1
}
}
fileprivate extension Data.CompressionAlgorithm
{
var lowLevelType: compression_algorithm {
switch self {
case .ZLIB : return COMPRESSION_ZLIB
case .LZFSE : return COMPRESSION_LZFSE
case .LZ4 : return COMPRESSION_LZ4
case .LZMA : return COMPRESSION_LZMA
}
}
}
fileprivate typealias Config = (operation: compression_stream_operation, algorithm: compression_algorithm)
fileprivate func perform(_ config: Config, source: UnsafePointer<UInt8>, sourceSize: Int) -> Data?
{
guard config.operation == COMPRESSION_STREAM_ENCODE || sourceSize > 0 else { return nil }
let streamBase = UnsafeMutablePointer<compression_stream>.allocate(capacity: 1)
defer { streamBase.deallocate(capacity: 1) }
var stream = streamBase.pointee
let status = compression_stream_init(&stream, config.operation, config.algorithm)
guard status != COMPRESSION_STATUS_ERROR else { return nil }
defer { compression_stream_destroy(&stream) }
let bufferSize = Swift.max( Swift.min(sourceSize, 64 * 1024), 64)
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
defer { buffer.deallocate(capacity: bufferSize) }
stream.dst_ptr = buffer
stream.dst_size = bufferSize
stream.src_ptr = source
stream.src_size = sourceSize
var res = Data()
let flags: Int32 = Int32(COMPRESSION_STREAM_FINALIZE.rawValue)
while true {
switch compression_stream_process(&stream, flags) {
case COMPRESSION_STATUS_OK:
guard stream.dst_size == 0 else { return nil }
res.append(buffer, count: stream.dst_ptr - buffer)
stream.dst_ptr = buffer
stream.dst_size = bufferSize
case COMPRESSION_STATUS_END:
res.append(buffer, count: stream.dst_ptr - buffer)
return res
default:
return nil
}
}
}
| unlicense | fae95cf5aa1a2302f63c991330075011 | 38.252294 | 134 | 0.635971 | 4.383709 | false | true | false | false |
AllisonWangJiaoJiao/KnowledgeAccumulation | 03-YFPageViewExtensionDemo/YFPageViewExtensionDemo/YFPageView/YFTitleView.swift | 1 | 8921 | //
// YFTitleView.swift
// YFPageViewDemo
//
// Created by Allison on 2017/4/27.
// Copyright © 2017年 Allison. All rights reserved.
//
import UIKit
protocol YFTitleViewDelegate : class {
func titleView(_ titleView : YFTitleView, targetIndex : Int)
}
class YFTitleView: UIView {
weak var delegate : YFTitleViewDelegate?
fileprivate var titlesArr : [String]
fileprivate var style : YFPageStyle
fileprivate lazy var titleLabelsArr : [UILabel] = [UILabel]()
fileprivate var currentIndex :Int = 0
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView(frame: self.bounds)
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
return scrollView
}()
fileprivate lazy var bottomLine : UIView = {
let bottomLine = UIView()
bottomLine.backgroundColor = self.style.bottomLineColor
bottomLine.frame.size.height = self.style.bottomLineHeight
return bottomLine
}()
init(frame: CGRect,titles:[String],style:YFPageStyle) {
self.titlesArr = titles
self.style = style
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension YFTitleView {
fileprivate func setupUI() {
//1.将UIScorllView添加到view中
addSubview(scrollView)
//2.将titleLabel添加到UIScorllView中
setupTitleLabels()
//3.设置titleLabel的frame
setupTitleLabelsFrame()
// 4.设置BottomLine
setupBottomLine()
}
private func setupBottomLine() {
// 1.判断是否需要显示底部线段
guard style.isShowBottomLine else { return }
// 2.将bottomLine添加到titleView中
scrollView.addSubview(bottomLine)
// 3.设置frame
bottomLine.frame.origin.x = titleLabelsArr.first!.frame.origin.x
bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight
bottomLine.frame.size.width = titleLabelsArr.first!.bounds.width
}
private func setupTitleLabels(){
for (i ,title) in titlesArr.enumerated() {
// 1.创建Label
let titleLabel = UILabel()
// 2.设置label的属性
titleLabel.text = title
titleLabel.font = UIFont.systemFont(ofSize: style.fontSize)
titleLabel.tag = i
titleLabel.textAlignment = .center
titleLabel.textColor = i == 0 ? style.selectColor : style.normalColor
// 3.添加到父控件中
scrollView.addSubview(titleLabel)
// 4.保存label
titleLabelsArr.append(titleLabel)
//给UILabel添加点击手势
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:)))
titleLabel.addGestureRecognizer(tapGes)
titleLabel.isUserInteractionEnabled = true
}
}
private func setupTitleLabelsFrame() {
let count = titlesArr.count
for (i, label) in titleLabelsArr.enumerated() {
var w : CGFloat = 0
let h : CGFloat = bounds.height
var x : CGFloat = 0
let y : CGFloat = 0
if style.isScrollEnable { // 可以滚动
w = (titlesArr[i] as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : label.font], context: nil).width
if i == 0 {
x = style.itemMargin * 0.5
} else {
let preLabel = titleLabelsArr[i - 1]
x = preLabel.frame.maxX + style.itemMargin
}
} else { // 不能滚动
w = bounds.width / CGFloat(count)
x = w * CGFloat(i)
}
label.frame = CGRect(x: x, y: y, width: w, height: h)
}
scrollView.contentSize = style.isScrollEnable ? CGSize(width: titleLabelsArr.last!.frame.maxX + style.itemMargin * 0.5, height: 0) : CGSize.zero
}
}
// MARK:- 监听事件
extension YFTitleView {
@objc fileprivate func titleLabelClick(_ tapGes : UITapGestureRecognizer) {
//1.取出用户点击的View
let targetLabel = tapGes.view as! UILabel
//2.调整title
adjustTitleLabel(targetIndex: targetLabel.tag)
//3.通知ContentView进行调整
delegate?.titleView(self, targetIndex: currentIndex)
// 4.调整BottomLine
if style.isShowBottomLine {
bottomLine.frame.origin.x = targetLabel.frame.origin.x
bottomLine.frame.size.width = targetLabel.frame.width
}
}
fileprivate func adjustTitleLabel(targetIndex : Int) {
if targetIndex == currentIndex {
return
}
//1.取出label
let targetLabel = titleLabelsArr[targetIndex]
let sourceLabel = titleLabelsArr[currentIndex]
//2.切换文字的颜色
sourceLabel.textColor = style.normalColor
targetLabel.textColor = style.selectColor
//3.记录下值
currentIndex = targetLabel.tag
//5.调整位置 -- 选中的按钮居中
if style.isScrollEnable {
var offsetX = targetLabel.center.x - scrollView.bounds.width * 0.5
if offsetX < 0 {
offsetX = 0
}
if offsetX > scrollView.contentSize.width - scrollView.bounds.width {
offsetX = scrollView.contentSize.width - scrollView.bounds.width
}
scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
}
//MARK:-遵循YFContentViewDelegate 滑动contentView标签调整
extension YFTitleView : YFContentViewDelegate{
func contentView(_ contentView: YFContentView, targetIndex: Int) {
adjustTitleLabel(targetIndex: targetIndex)
}
func contentView(_ contentView: YFContentView, targetIndex: Int, progress: CGFloat) {
print(progress)
//1.取出label
let sourceLabel = titleLabelsArr[currentIndex]
let targetLabel = titleLabelsArr[targetIndex]
//2.颜色渐变
let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor)
let selectRGB = style.selectColor.getRGB()
let normalRGB = style.normalColor.getRGB()
sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress)
targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress)
// 3.渐变BottomLine
if style.isShowBottomLine {
let deltaX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let deltaW = targetLabel.frame.width - sourceLabel.frame.width
bottomLine.frame.origin.x = sourceLabel.frame.origin.x + deltaX * progress
bottomLine.frame.size.width = sourceLabel.frame.width + deltaW * progress
}
}
}
// MARK:- 对外暴露的方法
extension YFTitleView {
func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
//1.取出label
let sourceLabel = titleLabelsArr[sourceIndex]
let targetLabel = titleLabelsArr[targetIndex]
//2.颜色渐变
let deltaRGB = UIColor.getRGBDelta(style.selectColor, style.normalColor)
let selectRGB = style.selectColor.getRGB()
let normalRGB = style.normalColor.getRGB()
sourceLabel.textColor = UIColor(r: selectRGB.0 - deltaRGB.0 * progress, g: selectRGB.1 - deltaRGB.1 * progress, b: selectRGB.2 - deltaRGB.2 * progress)
targetLabel.textColor = UIColor(r: normalRGB.0 + deltaRGB.0 * progress, g: normalRGB.1 + deltaRGB.1 * progress, b: normalRGB.2 + deltaRGB.2 * progress)
// 4.记录最新的index
currentIndex = targetIndex
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width
// 5.计算滚动的范围差值
if style.isShowBottomLine {
bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress
bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress
}
}
}
| mit | 3c4f6c0fb068cb9cda13c342929489af | 30.896296 | 212 | 0.60288 | 4.862789 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00232-swift-lookupresult-filter.swift | 11 | 1239 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class c {
func b((Any, c))(a: (Any, AnyObject)) {
b(a)
C: B, A {
override func d() -> String {
return ""
}
func c() -> String {
return ""
}
}
func e<T where T: A, T: B>(t: T) {
t.c()
}
func f(c: i, l: i) -> (((i, i) -> i) -> i) {
b {
(h -> i) d $k
}
let e: a {
}
class b<h, i> {
}
protocol c {
typealias g
}
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func C<D, E: A where D.C == E> {
}
func prefix(with: String) -> <T>(() -> T) -> String {
{ g in "\(withing
}
clasnintln(some(xs))
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
func i(c: () -> ()) {
}
class a {
var _ = i() {
}
}
| apache-2.0 | 82d82ccac68302b33595b98c45ff6019 | 17.772727 | 78 | 0.493947 | 2.841743 | false | false | false | false |
carabina/ios-installation-blog-example | Example/Application.swift | 1 | 11247 | //
// Application.swift
// Example
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Testlio, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Representation of an application installed on the iOS device
// Allows installing from manifests (using itms-service) and
// allows progress reporting from that process
//
// Assumptions made:
// 1) The code is not App Store compatible, as it uses private
// parts of MobileCoreServices.framework
// 2) The manifest is assumed to be valid (including the metadata)
//
// Created by Henri Normak on 25/08/15.
// Copyright (c) 2015 Testlio. All rights reserved.
//
import Foundation
import UIKit
let ApplicationErrorDomain = "application.proxy.error"
class Application: NSObject {
private var proxies = [LSApplicationProxy]()
private var bundleVersion: String?
private let bundleIdentifier: String
private var manifestURL: NSURL?
private var internalProgress: NSProgress?
private var installationProgress: NSProgress?
private var installationCompletion: ((Bool, NSError?) -> Void)?
private var installationCheckingTimer: NSTimer?
var version: String? {
get {
return self.bundleVersion ?? self.proxies.first?.bundleVersion
}
}
var isInstallable: Bool {
get {
return self.manifestURL != nil
}
}
var isInstalled: Bool {
get {
let count = self.proxies.filter({ $0.isInstalled }).count
return count > 0 && count == self.proxies.count
}
}
var isPlaceholder: Bool {
get {
return self.proxies.filter({ $0.isPlaceholder }).count > 0
}
}
private var itmsURL: NSURL? {
get {
if let URLString = self.manifestURL?.absoluteString {
let escapedString = CFURLCreateStringByAddingPercentEscapes(nil, URLString, nil, "/%&=?$#+-~@<>|\\*,.()[]{}^!", CFStringBuiltInEncodings.UTF8.rawValue)
return NSURL(string: "itms-services://?action=download-manifest&url=\(escapedString)")
}
return nil
}
}
///
/// Create a local representation of an application based on its bundle identifier
///
init(bundleIdentifier: String, manifestURL: NSURL? = nil) {
self.bundleIdentifier = bundleIdentifier
self.manifestURL = manifestURL
super.init()
self.reloadProxies()
}
///
/// Create an application that not only refers to local applications, but also allows installation from
/// a manifest online (using itms-service, so normal requirements apply)
///
static func createApplication(#manifestURL: NSURL, completion: ((Application?, NSError?) -> Void)) {
let request = NSURLRequest(URL: manifestURL)
self.createApplication(manifestRequest: request, completion: completion)
}
///
/// Create an application that not only refers to local applications, but also allows installation from
/// a manifest online (using itms-service, so normal requirements apply)
///
static func createApplication(#manifestRequest: NSURLRequest, completion: ((Application?, NSError?) -> Void)) {
if let URL = manifestRequest.URL {
// Fetch the manifest (we get our bundle identifier from there)
let task = NSURLSession.sharedSession().dataTaskWithRequest(manifestRequest) { data, response, error in
if let data = data {
var error: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data, options: 0, format: nil, error: &error)
if let dict = plist as? [String: AnyObject], items = dict["items"] as? [[String: AnyObject]], metadata = items.first?["metadata"] as? [String: String] {
let application = Application(bundleIdentifier: metadata["bundle-identifier"]!, manifestURL: URL)
application.bundleVersion = metadata["bundle-version"]
completion(application, nil)
} else {
completion(nil, error)
}
} else {
completion(nil, nil)
}
}
task.resume()
} else {
completion(nil, nil)
}
}
// MARK: Actions
///
/// Possible error codes
///
enum InstallError: Int {
case UserCancelled
case Internal
}
///
/// Install the application
/// This is only applicable for applications created with a manifest URL
///
/// :param: completion Block to be executed when the installation finishes (either fails or succeeds)
/// :returns: Progress for the installation
///
func install(completion: ((Bool, NSError?) -> Void)?) -> NSProgress? {
if let progress = self.installationProgress {
return progress
}
if !self.isInstallable {
return nil
}
// First step is to start the installation via itms-service
// If this can not be done, fail immediately
if let itmsURL = self.itmsURL where UIApplication.sharedApplication().canOpenURL(itmsURL) {
// We can now start the actual installation process
let progress = NSProgress(totalUnitCount: 101)
self.installationProgress = progress
self.installationCompletion = { success, error in
self // Capture ourselves so we won't be released during installation
completion?(success, error)
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: "startMonitoring", name: UIApplicationDidBecomeActiveNotification, object: nil)
UIApplication.sharedApplication().openURL(itmsURL)
return progress
} else {
return nil
}
}
///
/// Launch the application
///
/// :returns: True if launching was possible (does not guarantee the application was actually launched)
///
func launch() -> Bool {
let workspace = LSApplicationWorkspace.defaultWorkspace() as! LSApplicationWorkspace
return workspace.openApplicationWithBundleID(self.bundleIdentifier)
}
// MARK: Notifications
@objc private func startMonitoring() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
// We should now be a placeholder, if not, the user likely cancelled the operation
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC))), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.reloadProxies()
if self.isPlaceholder {
let workspace = LSApplicationWorkspace.defaultWorkspace() as! LSApplicationWorkspace
if let progress = workspace.installProgressForBundleID(self.bundleIdentifier, makeSynchronous: 1) as? NSProgress {
self.internalProgress = progress
progress.addObserver(self, forKeyPath: "fractionCompleted", options: .Initial, context: nil)
}
} else {
self.failInstallationWithError(.UserCancelled)
}
}
}
// MARK: KVO
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "fractionCompleted" {
if let progress = self.installationProgress, other = object as? NSProgress {
progress.completedUnitCount = other.completedUnitCount
self.installationCheckingTimer?.invalidate()
self.installationCheckingTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "checkIfFinishedInstallation", userInfo: nil, repeats: true)
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
// MARK: Helpers
@objc private func checkIfFinishedInstallation() {
self.reloadProxies()
if self.isInstalled {
self.installationCheckingTimer?.invalidate()
self.finishInstallation()
} else if !self.isPlaceholder {
self.installationCheckingTimer?.invalidate()
self.failInstallationWithError(.Internal)
}
}
private func reloadProxies() {
let workspace = LSApplicationWorkspace.defaultWorkspace() as! LSApplicationWorkspace
self.proxies = (workspace.allApplications() as! [LSApplicationProxy]).filter({ $0.applicationIdentifier == self.bundleIdentifier })
}
private func failInstallationWithError(error: InstallError) {
let info = [NSLocalizedDescriptionKey: error.description]
let error = NSError(domain: ApplicationErrorDomain, code: error.rawValue, userInfo: info)
self.installationCompletion?(false, error)
self.cleanup()
}
private func finishInstallation() {
self.installationCompletion?(true, nil)
self.cleanup()
}
private func cleanup() {
self.installationCompletion = nil
self.installationProgress = nil
}
}
//
// Convenience extensions for the error code
//
extension Application.InstallError: Printable {
var description: String {
get {
switch self {
case .UserCancelled:
return "User cancelled"
case .Internal:
return "Internal error"
}
}
}
}
func ==(lhs: Application.InstallError, rhs: Int) -> Bool {
return lhs.rawValue == rhs
}
func ==(lhs: Int, rhs: Application.InstallError) -> Bool {
return lhs == rhs.rawValue
}
| mit | 6f8fcfc1886271cf008c1687a2559d08 | 36.615385 | 177 | 0.6255 | 5.133272 | false | false | false | false |
nmacambira/NMCustomView | NMCustomViewDemo/NMCustomView/NMCustomView.swift | 2 | 3606 | //
// NMCustomView.swift
// NMCustomView
//
// Created by Natalia Macambira on 01/05/17.
// Copyright © 2017 Natalia Macambira. All rights reserved.
//
import UIKit
final public class NMCustomView: UIView {
private var backgroundView: UIView!
private var contentView = UIView()
public init(showView view: UIView, tapOnBackgroundToDismiss: Bool, blurEffect: Bool, blurEffectStyle: UIBlurEffectStyle?) {
super.init(frame: CGRect.zero)
self.setupView(view, tapOnBackgroundToDismiss: tapOnBackgroundToDismiss, blurEffect: blurEffect, blurEffectStyle: blurEffectStyle)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupView(_ view: UIView, tapOnBackgroundToDismiss: Bool, blurEffect: Bool, blurEffectStyle: UIBlurEffectStyle?) {
let keyWindow = UIApplication.shared.keyWindow
let keyWindowBounds: CGRect = (keyWindow?.bounds)!
self.frame = keyWindowBounds
keyWindow?.addSubview(self)
self.backgroundView = UIView(frame: keyWindowBounds)
darkBackground()
if blurEffect {
if !UIAccessibilityIsReduceTransparencyEnabled() {
blurBackground(blurEffectStyle)
}
}
if tapOnBackgroundToDismiss {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(NMCustomView.dismiss))
self.backgroundView.addGestureRecognizer(tapRecognizer)
}
self.addSubview(backgroundView)
self.contentView = view
self.contentView.center = CGPoint(x: (keyWindowBounds.midX), y: (keyWindowBounds.midY))
self.addSubview(contentView)
}
private func blurBackground(_ blurEffectStyle: UIBlurEffectStyle?) {
backgroundView.backgroundColor = UIColor.clear
backgroundView.alpha = 1
var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
if let blurStyle = blurEffectStyle {
blurEffect = UIBlurEffect(style: blurStyle)
}
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.backgroundView.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundView.addSubview(blurEffectView)
}
private func darkBackground() {
backgroundView.backgroundColor = UIColor(white: 0.0, alpha: 0.3)
backgroundView.alpha = 0
}
public func show() {
self.contentView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
self.contentView.transform = CGAffineTransform.identity
self.backgroundView.alpha = 1.0
self.contentView.alpha = 1.0
}) { (Bool) -> Void in
}
}
@objc public func dismiss() {
self.endEditing(true)
self.contentView.transform = CGAffineTransform.identity
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
self.contentView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
self.backgroundView.alpha = 0
self.contentView.alpha = 0
}) { (Bool) -> Void in
self.removeFromSuperview()
}
}
}
| mit | eaf2a11ea58c96c6be485c47c45039b8 | 34 | 138 | 0.635784 | 5.285924 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | ISaMaterialLogIn/Classes/ISaTransition.swift | 1 | 5847 | //
// ISaTransition.swift
// Pods
//
// Created by Francesco on 01/12/16.
//
//
import Foundation
import UIKit
open class ISaMaterialTransition: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
open weak var viewAnimated: UIView?
open var startFrame = CGRect()
open var defaultBackgroundColor: UIColor?
open var isBack = false
open var transitionDuration : TimeInterval = 0.5
convenience public init(viewAnimated: UIView) {
self.init()
self.viewAnimated = viewAnimated
}
//MARK - UIViewControllerAnimatedTransitioning
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return self.transitionDuration
}
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let viewAnimated = viewAnimated, let superview = viewAnimated.superview {
// Get the frame rect in the screen coordinates
self.startFrame = superview.convert(viewAnimated.frame, to: nil)
self.defaultBackgroundColor = viewAnimated.backgroundColor
}
// Use if the transitionContext.containerView is not fullscreen
let startFrame = transitionContext.containerView.superview?.convert(self.startFrame, to: transitionContext.containerView) ?? self.startFrame
let viewAnimatedForTransition = UIView(frame: startFrame)
transitionContext.containerView.addSubview(viewAnimatedForTransition)
viewAnimatedForTransition.clipsToBounds = true
viewAnimatedForTransition.layer.cornerRadius = viewAnimatedForTransition.frame.height / 2.0
viewAnimatedForTransition.backgroundColor = self.defaultBackgroundColor
let presentedController: UIViewController
if !self.isBack {
presentedController = transitionContext.viewController(forKey: .to)!
presentedController.view.layer.opacity = 0
}
else {
presentedController = transitionContext.viewController(forKey: .from)!
}
presentedController.view.frame = transitionContext.containerView.bounds
transitionContext.containerView.addSubview(presentedController.view)
let size = max(transitionContext.containerView.frame.height, transitionContext.containerView.frame.width) * 1.2
let scaleFactor = size / viewAnimatedForTransition.frame.width
let finalTransform = CGAffineTransform(scaleX: scaleFactor, y: scaleFactor)
if self.isBack {
viewAnimatedForTransition.transform = finalTransform
viewAnimatedForTransition.center = transitionContext.containerView.center
viewAnimatedForTransition.backgroundColor = presentedController.view.backgroundColor
UIView.animate(withDuration: self.transitionDuration(using: transitionContext) * 0.7, animations: {
presentedController.view.layer.opacity = 0
})
DispatchQueue.main.asyncAfter(deadline: .now() + self.transitionDuration(using: transitionContext) * 0.32) {
UIView.transition(with: viewAnimatedForTransition,
duration: self.transitionDuration(using: transitionContext) * 0.58,
options: [],
animations: {
viewAnimatedForTransition.transform = CGAffineTransform.identity
viewAnimatedForTransition.backgroundColor = self.defaultBackgroundColor
viewAnimatedForTransition.frame = startFrame
},
completion: { (_) in
viewAnimatedForTransition.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
else {
UIView.transition(with: viewAnimatedForTransition,
duration: self.transitionDuration(using: transitionContext) * 0.7,
options: [],
animations: {
viewAnimatedForTransition.transform = finalTransform
viewAnimatedForTransition.center = transitionContext.containerView.center
viewAnimatedForTransition.backgroundColor = presentedController.view.backgroundColor
},
completion: { (_) in
})
UIView.animate(withDuration: self.transitionDuration(using: transitionContext) * 0.42,
delay: self.transitionDuration(using: transitionContext) * 0.58,
animations: {
presentedController.view.layer.opacity = 1
},
completion: { (_) in
viewAnimatedForTransition.removeFromSuperview()
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
// MARK - UIViewControllerTransitioningDelegate
open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isBack = false
return self
}
open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.isBack = true
return self
}
}
| mit | 453662e36793d70e67e4c22e53400db6 | 45.03937 | 175 | 0.626133 | 6.599323 | false | false | false | false |
superk589/DereGuide | DereGuide/Model/Unit/RemoteUnit.swift | 2 | 3325 | //
// RemoteUnit.swift
// DereGuide
//
// Created by zzk on 2017/7/13.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import CloudKit
import CoreData
struct RemoteUnit: RemoteRecord {
var id: String
var creatorID: String
// var center: CKReference
var customAppeal: Int64
// var guest: CKReference
// var otherMembers: [CKReference]
var supportAppeal: Int64
var usesCustomAppeal: Int64
var localCreatedAt: Date
var localModifiedAt: Date
}
extension RemoteUnit {
static var recordType: String { return "Unit" }
init?(record: CKRecord) {
guard record.recordType == RemoteUnit.recordType else { return nil }
guard
// let center = record.object(forKey: "center") as? CKReference,
let customAppeal = record.object(forKey: "customAppeal") as? NSNumber,
// let guest = record.object(forKey: "guest") as? CKReference,
// let otherMembers = record["otherMembers"] as? [CKReference],
let supportAppeal = record["supportAppeal"] as? NSNumber,
let usesCustomAppeal = record["usesCustomAppeal"] as? NSNumber,
let localCreatedAt = record["localCreatedAt"] as? Date,
let localModifiedAt = record["localModifiedAt"] as? Date,
let creatorID = record.creatorUserRecordID?.recordName else {
return nil
}
self.id = record.recordID.recordName
self.creatorID = creatorID
self.localCreatedAt = localCreatedAt
// self.center = center
// self.guest = guest
// self.otherMembers = otherMembers
self.supportAppeal = supportAppeal.int64Value
self.customAppeal = customAppeal.int64Value
self.usesCustomAppeal = usesCustomAppeal.int64Value
self.localModifiedAt = localModifiedAt
}
}
extension RemoteUnit {
func insert(into context: NSManagedObjectContext, completion: @escaping (Bool) -> ()) {
let recordToMatch = CKRecord.Reference(recordID: CKRecord.ID(recordName: id), action: .deleteSelf)
let predicate = NSPredicate(format: "participatedUnit = %@", recordToMatch)
SyncCoordinator.shared.membersRemote.fetchRecordsForCurrentUserWith([predicate], [NSSortDescriptor.init(key: "participatedPosition", ascending: true)], completion: { (remoteMembers) in
guard remoteMembers.count == 6 else {
// SyncCoordinator.shared.unitsRemote.remove([self.id], completion: { _, _ in
// // no check
// })
// this situation may occur when the remote unit exists, but members are still uploading, so completion(false) and let the context to retry later
completion(false)
return
}
context.perform {
let unit = Unit.insert(into: context, customAppeal: Int(self.customAppeal), supportAppeal: Int(self.supportAppeal), usesCustomAppeal: self.usesCustomAppeal == 0 ? false : true, members: remoteMembers.map { $0.insert(into: context) })
unit.creatorID = self.creatorID
unit.remoteIdentifier = self.id
unit.createdAt = self.localCreatedAt
unit.updatedAt = self.localModifiedAt
completion(true)
}
})
}
}
| mit | 2b94342f0ea6ae59a466a94b7dff5408 | 37.651163 | 249 | 0.643201 | 4.504065 | false | false | false | false |
cubixlabs/SocialGIST | Pods/GISTFramework/GISTFramework/Classes/GISTCore/GISTApplication.swift | 1 | 7048 | //
// GISTApplication.swift
// GISTFramework
//
// Created by Shoaib Abdul on 07/09/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// GISTApplication protocol to receive events
@objc public protocol GISTApplicationDelegate {
@objc optional func applicationWillTerminate(_ application: UIApplication);
@objc optional func applicationDidBecomeActive(_ application: UIApplication);
@objc optional func applicationWillResignActive(_ application: UIApplication);
@objc optional func applicationDidEnterBackground(_ application: UIApplication);
@objc optional func applicationDidFinishLaunching(_ application: UIApplication);
@objc optional func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void);
} //F.E.
/// GISTApplication is a singleton class to handle UIApplicationDelegate events to send callbacks in a registerd delegate classes
open class GISTApplication: NSObject, UIApplicationDelegate {
//MARK: - Properties
/// Singleton sharedInstance for GISTApplication
open static var sharedInstance:GISTApplication = GISTApplication();
/// Registers delegate - it may hold more than one delegate.
open var delegate:GISTApplicationDelegate? {
set {
guard (newValue != nil) else {
return;
}
self.registerDelegate(newValue!);
}
get {
assertionFailure("getter not available")
return nil; // Unavailable
}
} //P.E.
/// Holding a collection fo weak delegate instances
private var _delegates:NSHashTable<Weak<GISTApplicationDelegate>> = NSHashTable();
//MARK: - Constructors
/// Private constuctor so that it can not be initialized from outside of the class
private override init() {
super.init();
} //F.E.
//MARK: - Methods
/**
Registers delegate targets.
It may register multiple targets.
*/
open func registerDelegate(_ target:GISTApplicationDelegate) {
if self.weakDelegateForTarget(target) == nil {
//Adding if not added
_delegates.add(Weak<GISTApplicationDelegate>(value: target))
}
} //F.E.
/**
Unregisters a delegate target.
It should be called when, the target does not want to reveice application events.
*/
open func unregisterDelegate(_ target:GISTApplicationDelegate) {
if let wTarget:Weak<GISTApplicationDelegate> = self.weakDelegateForTarget(target) {
_delegates.remove(wTarget);
}
} //F.E.
/// Retrieving weak instance of a given target
///
/// - Parameter target: GISTApplicationDelegate
/// - Returns: an optional weak target of a target (e.g. Weak<GISTApplicationDelegate>?).
private func weakDelegateForTarget(_ target:GISTApplicationDelegate) -> Weak<GISTApplicationDelegate>?{
let enumerator:NSEnumerator = _delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
if (wTarget.value == nil) {
//Removing if lost target already
_delegates.remove(wTarget);
} else if ((target as AnyObject).isEqual(wTarget.value)) {
return wTarget;
}
}
return nil;
} //F.E.
//MARK: - UIApplicationDelegate methods
/// Protocol method for applicationWillTerminate
///
/// - Parameter application: UIApplication
open func applicationWillTerminate(_ application: UIApplication) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.applicationWillTerminate?(application);
}
} //F.E.
/// Protocol method for applicationDidBecomeActive
///
/// - Parameter application: UIApplication
open func applicationDidBecomeActive(_ application: UIApplication) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.applicationDidBecomeActive?(application);
}
} //F.E.
/// Protocol method for applicationWillResignActive
///
/// - Parameter application: UIApplication
open func applicationWillResignActive(_ application: UIApplication) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.applicationWillResignActive?(application);
}
} //F.E.
/// Protocol method for applicationDidEnterBackground
///
/// - Parameter application: UIApplication
open func applicationDidEnterBackground(_ application: UIApplication) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.applicationDidEnterBackground?(application);
}
} //F.E.
/// Protocol method for applicationDidFinishLaunching
///
/// - Parameter application: UIApplication
open func applicationDidFinishLaunching(_ application: UIApplication) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.applicationDidFinishLaunching?(application);
}
} //F.E.
/// Protocol method for didReceiveRemoteNotification
///
/// - Parameters:
/// - application: UIApplication
/// - userInfo: User Info
/// - completionHandler: Completion block
open func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//Calling Delegate Methods
let enumerator:NSEnumerator = self._delegates.objectEnumerator();
while let wTarget:Weak<GISTApplicationDelegate> = enumerator.nextObject() as? Weak<GISTApplicationDelegate> {
wTarget.value?.application?(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler);
}
} //F.E.
} //CLS END
| gpl-3.0 | 18d37c7debea1e1f520495426815603d | 39.039773 | 213 | 0.673336 | 5.743276 | false | false | false | false |
claudioredi/aerogear-ios-oauth2 | AeroGearOAuth2/OAuth2WebViewController.swift | 1 | 1732 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
/**
OAuth2WebViewController is a UIViewController to be used when the Oauth2 flow used an embedded view controller
rather than an external browser approach.
*/
class OAuth2WebViewController: UIViewController, UIWebViewDelegate {
/// Login URL for OAuth.
var targetURL : NSURL = NSURL()
/// WebView intance used to load login page.
var webView : UIWebView = UIWebView()
/// Overrride of viewDidLoad to load the login page.
override internal func viewDidLoad() {
super.viewDidLoad()
webView.frame = UIScreen.mainScreen().applicationFrame
webView.delegate = self
self.view.addSubview(webView)
loadAddressURL()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.webView.frame = self.view.bounds
}
override internal func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func loadAddressURL() {
let req = NSURLRequest(URL: targetURL)
webView.loadRequest(req)
}
}
| apache-2.0 | 80d8a61a3c6bacb1c3695c163080988f | 31.679245 | 111 | 0.709584 | 4.745205 | false | false | false | false |
YevhenHerasymenko/SwiftGroup1 | ConstraintsImage/ConstraintsImage/ViewController.swift | 1 | 2153 | //
// ViewController.swift
// ConstraintsImage
//
// Created by Yevhen Herasymenko on 24/06/2016.
// Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var leftImageConstraint: NSLayoutConstraint!
@IBOutlet var imageView: UIImageView!
var topConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
//MARK: - Actions
extension ViewController {
@IBAction func buttonAction(sender: AnyObject) {
UIView.animateWithDuration(2) {
self.leftImageConstraint.constant += 30
self.topConstraint.constant += 50
self.view.layoutIfNeeded()
}
}
}
//MARK: - Setup UI
extension ViewController {
func setupUI() {
imageView.image = UIImage(named: "user")
imageView.layer.masksToBounds = true
imageView.layer.cornerRadius = imageView.frame.height/2
addView()
}
func addView() {
let myRect = CGRectMake(imageView.frame.maxX, imageView.frame.minY, imageView.frame.width, imageView.frame.height)
let myView = UIView(frame: myRect)
myView.backgroundColor = UIColor.redColor()
view.addSubview(myView)
addConstraintToView(myView)
}
func addConstraintToView(myView: UIView) {
myView.translatesAutoresizingMaskIntoConstraints = false
topConstraint = NSLayoutConstraint(item: myView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 40)
topConstraint.active = true
NSLayoutConstraint(item: myView, attribute: .Left, relatedBy: .Equal, toItem: imageView, attribute: .Right, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100).active = true
NSLayoutConstraint(item: myView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 100).active = true
}
}
| apache-2.0 | 12570353db7d4a7dfebfe5bfda95e812 | 32.625 | 164 | 0.674257 | 4.708972 | false | false | false | false |
zixun/CocoaChinaPlus | Code/CocoaChinaPlus/Application/Vender/RxDataSourceStarterKit/DataSources/RxCollectionViewSectionedDataSource.swift | 1 | 5740 | //
// RxCollectionViewSectionedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 7/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
open class _RxCollectionViewSectionedDataSource : NSObject
, UICollectionViewDataSource {
func _numberOfSectionsInCollectionView(_ collectionView: UICollectionView) -> Int {
return 0
}
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return _numberOfSectionsInCollectionView(collectionView)
}
func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return _collectionView(collectionView, numberOfItemsInSection: section)
}
func _collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
return (nil as UICollectionViewCell?)!
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return _collectionView(collectionView, cellForItemAtIndexPath: indexPath)
}
func _collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: IndexPath) -> UICollectionReusableView {
return (nil as UICollectionReusableView?)!
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return _collectionView(collectionView, viewForSupplementaryElementOfKind: kind, atIndexPath: indexPath)
}
}
open class RxCollectionViewSectionedDataSource<S: SectionModelType> : _RxCollectionViewSectionedDataSource {
public typealias I = S.Item
public typealias Section = S
public typealias CellFactory = (UICollectionView, IndexPath, I) -> UICollectionViewCell
public typealias SupplementaryViewFactory = (UICollectionView, String, IndexPath) -> UICollectionReusableView
public typealias IncrementalUpdateObserver = AnyObserver<Changeset<S>>
public typealias IncrementalUpdateDisposeKey = Bag<IncrementalUpdateObserver>.KeyType
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<S, I>
var sectionModels: [SectionModelSnapshot] = []
open func sectionAtIndex(_ section: Int) -> S {
return self.sectionModels[section].model
}
open func itemAtIndexPath(_ indexPath: IndexPath) -> I {
return self.sectionModels[indexPath.section].items[indexPath.item]
}
var incrementalUpdateObservers: Bag<IncrementalUpdateObserver> = Bag()
open func setSections(_ sections: [S]) {
self.sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
open var cellFactory: CellFactory! = nil
open var supplementaryViewFactory: SupplementaryViewFactory
public override init() {
self.cellFactory = { _, _, _ in return (nil as UICollectionViewCell?)! }
self.supplementaryViewFactory = { _, _, _ in (nil as UICollectionReusableView?)! }
super.init()
self.cellFactory = { [weak self] _ in
precondition(false, "There is a minor problem. `cellFactory` property on \(self!) was not set. Please set it manually, or use one of the `rx_bindTo` methods.")
return (nil as UICollectionViewCell!)!
}
self.supplementaryViewFactory = { [weak self] _, _, _ in
precondition(false, "There is a minor problem. `supplementaryViewFactory` property on \(self!) was not set.")
return (nil as UICollectionReusableView?)!
}
}
// observers
open func addIncrementalUpdatesObserver(_ observer: IncrementalUpdateObserver) -> IncrementalUpdateDisposeKey {
return incrementalUpdateObservers.insert(observer)
}
open func removeIncrementalUpdatesObserver(_ key: IncrementalUpdateDisposeKey) {
let element = incrementalUpdateObservers.removeKey(key)
precondition(element != nil, "Element removal failed")
}
// UITableViewDataSource
override func _numberOfSectionsInCollectionView(_ collectionView: UICollectionView) -> Int {
return sectionModels.count
}
override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sectionModels[section].items.count
}
override func _collectionView(_ collectionView: UICollectionView, cellForItemAtIndexPath indexPath: IndexPath) -> UICollectionViewCell {
precondition(indexPath.item < sectionModels[indexPath.section].items.count)
return cellFactory(collectionView, indexPath, itemAtIndexPath(indexPath))
}
override func _collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: IndexPath) -> UICollectionReusableView {
return supplementaryViewFactory(collectionView, kind, indexPath)
}
}
| mit | 65538a92b1fd13144fc3c186c9eb46bc | 40.89781 | 181 | 0.709756 | 5.893224 | false | false | false | false |
HeartRateLearning/HRLApp | HRLApp/Modules/ListWorkoutDates/Configurator/ListWorkoutDatesConfigurator.swift | 1 | 1790 | //
// ListWorkoutDatesListWorkoutDatesConfigurator.swift
// HRLApp
//
// Created by Enrique de la Torre on 30/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import UIKit
// MARK: - Main body
final class ListWorkoutDatesModuleConfigurator {
// MARK: - Public methods
func configureDependencies(for viewInput: UIViewController, with store: WorkoutStoreProtocol) {
guard let viewController = viewInput as? ListWorkoutDatesViewController else {
return
}
configureDependencies(for: viewController, with: store)
}
func configureModule(for viewInput: UIViewController, withWorkoutAt index: Int) {
guard let viewController = viewInput as? ListWorkoutDatesViewController else {
return
}
configureModule(for: viewController, withWorkoutAt: index)
}
}
// MARK: - Private body
private extension ListWorkoutDatesModuleConfigurator {
// MARK: - Private methods
func configureDependencies(for viewController: ListWorkoutDatesViewController,
with store: WorkoutStoreProtocol) {
let presenter = ListWorkoutDatesPresenter()
presenter.view = viewController
presenter.router = viewController
let interactor = GetWorkoutDatesInteractor()
interactor.store = store
interactor.output = presenter
presenter.interactor = interactor
viewController.output = presenter
}
func configureModule(for viewController: ListWorkoutDatesViewController,
withWorkoutAt index: Int) {
guard let input = viewController.output as? ListWorkoutDatesModuleInput else {
return
}
input.configure(withWorkoutAt: index)
}
}
| mit | 263a4e2576692e6a0919d91d5743c2f3 | 27.854839 | 99 | 0.683063 | 5.140805 | false | true | false | false |
benlangmuir/swift | test/refactoring/ConvertAsync/convert_async_renames.swift | 12 | 22358 | // REQUIRES: concurrency
// RUN: %empty-directory(%t)
func simple(_ completion: @escaping (String) -> Void) { }
func simple() async -> String { }
func simpleArg(arg: String, _ completion: @escaping (String) -> Void) { }
func simpleArg(arg: String) async -> String { }
func simpleErr(arg: String, _ completion: @escaping (String?, Error?) -> Void) { }
func simpleErr(arg: String) async throws -> String { }
func whatever() -> Bool { return true }
// Ideally we wouldn't rename anything here since it's correct as is, but the
// collector picks up the param `str` use in the if condition.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+1):6 | %FileCheck -check-prefix=LOCALREDECL %s
func localRedecl(str: String?) {
if let str = str {
print(str)
}
let str = "str"
print(str)
}
// LOCALREDECL: func localRedecl(str: String?) async {
// LOCALREDECL-NEXT: if let str = str {
// LOCALREDECL-NEXT: print(str)
// LOCALREDECL-NEXT: }
// LOCALREDECL-NEXT: let str1 = "str"
// LOCALREDECL-NEXT: print(str1)
// Again, ideally wouldn't rename as the use of `str` is above the hoisted call.
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefixes=SHADOWUNUSEDPARAM %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func shadowUnusedParam(str: String) {
print(str)
simple { str in
print(str)
}
}
// SHADOWUNUSEDPARAM: func shadowUnusedParam(str: String) async {
// SHADOWUNUSEDPARAM-NEXT: print(str)
// SHADOWUNUSEDPARAM-NEXT: let str1 = await simple()
// SHADOWUNUSEDPARAM-NEXT: print(str1)
// HOISTED-SIMPLE-CALL: let str = await simple()
// HOISTED-SIMPLE-CALL-NEXT: print(str)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=SHADOWUSEDPARAM %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func shadowUsedParam(str: String) {
print(str)
simple { str in
print(str)
}
print(str)
}
// SHADOWUSEDPARAM: func shadowUsedParam(str: String) async {
// SHADOWUSEDPARAM-NEXT: print(str)
// SHADOWUSEDPARAM-NEXT: let str1 = await simple()
// SHADOWUSEDPARAM-NEXT: print(str1)
// SHADOWUSEDPARAM-NEXT: print(str)
// RENAMED-SIMPLE-CALL: let str1 = await simple()
// RENAMED-SIMPLE-CALL-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTEDBEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+5):5 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func nestedBefore() {
let str = "str"
print(str)
if whatever() {
simple { str in
print(str)
}
}
}
// NESTEDBEFORE: func nestedBefore() async {
// NESTEDBEFORE-NEXT: let str = "str"
// NESTEDBEFORE-NEXT: print(str)
// NESTEDBEFORE-NEXT: if whatever() {
// NESTEDBEFORE-NEXT: let str = await simple()
// NESTEDBEFORE-NEXT: print(str)
// NESTEDBEFORE-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTEDAFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):5 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func nestedAfter() {
if whatever() {
simple { str in
print(str)
}
}
let str = "str"
print(str)
}
// NESTEDAFTER: func nestedAfter() async {
// NESTEDAFTER-NEXT: if whatever() {
// NESTEDAFTER-NEXT: let str = await simple()
// NESTEDAFTER-NEXT: print(str)
// NESTEDAFTER-NEXT: }
// NESTEDAFTER-NEXT: let str = "str"
// NESTEDAFTER-NEXT: print(str)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTED-DECL-BEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+4):5 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func nestedDeclBefore() {
if whatever() {
let str = "str"
simple { str in
print(str)
}
}
}
// NESTED-DECL-BEFORE: func nestedDeclBefore() async {
// NESTED-DECL-BEFORE-NEXT: if whatever() {
// NESTED-DECL-BEFORE-NEXT: let str = "str"
// NESTED-DECL-BEFORE-NEXT: let str1 = await simple()
// NESTED-DECL-BEFORE-NEXT: print(str1)
// NESTED-DECL-BEFORE-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTED-DECL-AFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):5 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func nestedDeclAfter() {
if whatever() {
simple { str in
print(str)
}
let str = "str"
}
}
// NESTED-DECL-AFTER: func nestedDeclAfter() async {
// NESTED-DECL-AFTER-NEXT: if whatever() {
// NESTED-DECL-AFTER-NEXT: let str = await simple()
// NESTED-DECL-AFTER-NEXT: print(str)
// NESTED-DECL-AFTER-NEXT: let str1 = "str"
// NESTED-DECL-AFTER-NEXT: }
// Ideally wouldn't rename, but is for the same reason as before
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTED-USE-BEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+5):5 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func nestedUseBefore() {
let str = "str"
if whatever() {
print(str)
simple { str in
print(str)
}
}
}
// NESTED-USE-BEFORE: func nestedUseBefore() async {
// NESTED-USE-BEFORE-NEXT: let str = "str"
// NESTED-USE-BEFORE-NEXT: if whatever() {
// NESTED-USE-BEFORE-NEXT: print(str)
// NESTED-USE-BEFORE-NEXT: let str1 = await simple()
// NESTED-USE-BEFORE-NEXT: print(str1)
// NESTED-USE-BEFORE-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=NESTED-USE-AFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+4):5 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func nestedUseAfter() {
let str = "str"
if whatever() {
simple { str in
print(str)
}
print(str)
}
}
// NESTED-USE-AFTER: func nestedUseAfter() async {
// NESTED-USE-AFTER-NEXT: let str = "str"
// NESTED-USE-AFTER-NEXT: if whatever() {
// NESTED-USE-AFTER-NEXT: let str1 = await simple()
// NESTED-USE-AFTER-NEXT: print(str1)
// NESTED-USE-AFTER-NEXT: print(str)
// NESTED-USE-AFTER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=REDECLBEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+4):3 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func redeclBefore() {
let str = "do not redecl"
print(str)
simple { str in
print(str)
}
}
// REDECLBEFORE: func redeclBefore() async {
// REDECLBEFORE-NEXT: let str = "do not redecl"
// REDECLBEFORE-NEXT: print(str)
// REDECLBEFORE-NEXT: let str1 = await simple()
// REDECLBEFORE-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=GUARDREDECLBEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+6):3 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func guardRedeclBefore(arg: String?) {
guard let str = arg else {
return
}
print(str)
simple { str in
print(str)
}
}
// GUARDREDECLBEFORE: func guardRedeclBefore(arg: String?) async {
// GUARDREDECLBEFORE-NEXT: guard let str = arg else {
// GUARDREDECLBEFORE-NEXT: return
// GUARDREDECLBEFORE-NEXT: }
// GUARDREDECLBEFORE-NEXT: print(str)
// GUARDREDECLBEFORE-NEXT: let str1 = await simple()
// GUARDREDECLBEFORE-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=IFDECLBEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+5):3 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func ifDeclBefore(arg: String?) {
if let str = arg {
print(str)
}
simple { str in
print(str)
}
}
// IFDECLBEFORE: func ifDeclBefore(arg: String?) async {
// IFDECLBEFORE-NEXT: if let str = arg {
// IFDECLBEFORE-NEXT: print(str)
// IFDECLBEFORE-NEXT: }
// IFDECLBEFORE-NEXT: let str = await simple()
// IFDECLBEFORE-NEXT: print(str)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=REDECLAFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func redeclAfter() {
simple { str in
print(str)
}
let str = "do not redecl"
print(str)
}
// REDECLAFTER: func redeclAfter() async {
// REDECLAFTER-NEXT: let str = await simple()
// REDECLAFTER-NEXT: print(str)
// REDECLAFTER-NEXT: let str1 = "do not redecl"
// REDECLAFTER-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=GUARDREDECLAFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=RENAMED-SIMPLE-CALL %s
func guardRedeclAfter(arg: String?) {
simple { str in
print(str)
}
guard let str = arg else {
return
}
print(str)
}
// GUARDREDECLAFTER: func guardRedeclAfter(arg: String?) async {
// GUARDREDECLAFTER-NEXT: let str = await simple()
// GUARDREDECLAFTER-NEXT: print(str)
// GUARDREDECLAFTER-NEXT: guard let str1 = arg else {
// GUARDREDECLAFTER-NEXT: return
// GUARDREDECLAFTER-NEXT: }
// GUARDREDECLAFTER-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=IFDECLAFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func ifDeclAfter(arg: String?) {
simple { str in
print(str)
}
if let str = arg {
print(str)
}
}
// IFDECLAFTER: func ifDeclAfter(arg: String?) async {
// IFDECLAFTER-NEXT: let str = await simple()
// IFDECLAFTER-NEXT: print(str)
// IFDECLAFTER-NEXT: if let str = arg {
// IFDECLAFTER-NEXT: print(str)
// IFDECLAFTER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=REDECLINNER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=REDECLINNER %s
func redeclInner() {
simple { str in
simpleArg(arg: str) { other in
let str = other
print(str)
}
}
}
// REDECLINNER: let str = await simple()
// REDECLINNER-NEXT: let other = await simpleArg(arg: str)
// REDECLINNER-NEXT: let str1 = other
// REDECLINNER-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=DECLINNER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=DECLINNER %s
func declInner() {
simple { str in
simpleArg(arg: str) { other in
if other == "anything" {
let str = other
print(str)
}
}
}
}
// DECLINNER: let str = await simple()
// DECLINNER-NEXT: let other = await simpleArg(arg: str)
// DECLINNER-NEXT: if other == "anything" {
// DECLINNER-NEXT: let str = other
// DECLINNER-NEXT: print(str)
// DECLINNER-NEXT: }
// TODO: `throws` isn't added to the function declaration
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=REDECLHOISTED %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=REDECLHOISTED %s
func redeclInnerHoisted() {
simple { str in
simpleErr(arg: str) { other, err in
if let other = other {
let str = other
print(str)
}
}
}
}
// REDECLHOISTED: let str = await simple()
// REDECLHOISTED-NEXT: let other = try await simpleErr(arg: str)
// REDECLHOISTED-NEXT: let str1 = other
// REDECLHOISTED-NEXT: print(str1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=SHADOWINNER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=SHADOWINNER %s
func shadowInner() {
simple { str in
simpleArg(arg: str) { str in
print(str)
}
}
}
// SHADOWINNER: let str = await simple()
// SHADOWINNER-NEXT: let str1 = await simpleArg(arg: str)
// SHADOWINNER-NEXT: print(str1)
// TODO: `throws` isn't added to the function declaration
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=SHADOWINNERBIND %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=SHADOWINNERBIND %s
func shadowInnerBind() {
simple { str in
simpleErr(arg: str) { other, err in
if let str = other {
print(str)
}
}
}
}
// SHADOWINNERBIND: let str = await simple()
// SHADOWINNERBIND-NEXT: let str1 = try await simpleErr(arg: str)
// SHADOWINNERBIND-NEXT: print(str1)
// TODO: `throws` isn't added to the function declaration
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=SHADOWNAMEEXISTS %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=SHADOWNAMEEXISTS %s
func shadowNameAlreadyExists() {
simple { str in
simpleErr(arg: str) { str, err in
let str1 = "str1"
print(str1)
if let str1 = str {
print(str1)
}
if let str2 = str {
print(str2)
}
}
}
}
// SHADOWNAMEEXISTS: let str = await simple()
// SHADOWNAMEEXISTS-NEXT: let str1 = try await simpleErr(arg: str)
// SHADOWNAMEEXISTS-NEXT: let str11 = "str1"
// SHADOWNAMEEXISTS-NEXT: print(str11)
// SHADOWNAMEEXISTS-NEXT: print(str1)
// SHADOWNAMEEXISTS-NEXT: print(str1)
func shadowsUsedDecl() {
let inOuter: String = "str"
print(inOuter)
// TODO: `throws` isn't added to the function declaration
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):8 | %FileCheck -check-prefix=SHADOWOUTERUSED %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):10 | %FileCheck -check-prefix=SHADOWOUTERUSED %s
func inner() {
simpleErr(arg: "str") { inCall, err in
if inCall != nil {
let inOuter = inCall!
print(inOuter)
}
print(inOuter)
}
}
}
// SHADOWOUTERUSED: let inCall = try await simpleErr(arg: "str")
// SHADOWOUTERUSED-NEXT: let inOuter1 = inCall
// SHADOWOUTERUSED-NEXT: print(inOuter1)
// SHADOWOUTERUSED-NEXT: print(inOuter)
func shadowsUnusedDecl() {
let inOuter: String = "str"
print(inOuter)
// TODO: `throws` isn't added to the function declaration
// RUN: %refactor -convert-to-async -dump-text -source-filename %s -pos=%(line+2):8 | %FileCheck -check-prefix=SHADOWOUTERUNUSED %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):10 | %FileCheck -check-prefix=SHADOWOUTERUNUSED %s
func inner() {
simpleErr(arg: "str") { inCall, err in
if inCall != nil {
let inOuter = inCall!
print(inOuter)
}
}
}
}
// SHADOWOUTERUNUSED: let inCall = try await simpleErr(arg: "str")
// SHADOWOUTERUNUSED-NEXT: let inOuter = inCall
// SHADOWOUTERUNUSED-NEXT: print(inOuter)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=IGNORE-SCOPED-BEFORE %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+16):3 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func ignoreScopedBefore(arg: String?, args: [String]) {
if let str = arg {
print(str)
}
for str in args {
print(str)
}
var check = arg
while let str = check {
check = str
}
do {
let str = arg!
print(str)
}
simple { str in
print(str)
}
}
// IGNORE-SCOPED-BEFORE: if let str = arg {
// IGNORE-SCOPED-BEFORE-NEXT: print(str)
// IGNORE-SCOPED-BEFORE-NEXT: }
// IGNORE-SCOPED-BEFORE-NEXT: for str in args {
// IGNORE-SCOPED-BEFORE-NEXT: print(str)
// IGNORE-SCOPED-BEFORE-NEXT: }
// IGNORE-SCOPED-BEFORE-NEXT: var check = arg
// IGNORE-SCOPED-BEFORE-NEXT: while let str = check {
// IGNORE-SCOPED-BEFORE-NEXT: check = str
// IGNORE-SCOPED-BEFORE-NEXT: }
// IGNORE-SCOPED-BEFORE-NEXT: do {
// IGNORE-SCOPED-BEFORE-NEXT: let str = arg!
// IGNORE-SCOPED-BEFORE-NEXT: print(str)
// IGNORE-SCOPED-BEFORE-NEXT: }
// IGNORE-SCOPED-BEFORE-NEXT: let str = await simple()
// IGNORE-SCOPED-BEFORE-NEXT: print(str)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=IGNORE-SCOPED-AFTER %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):3 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func ignoreScopedAfter(arg: String?, args: [String]) {
simple { str in
print(str)
}
if let str = arg {
print(str)
}
for str in args {
print(str)
}
var check = arg
while let str = check {
check = str
}
do {
let str = arg!
print(str)
}
}
// IGNORE-SCOPED-AFTER: let str = await simple()
// IGNORE-SCOPED-AFTER-NEXT: print(str)
// IGNORE-SCOPED-AFTER-NEXT: if let str = arg {
// IGNORE-SCOPED-AFTER-NEXT: print(str)
// IGNORE-SCOPED-AFTER-NEXT: }
// IGNORE-SCOPED-AFTER-NEXT: for str in args {
// IGNORE-SCOPED-AFTER-NEXT: print(str)
// IGNORE-SCOPED-AFTER-NEXT: }
// IGNORE-SCOPED-AFTER-NEXT: var check = arg
// IGNORE-SCOPED-AFTER-NEXT: while let str = check {
// IGNORE-SCOPED-AFTER-NEXT: check = str
// IGNORE-SCOPED-AFTER-NEXT: }
// IGNORE-SCOPED-AFTER-NEXT: do {
// IGNORE-SCOPED-AFTER-NEXT: let str = arg!
// IGNORE-SCOPED-AFTER-NEXT: print(str)
// IGNORE-SCOPED-AFTER-NEXT: }
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefixes=TYPE-BEFORE,TYPE-BEFORE-CALL %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=TYPE-BEFORE-CALL %s
func typeBefore() {
struct Foo {}
simple { Foo in
print(Foo)
}
}
// TYPE-BEFORE: struct Foo {}
// TYPE-BEFORE-CALL: let Foo1 = await simple()
// TYPE-BEFORE-CALL-NEXT: print(Foo1)
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefixes=FUNC-BEFORE,FUNC-BEFORE-CALL %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+3):3 | %FileCheck -check-prefix=FUNC-BEFORE-CALL %s
func funcBefore() {
func foo() {}
simple { foo in
print(foo)
}
}
// FUNC-BEFORE: func foo() {}
// FUNC-BEFORE-CALL: let foo1 = await simple()
// FUNC-BEFORE-CALL-NEXT: print(foo1)
enum SomeEnum {
case foo(String)
case bar(String)
case baz(String)
}
// RUN: %refactor-check-compiles -convert-to-async -dump-text -source-filename %s -pos=%(line+2):6 | %FileCheck -check-prefix=CASE-SCOPES %s
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+15):5 | %FileCheck -check-prefix=HOISTED-SIMPLE-CALL %s
func caseScopes() {
switch SomeEnum.foo("a") {
case .foo(let arg):
simple { str in
print(str)
}
case .bar(let str):
simple { str in
print(str)
}
case .baz(let arg):
simple { str in
print(str)
}
simple { str in
print(str)
}
}
}
// CASE-SCOPES: func caseScopes() async {
// CASE-SCOPES-NEXT: switch SomeEnum.foo("a") {
// CASE-SCOPES-NEXT: case .foo(let arg):
// CASE-SCOPES-NEXT: let str = await simple()
// CASE-SCOPES-NEXT: print(str)
// CASE-SCOPES-NEXT: case .bar(let str):
// CASE-SCOPES-NEXT: let str = await simple()
// CASE-SCOPES-NEXT: print(str)
// CASE-SCOPES-NEXT: case .baz(let arg):
// CASE-SCOPES-NEXT: let str = await simple()
// CASE-SCOPES-NEXT: print(str)
// CASE-SCOPES-NEXT: let str1 = await simple()
// CASE-SCOPES-NEXT: print(str1)
// CASE-SCOPES-NEXT: }
// CASE-SCOPES-NEXT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 | %FileCheck -check-prefix=TOP-LEVEL-VAR %s
let inFile = "inFile"
simple { inFile in
print(inFile)
}
// TOP-LEVEL-VAR: let inFile1 = await simple()
// TOP-LEVEL-VAR-NEXT: print(inFile1)
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 | %FileCheck -check-prefix=TOP-LEVEL-FUNC %s
func fileFunc() {}
simple { fileFunc in
print(fileFunc)
}
// TOP-LEVEL-FUNC: let fileFunc1 = await simple()
// TOP-LEVEL-FUNC-NEXT: print(fileFunc1)
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+2):1 | %FileCheck -check-prefix=TOP-LEVEL-PROTO %s
protocol FileProto {}
simple { FileProto in
print(FileProto)
}
// TOP-LEVEL-PROTO: let FileProto1 = await simple()
// TOP-LEVEL-PROTO-NEXT: print(FileProto1)
// The following results in two TopLevelCodeDecls each with their own BraceStmt,
// we want to make sure that we still find the `someGlobal` reference and thus
// rename the `someGlobal` closure arg.
let someGlobal = "someGlobal"
func between1() {}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=TOP-LEVEL-REFERENCE %s
simple { someGlobal in
print(someGlobal)
}
func between2() {}
print(someGlobal)
// TOP-LEVEL-REFERENCE: let someGlobal1 = await simple()
// TOP-LEVEL-REFERENCE-NEXT: print(someGlobal1)
| apache-2.0 | 368ca890a96dbb6ba82cc80e643e6109 | 35.955372 | 159 | 0.682843 | 3.039837 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/SIL/Type.swift | 2 | 3353 | //===--- Type.swift - Value type ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
public struct Type : CustomStringConvertible, CustomReflectable {
public let bridged: BridgedType
public var isAddress: Bool { SILType_isAddress(bridged) != 0 }
public var isObject: Bool { !isAddress }
public func isTrivial(in function: Function) -> Bool {
return SILType_isTrivial(bridged, function.bridged) != 0
}
public func isReferenceCounted(in function: Function) -> Bool {
return SILType_isReferenceCounted(bridged, function.bridged) != 0
}
public func isNonTrivialOrContainsRawPointer(in function: Function) -> Bool {
return SILType_isNonTrivialOrContainsRawPointer(bridged, function.bridged) != 0
}
public var isNominal: Bool { SILType_isNominal(bridged) != 0 }
public var isClass: Bool { SILType_isClass(bridged) != 0 }
public var isStruct: Bool { SILType_isStruct(bridged) != 0 }
public var isTuple: Bool { SILType_isTuple(bridged) != 0 }
public var isEnum: Bool { SILType_isEnum(bridged) != 0 }
public var tupleElements: TupleElementArray { TupleElementArray(type: self) }
public func getNominalFields(in function: Function) -> NominalFieldsArray {
NominalFieldsArray(type: self, function: function)
}
public func getIndexOfEnumCase(withName name: String) -> Int? {
let idx = name._withStringRef {
SILType_getCaseIdxOfEnumType(bridged, $0)
}
return idx >= 0 ? idx : nil
}
public var description: String {
String(_cxxString: SILType_debugDescription(bridged))
}
public var customMirror: Mirror { Mirror(self, children: []) }
}
extension Type: Equatable {
public static func ==(lhs: Type, rhs: Type) -> Bool {
lhs.bridged.typePtr == rhs.bridged.typePtr
}
}
public struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray {
fileprivate let type: Type
fileprivate let function: Function
public var startIndex: Int { return 0 }
public var endIndex: Int { SILType_getNumNominalFields(type.bridged) }
public subscript(_ index: Int) -> Type {
SILType_getNominalFieldType(type.bridged, index, function.bridged).type
}
public func getIndexOfField(withName name: String) -> Int? {
let idx = name._withStringRef {
SILType_getFieldIdxOfNominalType(type.bridged, $0)
}
return idx >= 0 ? idx : nil
}
public func getNameOfField(withIndex idx: Int) -> StringRef {
StringRef(bridged: SILType_getNominalFieldName(type.bridged, idx))
}
}
public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray {
fileprivate let type: Type
public var startIndex: Int { return 0 }
public var endIndex: Int { SILType_getNumTupleElements(type.bridged) }
public subscript(_ index: Int) -> Type {
SILType_getTupleElementType(type.bridged, index).type
}
}
extension BridgedType {
var type: Type { Type(bridged: self) }
}
| apache-2.0 | eace2b8468d108fc06eb16010c32bb47 | 31.872549 | 83 | 0.694304 | 4.104039 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Classes/Components/LeftAlignedIconButton.swift | 4 | 532 | @IBDesignable
class LeftAlignedIconButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
contentHorizontalAlignment = .left
let availableSpace = UIEdgeInsetsInsetRect(bounds, contentEdgeInsets)
let imageWidth = imageView?.frame.width ?? 0
let titleWidth = titleLabel?.frame.width ?? 0
let availableWidth = availableSpace.width - imageEdgeInsets.right - imageWidth * 2 - titleWidth
titleEdgeInsets = UIEdgeInsets(top: 0, left: floor(availableWidth) / 2, bottom: 0, right: 0)
}
}
| apache-2.0 | 390c6740ad308ca55ce35b36562b1113 | 39.923077 | 99 | 0.740602 | 4.925926 | false | false | false | false |
pusher/pusher-websocket-swift | Sources/Models/ChannelsProtocolCloseCode.swift | 2 | 3062 | import Foundation
// MARK: - Channels Protocol close codes
/// Describes closure codes as specified by the Pusher Channels Protocol.
///
/// These closure codes fall in the 4000 - 4999 range, i.e. the `privateCode` case of `NWProtocolWebSocket.CloseCode`.
///
/// Reference: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#error-codes
enum ChannelsProtocolCloseCode: UInt16 {
// MARK: - Channels Protocol reconnection strategies
/// Describes the reconnection strategy for a given `PusherChannelsProtocolCloseCode`.
///
/// Reference: https://pusher.com/docs/channels/library_auth_reference/pusher-websockets-protocol#connection-closure
enum ReconnectionStrategy: UInt16 {
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that attempting to reconnect using the same parameters will not succeed.
case doNotReconnectUnchanged
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that the client may reconnect after 1s or more.
case reconnectAfterBackingOff
/// Indicates an error resulting in the connection being closed by Pusher Channels,
/// and that the client may reconnect immediately.
case reconnectImmediately
/// Indicates that the reconnection strategy is unknown due to the closure code being
/// outside of the expected range as specified by the Pusher Channels Protocol.
case unknown
// MARK: - Initialization
init(rawValue: UInt16) {
switch rawValue {
case 4000...4099:
self = .doNotReconnectUnchanged
case 4100...4199:
self = .reconnectAfterBackingOff
case 4200...4299:
self = .reconnectImmediately
default:
self = .unknown
}
}
}
// 4000 - 4099
case applicationOnlyAcceptsSSLConnections = 4000
case applicationDoesNotExist = 4001
case applicationDisabled = 4003
case applicationIsOverConnectionQuota = 4004
case pathNotFound = 4005
case invalidVersionStringFormat = 4006
case unsupportedProtocolVersion = 4007
case noProtocolVersionSupplied = 4008
case connectionIsUnauthorized = 4009
// 4100 - 4199
case overCapacity = 4100
// 4200 - 4299
case genericReconnectImmediately = 4200
/// Ping was sent to the client, but no reply was received
case pongReplyNotReceived = 4201
/// Client has been inactive for a long time (currently 24 hours)
/// and client does not support ping.
case closedAfterInactivity = 4202
// MARK: - Public properties
var reconnectionStrategy: ReconnectionStrategy {
return ReconnectionStrategy(rawValue: self.rawValue)
}
}
| mit | f7d6cf314ed2ef36ac87ab411415f9f8 | 35.891566 | 120 | 0.642391 | 5.315972 | false | false | false | false |
dudash/swiftkick | Sources/Extensions/UITypes/UIImage+Tint.swift | 1 | 2605 | //
// UIImage+Tint.swift
// SwiftKick
// https://github.com/dudash/swiftkick
//
// Created by Jason on 1/28/16.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Jason Dudash
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#if !(SK_IGNORE_UIIMAGETINT) //legacy
#if !(SK_IGNORE_UIIMAGE)
import UIKit
extension UIImage {
public var halfSizeImage: UIImage? {
let halfWidth = self.size.width / 2
let halfHeight = self.size.height / 2
UIGraphicsBeginImageContext(CGSize(width: halfWidth, height: halfHeight))
self.draw(in: CGRect(x: 0, y: 0, width: halfWidth, height: halfHeight))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
//--------------------------------------------------------------------------
public func tint(_ color: UIColor, blendMode: CGBlendMode) -> UIImage {
let drawRect = CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
context!.clip(to: drawRect, mask: cgImage!)
color.setFill()
UIRectFill(drawRect)
draw(in: drawRect, blendMode: blendMode, alpha: 1.0)
let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return tintedImage!
}
}
#endif //#if SK_IGNORE_UIIMAGE
#endif //SK_IGNORE_UIIMAGETINT | mit | 200c0415d257d37e15e43d75fab426d6 | 39.092308 | 85 | 0.665259 | 4.491379 | false | false | false | false |
raulriera/HuntingCompanion | ProductHunt/UIViewControllerExt.swift | 1 | 1635 | //
// UIViewControllerExt.swift
// ProductHunt
//
// Created by Raúl Riera on 03/05/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
extension UIViewController {
func displayError(error: NSError) {
let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(action)
presentViewController(alertController, animated: true, completion: nil)
}
// If a navigation controller it will return the first visible view controller, otherwise
// it will return itself
var contentViewController: UIViewController {
if let navigationController = self as? UINavigationController {
return navigationController.visibleViewController
} else {
return self
}
}
/**
Helper method when using `sbconstants gem`.
Created by the guys at https://github.com/artsy/eidolon/
:param: identifier of the segue to perform
*/
public func performSegue(identifier:SegueIdentifier) {
performSegueWithIdentifier(identifier.rawValue, sender: self)
}
/**
Helper method to quickly fire a handoff to a given website
:param: url to handoff to
*/
public func updateUserActivityForWebsite(url: NSURL) {
let activity = NSUserActivity(activityType: "com.raulriera.producthunt.handoff.web")
activity.webpageURL = url
activity.becomeCurrent()
userActivity = activity
}
} | mit | 394fe85ae53f066c526631976332b22b | 31.058824 | 124 | 0.678703 | 4.996942 | false | false | false | false |
anilkumarbp/ringcentral-swift-NEW | ringcentral-swift-new/src/Auth.swift | 1 | 13678 | //
// Auth.swift
// src
//
// Created by Anil Kumar BP on 10/27/15.
// Copyright (c) 2015 Anil Kumar BP. All rights reserved.
//
import Foundation
/// Authorization object for the platform.
class Auth {
static let MAINCOMPANY = "101"
// Authorization information
var token_type: String?
var access_token: String?
var expires_in: Double = 0
var expire_time: Double = 0
// var app_key: String?
// var app_secret: String?
var refresh_token: String?
var refresh_token_expires_in: Double = 0
var refresh_token_expire_time: Double = 0
var scope: String?
var owner_id: String?
// let username: String
// let password: String
// let ext: String
// let server: String
//
// var authenticated: Bool = false
//Default constructor for the
init() {
// reset()
self.token_type = nil
self.access_token = nil
self.expires_in = 0
self.expire_time = 0
self.refresh_token = nil
self.refresh_token_expires_in = 0
self.refresh_token_expire_time = 0
self.scope = nil
self.owner_id = nil
}
/// Set the authentication data.
///
func setData(data: Dictionary<String, AnyObject>) -> Auth {
if data.count < 0 {
println("The count is :",data.count)
return self
}
// Misc
if let token_type = data["token_type"] as? String {
self.token_type = token_type
}
if let owner_id = data["owner_id"] as? String {
self.owner_id = owner_id
}
if let scope = data["scope"] as? String {
self.scope = scope
}
// Access Token
if let access_token = data["access_token"] as? String {
self.access_token = access_token
}
if let expires_in = data["expires_in"] as? Double {
self.expires_in = expires_in
}
if data["expire_time"] == nil {
if data["expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.expire_time = time + self.expires_in
}
}else if let expire_time = data["expire_time"] as? Double {
self.expire_time = expire_time
}
// Refresh Token
if let access_token = data["refresh_token"] as? String {
self.refresh_token = access_token
}
if let refresh_token_expires_in = data["refresh_token_expires_in"] as? Double {
self.refresh_token_expires_in = refresh_token_expires_in
}
if data["refresh_token_expire_time"] == nil {
if data["refresh_token_expires_in"] != nil {
let time = NSDate().timeIntervalSince1970
self.refresh_token_expire_time = time + self.refresh_token_expires_in
}
}else if let refresh_token_expire_time = data["refresh_token_expire_time"] as? Double {
self.refresh_token_expire_time = refresh_token_expire_time
}
return self
}
/// Reset the authentication data.
///
func reset() -> Void {
self.token_type = " ";
self.access_token = "";
self.expires_in = 0;
self.expire_time = 0;
self.refresh_token = "";
self.refresh_token_expires_in = 0;
self.refresh_token_expire_time = 0;
self.scope = "";
self.owner_id = "";
// return self
}
/// Return the authnetication data
func data()-> [String: AnyObject] {
var data: [String: AnyObject] = [:]
data["token_type"]=self.token_type
data["access_token"]=self.access_token
data["expires_in"]=self.expires_in
data["expire_time"]=self.expire_time
data["refresh_token"]=self.refresh_token
data["refresh_token_expires_in"]=self.refresh_token_expires_in
data["refresh_token_expire_time"]=self.refresh_token_expire_time
data["scope"]=self.scope
data["owner_id"]=self.owner_id
return data
}
/// Logs the user in with the current credentials.
///
/// :param: key The appKey for RC account
/// :param: secret The appSecret for RC account
// func login(key: String, secret: String) -> (NSData?, NSURLResponse?, NSError?) {
// self.app_key = key
// self.app_secret = secret
//
// // URL api call for getting token
//// let url = NSURL(string: server + "/restapi/oauth/token")
//
// // Setting up User info for parsing
// let bodyString = "grant_type=password&" + "username=" + self.username + "&" + "password=" + self.password + "&" + "extension=" + self.ext
// let plainData = (key + ":" + secret as NSString).dataUsingEncoding(NSUTF8StringEncoding)
// let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
//
// // Setting up HTTP request
// let request = NSMutableURLRequest(URL: url!)
// request.HTTPMethod = "POST"
// request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)
// request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
// request.setValue("application/json", forHTTPHeaderField: "Accept")
// request.setValue("Basic" + " " + base64String, forHTTPHeaderField: "Authorization")
//
// // Sending HTTP request
// var response: NSURLResponse?
// var error: NSError?
// let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
//
// if (response as! NSHTTPURLResponse).statusCode / 100 != 2 {
// return (data, response, error)
// }
//
// var errors: NSError?
// let readdata = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &errors) as! NSDictionary
//
// // Setting authentication information
// self.authenticated = true
// self.access_token = readdata["access_token"] as? String
// self.expires_in = readdata["expires_in"] as! Double
// self.refresh_token = readdata["refresh_token"] as? String
// self.refresh_token_expires_in = readdata["refresh_token_expires_in"] as! Double
// self.token_type = readdata["token_type"] as? String
// self.scope = readdata["scope"] as? String
// self.owner_id = readdata["owner_id"] as? String
// let time = NSDate().timeIntervalSince1970
// self.expire_time = time + self.expires_in
// self.refresh_token_expire_time = time + self.refresh_token_expires_in
//
// return (data, response, error)
//
// }
//
// /// Refreshes the access_token and refresh_token with the current refresh_token
// ///
// /// :returns: tuple for responses
// func refresh() -> (NSData?, NSURLResponse?, NSError?) {
// // URL api call for getting token
// let url = NSURL(string: server + "/oauth/token")
//
// // Setting up User info for parsing
// var bodyString = "grant_type=refresh_token&" + "username=" + self.username + "&" + "password=" + self.password + "&" + "extension=" + self.ext + "&" + "refresh_token=" + self.refresh_token!
// let plainData = (self.app_key! + ":" + self.app_secret! as NSString).dataUsingEncoding(NSUTF8StringEncoding)
// let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
//
// // Setting up HTTP request
// let request = NSMutableURLRequest(URL: url!)
// request.HTTPMethod = "POST"
// request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)
// request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
// request.setValue("application/json", forHTTPHeaderField: "Accept")
// request.setValue("Basic" + " " + base64String, forHTTPHeaderField: "Authorization")
//
// // Sending HTTP request
// var response: NSURLResponse?
// var error: NSError?
// let data: NSData! = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
// var errors: NSError?
// let readdata = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &errors) as! NSDictionary
//
// // Setting authentication information
// self.authenticated = true
// self.access_token = readdata["access_token"] as? String
// self.expires_in = readdata["expires_in"] as! Double
// self.refresh_token = readdata["refresh_token"] as? String
// self.refresh_token_expires_in = readdata["refresh_token_expires_in"] as! Double
// self.token_type = readdata["token_type"] as? String
// self.scope = readdata["scope"] as? String
// self.owner_id = readdata["owner_id"] as? String
// let time = NSDate().timeIntervalSince1970
// self.expire_time = time + self.expires_in
// self.refresh_token_expire_time = time + self.refresh_token_expires_in
//
// return (data, response, error)
//
// }
/// Checks whether or not the access token is valid
///
/// :returns: A boolean for validity of access token
func isAccessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if(self.expire_time > time) {
return true
}
return false
}
/// Checks for the validity of the refresh token
///
/// :returns: A boolean for validity of the refresh token
func isRefreshTokenVald() -> Bool {
return false
}
/// Revokes the access_token
///
/// :returns: tuple for response
// func revokeToken() -> (NSData?, NSURLResponse?, NSError?) {
// let url = NSURL(string: server + "/oauth/revoke")
//
//
// // Setting up User info for parsing
// let bodyString = "token=" + access_token!
// let plainData = (app_key! + ":" + app_secret! as NSString).dataUsingEncoding(NSUTF8StringEncoding)
// let base64String = plainData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
//
// // Setting up request
// let request = NSMutableURLRequest(URL: url!)
// request.HTTPMethod = "POST"
// request.HTTPBody = bodyString.dataUsingEncoding(NSUTF8StringEncoding)
// request.setValue("application/x-www-form-urlencoded;charset=UTF-8", forHTTPHeaderField: "Content-Type")
// request.setValue("application/json", forHTTPHeaderField: "Accept")
// request.setValue("Basic" + " " + base64String, forHTTPHeaderField: "Authorization")
//
// var response: NSURLResponse?
// var error: NSError?
// let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
//
// self.access_token = nil
// self.expires_in = 0
// self.expire_time = 0
// self.refresh_token = nil
// self.refresh_token_expires_in = 0
// self.refresh_token_expire_time = 0
//
// return (data, response, error)
// }
//
/// Returns the 'access token'
///
/// :returns: String of 'access token'
func accessToken() -> String {
return self.access_token!
}
/// Returns the 'refresh token'
///
/// :returns: String of 'refresh token'
func refreshToken() -> String {
return self.refresh_token!
}
/// Returns the 'tokenType'
///
/// :returns: String of 'token Type'
func tokenType() -> String {
return self.token_type!
}
/// Returns bool if 'accessTokenValid'
///
/// :returns: Bool if 'access token valid'
func accessTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.expire_time > time {
return true
}
return false
}
/// Returns bool if 'refreshTokenValid'
///
/// :returns: String of 'refresh token valid'
func refreshTokenValid() -> Bool {
let time = NSDate().timeIntervalSince1970
if self.refresh_token_expire_time > time {
return true
}
return false
}
/// Returns the 'username'
///
/// :returns: String of 'username'
// func getUsername() -> String {
// return self.username
// }
//
// /// Returns the access token
///
/// :returns: String of access token
// func getAppKey() -> String {
// return self.app_key!
// }
/// Returns the 'app secret'
///
/// :returns: String of 'app secret'
// func getAppSecret() -> String {
// return self.app_secret!
// }
//
/// Returns the 'extension'
///
// /// :returns: String of 'extension'
// func getExtension() -> String {
// return self.ext
// }
} | mit | bc26a11cd99f4434305dbc804f59e52f | 35.092348 | 203 | 0.560535 | 4.255756 | false | false | false | false |
jonnguy/HSTracker | HSTracker/ArenaHelper/ArenaWatcher.swift | 2 | 3489 | //
// Created by Benjamin Michotte on 25/02/17.
// Copyright (c) 2017 Benjamin Michotte. All rights reserved.
//
import Foundation
import Unbox
class ArenaWatcher: Watcher {
static let _instance = ArenaWatcher()
static func start(handler: PowerEventHandler) {
_instance.handler = handler
_instance.startWatching()
}
static func stop() {
_instance.stopWatching()
}
static func isRunning() -> Bool {
return _instance.isRunning
}
private let heroes: [CardClass] = [
.warrior,
.shaman,
.rogue,
.paladin,
.hunter,
.druid,
.warlock,
.mage,
.priest
]
static var hero: CardClass = .neutral
private var cardTiers: [ArenaCard] = []
private var currentCards: [String] = []
private var handler: PowerEventHandler?
override func run() {
if cardTiers.count == 0 {
loadCardTiers()
}
while isRunning {
guard let choices = MirrorHelper.getArenaDraftChoices() else {
Thread.sleep(forTimeInterval: refreshInterval)
continue
}
if choices.count != 3 {
Thread.sleep(forTimeInterval: refreshInterval)
continue
}
var cards: [Card] = []
for mirrorCard in choices {
if let cardInfo = cardTiers.first(where: { $0.id == mirrorCard.cardId }),
let card = Cards.by(cardId: mirrorCard.cardId),
let index = heroes.index(of: ArenaWatcher.hero) {
let value = cardInfo.values[index]
let costs = value.matches("([0-9]+)")
card.cost = Int(costs.first?.value ?? "0") ?? 0
card.isBadAsMultiple = value.contains("*")
card.count = 1
cards.append(card)
}
}
if cards.count == 3 {
let ids = cards.map { $0.id }
if ids.sorted() != currentCards.sorted() {
logger.debug("cards: \(cards)")
currentCards = ids
handler?.setArenaOptions(cards: cards.sorted { $0.cost > $1.cost })
}
}
Thread.sleep(forTimeInterval: refreshInterval)
}
handler?.setArenaOptions(cards: [])
queue = nil
}
private func loadCardTiers() {
let jsonFile = Paths.arenaJson.appendingPathComponent("cardtier.json")
var jsonData = try? Data(contentsOf: jsonFile)
if jsonData != nil {
logger.info("Using \(jsonFile)")
} else {
logger.error("\(jsonFile) is not a valid file")
let cardFile = URL(fileURLWithPath:
"\(Bundle.main.resourcePath!)/Resources/cardtier.json")
jsonData = try? Data(contentsOf: cardFile)
}
guard let data = jsonData else {
logger.warning("Can not load cardtier.json")
return
}
guard let cardTiers: [ArenaCard] = try? unbox(data: data) else {
logger.warning("Can not parse cardtier.json")
return
}
self.cardTiers = cardTiers
}
}
struct ArenaCard {
let id: String
let values: [String]
}
extension ArenaCard: Unboxable {
init(unboxer: Unboxer) throws {
self.id = try unboxer.unbox(key: "id")
self.values = try unboxer.unbox(key: "value")
}
}
| mit | 6a5e15e1e2214351f6ffe661670b3200 | 26.912 | 89 | 0.537976 | 4.32342 | false | false | false | false |
v2panda/DaysofSwift | swift2.3/My-Where/My-Where/ViewController.swift | 1 | 2462 | //
// ViewController.swift
// My-Where
//
// Created by Panda on 16/2/22.
// Copyright © 2016年 v2panda. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var locationLabel: UILabel!
var locationManager : CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
@IBAction func findButtonDidTouched(sender: AnyObject) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) -> Void in
if error != nil {
self.locationLabel.text = "Reverse geocoder failed with error" + error!.localizedDescription
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
}else{
self.locationLabel.text = "Problem with the data received from geocoder"
}
}
}
func displayLocationInfo(placemark: CLPlacemark?){
if let containsPlacemark = placemark {
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
self.locationLabel.text = locality! + postalCode! + administrativeArea! + country!
}
}
}
| mit | b8c53f4885a6128e35ba186a193b7b78 | 31.786667 | 126 | 0.633998 | 6.05665 | false | false | false | false |
mohssenfathi/MTLImage | MTLImage/Sources/Filters/Histogram.swift | 1 | 3267 | //
// Histogram.swift
// MTLImage
//
// Created by Mohssen Fathi on 8/24/17.
//
import MetalPerformanceShaders
public
class Histogram: MPS {
@objc public var numberOfEntries: Int = 256 {
didSet {
reloadKernel()
needsUpdate = true
}
}
public var newHistogramAvailable: (((red: [UInt32], green: [UInt32], blue: [UInt32], alpha: [UInt32])) -> ())?
public var red: [UInt32]!
public var green: [UInt32]!
public var blue: [UInt32]!
public var alpha: [UInt32]!
private var histogramValues: [UInt32] = []
private var histogramBuffer: MTLBuffer!
public init() {
super.init(functionName: nil)
commonInit()
}
override init(functionName: String?) {
super.init(functionName: nil)
commonInit()
}
func reloadKernel() {
red = [UInt32](repeating: 0, count: numberOfEntries)
green = [UInt32](repeating: 0, count: numberOfEntries)
blue = [UInt32](repeating: 0, count: numberOfEntries)
var info = MPSImageHistogramInfo(
numberOfHistogramEntries: numberOfEntries,
histogramForAlpha: true,
minPixelValue: vector_float4([0, 0, 0, 0]),
maxPixelValue: vector_float4([1, 1, 1, 1])
)
kernel = MPSImageHistogram(device: context.device, histogramInfo: &info)
(kernel as! MPSImageHistogram).zeroHistogram = true
}
override func update() {
super.update()
guard histogramBuffer != nil else { return }
let pointer = histogramBuffer.contents().assumingMemoryBound(to: UInt32.self)
let bufferPointer = UnsafeBufferPointer(start: pointer, count: histogramBuffer.length)
histogramValues = [UInt32](bufferPointer)
let len = numberOfEntries
red = [UInt32](histogramValues[len * 0 ..< len * 1])
green = [UInt32](histogramValues[len * 1 ..< len * 2])
blue = [UInt32](histogramValues[len * 2 ..< len * 3])
alpha = [UInt32](histogramValues[len * 3 ..< len * 4])
newHistogramAvailable?((red, green, blue, alpha))
}
public override func process() {
texture = input?.texture
super.process()
}
override func configureCommandBuffer(_ commandBuffer: MTLCommandBuffer) {
super.configureCommandBuffer(commandBuffer)
guard let inputTexture = input?.texture else { return }
let bufferLength = (kernel as! MPSImageHistogram).histogramSize(forSourceFormat: inputTexture.pixelFormat)/MemoryLayout<UInt32>.size
histogramBuffer = device.makeBuffer(length: bufferLength, options: [.storageModePrivate])
(kernel as! MPSImageHistogram).encode(
to: commandBuffer,
sourceTexture: inputTexture,
histogram: histogramBuffer,
histogramOffset: 0
)
}
func commonInit() {
title = "Histogram"
properties = [Property(key: "numberOfEntries", title: "Number of Entries")]
reloadKernel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | e8452fb82d3eb0c90ccab340819d592b | 28.972477 | 140 | 0.597796 | 4.634043 | false | false | false | false |
BalestraPatrick/Tweetometer | Carthage/Checkouts/Presentr/Presentr/KeyboardTranslation.swift | 2 | 2908 | //
// KeyboardTranslation.swift
// Presentr
//
// Created by Aaron Satterfield on 7/15/16.
// Copyright © 2016 danielozano. All rights reserved.
//
import Foundation
import UIKit
public enum KeyboardTranslationType {
case none
case moveUp
case compress
case stickToTop
/**
Calculates the correct frame for the keyboard translation type.
- parameter keyboardFrame: The UIKeyboardFrameEndUserInfoKey CGRect Value of the Keyboard
- parameter presentedFrame: The frame of the presented controller that may need to be translated.
- returns: CGRect representing the new frame of the presented view.
*/
public func getTranslationFrame(keyboardFrame: CGRect, presentedFrame: CGRect) -> CGRect {
let keyboardTop = UIScreen.main.bounds.height - keyboardFrame.size.height
let buffer: CGFloat = (presentedFrame.origin.y + presentedFrame.size.height == UIScreen.main.bounds.height) ? 0 : 20.0 // add a 20 pt buffer except when the presentedFrame is stick to bottom
let presentedViewBottom = presentedFrame.origin.y + presentedFrame.height + buffer
let offset = presentedViewBottom - keyboardTop
switch self {
case .moveUp:
if offset > 0.0 {
let frame = CGRect(x: presentedFrame.origin.x, y: presentedFrame.origin.y-offset, width: presentedFrame.size.width, height: presentedFrame.size.height)
return frame
}
return presentedFrame
case .compress:
if offset > 0.0 {
let y = max(presentedFrame.origin.y-offset, 20.0)
let newHeight = y != 20.0 ? presentedFrame.size.height : keyboardTop - 40.0
let frame = CGRect(x: presentedFrame.origin.x, y: y, width: presentedFrame.size.width, height: newHeight)
return frame
}
return presentedFrame
case .stickToTop:
if offset > 0.0 {
let y = max(presentedFrame.origin.y-offset, 20.0)
let frame = CGRect(x: presentedFrame.origin.x, y: y, width: presentedFrame.size.width, height: presentedFrame.size.height)
return frame
}
return presentedFrame
case .none:
return presentedFrame
}
}
}
// MARK: Notification + UIKeyboardInfo
extension Notification {
/// Gets the optional CGRect value of the UIKeyboardFrameEndUserInfoKey from a UIKeyboard notification
func keyboardEndFrame () -> CGRect? {
return (self.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
}
/// Gets the optional AnimationDuration value of the UIKeyboardAnimationDurationUserInfoKey from a UIKeyboard notification
func keyboardAnimationDuration () -> Double? {
return (self.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
}
}
| mit | 4ac34c6f9a27a8fead0999931a55289d | 39.375 | 198 | 0.666323 | 5.029412 | false | false | false | false |
piresivan/coredata-swift-2.0 | CoreData/AppDelegate.swift | 1 | 6443 | //
// AppDelegate.swift
// CoreData
//
// Created by Lucas Conceição on 17/08/14.
// Copyright (c) 2014 Lucas Conceicao. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
//Good Times Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.lucasconceicao.blog.CoreData" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoreData", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL!)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreData.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch var error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| gpl-2.0 | 88b97ed2be03e1c125c07e02809c1b8f | 52.231405 | 290 | 0.696941 | 5.850136 | false | false | false | false |
2794129697/-----mx | CoolXuePlayer/RegisterViewController.swift | 1 | 5350 | //
// RegisterViewController.swift
// CoolXuePlayer
//
// Created by lion-mac on 15/6/4.
// Copyright (c) 2015年 lion-mac. All rights reserved.
//
import UIKit
class RegisterViewController: UIViewController,UITextFieldDelegate,UIAlertViewDelegate{
@IBOutlet weak var userIdTextField: UITextField!
@IBOutlet weak var pwdTextField: UITextField!
@IBOutlet weak var pwdAgainTextField: UITextField!
@IBOutlet weak var jobTextField: UITextField!
@IBOutlet weak var bnSelectJop: UIButton!
var alertView:UIAlertView!
var popView:uiPopView!
var job:Int!
//实现job选择后的回调函数
func selectionHandler(selectedItem:NSDictionary){
self.popView = nil
jobTextField.text = selectedItem["name"] as! String
self.job = selectedItem["id"] as! Int
}
//展开职业选项
@IBAction func bnSelectJobClicked(sender: UIButton) {
let btn = sender
if self.popView == nil {
self.popView = uiPopView(selectedItemCallBack: self.selectionHandler)
self.popView.showDropDown(sender.superview!, frame: sender.frame, bounds: sender.bounds)
}else{
self.popView.hideDropDown()
self.popView = nil
}
}
func showAlertView(tag _tag:Int,title:String,message:String,delegate:UIAlertViewDelegate,cancelButtonTitle:String){
if alertView == nil {
alertView = UIAlertView()
}
alertView.title = title
alertView.message = message
alertView.delegate = self
alertView.addButtonWithTitle(cancelButtonTitle)
alertView.tag = _tag
alertView.show()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.registerBnClicked("")
self.userIdTextField.resignFirstResponder()
self.pwdTextField.resignFirstResponder()
self.pwdAgainTextField.resignFirstResponder()
return true
}
@IBAction func registerBnClicked(sender: AnyObject) {
var userid = self.userIdTextField.text
var pwd = self.pwdTextField.text
var pwdAgain = self.pwdAgainTextField.text
if userid.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
self.showAlertView(tag: 0,title: "提示", message: "用户名不能为空!", delegate: self, cancelButtonTitle: "确定")
return
}
if self.job == nil {
self.showAlertView(tag: 0,title: "提示", message: "请选择职业!", delegate: self, cancelButtonTitle: "确定")
return
}
if pwd.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
self.showAlertView(tag: 0,title: "提示", message: "密码不能为空!", delegate: self, cancelButtonTitle: "确定")
return
}
if pwdAgain.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
self.showAlertView(tag: 0,title: "提示", message: "确认密码不能为空!", delegate: self, cancelButtonTitle: "确定")
return
}
if pwd != pwdAgain {
self.showAlertView(tag: 0,title: "提示", message: "两次密码输入不一致!", delegate: self, cancelButtonTitle: "确定")
return
}
var url = "http://www.icoolxue.com/account/register"
var bodyParam:NSDictionary = ["username":userid,"job":self.job!,"password":pwd,"passwordAgain":pwdAgain]
HttpManagement.requestttt(url, method: "POST",bodyParam: bodyParam as! Dictionary<String, AnyObject>,headParam:nil) { (repsone:NSHTTPURLResponse,data:NSData) -> Void in
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
println(bdict)
var code:Int = bdict["code"] as! Int
if HttpManagement.HttpResponseCodeCheck(code, viewController: self){
self.showAlertView(tag: 1,title: "提示", message: "注册成功!", delegate: self, cancelButtonTitle: "确定")
}else{
self.showAlertView(tag: 0,title: "提示", message: "注册失败!", delegate: self, cancelButtonTitle: "确定")
}
}
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
println("buttonIndex=\(buttonIndex)")
if alertView.tag == 0 {
}else if alertView.tag == 1 {
self.navigationController?.popViewControllerAnimated(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.userIdTextField.delegate = self
self.pwdTextField.delegate = self
self.pwdAgainTextField.delegate = self
// 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.
}
*/
}
| lgpl-3.0 | 70a13c5eced9f2f524d388d75c6a69be | 38.692308 | 176 | 0.64845 | 4.627803 | false | false | false | false |
ShamylZakariya/Squizit | Squizit/Views/RootBorderView.swift | 1 | 2777 | //
// RootBorderView.swift
// Squizit
//
// Created by Shamyl Zakariya on 9/16/14.
// Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import UIKit
class RootBorderView : UIView {
var topLeftColor:UIColor = UIColor(red: 0.49, green: 1, blue: 0, alpha: 1) {
didSet {
setNeedsDisplay()
}
}
var bottomRightColor:UIColor = UIColor(red: 1, green: 0, blue: 0.71, alpha: 1) {
didSet {
setNeedsDisplay()
}
}
var borderSize:Int = 32 {
didSet {
setNeedsDisplay()
}
}
var edgeInsets:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) {
didSet {
setNeedsDisplay()
}
}
override func drawRect(rect: CGRect) {
var context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextTranslateCTM(context, 0.5, 0.5)
let frame = UIEdgeInsetsInsetRect(bounds, edgeInsets)
let borderSize = CGFloat(self.borderSize)
func plot( x:Int, y:Int ) -> CGPoint {
let px = x >= 0 ? frame.minX + CGFloat(x) * borderSize : frame.maxX + CGFloat(x)*borderSize
let py = y >= 0 ? frame.minY + CGFloat(y) * borderSize : frame.maxY + CGFloat(y)*borderSize
return CGPoint( x: px, y: py )
}
func m( p:CGPoint ) {
CGContextMoveToPoint(context, p.x, p.y)
}
func l( p:CGPoint ) {
CGContextAddLineToPoint(context, p.x, p.y)
}
m(plot( 1, y: 1))
l(plot( 2, y: 1))
l(plot( 2,y: -1))
l(plot( 1,y: -1))
l(plot( 1,y: -2))
l(plot(-1,y: -2))
l(plot(-1,y: -1))
l(plot(-2,y: -1))
l(plot(-2, y: 1))
l(plot(-1, y: 1))
l(plot(-1, y: 2))
l(plot( 1, y: 2))
CGContextClosePath(context)
m(plot( 3, y: 1))
l(plot(-3, y: 1))
l(plot(-3, y: 3))
l(plot(-1, y: 3))
l(plot(-1,y: -3))
l(plot(-3,y: -3))
l(plot(-3,y: -1))
l(plot( 3,y: -1))
l(plot( 3,y: -3))
l(plot( 1,y: -3))
l(plot( 1, y: 3))
l(plot( 3, y: 3))
CGContextClosePath(context)
CGContextSetLineWidth(context, 1)
CGContextSetLineCap(context, CGLineCap.Square)
CGContextReplacePathWithStrokedPath(context)
CGContextClip(context)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(colorSpace, [topLeftColor.CGColor,bottomRightColor.CGColor], [0.0,1.0])
let topLeft = plot(1,y: 1)
let bottomRight = plot(-1,y: -1)
CGContextDrawLinearGradient(context, gradient, topLeft, bottomRight, CGGradientDrawingOptions(rawValue: 0))
// fix a rendering error on retina where the top left point of the path isn't drawn
let pointRect = CGRect(center: plot(1,y: 1), radius: 0.5)
CGContextSetFillColorWithColor(context, topLeftColor.CGColor)
CGContextFillRect(context, pointRect)
CGContextRestoreGState(context)
}
override func awakeFromNib() {
contentMode = UIViewContentMode.Redraw
opaque = false
backgroundColor = UIColor.clearColor()
}
}
| mit | 939b2e01af7a5365406abbcaf9b1ebed | 23.147826 | 115 | 0.657184 | 2.848205 | false | false | false | false |
yuxiuyu/TrendBet | TrendBetting_0531换首页/Pods/Charts/Source/Charts/Highlight/RadarHighlighter.swift | 7 | 2460 | //
// RadarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(RadarChartHighlighter)
open class RadarHighlighter: PieRadarHighlighter
{
open override func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight?
{
guard let chart = self.chart as? RadarChartView else { return nil }
let highlights = getHighlights(forIndex: index)
let distanceToCenter = Double(chart.distanceToCenter(x: x, y: y) / chart.factor)
var closest: Highlight?
var distance = Double.greatestFiniteMagnitude
for high in highlights
{
let cdistance = abs(high.y - distanceToCenter)
if cdistance < distance
{
closest = high
distance = cdistance
}
}
return closest
}
/// - returns: An array of Highlight objects for the given index.
/// The Highlight objects give information about the value at the selected index and DataSet it belongs to.
///
/// - parameter index:
internal func getHighlights(forIndex index: Int) -> [Highlight]
{
var vals = [Highlight]()
guard
let chart = self.chart as? RadarChartView,
let chartData = chart.data
else { return vals }
let phaseX = chart.chartAnimator.phaseX
let phaseY = chart.chartAnimator.phaseY
let sliceangle = chart.sliceAngle
let factor = chart.factor
for i in chartData.dataSets.indices
{
guard
let dataSet = chartData.getDataSetByIndex(i),
let entry = dataSet.entryForIndex(index)
else { continue }
let y = (entry.y - chart.chartYMin)
let p = chart.centerOffsets.moving(distance: CGFloat(y) * factor * CGFloat(phaseY),
atAngle: sliceangle * CGFloat(index) * CGFloat(phaseX) + chart.rotationAngle)
let highlight = Highlight(x: Double(index), y: entry.y, xPx: p.x, yPx: p.y, dataSetIndex: i, axis: dataSet.axisDependency)
vals.append(highlight)
}
return vals
}
}
| apache-2.0 | 95e51dff84f2bac5b3d1f2a3b9b7af63 | 30.538462 | 134 | 0.581301 | 4.949698 | false | false | false | false |
shujincai/DouYu | DouYu/DouYu/Classes/Home/Controller/RecommendViewController.swift | 1 | 7348 | //
// RecommendViewController.swift
// DouYu
//
// Created by pingtong on 2017/6/20.
// Copyright © 2017年 PTDriver. All rights reserved.
//
import UIKit
import SDCycleScrollView
fileprivate let KNormalCellID = "KNormalCellID"
fileprivate let KHeaderViewID = "KHeaderViewID"
fileprivate let KPrettyCellID = "CollectionPrettyCell"
fileprivate let KCycleViewH = KScreenW * 3 / 8
fileprivate let KItemMargin: CGFloat = 10.0
fileprivate let KItemW = (KScreenW - 3*KItemMargin)/2
fileprivate let KNormalItemH = KItemW * 3/4
fileprivate let KPrettyItemH = KItemW * 4/3
fileprivate let KHeaderViewH: CGFloat = 50
fileprivate let KGameViewH: CGFloat = 90
class RecommendViewController: UIViewController {
//MARK:- 懒加载属性
fileprivate lazy var recommendVM: RecommendViewModel = RecommendViewModel()
fileprivate lazy var cycleScrollView: SDCycleScrollView = {
let cycleScrollView = SDCycleScrollView(frame: CGRect(x: 0, y: -(KCycleViewH+KGameViewH), width: KScreenW, height: KCycleViewH))
cycleScrollView.currentPageDotColor = UIColor.orange
cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight
return cycleScrollView
}()
fileprivate lazy var collectionView: UICollectionView = { [unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: KItemW, height: KNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = KItemMargin
layout.headerReferenceSize = CGSize(width: KScreenW, height: KHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
//创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: KNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: KPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: KHeaderViewID)
return collectionView
}()
fileprivate lazy var gameView: RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -KGameViewH, width: KScreenW, height: KGameViewH)
return gameView
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
//发送网络请求
loadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK:- 设置ui界面
extension RecommendViewController {
fileprivate func setupUI() {
// 1.将UICollectionView添加到控制器的View中
view.addSubview(collectionView)
// 2.将cycleScrollVIew添加到UICollectionView
collectionView.addSubview(cycleScrollView)
// 3.将gameView添加collectionView中
collectionView.addSubview(gameView)
// 3.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: KCycleViewH + KGameViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 遵守UICollectionView的数据源协议
extension RecommendViewController: UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
if recommendVM.cycleGroup == nil {
return 0
}
return (recommendVM.cycleGroup?.data?.count)! + 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return (recommendVM.bigDataGroup?.data?.count)!
}else if (section == 1) {
return (recommendVM.prettyGroup?.data?.count)!
}else {
return (recommendVM.cycleGroup?.data![section-2].room_list?.count)!
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KPrettyCellID, for: indexPath) as? CollectionPrettyCell
cell?.anchor = recommendVM.prettyGroup?.data?[indexPath.item]
return cell!
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KNormalCellID, for: indexPath) as? CollectionNormalCell
if indexPath.section == 0 {
cell?.anchorHot = recommendVM.bigDataGroup?.data?[indexPath.item]
}else {
cell?.anchor = recommendVM.cycleGroup?.data?[indexPath.section-2].room_list?[indexPath.item]
}
return cell!
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: KHeaderViewID, for: indexPath) as! CollectionHeaderView
if indexPath.section == 0 {
headerView.titleLbael.text = "热门"
headerView.iconImageView.image = #imageLiteral(resourceName: "home_header_hot")
} else if (indexPath.section == 1) {
headerView.titleLbael.text = "颜值"
headerView.iconImageView.image = #imageLiteral(resourceName: "home_header_phone")
}else {
headerView.titleLbael.text = recommendVM.cycleGroup?.data?[indexPath.section-2].tag_name
headerView.iconImageView.image = #imageLiteral(resourceName: "home_header_normal")
}
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: KItemW, height: KPrettyItemH)
}else{
return CGSize(width: KItemW, height: KNormalItemH)
}
}
}
// MARK:- 请求数据
extension RecommendViewController {
fileprivate func loadData() {
//请推荐数据
recommendVM.requsetData {
// 1. 显示推荐数据
self.collectionView.reloadData()
// 2.将数据传递给GameView
self.gameView.groups = self.recommendVM.cycleGroup
}
//请求轮播数据
recommendVM.requestCycleData { (cycle) in
var imageGroup = [String]()
var titleGroup = [String]()
for data in cycle.data! {
imageGroup.append(data.pic_url!)
titleGroup.append(data.title!)
}
self.cycleScrollView.imageURLStringsGroup = imageGroup
self.cycleScrollView.titlesGroup = titleGroup
}
}
}
| mit | a9afa8412764f78299203d671ba8c64a | 43.042945 | 186 | 0.683382 | 5.146237 | false | false | false | false |
haskellswift/swift-package-manager | Sources/PackageDescription/JSON.swift | 2 | 1678 | /*
This source file is part of the Swift.org open source project
Copyright 2015 - 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
/// A very minimal JSON type to serialize the manifest.
// FIXME: A more complete JSON type is already present in Basic but
// it needs to discussed if and how PackageDescription should handle
// dependencies.
enum JSON {
case null
case int(Int)
case double(Double)
case bool(Bool)
case string(String)
case array([JSON])
case dictionary([String: JSON])
}
extension JSON {
/// Converts the JSON to string representation.
// FIXME: No escaping implemented for now.
func toString() -> String {
switch self {
case .null:
return "null"
case .bool(let value):
return value ? "true" : "false"
case .int(let value):
return value.description
case .double(let value):
return value.debugDescription
case .string(let value):
return "\"" + value + "\""
case .array(let contents):
return "[" + contents.map{ $0.toString() }.joined(separator: ", ") + "]"
case .dictionary(let contents):
var output = "{"
for (i, key) in contents.keys.sorted().enumerated() {
if i != 0 { output += ", " }
output += "\"" + key + "\"" + ": " + contents[key]!.toString()
}
output += "}"
return output
}
}
}
| apache-2.0 | 747572e3db2701793553de37772c87e6 | 31.269231 | 84 | 0.587604 | 4.474667 | false | false | false | false |
AaronMT/firefox-ios | Client/DocumentServicesHelper.swift | 8 | 2647 | /* 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 Shared
import Storage
import NaturalLanguage
protocol DocumentAnalyser {
var name: String { get }
associatedtype NewMetadata
func analyse(metadata: PageMetadata) -> NewMetadata?
}
struct LanguageDetector: DocumentAnalyser {
let name = "language" //This key matches the DerivedMetadata property
typealias NewMetadata = String //This matches the value for the DerivedMetadata key above
func analyse(metadata: PageMetadata) -> LanguageDetector.NewMetadata? {
if let metadataLanguage = metadata.language {
return metadataLanguage
}
// Lets not use any language detection until we can pass more text to the language detector
return nil // https://bugzilla.mozilla.org/show_bug.cgi?id=1519503
/*
guard let text = metadata.description else { return nil }
let language: String?
if #available(iOS 12.0, *) {
language = NLLanguageRecognizer.dominantLanguage(for: text)?.rawValue
} else {
language = NSLinguisticTagger.dominantLanguage(for: text)
}
return language
*/
}
}
struct DerivedMetadata: Codable {
let language: String?
// New keys need to be mapped in this constructor
static func from(dict: [String: Any?]) -> DerivedMetadata? {
return DerivedMetadata(language: dict["language"] as? String)
}
}
class DocumentServicesHelper: TabEventHandler {
private lazy var singleThreadedQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Document Services queue"
queue.maxConcurrentOperationCount = 1
queue.qualityOfService = .userInitiated
return queue
}()
init() {
register(self, forTabEvents: .didLoadPageMetadata)
}
func tab(_ tab: Tab, didLoadPageMetadata metadata: PageMetadata) {
singleThreadedQueue.addOperation {
// New analyzers go here. We map through each one and reduce into one dictionary
let analyzers = [LanguageDetector()]
let dict = analyzers.map({ [$0.name: $0.analyse(metadata: metadata)] }).compactMap({$0}).reduce([:]) { $0.merging($1) { (current, _) in current } }
guard let derivedMetadata = DerivedMetadata.from(dict: dict) else { return }
DispatchQueue.main.async {
TabEvent.post(.didDeriveMetadata(derivedMetadata), for: tab)
}
}
}
}
| mpl-2.0 | e51e1775d96fb0975c9a24706cd1fb1f | 35.763889 | 159 | 0.659615 | 4.595486 | false | false | false | false |
NorthFacing/blog4j | src/test/temp/main.swift | 3 | 2531 | print("Hello, swift!")
// 使用func来声明一个函数,使用名字和参数来调用函数。使用->来指定函数返回值的类型。
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
let result1 = greet(person:"Bob", day: "Tuesday") // person 和 day 为默认参数标签
print(result1)
// 默认情况下,函数使用它们的参数名称作为它们参数的标签,在参数名称前可以自定义参数标签,或者使用 _ 表示不使用参数标签。
func greet(_ person: String, on day: String) -> String { // TODO function name could be the same one, sa long as they have different params
return "Hello \(person), today is \(day)."
}
let result2 = greet("John", on: "Wednesday") // on 为自定义参数标签
print(result2)
// 使用元组来让一个函数返回多个值。该元组的元素可以用名称或数字来表示。
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics(scores:[5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
// 可变个数的参数
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers { // 参数 numbers 在函数内表现为数组的形式
sum += number
}
return sum
}
let sum1 = sumOf()
print(sum1)
let sum2 = sumOf(numbers: 42, 597, 12)
print(sum2)
// 函数可以嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
let add = returnFifteen()
print(add)
// 函数是第一等类型
// -- 这意味着函数可以作为另一个函数的返回值。
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
let increm = increment(7)
print(increm)
// -- 也可以当做参数传入另一个函数。
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
let match = hasAnyMatches(list: numbers, condition: lessThanTen)
print(match)
| gpl-2.0 | e70f3fb7aa221dacfbf1d52aa6c03251 | 21.37234 | 139 | 0.616738 | 3.157658 | false | false | false | false |
JohnPJenkins/swift-t | stc/docs/gallery/mtc/mtc3.swift | 2 | 310 | import files;
import string;
import unix;
app (file o) g(string s)
{
"/bin/echo" s @stdout=o;
}
string lines[] = file_lines(input("mtc3.swift"));
file fragments[];
foreach line,i in lines
{
file y <sprintf("out-%i.txt",i)> = g(line);
fragments[i] = y;
}
file result <"assembled.txt"> = cat(fragments);
| apache-2.0 | 660f55c65f16ee9d8a54f60a9ce2fde5 | 17.235294 | 49 | 0.645161 | 2.649573 | false | false | false | false |
xwu/swift | test/Interop/Cxx/namespace/classes-module-interface.swift | 2 | 2327 | // RUN: %target-swift-ide-test -print-module -module-to-print=Classes -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s
// CHECK: enum ClassesNS1 {
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS2 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: struct ForwardDeclaredStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS3 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: mutating func basicMember() -> UnsafePointer<CChar>!
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias GlobalAliasToNS1 = ClassesNS1
// CHECK-NEXT: enum ClassesNS4 {
// CHECK-NEXT: typealias AliasToGlobalNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasToGlobalNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToInnerNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: typealias AliasToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: typealias AliasChainToNS1 = ClassesNS1
// CHECK-NEXT: typealias AliasChainToNS2 = ClassesNS1.ClassesNS2
// CHECK-NEXT: }
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToAnotherNS5 = ClassesNS4.ClassesNS5
// CHECK-NEXT: enum ClassesNS5 {
// CHECK-NEXT: struct BasicStruct {
// CHECK-NEXT: init()
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToNS5NS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
// CHECK-NEXT: typealias AliasToGlobalNS5 = ClassesNS5
// CHECK-NEXT: typealias AliasToLocalNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: typealias AliasToNS5 = ClassesNS5.ClassesNS5
// CHECK-NEXT: }
| apache-2.0 | da3063f5913ea93f43d831fa7cfb7bf2 | 39.824561 | 137 | 0.67254 | 3.509804 | false | false | false | false |
feiin/BRBubbles.Swift | BRBubbles.Swift/ViewController.swift | 1 | 8567 | //
// ViewController.swift
// BRBubbles.Swift
//
// Created by feiin on 14-10-15.
// Copyright (c) 2014年 swiftmi. All rights reserved.
//
import UIKit
import QuartzCore
let notAnimating = 0
let isAnimating = 1
class ViewController: UIViewController,UIScrollViewDelegate{
@IBOutlet weak var scrollView: UIScrollView!
fileprivate var imagesArray:[UIImageView]?
fileprivate var imageNameArray:[String]?
fileprivate var viewBarrierOuter:UIView?
fileprivate var viewBarrierInner:UIView?
fileprivate var bigSize:CGSize?
fileprivate var smallSize:CGSize?
override func viewDidLoad() {
super.viewDidLoad()
self.imageNameArray=["icon_one.png","icon_two.png","icon_three.png","icon_four.png","icon_five.png","icon_six.png","icon_eight.png","icon_nine.png","icon_ten.png"]
self.bigSize = CGSize(width: 60, height: 60);
self.smallSize = CGSize(width: 30, height: 30);
let gutter:CGFloat = 20.0;
self.imagesArray = [UIImageView]()
self.scrollView.backgroundColor=UIColor.black
let width = self.view.frame.size.width*2+(gutter*2)
let height = self.view.frame.size.height*2+(gutter*3)
self.scrollView.contentSize=CGSize(width: width, height: height)
self.scrollView.contentOffset = CGPoint(x: self.scrollView.contentSize.width/2-self.view.frame.size.width/2, y: self.scrollView.contentSize.height/2-self.view.frame.size.height/2)
self.scrollView.delegate = self
let gap:CGFloat = 5;
var xValue:CGFloat = gutter
var yValue:CGFloat = gutter
var rowNumber = 1
for _ in 0 ..< 162
{
let imageOne:UIImageView = UIImageView(frame: CGRect(x: xValue, y: yValue, width: 60, height: 60))
self.addImageToScrollView(imageOne)
xValue += (60+gap+gap);
if xValue > (self.scrollView.contentSize.width-(gutter*3))
{
if rowNumber % 2 == 0
{
xValue = 30 + gutter;
}else{
xValue = 0 + gutter;
}
yValue += (60+gap);
rowNumber += 1;
}
}
self.viewBarrierOuter = UIView(frame: CGRect(x: self.view.frame.size.width/8,y: self.view.frame.size.height/8, width: self.view.frame.size.width-self.view.frame.size.width/4, height: self.view.frame.size.height-self.view.frame.size.height/4))
self.viewBarrierOuter!.backgroundColor = UIColor.red
self.viewBarrierOuter!.alpha = 0.3
self.viewBarrierOuter!.isHidden = true
self.viewBarrierOuter!.isUserInteractionEnabled = false
self.view.addSubview(self.viewBarrierOuter!)
self.viewBarrierInner = UIView(frame: CGRect(x: self.view.frame.size.width/4,y: self.view.frame.size.height/4, width: self.view.frame.size.width-self.view.frame.size.width/2, height: self.view.frame.size.height-self.view.frame.size.height/2))
self.viewBarrierInner!.backgroundColor = UIColor.red
self.viewBarrierInner!.alpha = 0.3;
self.viewBarrierInner!.isHidden = true;
self.viewBarrierInner!.isUserInteractionEnabled = false
self.view.addSubview(self.viewBarrierInner!)
self.initImageScale()
}
func addImageToScrollView(_ image:UIImageView){
image.image=UIImage(named: self.imageNameArray![(Int)(arc4random()%9)])
image.layer.cornerRadius=12
image.layer.masksToBounds=true
image.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
image.contentMode = UIViewContentMode.scaleAspectFill
self.scrollView.addSubview(image)
self.imagesArray!.append(image)
}
func scrollViewDidScroll(_ scrollView: UIScrollView)
{
let container = CGRect(x: scrollView.contentOffset.x+(self.viewBarrierOuter!.frame.size.width/8), y: scrollView.contentOffset.y+(self.viewBarrierOuter!.frame.size.height/8), width: self.viewBarrierOuter!.frame.size.width, height: self.viewBarrierOuter!.frame.size.height)
let containerTwo = CGRect(x: scrollView.contentOffset.x+(self.viewBarrierInner!.frame.size.width/2), y: scrollView.contentOffset.y+(self.viewBarrierInner!.frame.size.height/2), width: self.viewBarrierInner!.frame.size.width, height: self.viewBarrierInner!.frame.size.height)
let fetchQ:DispatchQueue = DispatchQueue(label: "BubbleQueue", attributes: [])
fetchQ.async(execute: {
for imageView in self.imagesArray!
{
let thePosition:CGRect = imageView.frame;
if(containerTwo.intersects(thePosition))
{
if (imageView.tag == notAnimating)
{
imageView.tag = isAnimating;
DispatchQueue.main.async(execute: {
UIView.animate(withDuration: 0.5, animations: {
imageView.transform = CGAffineTransform(scaleX: 1.0,y: 1.0)
}, completion: {(finished:Bool) in
imageView.tag = notAnimating;
})
})
}
}else if(container.intersects(thePosition))
{
if (imageView.tag == notAnimating)
{
imageView.tag = isAnimating;
DispatchQueue.main.async(execute: {
UIView.animate(withDuration: 0.5, animations: {
imageView.transform = CGAffineTransform(scaleX: 0.7,y: 0.7)
}, completion: { (finished:Bool) in
imageView.tag = notAnimating;
})
})
}
}else{
if (imageView.tag == notAnimating)
{
imageView.tag = isAnimating;
DispatchQueue.main.async(execute: {
UIView.animate(withDuration: 0.5, animations: {
imageView.transform = CGAffineTransform(scaleX: 0.5,y: 0.5)
}, completion: {(finished:Bool) in
imageView.tag = notAnimating;
})
})
}
}
}
})
}
func initImageScale()
{
let container = CGRect(x: scrollView.contentOffset.x+(self.viewBarrierOuter!.frame.size.width/8), y: scrollView.contentOffset.y+(self.viewBarrierOuter!.frame.size.height/8), width: self.viewBarrierOuter!.frame.size.width, height: self.viewBarrierOuter!.frame.size.height)
let containerTwo = CGRect(x: scrollView.contentOffset.x+(self.viewBarrierInner!.frame.size.width/2), y: scrollView.contentOffset.y+(self.viewBarrierInner!.frame.size.height/2), width: self.viewBarrierInner!.frame.size.width, height: self.viewBarrierInner!.frame.size.height)
for imageView in self.imagesArray!
{
let thePosition:CGRect = imageView.frame;
if(containerTwo.intersects(thePosition))
{
imageView.transform = CGAffineTransform(scaleX: 1.0,y: 1.0)
}else if(container.intersects(thePosition))
{
imageView.transform = CGAffineTransform(scaleX: 0.7,y: 0.7)
}else{
imageView.transform = CGAffineTransform(scaleX: 0.5,y: 0.5)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 24ef1ff44a5590ae04eb5dd578cbe471 | 34.83682 | 282 | 0.535552 | 4.852691 | false | false | false | false |
jarrroo/MarkupKitLint | Tools/Pods/Nimble/Sources/Nimble/Matchers/ContainElementSatisfying.swift | 28 | 2203 | import Foundation
public func containElementSatisfying<S: Sequence, T>(_ predicate: @escaping ((T) -> Bool), _ predicateDescription: String = "") -> Predicate<S> where S.Iterator.Element == T {
return Predicate.fromDeprecatedClosure { actualExpression, failureMessage in
failureMessage.actualValue = nil
if predicateDescription == "" {
failureMessage.postfixMessage = "find object in collection that satisfies predicate"
} else {
failureMessage.postfixMessage = "find object in collection \(predicateDescription)"
}
if let sequence = try actualExpression.evaluate() {
for object in sequence {
if predicate(object) {
return true
}
}
return false
}
return false
}.requireNonNil
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func containElementSatisfyingMatcher(_ predicate: @escaping ((NSObject) -> Bool)) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let value = try! actualExpression.evaluate()
guard let enumeration = value as? NSFastEnumeration else {
failureMessage.postfixMessage = "containElementSatisfying must be provided an NSFastEnumeration object"
failureMessage.actualValue = nil
failureMessage.expected = ""
failureMessage.to = ""
return false
}
var iterator = NSFastEnumerationIterator(enumeration)
while let item = iterator.next() {
guard let object = item as? NSObject else {
continue
}
if predicate(object) {
return true
}
}
failureMessage.actualValue = nil
failureMessage.postfixMessage = ""
failureMessage.to = "to find object in collection that satisfies predicate"
return false
}
}
}
#endif
| mit | 8cb7f7d8afa8decdc81ddbfc7aa20217 | 36.338983 | 175 | 0.562869 | 6.367052 | false | false | false | false |
Sharelink/Bahamut | Bahamut/BahamutUIKit/UIImagePicker+SourceAlert.swift | 1 | 2145 | //
// UIImagePicker+SourceAlert.swift
// Vessage
//
// Created by Alex Chow on 2016/11/26.
// Copyright © 2016年 Bahamut. All rights reserved.
//
import Foundation
import UIKit
extension UIImagePickerController{
static func showUIImagePickerAlert(_ viewController:UIViewController,title:String!,message:String!,allowsEditing:Bool = false,alertStyle:UIAlertController.Style = .actionSheet,extraAlertAction:[UIAlertAction]? = nil) -> UIImagePickerController{
let imagePicker = UIImagePickerController()
let style = UIDevice.current.userInterfaceIdiom == .phone ? alertStyle : .alert
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
let camera = UIAlertAction(title: "TAKE_NEW_PHOTO".bahamutCommonLocalizedString, style: .default) { _ in
imagePicker.sourceType = .camera
imagePicker.allowsEditing = allowsEditing
viewController.present(imagePicker, animated: true, completion: nil)
}
if let cameraIcon = UIImage(named: "avartar_camera")?.withRenderingMode(.alwaysOriginal) {
camera.setValue(cameraIcon, forKey: "image")
}
if !UIDevice.isSimulator() {
alert.addAction(camera)
}
let album = UIAlertAction(title:"SELECT_PHOTO".bahamutCommonLocalizedString, style: .default) { _ in
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = allowsEditing
viewController.present(imagePicker, animated: true, completion: nil)
}
if let albumIcon = UIImage(named: "avartar_select")?.withRenderingMode(.alwaysOriginal){
album.setValue(albumIcon, forKey: "image")
}
alert.addAction(album)
if let exActs = extraAlertAction{
for ac in exActs {
alert.addAction(ac)
}
}
alert.addAction(UIAlertAction(title: "CANCEL".bahamutCommonLocalizedString, style: .cancel){ _ in})
viewController.present(alert, animated: true, completion: nil)
return imagePicker
}
}
| mit | 2a968cba0295d84230bfd6b9d7e0694a | 40.192308 | 248 | 0.659197 | 4.924138 | false | false | false | false |
shorlander/firefox-ios | Storage/SQL/BrowserTable.swift | 1 | 46718 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
let BookmarksFolderTitleMobile: String = NSLocalizedString("Mobile Bookmarks", tableName: "Storage", comment: "The title of the folder that contains mobile bookmarks. This should match bookmarks.folder.mobile.label on Android.")
let BookmarksFolderTitleMenu: String = NSLocalizedString("Bookmarks Menu", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the menu. This should match bookmarks.folder.menu.label on Android.")
let BookmarksFolderTitleToolbar: String = NSLocalizedString("Bookmarks Toolbar", tableName: "Storage", comment: "The name of the folder that contains desktop bookmarks in the toolbar. This should match bookmarks.folder.toolbar.label on Android.")
let BookmarksFolderTitleUnsorted: String = NSLocalizedString("Unsorted Bookmarks", tableName: "Storage", comment: "The name of the folder that contains unsorted desktop bookmarks. This should match bookmarks.folder.unfiled.label on Android.")
let _TableBookmarks = "bookmarks" // Removed in v12. Kept for migration.
let TableBookmarksMirror = "bookmarksMirror" // Added in v9.
let TableBookmarksMirrorStructure = "bookmarksMirrorStructure" // Added in v10.
let TableBookmarksBuffer = "bookmarksBuffer" // Added in v12. bookmarksMirror is renamed to bookmarksBuffer.
let TableBookmarksBufferStructure = "bookmarksBufferStructure" // Added in v12.
let TableBookmarksLocal = "bookmarksLocal" // Added in v12. Supersedes 'bookmarks'.
let TableBookmarksLocalStructure = "bookmarksLocalStructure" // Added in v12.
let TablePendingBookmarksDeletions = "pending_deletions" // Added in v28.
let TableFavicons = "favicons"
let TableHistory = "history"
let TableCachedTopSites = "cached_top_sites"
let TablePinnedTopSites = "pinned_top_sites"
let TableDomains = "domains"
let TableVisits = "visits"
let TableFaviconSites = "favicon_sites"
let TableQueuedTabs = "queue"
let TableActivityStreamBlocklist = "activity_stream_blocklist"
let TablePageMetadata = "page_metadata"
let TableHighlights = "highlights"
let ViewBookmarksBufferOnMirror = "view_bookmarksBuffer_on_mirror"
let ViewBookmarksBufferWithDeletionsOnMirror = "view_bookmarksBuffer_with_deletions_on_mirror"
let ViewBookmarksBufferStructureOnMirror = "view_bookmarksBufferStructure_on_mirror"
let ViewBookmarksLocalOnMirror = "view_bookmarksLocal_on_mirror"
let ViewBookmarksLocalStructureOnMirror = "view_bookmarksLocalStructure_on_mirror"
let ViewAllBookmarks = "view_all_bookmarks"
let ViewAwesomebarBookmarks = "view_awesomebar_bookmarks"
let ViewAwesomebarBookmarksWithIcons = "view_awesomebar_bookmarks_with_favicons"
let ViewHistoryVisits = "view_history_visits"
let ViewWidestFaviconsForSites = "view_favicons_widest"
let ViewHistoryIDsWithWidestFavicons = "view_history_id_favicon"
let ViewIconForURL = "view_icon_for_url"
let IndexHistoryShouldUpload = "idx_history_should_upload"
let IndexVisitsSiteIDDate = "idx_visits_siteID_date" // Removed in v6.
let IndexVisitsSiteIDIsLocalDate = "idx_visits_siteID_is_local_date" // Added in v6.
let IndexBookmarksMirrorStructureParentIdx = "idx_bookmarksMirrorStructure_parent_idx" // Added in v10.
let IndexBookmarksLocalStructureParentIdx = "idx_bookmarksLocalStructure_parent_idx" // Added in v12.
let IndexBookmarksBufferStructureParentIdx = "idx_bookmarksBufferStructure_parent_idx" // Added in v12.
let IndexBookmarksMirrorStructureChild = "idx_bookmarksMirrorStructure_child" // Added in v14.
let IndexPageMetadataCacheKey = "idx_page_metadata_cache_key_uniqueindex" // Added in v19
let IndexPageMetadataSiteURL = "idx_page_metadata_site_url_uniqueindex" // Added in v21
private let AllTables: [String] = [
TableDomains,
TableFavicons,
TableFaviconSites,
TableHistory,
TableVisits,
TableCachedTopSites,
TableBookmarksBuffer,
TableBookmarksBufferStructure,
TableBookmarksLocal,
TableBookmarksLocalStructure,
TableBookmarksMirror,
TableBookmarksMirrorStructure,
TablePendingBookmarksDeletions,
TableQueuedTabs,
TableActivityStreamBlocklist,
TablePageMetadata,
TableHighlights,
TablePinnedTopSites
]
private let AllViews: [String] = [
ViewHistoryIDsWithWidestFavicons,
ViewWidestFaviconsForSites,
ViewIconForURL,
ViewBookmarksBufferOnMirror,
ViewBookmarksBufferWithDeletionsOnMirror,
ViewBookmarksBufferStructureOnMirror,
ViewBookmarksLocalOnMirror,
ViewBookmarksLocalStructureOnMirror,
ViewAllBookmarks,
ViewAwesomebarBookmarks,
ViewAwesomebarBookmarksWithIcons,
ViewHistoryVisits
]
private let AllIndices: [String] = [
IndexHistoryShouldUpload,
IndexVisitsSiteIDIsLocalDate,
IndexBookmarksBufferStructureParentIdx,
IndexBookmarksLocalStructureParentIdx,
IndexBookmarksMirrorStructureParentIdx,
IndexBookmarksMirrorStructureChild,
IndexPageMetadataCacheKey,
IndexPageMetadataSiteURL
]
private let AllTablesIndicesAndViews: [String] = AllViews + AllIndices + AllTables
private let log = Logger.syncLogger
/**
* The monolithic class that manages the inter-related history etc. tables.
* We rely on SQLiteHistory having initialized the favicon table first.
*/
open class BrowserTable: Table {
static let DefaultVersion = 28 // Bug 1380062.
// TableInfo fields.
var name: String { return "BROWSER" }
var version: Int { return BrowserTable.DefaultVersion }
let sqliteVersion: Int32
let supportsPartialIndices: Bool
public init() {
let v = sqlite3_libversion_number()
self.sqliteVersion = v
self.supportsPartialIndices = v >= 3008000 // 3.8.0.
let ver = String(cString: sqlite3_libversion())
log.info("SQLite version: \(ver) (\(v)).")
}
func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in BrowserTable: \(err?.localizedDescription ?? "nil")")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(_ db: SQLiteDBConnection, queries: [(String, Args?)]) -> Bool {
for (sql, args) in queries {
if !run(db, sql: sql, args: args) {
return false
}
}
return true
}
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql) {
return false
}
}
return true
}
func runValidQueries(_ db: SQLiteDBConnection, queries: [(String?, Args?)]) -> Bool {
for (sql, args) in queries {
if let sql = sql {
if !run(db, sql: sql, args: args) {
return false
}
}
}
return true
}
func runValidQueries(_ db: SQLiteDBConnection, queries: [String?]) -> Bool {
return self.run(db, queries: optFilter(queries))
}
func prepopulateRootFolders(_ db: SQLiteDBConnection) -> Bool {
let type = BookmarkNodeType.folder.rawValue
let now = Date.nowNumber()
let status = SyncStatus.new.rawValue
let localArgs: Args = [
BookmarkRoots.RootID, BookmarkRoots.RootGUID, type, BookmarkRoots.RootGUID, status, now,
BookmarkRoots.MobileID, BookmarkRoots.MobileFolderGUID, type, BookmarkRoots.RootGUID, status, now,
BookmarkRoots.MenuID, BookmarkRoots.MenuFolderGUID, type, BookmarkRoots.RootGUID, status, now,
BookmarkRoots.ToolbarID, BookmarkRoots.ToolbarFolderGUID, type, BookmarkRoots.RootGUID, status, now,
BookmarkRoots.UnfiledID, BookmarkRoots.UnfiledFolderGUID, type, BookmarkRoots.RootGUID, status, now,
]
// Compute these args using the sequence in RootChildren, rather than hard-coding.
var idx = 0
var structureArgs = Args()
structureArgs.reserveCapacity(BookmarkRoots.RootChildren.count * 3)
BookmarkRoots.RootChildren.forEach { guid in
structureArgs.append(BookmarkRoots.RootGUID)
structureArgs.append(guid)
structureArgs.append(idx)
idx += 1
}
// Note that we specify an empty title and parentName for these records. We should
// never need a parentName -- we don't use content-based reconciling or
// reparent these -- and we'll use the current locale's string, retrieved
// via titleForSpecialGUID, if necessary.
let local =
"INSERT INTO \(TableBookmarksLocal) " +
"(id, guid, type, parentid, title, parentName, sync_status, local_modified) VALUES " +
Array(repeating: "(?, ?, ?, ?, '', '', ?, ?)", count: BookmarkRoots.RootChildren.count + 1).joined(separator: ", ")
let structure =
"INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) VALUES " +
Array(repeating: "(?, ?, ?)", count: BookmarkRoots.RootChildren.count).joined(separator: ", ")
return self.run(db, queries: [(local, localArgs), (structure, structureArgs)])
}
let topSitesTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableCachedTopSites) (" +
"historyID INTEGER, " +
"url TEXT NOT NULL, " +
"title TEXT NOT NULL, " +
"guid TEXT NOT NULL UNIQUE, " +
"domain_id INTEGER, " +
"domain TEXT NO NULL, " +
"localVisitDate REAL, " +
"remoteVisitDate REAL, " +
"localVisitCount INTEGER, " +
"remoteVisitCount INTEGER, " +
"iconID INTEGER, " +
"iconURL TEXT, " +
"iconDate REAL, " +
"iconType INTEGER, " +
"iconWidth INTEGER, " +
"frecencies REAL" +
")"
let pinnedTopSitesTableCreate =
"CREATE TABLE IF NOT EXISTS \(TablePinnedTopSites) (" +
"historyID INTEGER, " +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT, " +
"guid TEXT, " +
"pinDate REAL, " +
"domain TEXT NOT NULL " +
")"
let domainsTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableDomains) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"domain TEXT NOT NULL UNIQUE, " +
"showOnTopSites TINYINT NOT NULL DEFAULT 1" +
")"
let queueTableCreate =
"CREATE TABLE IF NOT EXISTS \(TableQueuedTabs) (" +
"url TEXT NOT NULL UNIQUE, " +
"title TEXT" +
") "
let activityStreamBlocklistCreate =
"CREATE TABLE IF NOT EXISTS \(TableActivityStreamBlocklist) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"created_at DATETIME DEFAULT CURRENT_TIMESTAMP " +
") "
let pageMetadataCreate =
"CREATE TABLE IF NOT EXISTS \(TablePageMetadata) (" +
"id INTEGER PRIMARY KEY, " +
"cache_key LONGVARCHAR UNIQUE, " +
"site_url TEXT, " +
"media_url LONGVARCHAR, " +
"title TEXT, " +
"type VARCHAR(32), " +
"description TEXT, " +
"provider_name TEXT, " +
"created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
"expired_at LONG" +
") "
let highlightsCreate =
"CREATE TABLE IF NOT EXISTS \(TableHighlights) (" +
"historyID INTEGER PRIMARY KEY," +
"cache_key LONGVARCHAR," +
"url TEXT," +
"title TEXT," +
"guid TEXT," +
"visitCount INTEGER," +
"visitDate DATETIME," +
"is_bookmarked INTEGER" +
") "
let indexPageMetadataCacheKeyCreate =
"CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataCacheKey) ON page_metadata (cache_key)"
let indexPageMetadataSiteURLCreate =
"CREATE UNIQUE INDEX IF NOT EXISTS \(IndexPageMetadataSiteURL) ON page_metadata (site_url)"
let iconColumns = ", faviconID INTEGER REFERENCES \(TableFavicons)(id) ON DELETE SET NULL"
let mirrorColumns = ", is_overridden TINYINT NOT NULL DEFAULT 0"
let serverColumns = ", server_modified INTEGER NOT NULL" + // Milliseconds.
", hasDupe TINYINT NOT NULL DEFAULT 0" // Boolean, 0 (false) if deleted.
let localColumns = ", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", sync_status TINYINT NOT NULL" // SyncStatus enum. Set when changed or created.
func getBookmarksTableCreationStringForTable(_ table: String, withAdditionalColumns: String="") -> String {
// The stupid absence of naming conventions here is thanks to pre-Sync Weave. Sorry.
// For now we have the simplest possible schema: everything in one.
let sql =
"CREATE TABLE IF NOT EXISTS \(table) " +
// Shared fields.
"( id INTEGER PRIMARY KEY AUTOINCREMENT" +
", guid TEXT NOT NULL UNIQUE" +
", type TINYINT NOT NULL" + // Type enum.
// Record/envelope metadata that'll allow us to do merges.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean
", parentid TEXT" + // GUID
", parentName TEXT" +
// Type-specific fields. These should be NOT NULL in many cases, but we're going
// for a sparse schema, so this'll do for now. Enforce these in the application code.
", feedUri TEXT, siteUri TEXT" + // LIVEMARKS
", pos INT" + // SEPARATORS
", title TEXT, description TEXT" + // FOLDERS, BOOKMARKS, QUERIES
", bmkUri TEXT, tags TEXT, keyword TEXT" + // BOOKMARKS, QUERIES
", folderName TEXT, queryId TEXT" + // QUERIES
withAdditionalColumns +
", CONSTRAINT parentidOrDeleted CHECK (parentid IS NOT NULL OR is_deleted = 1)" +
", CONSTRAINT parentNameOrDeleted CHECK (parentName IS NOT NULL OR is_deleted = 1)" +
")"
return sql
}
/**
* We need to explicitly store what's provided by the server, because we can't rely on
* referenced child nodes to exist yet!
*/
func getBookmarksStructureTableCreationStringForTable(_ table: String, referencingMirror mirror: String) -> String {
let sql =
"CREATE TABLE IF NOT EXISTS \(table) " +
"( parent TEXT NOT NULL REFERENCES \(mirror)(guid) ON DELETE CASCADE" +
", child TEXT NOT NULL" + // Should be the GUID of a child.
", idx INTEGER NOT NULL" + // Should advance from 0.
")"
return sql
}
fileprivate let bufferBookmarksView =
"CREATE VIEW \(ViewBookmarksBufferOnMirror) AS " +
"SELECT" +
" -1 AS id" +
", mirror.guid AS guid" +
", mirror.type AS type" +
", mirror.is_deleted AS is_deleted" +
", mirror.parentid AS parentid" +
", mirror.parentName AS parentName" +
", mirror.feedUri AS feedUri" +
", mirror.siteUri AS siteUri" +
", mirror.pos AS pos" +
", mirror.title AS title" +
", mirror.description AS description" +
", mirror.bmkUri AS bmkUri" +
", mirror.keyword AS keyword" +
", mirror.folderName AS folderName" +
", null AS faviconID" +
", 0 AS is_overridden" +
// LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer.
// We don't have an is_overridden flag to help us here.
" FROM \(TableBookmarksMirror) mirror LEFT JOIN" +
" \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" +
" WHERE buffer.guid IS NULL" +
" UNION ALL " +
"SELECT" +
" -1 AS id" +
", guid" +
", type" +
", is_deleted" +
", parentid" +
", parentName" +
", feedUri" +
", siteUri" +
", pos" +
", title" +
", description" +
", bmkUri" +
", keyword" +
", folderName" +
", null AS faviconID" +
", 1 AS is_overridden" +
" FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0"
fileprivate let bufferBookmarksWithDeletionsView =
"CREATE VIEW \(ViewBookmarksBufferWithDeletionsOnMirror) AS " +
"SELECT" +
" -1 AS id" +
", mirror.guid AS guid" +
", mirror.type AS type" +
", mirror.is_deleted AS is_deleted" +
", mirror.parentid AS parentid" +
", mirror.parentName AS parentName" +
", mirror.feedUri AS feedUri" +
", mirror.siteUri AS siteUri" +
", mirror.pos AS pos" +
", mirror.title AS title" +
", mirror.description AS description" +
", mirror.bmkUri AS bmkUri" +
", mirror.keyword AS keyword" +
", mirror.folderName AS folderName" +
", null AS faviconID" +
", 0 AS is_overridden" +
// LEFT EXCLUDING JOIN to get mirror records that aren't in the buffer.
// We don't have an is_overridden flag to help us here.
" FROM \(TableBookmarksMirror) mirror LEFT JOIN" +
" \(TableBookmarksBuffer) buffer ON mirror.guid = buffer.guid" +
" WHERE buffer.guid IS NULL" +
" UNION ALL " +
"SELECT" +
" -1 AS id" +
", guid" +
", type" +
", is_deleted" +
", parentid" +
", parentName" +
", feedUri" +
", siteUri" +
", pos" +
", title" +
", description" +
", bmkUri" +
", keyword" +
", folderName" +
", null AS faviconID" +
", 1 AS is_overridden" +
" FROM \(TableBookmarksBuffer) WHERE is_deleted IS 0" +
" AND NOT EXISTS (SELECT 1 FROM \(TablePendingBookmarksDeletions) deletions WHERE deletions.id = guid)"
// TODO: phrase this without the subselect…
fileprivate let bufferBookmarksStructureView =
// We don't need to exclude deleted parents, because we drop those from the structure
// table when we see them.
"CREATE VIEW \(ViewBookmarksBufferStructureOnMirror) AS " +
"SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksBufferStructure) " +
"UNION ALL " +
// Exclude anything from the mirror that's present in the buffer -- dynamic is_overridden.
"SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " +
"LEFT JOIN \(TableBookmarksBuffer) ON parent = guid WHERE guid IS NULL"
fileprivate let localBookmarksView =
"CREATE VIEW \(ViewBookmarksLocalOnMirror) AS " +
"SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri," +
" siteUri, pos, title, description, bmkUri, folderName, faviconID, NULL AS local_modified, server_modified, 0 AS is_overridden " +
"FROM \(TableBookmarksMirror) WHERE is_overridden IS NOT 1 " +
"UNION ALL " +
"SELECT -1 AS id, guid, type, is_deleted, parentid, parentName, feedUri, siteUri, pos, title, description, bmkUri, folderName, faviconID," +
" local_modified, NULL AS server_modified, 1 AS is_overridden " +
"FROM \(TableBookmarksLocal) WHERE is_deleted IS NOT 1"
// TODO: phrase this without the subselect…
fileprivate let localBookmarksStructureView =
"CREATE VIEW \(ViewBookmarksLocalStructureOnMirror) AS " +
"SELECT parent, child, idx, 1 AS is_overridden FROM \(TableBookmarksLocalStructure) " +
"WHERE " +
"((SELECT is_deleted FROM \(TableBookmarksLocal) WHERE guid = parent) IS NOT 1) " +
"UNION ALL " +
"SELECT parent, child, idx, 0 AS is_overridden FROM \(TableBookmarksMirrorStructure) " +
"WHERE " +
"((SELECT is_overridden FROM \(TableBookmarksMirror) WHERE guid = parent) IS NOT 1) "
// This view exists only to allow for text searching of URLs and titles in the awesomebar.
// As such, we cheat a little: we include buffer, non-overridden mirror, and local.
// Usually this will be indistinguishable from a more sophisticated approach, and it's way
// easier.
fileprivate let allBookmarksView =
"CREATE VIEW \(ViewAllBookmarks) AS " +
"SELECT guid, bmkUri AS url, title, description, faviconID FROM " +
"\(TableBookmarksMirror) WHERE " +
"type = \(BookmarkNodeType.bookmark.rawValue) AND is_overridden IS 0 AND is_deleted IS 0 " +
"UNION ALL " +
"SELECT guid, bmkUri AS url, title, description, faviconID FROM " +
"\(TableBookmarksLocal) WHERE " +
"type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0 " +
"UNION ALL " +
"SELECT guid, bmkUri AS url, title, description, -1 AS faviconID FROM " +
"\(TableBookmarksBuffer) WHERE " +
"type = \(BookmarkNodeType.bookmark.rawValue) AND is_deleted IS 0"
// This smushes together remote and local visits. So it goes.
fileprivate let historyVisitsView =
"CREATE VIEW \(ViewHistoryVisits) AS " +
"SELECT h.url AS url, MAX(v.date) AS visitDate, h.domain_id AS domain_id FROM " +
"\(TableHistory) h JOIN \(TableVisits) v ON v.siteID = h.id " +
"GROUP BY h.id"
// Join all bookmarks against history to find the most recent visit.
// visits.
fileprivate let awesomebarBookmarksView =
"CREATE VIEW \(ViewAwesomebarBookmarks) AS " +
"SELECT b.guid AS guid, b.url AS url, b.title AS title, " +
"b.description AS description, b.faviconID AS faviconID, " +
"h.visitDate AS visitDate " +
"FROM \(ViewAllBookmarks) b " +
"LEFT JOIN " +
"\(ViewHistoryVisits) h ON b.url = h.url"
fileprivate let awesomebarBookmarksWithIconsView =
"CREATE VIEW \(ViewAwesomebarBookmarksWithIcons) AS " +
"SELECT b.guid AS guid, b.url AS url, b.title AS title, " +
"b.description AS description, b.visitDate AS visitDate, " +
"f.id AS iconID, f.url AS iconURL, f.date AS iconDate, " +
"f.type AS iconType, f.width AS iconWidth " +
"FROM \(ViewAwesomebarBookmarks) b " +
"LEFT JOIN " +
"\(TableFavicons) f ON f.id = b.faviconID"
fileprivate let pendingBookmarksDeletions =
"CREATE TABLE IF NOT EXISTS \(TablePendingBookmarksDeletions) (" +
"id TEXT PRIMARY KEY REFERENCES \(TableBookmarksBuffer)(guid) ON DELETE CASCADE" +
")"
func create(_ db: SQLiteDBConnection) -> Bool {
let favicons =
"CREATE TABLE IF NOT EXISTS \(TableFavicons) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"url TEXT NOT NULL UNIQUE, " +
"width INTEGER, " +
"height INTEGER, " +
"type INTEGER NOT NULL, " +
"date REAL NOT NULL" +
") "
let history =
"CREATE TABLE IF NOT EXISTS \(TableHistory) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " + // Not null, but the value might be replaced by the server's.
"url TEXT UNIQUE, " + // May only be null for deleted records.
"title TEXT NOT NULL, " +
"server_modified INTEGER, " + // Can be null. Integer milliseconds.
"local_modified INTEGER, " + // Can be null. Client clock. In extremis only.
"is_deleted TINYINT NOT NULL, " + // Boolean. Locally deleted.
"should_upload TINYINT NOT NULL, " + // Boolean. Set when changed or visits added.
"domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE, " +
"CONSTRAINT urlOrDeleted CHECK (url IS NOT NULL OR is_deleted = 1)" +
")"
// Right now we don't need to track per-visit deletions: Sync can't
// represent them! See Bug 1157553 Comment 6.
// We flip the should_upload flag on the history item when we add a visit.
// If we ever want to support logic like not bothering to sync if we added
// and then rapidly removed a visit, then we need an 'is_new' flag on each visit.
let visits =
"CREATE TABLE IF NOT EXISTS \(TableVisits) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"date REAL NOT NULL, " + // Microseconds since epoch.
"type INTEGER NOT NULL, " +
"is_local TINYINT NOT NULL, " + // Some visits are local. Some are remote ('mirrored'). This boolean flag is the split.
"UNIQUE (siteID, date, type) " +
") "
let indexShouldUpload: String
if self.supportsPartialIndices {
// There's no point tracking rows that are not flagged for upload.
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload) WHERE should_upload = 1"
} else {
indexShouldUpload =
"CREATE INDEX IF NOT EXISTS \(IndexHistoryShouldUpload) " +
"ON \(TableHistory) (should_upload)"
}
let indexSiteIDDate =
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) " +
"ON \(TableVisits) (siteID, is_local, date)"
let faviconSites =
"CREATE TABLE IF NOT EXISTS \(TableFaviconSites) (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"siteID INTEGER NOT NULL REFERENCES \(TableHistory)(id) ON DELETE CASCADE, " +
"faviconID INTEGER NOT NULL REFERENCES \(TableFavicons)(id) ON DELETE CASCADE, " +
"UNIQUE (siteID, faviconID) " +
") "
let widestFavicons =
"CREATE VIEW IF NOT EXISTS \(ViewWidestFaviconsForSites) AS " +
"SELECT " +
"\(TableFaviconSites).siteID AS siteID, " +
"\(TableFavicons).id AS iconID, " +
"\(TableFavicons).url AS iconURL, " +
"\(TableFavicons).date AS iconDate, " +
"\(TableFavicons).type AS iconType, " +
"MAX(\(TableFavicons).width) AS iconWidth " +
"FROM \(TableFaviconSites), \(TableFavicons) WHERE " +
"\(TableFaviconSites).faviconID = \(TableFavicons).id " +
"GROUP BY siteID "
let historyIDsWithIcon =
"CREATE VIEW IF NOT EXISTS \(ViewHistoryIDsWithWidestFavicons) AS " +
"SELECT \(TableHistory).id AS id, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM \(TableHistory) " +
"LEFT OUTER JOIN " +
"\(ViewWidestFaviconsForSites) ON history.id = \(ViewWidestFaviconsForSites).siteID "
let iconForURL =
"CREATE VIEW IF NOT EXISTS \(ViewIconForURL) AS " +
"SELECT history.url AS url, icons.iconID AS iconID FROM " +
"\(TableHistory), \(ViewWidestFaviconsForSites) AS icons WHERE " +
"\(TableHistory).id = icons.siteID "
// Locally we track faviconID.
// Local changes end up in the mirror, so we track it there too.
// The buffer and the mirror additionally track some server metadata.
let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns)
let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal)
let bookmarksBuffer = getBookmarksTableCreationStringForTable(TableBookmarksBuffer, withAdditionalColumns: self.serverColumns)
let bookmarksBufferStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksBufferStructure, referencingMirror: TableBookmarksBuffer)
let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns)
let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)
let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " +
"ON \(TableBookmarksLocalStructure) (parent, idx)"
let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " +
"ON \(TableBookmarksBufferStructure) (parent, idx)"
let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let indexMirrorStructureChild = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " +
"ON \(TableBookmarksMirrorStructure) (child)"
let queries: [String] = [
self.domainsTableCreate,
history,
favicons,
visits,
bookmarksBuffer,
bookmarksBufferStructure,
bookmarksLocal,
bookmarksLocalStructure,
bookmarksMirror,
bookmarksMirrorStructure,
self.pendingBookmarksDeletions,
indexBufferStructureParentIdx,
indexLocalStructureParentIdx,
indexMirrorStructureParentIdx,
indexMirrorStructureChild,
faviconSites,
indexShouldUpload,
indexSiteIDDate,
widestFavicons,
historyIDsWithIcon,
iconForURL,
pageMetadataCreate,
pinnedTopSitesTableCreate,
highlightsCreate,
indexPageMetadataSiteURLCreate,
indexPageMetadataCacheKeyCreate,
self.queueTableCreate,
self.topSitesTableCreate,
self.localBookmarksView,
self.localBookmarksStructureView,
self.bufferBookmarksView,
self.bufferBookmarksWithDeletionsView,
self.bufferBookmarksStructureView,
allBookmarksView,
historyVisitsView,
awesomebarBookmarksView,
awesomebarBookmarksWithIconsView,
activityStreamBlocklistCreate
]
assert(queries.count == AllTablesIndicesAndViews.count, "Did you forget to add your table, index, or view to the list?")
log.debug("Creating \(queries.count) tables, views, and indices.")
return self.run(db, queries: queries) &&
self.prepopulateRootFolders(db)
}
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
let to = BrowserTable.DefaultVersion
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating browser tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from > to {
// This is likely an upgrade from before Bug 1160399.
log.debug("Downgrading browser tables. Assuming drop and recreate.")
return drop(db) && create(db)
}
log.debug("Updating browser tables from \(from) to \(to).")
if from < 4 && to >= 4 {
return drop(db) && create(db)
}
if from < 5 && to >= 5 {
if !self.run(db, sql: self.queueTableCreate) {
return false
}
}
if from < 6 && to >= 6 {
if !self.run(db, queries: [
"DROP INDEX IF EXISTS \(IndexVisitsSiteIDDate)",
"CREATE INDEX IF NOT EXISTS \(IndexVisitsSiteIDIsLocalDate) ON \(TableVisits) (siteID, is_local, date)",
self.domainsTableCreate,
"ALTER TABLE \(TableHistory) ADD COLUMN domain_id INTEGER REFERENCES \(TableDomains)(id) ON DELETE CASCADE",
]) {
return false
}
let urls = db.executeQuery("SELECT DISTINCT url FROM \(TableHistory) WHERE url IS NOT NULL",
factory: { $0["url"] as! String })
if !fillDomainNamesFromCursor(urls, db: db) {
return false
}
}
if from < 8 && to == 8 {
// Nothing to do: we're just shifting the favicon table to be owned by this class.
return true
}
if from < 9 && to >= 9 {
if !self.run(db, sql: getBookmarksTableCreationStringForTable(TableBookmarksMirror)) {
return false
}
}
if from < 10 && to >= 10 {
if !self.run(db, sql: getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)) {
return false
}
let indexStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
if !self.run(db, sql: indexStructureParentIdx) {
return false
}
}
if from < 11 && to >= 11 {
if !self.run(db, sql: self.topSitesTableCreate) {
return false
}
}
if from < 12 && to >= 12 {
let bookmarksLocal = getBookmarksTableCreationStringForTable(TableBookmarksLocal, withAdditionalColumns: self.localColumns + self.iconColumns)
let bookmarksLocalStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksLocalStructure, referencingMirror: TableBookmarksLocal)
let bookmarksMirror = getBookmarksTableCreationStringForTable(TableBookmarksMirror, withAdditionalColumns: self.serverColumns + self.mirrorColumns + self.iconColumns)
let bookmarksMirrorStructure = getBookmarksStructureTableCreationStringForTable(TableBookmarksMirrorStructure, referencingMirror: TableBookmarksMirror)
let indexLocalStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksLocalStructureParentIdx) " +
"ON \(TableBookmarksLocalStructure) (parent, idx)"
let indexBufferStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksBufferStructureParentIdx) " +
"ON \(TableBookmarksBufferStructure) (parent, idx)"
let indexMirrorStructureParentIdx = "CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureParentIdx) " +
"ON \(TableBookmarksMirrorStructure) (parent, idx)"
let prep = [
// Drop indices.
"DROP INDEX IF EXISTS idx_bookmarksMirrorStructure_parent_idx",
// Rename the old mirror tables to buffer.
// The v11 one is the same shape as the current buffer table.
"ALTER TABLE \(TableBookmarksMirror) RENAME TO \(TableBookmarksBuffer)",
"ALTER TABLE \(TableBookmarksMirrorStructure) RENAME TO \(TableBookmarksBufferStructure)",
// Create the new mirror and local tables.
bookmarksLocal,
bookmarksMirror,
bookmarksLocalStructure,
bookmarksMirrorStructure,
]
// Only migrate bookmarks. The only folders are our roots, and we'll create those later.
// There should be nothing else in the table, and no structure.
// Our old bookmarks table didn't have creation date, so we use the current timestamp.
let modified = Date.now()
let status = SyncStatus.new.rawValue
// We don't specify a title, expecting it to be generated on the fly, because we're smarter than Android.
// We also don't migrate the 'id' column; we'll generate new ones that won't conflict with our roots.
let migrateArgs: Args = [BookmarkRoots.MobileFolderGUID]
let migrateLocal =
"INSERT INTO \(TableBookmarksLocal) " +
"(guid, type, bmkUri, title, faviconID, local_modified, sync_status, parentid, parentName) " +
"SELECT guid, type, url AS bmkUri, title, faviconID, " +
"\(modified) AS local_modified, \(status) AS sync_status, ?, '' " +
"FROM \(_TableBookmarks) WHERE type IS \(BookmarkNodeType.bookmark.rawValue)"
// Create structure for our migrated bookmarks.
// In order to get contiguous positions (idx), we first insert everything we just migrated under
// Mobile Bookmarks into a temporary table, then use rowid as our idx.
let temporaryTable =
"CREATE TEMPORARY TABLE children AS " +
"SELECT guid FROM \(_TableBookmarks) WHERE " +
"type IS \(BookmarkNodeType.bookmark.rawValue) ORDER BY id ASC"
let createStructure =
"INSERT INTO \(TableBookmarksLocalStructure) (parent, child, idx) " +
"SELECT ? AS parent, guid AS child, (rowid - 1) AS idx FROM children"
let migrate: [(String, Args?)] = [
(migrateLocal, migrateArgs),
(temporaryTable, nil),
(createStructure, migrateArgs),
// Drop the temporary table.
("DROP TABLE children", nil),
// Drop the old bookmarks table.
("DROP TABLE \(_TableBookmarks)", nil),
// Create indices for each structure table.
(indexBufferStructureParentIdx, nil),
(indexLocalStructureParentIdx, nil),
(indexMirrorStructureParentIdx, nil)
]
if !self.run(db, queries: prep) ||
!self.prepopulateRootFolders(db) ||
!self.run(db, queries: migrate) {
return false
}
// TODO: trigger a sync?
}
// Add views for the overlays.
if from < 14 && to >= 14 {
let indexMirrorStructureChild =
"CREATE INDEX IF NOT EXISTS \(IndexBookmarksMirrorStructureChild) " +
"ON \(TableBookmarksMirrorStructure) (child)"
if !self.run(db, queries: [
self.bufferBookmarksView,
self.bufferBookmarksStructureView,
self.localBookmarksView,
self.localBookmarksStructureView,
indexMirrorStructureChild]) {
return false
}
}
if from == 14 && to >= 15 {
// We screwed up some of the views. Recreate them.
if !self.run(db, queries: [
"DROP VIEW IF EXISTS \(ViewBookmarksBufferStructureOnMirror)",
"DROP VIEW IF EXISTS \(ViewBookmarksLocalStructureOnMirror)",
"DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)",
"DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)",
self.bufferBookmarksView,
self.bufferBookmarksStructureView,
self.localBookmarksView,
self.localBookmarksStructureView]) {
return false
}
}
if from < 16 && to >= 16 {
if !self.run(db, queries: [
allBookmarksView,
historyVisitsView,
awesomebarBookmarksView,
awesomebarBookmarksWithIconsView]) {
return false
}
}
if from < 17 && to >= 17 {
if !self.run(db, queries: [
// Adds the local_modified, server_modified times to the local bookmarks view
"DROP VIEW IF EXISTS \(ViewBookmarksLocalOnMirror)",
self.localBookmarksView]) {
return false
}
}
if from < 18 && to >= 18 {
if !self.run(db, queries: [
// Adds the Activity Stream blocklist table
activityStreamBlocklistCreate]) {
return false
}
}
if from < 19 && to >= 19 {
if !self.run(db, queries: [
// Adds tables/indicies for metadata content
pageMetadataCreate,
indexPageMetadataCacheKeyCreate]) {
return false
}
}
if from < 20 && to >= 20 {
if !self.run(db, queries: [
"DROP VIEW IF EXISTS \(ViewBookmarksBufferOnMirror)",
self.bufferBookmarksView]) {
return false
}
}
if from < 21 && to >= 21 {
if !self.run(db, queries: [
"DROP VIEW IF EXISTS \(ViewHistoryVisits)",
self.historyVisitsView,
indexPageMetadataSiteURLCreate]) {
return false
}
}
// Someone upgrading from v21 will get these tables anyway.
// So, there's no need to create them only to be dropped and
// re-created at v27 anyway.
// if from < 22 && to >= 22 {
// if !self.run(db, queries: [
// "DROP TABLE IF EXISTS \(TablePageMetadata)",
// pageMetadataCreate,
// indexPageMetadataCacheKeyCreate,
// indexPageMetadataSiteURLCreate]) {
// return false
// }
// }
//
// if from < 23 && to >= 23 {
// if !self.run(db, queries: [
// highlightsCreate]) {
// return false
// }
// }
//
// if from < 24 && to >= 24 {
// if !self.run(db, queries: [
// // We can safely drop the highlights cache table since it gets cleared on every invalidate anyways.
// "DROP TABLE IF EXISTS \(TableHighlights)",
// highlightsCreate
// ]) {
// return false
// }
// }
// Someone upgrading from v21 will get this table anyway.
// So, there's no need to create it only to be dropped and
// re-created at v26 anyway.
// if from < 25 && to >= 25 {
// if !self.run(db, queries: [
// pinnedTopSitesTableCreate
// ]) {
// return false
// }
// }
if from < 26 && to >= 26 {
if !self.run(db, queries: [
// The old pin table was never released so we can safely drop
"DROP TABLE IF EXISTS \(TablePinnedTopSites)",
pinnedTopSitesTableCreate
]) {
return false
}
}
if from < 27 && to >= 27 {
if !self.run(db, queries: [
"DROP TABLE IF EXISTS \(TablePageMetadata)",
"DROP TABLE IF EXISTS \(TableHighlights)",
pageMetadataCreate,
indexPageMetadataCacheKeyCreate,
indexPageMetadataSiteURLCreate,
highlightsCreate
]) {
return false
}
}
if from < 28 && to >= 28 {
if !self.run(db, queries: [
self.pendingBookmarksDeletions,
self.bufferBookmarksWithDeletionsView
]) {
return false
}
}
return true
}
fileprivate func fillDomainNamesFromCursor(_ cursor: Cursor<String>, db: SQLiteDBConnection) -> Bool {
if cursor.count == 0 {
return true
}
// URL -> hostname, flattened to make args.
var pairs = Args()
pairs.reserveCapacity(cursor.count * 2)
for url in cursor {
if let url = url, let host = url.asURL?.normalizedHost {
pairs.append(url)
pairs.append(host)
}
}
cursor.close()
let tmpTable = "tmp_hostnames"
let table = "CREATE TEMP TABLE \(tmpTable) (url TEXT NOT NULL UNIQUE, domain TEXT NOT NULL, domain_id INT)"
if !self.run(db, sql: table, args: nil) {
log.error("Can't create temporary table. Unable to migrate domain names. Top Sites is likely to be broken.")
return false
}
// Now insert these into the temporary table. Chunk by an even number, for obvious reasons.
let chunks = chunk(pairs, by: BrowserDB.MaxVariableNumber - (BrowserDB.MaxVariableNumber % 2))
for chunk in chunks {
let ins = "INSERT INTO \(tmpTable) (url, domain) VALUES " +
Array<String>(repeating: "(?, ?)", count: chunk.count / 2).joined(separator: ", ")
if !self.run(db, sql: ins, args: Array(chunk)) {
log.error("Couldn't insert domains into temporary table. Aborting migration.")
return false
}
}
// Now make those into domains.
let domains = "INSERT OR IGNORE INTO \(TableDomains) (domain) SELECT DISTINCT domain FROM \(tmpTable)"
// … and fill that temporary column.
let domainIDs = "UPDATE \(tmpTable) SET domain_id = (SELECT id FROM \(TableDomains) WHERE \(TableDomains).domain = \(tmpTable).domain)"
// Update the history table from the temporary table.
let updateHistory = "UPDATE \(TableHistory) SET domain_id = (SELECT domain_id FROM \(tmpTable) WHERE \(tmpTable).url = \(TableHistory).url)"
// Clean up.
let dropTemp = "DROP TABLE \(tmpTable)"
// Now run these.
if !self.run(db, queries: [domains,
domainIDs,
updateHistory,
dropTemp]) {
log.error("Unable to migrate domains.")
return false
}
return true
}
/**
* The Table mechanism expects to be able to check if a 'table' exists. In our (ab)use
* of Table, that means making sure that any of our tables and views exist.
* We do that by fetching all tables from sqlite_master with matching names, and verifying
* that we get back more than one.
* Note that we don't check for views -- trust to luck.
*/
func exists(_ db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllTables)
}
func drop(_ db: SQLiteDBConnection) -> Bool {
log.debug("Dropping all browser tables.")
let additional = [
"DROP TABLE IF EXISTS faviconSites" // We renamed it to match naming convention.
]
let views = AllViews.map { "DROP VIEW IF EXISTS \($0)" }
let indices = AllIndices.map { "DROP INDEX IF EXISTS \($0)" }
let tables = AllTables.map { "DROP TABLE IF EXISTS \($0)" }
let queries = Array([views, indices, tables, additional].joined())
return self.run(db, queries: queries)
}
}
| mpl-2.0 | 75fb178b7d98802fed21c6c46f80cc33 | 41.620438 | 246 | 0.610935 | 4.770425 | false | false | false | false |
sman591/csh-drink-ios | CSH Drink/AccountViewController.swift | 1 | 2300 | //
// AccountViewController.swift
// CSH Drink
//
// Created by Stuart Olivera on 5/25/15.
// Copyright (c) 2015 Stuart Olivera. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class AccountViewController: UIViewController {
@IBOutlet weak var backgroundImage: UIImageView!
@IBOutlet weak var creditsLabel: UILabel!
@IBAction func openWebDrinkAction(_ sender: UIButton) {
UIApplication.shared.openURL(URL(string: "https://webdrink.csh.rit.edu/#/settings")!)
}
@IBAction func openGitHubAction(_ sender: UIButton) {
UIApplication.shared.openURL(URL(string: "https://github.com/sman591/csh-drink-ios")!)
}
@IBAction func dismissAction(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
addParallax()
let credits = CurrentUser.sharedInstance.credits.value
creditsLabel.text = "\(credits) " + ("credit".pluralize(count: credits))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func addParallax() {
let relativeAbsoluteValue = 15
// Set vertical effect
let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: UIInterpolatingMotionEffectType.tiltAlongVerticalAxis)
verticalMotionEffect.minimumRelativeValue = -1 * relativeAbsoluteValue
verticalMotionEffect.maximumRelativeValue = relativeAbsoluteValue
// Set horizontal effect
let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: UIInterpolatingMotionEffectType.tiltAlongVerticalAxis)
horizontalMotionEffect.minimumRelativeValue = -1 * relativeAbsoluteValue
horizontalMotionEffect.maximumRelativeValue = relativeAbsoluteValue
// Create group to combine both
let group = UIMotionEffectGroup()
group.motionEffects = [horizontalMotionEffect, verticalMotionEffect]
self.backgroundImage.addMotionEffect(group)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "signOut" {
CurrentUser.logout()
}
}
}
| mit | 6bbf21d784ee365b7f62b4d145c3f796 | 34.384615 | 147 | 0.687826 | 5.18018 | false | false | false | false |
proversity-org/edx-app-ios | Source/DiscussionNewPostViewController.swift | 1 | 17685 | //
// DiscussionNewPostViewController.swift
// edX
//
// Created by Tang, Jeff on 6/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
struct DiscussionNewThread {
let courseID: String
let topicID: String
let type: DiscussionThreadType
let title: String
let rawBody: String
}
protocol DiscussionNewPostViewControllerDelegate : class {
func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread)
}
public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding {
public typealias Environment = DataManagerProvider & NetworkManagerProvider & OEXRouterProvider & OEXAnalyticsProvider
private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text
private let environment: Environment
private let growingTextController = GrowingTextViewController()
private let insetsController = ContentInsetsController()
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var contentTextView: OEXPlaceholderTextView!
@IBOutlet private var titleTextField: UITextField!
@IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl!
@IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private var topicButton: UIButton!
@IBOutlet private var postButton: SpinnerButton!
@IBOutlet weak var contentTitleLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
private let loadController = LoadStateViewController()
private let courseID: String
fileprivate let topics = BackedStream<[DiscussionTopic]>()
private var selectedTopic: DiscussionTopic?
private var optionsViewController: MenuOptionsViewController?
weak var delegate: DiscussionNewPostViewControllerDelegate?
private let tapButton = UIButton()
var titleTextStyle: OEXTextStyle {
return OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().neutralDark())
}
private var selectedThreadType: DiscussionThreadType = .Discussion {
didSet {
switch selectedThreadType {
case .Discussion:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.Dashboard.courseDiscussion), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion)
contentTextView.accessibilityLabel = Strings.Dashboard.courseDiscussion
case .Question:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.question), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle, withTitle: Strings.postQuestion)
contentTextView.accessibilityLabel = Strings.question
}
}
}
public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) {
self.environment = environment
self.courseID = courseID
super.init(nibName: "DiscussionNewPostViewController", bundle: nil)
let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID: courseID).topics
topics.backWithStream(stream.map {
return DiscussionTopic.linearizeTopics(topics: $0)
}
)
self.selectedTopic = selectedTopic
}
private var firstSelectableTopic : DiscussionTopic? {
let selectablePredicate = { (topic : DiscussionTopic) -> Bool in
topic.isSelectable
}
guard let topics = self.topics.value, let selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else {
return nil
}
return topics[selectableTopicIndex]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func postTapped(sender: AnyObject) {
postButton.isEnabled = false
postButton.showProgress = true
// create new thread (post)
if let topic = selectedTopic, let topicID = topic.id {
let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType , title: titleTextField.text ?? "", rawBody: contentTextView.text)
let apiRequest = DiscussionAPI.createNewThread(newThread: newThread)
environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
self?.postButton.isEnabled = true
self?.postButton.showProgress = false
if let post = result.data {
self?.delegate?.newPostController(controller: self!, addedPost: post)
self?.dismiss(animated: true, completion: nil)
}
else {
DiscussionHelper.showErrorMessage(controller: self, error: result.error)
}
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = Strings.post
let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
cancelItem.oex_setAction { [weak self]() -> Void in
self?.dismiss(animated: true, completion: nil)
}
self.navigationItem.leftBarButtonItem = cancelItem
contentTitleLabel.isAccessibilityElement = false
titleLabel.isAccessibilityElement = false
titleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.title), titleTextStyle.attributedString(withText: Strings.asteric)])
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.applyStandardBorderStyle()
contentTextView.delegate = self
titleTextField.accessibilityLabel = Strings.title
self.view.backgroundColor = OEXStyles.shared().neutralXXLight()
configureSegmentControl()
titleTextField.defaultTextAttributes = OEXStyles.shared().textAreaBodyStyle.attributes.attributedKeyDictionary()
setTopicsButtonTitle()
let insets = OEXStyles.shared().standardTextViewInsets
topicButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: insets.left, bottom: 0, right: insets.right)
topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint
topicButton.applyBorderStyle(style: OEXStyles.shared().entryFieldBorderStyle)
topicButton.localizedHorizontalContentAlignment = .Leading
let dropdownLabel = UILabel()
dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style: titleTextStyle)
topicButton.addSubview(dropdownLabel)
dropdownLabel.snp.makeConstraints { make in
make.trailing.equalTo(topicButton).offset(-insets.right)
make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0)
}
topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in
self?.showTopicPicker()
}, for: UIControl.Event.touchUpInside)
postButton.isEnabled = false
titleTextField.oex_addAction({[weak self] _ in
self?.validatePostButton()
}, for: .editingChanged)
self.growingTextController.setupWithScrollView(scrollView: scrollView, textView: contentTextView, bottomView: postButton)
self.insetsController.setupInController(owner: self, scrollView: scrollView)
// Force setting it to call didSet which is only called out of initialization context
self.selectedThreadType = .Question
loadController.setupInController(controller: self, contentView: self.scrollView)
topics.listen(self, success : {[weak self]_ in
self?.loadedData()
}, failure : {[weak self] error in
self?.loadController.state = LoadState.failed(error: error)
})
backgroundView.addSubview(tapButton)
backgroundView.sendSubviewToBack(tapButton)
tapButton.backgroundColor = UIColor.clear
tapButton.frame = CGRect(x: 0, y: 0, width: backgroundView.frame.size.width, height: backgroundView.frame.size.height)
tapButton.isAccessibilityElement = false
tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard
tapButton.oex_addAction({[weak self] (sender) in
self?.view.endEditing(true)
}, for: .touchUpInside)
}
private func configureSegmentControl() {
discussionQuestionSegmentedControl.removeAllSegments()
let questionIcon = Icon.Question.attributedTextWithStyle(style: titleTextStyle)
let questionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [questionIcon,
titleTextStyle.attributedString(withText: Strings.question)])
let discussionIcon = Icon.Comments.attributedTextWithStyle(style: titleTextStyle)
let discussionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [discussionIcon,
titleTextStyle.attributedString(withText: Strings.discussion)])
let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [
(title : questionTitle, value : .Question),
(title : discussionTitle, value : .Discussion),
]
for i in 0..<segmentOptions.count {
discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(title: segmentOptions[i].title, index: i, animated: false)
discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string
}
discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in
if let segmentedControl = control as? UISegmentedControl {
let index = segmentedControl.selectedSegmentIndex
let threadType = segmentOptions[index].value
self?.selectedThreadType = threadType
self?.updateSelectedTabColor()
}
else {
assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum")
}
}, for: UIControl.Event.valueChanged)
discussionQuestionSegmentedControl.tintColor = OEXStyles.shared().neutralDark()
discussionQuestionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: OEXStyles.shared().neutralWhite()], for: UIControl.State.selected)
discussionQuestionSegmentedControl.selectedSegmentIndex = 0
updateSelectedTabColor()
}
private func updateSelectedTabColor() {
// //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour
let subViews:NSArray = discussionQuestionSegmentedControl.subviews as NSArray
for i in 0..<subViews.count {
if (subViews.object(at: i) as AnyObject).isSelected ?? false {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().primaryBaseColor()
}
else {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().neutralDark()
}
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.environment.analytics.trackDiscussionScreen(withName: AnalyticsScreenName.CreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil)
}
override public var shouldAutorotate: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func loadedData() {
loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded
if selectedTopic == nil {
selectedTopic = firstSelectableTopic
}
setTopicsButtonTitle()
}
private func setTopicsButtonTitle() {
if let topic = selectedTopic, let name = topic.name {
let title = Strings.topic(topic: name)
topicButton.setAttributedTitle(OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().neutralDark()).attributedString(withText: title), for: .normal)
}
}
func showTopicPicker() {
if self.optionsViewController != nil {
return
}
view.endEditing(true)
self.optionsViewController = MenuOptionsViewController()
self.optionsViewController?.delegate = self
guard let courseTopics = topics.value else {
//Don't need to configure an empty state here because it's handled in viewDidLoad()
return
}
self.optionsViewController?.options = courseTopics.map {
return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "")
}
self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex()
self.view.addSubview(self.optionsViewController!.view)
self.optionsViewController!.view.snp.makeConstraints { make in
make.trailing.equalTo(self.topicButton)
make.leading.equalTo(self.topicButton)
make.top.equalTo(self.topicButton.snp.bottom).offset(-3)
make.bottom.equalTo(safeBottom)
}
self.optionsViewController?.view.alpha = 0.0
UIView.animate(withDuration: 0.3) {
self.optionsViewController?.view.alpha = 1.0
}
}
private func selectedTopicIndex() -> Int? {
guard let selected = selectedTopic else {
return 0
}
return self.topics.value?.firstIndexMatching {
return $0.id == selected.id
}
}
public func textViewDidChange(_ textView: UITextView) {
validatePostButton()
growingTextController.handleTextChange()
}
public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool {
return self.topics.value?[index].isSelectable ?? false
}
private func validatePostButton() {
self.postButton.isEnabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil
}
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) {
selectedTopic = self.topics.value?[index]
if let topic = selectedTopic, topic.id != nil {
setTopicsButtonTitle()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: titleTextField);
UIView.animate(withDuration: 0.3, animations: {
self.optionsViewController?.view.alpha = 0.0
}, completion: {[weak self](finished: Bool) in
self?.optionsViewController?.view.removeFromSuperview()
self?.optionsViewController = nil
})
}
}
public override func viewDidLayoutSubviews() {
self.insetsController.updateInsets()
growingTextController.scrollToVisible()
}
private func textFieldDidBeginEditing(textField: UITextField) {
tapButton.isAccessibilityElement = true
}
private func textFieldDidEndEditing(textField: UITextField) {
tapButton.isAccessibilityElement = false
}
public func textViewDidBeginEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = true
}
public func textViewDidEndEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = false
}
}
extension UISegmentedControl {
//UIsegmentControl didn't support attributedTitle by default
func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) {
let segmentLabel = UILabel()
segmentLabel.backgroundColor = UIColor.clear
segmentLabel.textAlignment = .center
segmentLabel.attributedText = title
segmentLabel.sizeToFit()
self.insertSegment(with: segmentLabel.toImage(), at: 1, animated: false)
}
}
extension UILabel {
func toImage()-> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image;
}
}
// For use in testing only
extension DiscussionNewPostViewController {
public func t_topicsLoaded() -> OEXStream<[DiscussionTopic]> {
return topics
}
}
| apache-2.0 | a516df64b9c06b1f9190d779ff7028a1 | 42.883375 | 254 | 0.676562 | 5.639349 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Comments/CommentContentTableViewCell.swift | 1 | 20918 | import UIKit
class CommentContentTableViewCell: UITableViewCell, NibReusable {
// all the available images for the accessory button.
enum AccessoryButtonType {
case share
case ellipsis
case info
}
enum RenderMethod {
/// Uses WebKit to render the comment body.
case web
/// Uses WPRichContent to render the comment body.
case richContent
}
// MARK: - Public Properties
/// A closure that's called when the accessory button is tapped.
/// The button's view is sent as the closure's parameter for reference.
@objc var accessoryButtonAction: ((UIView) -> Void)? = nil
@objc var replyButtonAction: (() -> Void)? = nil
@objc var likeButtonAction: (() -> Void)? = nil
@objc var contentLinkTapAction: ((URL) -> Void)? = nil
@objc weak var richContentDelegate: WPRichContentViewDelegate? = nil
/// Encapsulate the accessory button image assignment through an enum, to apply a standardized image configuration.
/// See `accessoryIconConfiguration` in `WPStyleGuide+CommentDetail`.
var accessoryButtonType: AccessoryButtonType = .share {
didSet {
accessoryButton.setImage(accessoryButtonImage, for: .normal)
}
}
/// When supplied with a non-empty string, the cell will show a badge label beside the name label.
/// Note that the badge will be hidden when the title is nil or empty.
var badgeTitle: String? = nil {
didSet {
let title: String = {
if let title = badgeTitle {
return title.localizedUppercase
}
return String()
}()
badgeLabel.setText(title)
badgeLabel.isHidden = title.isEmpty
badgeLabel.updateConstraintsIfNeeded()
}
}
override var indentationWidth: CGFloat {
didSet {
updateContainerLeadingConstraint()
}
}
override var indentationLevel: Int {
didSet {
updateContainerLeadingConstraint()
}
}
/// A custom highlight style for the cell that is more controllable than `isHighlighted`.
/// Cell selection for this cell is disabled, and highlight style may be disabled based on the table view settings.
@objc var isEmphasized: Bool = false {
didSet {
backgroundColor = isEmphasized ? Style.highlightedBackgroundColor : nil
highlightBarView.backgroundColor = isEmphasized ? Style.highlightedBarBackgroundColor : .clear
}
}
@objc var isReplyHighlighted: Bool = false {
didSet {
replyButton?.tintColor = isReplyHighlighted ? Style.highlightedReplyButtonTintColor : Style.reactionButtonTextColor
replyButton?.setTitleColor(isReplyHighlighted ? Style.highlightedReplyButtonTintColor : Style.reactionButtonTextColor, for: .normal)
replyButton?.setImage(isReplyHighlighted ? Style.highlightedReplyIconImage : Style.replyIconImage, for: .normal)
}
}
// MARK: Constants
private let customBottomSpacing: CGFloat = 10
private let contentButtonsTopSpacing: CGFloat = 15
// MARK: Outlets
@IBOutlet private weak var containerStackView: UIStackView!
@IBOutlet private weak var containerStackBottomConstraint: NSLayoutConstraint!
@IBOutlet private weak var containerStackLeadingConstraint: NSLayoutConstraint!
@IBOutlet private weak var containerStackTrailingConstraint: NSLayoutConstraint!
private var defaultLeadingMargin: CGFloat = 0
@IBOutlet private weak var avatarImageView: CircularImageView!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var badgeLabel: BadgeLabel!
@IBOutlet private weak var dateLabel: UILabel!
@IBOutlet private(set) weak var accessoryButton: UIButton!
@IBOutlet private weak var contentContainerView: UIView!
@IBOutlet private weak var contentContainerHeightConstraint: NSLayoutConstraint!
@IBOutlet private weak var replyButton: UIButton!
@IBOutlet private weak var likeButton: UIButton!
@IBOutlet private weak var highlightBarView: UIView!
@IBOutlet private weak var separatorView: UIView!
// MARK: Private Properties
/// Called when the cell has finished loading and calculating the height of the HTML content. Passes the new content height as parameter.
private var onContentLoaded: ((CGFloat) -> Void)? = nil
/// Cache the HTML template format. We only need read the template once.
private static let htmlTemplateFormat: String? = {
guard let templatePath = Bundle.main.path(forResource: "richCommentTemplate", ofType: "html"),
let templateString = try? String(contentsOfFile: templatePath) else {
return nil
}
return templateString
}()
private var renderer: CommentContentRenderer? = nil
private var renderMethod: RenderMethod?
// MARK: Like Button State
private var isLiked: Bool = false
private var likeCount: Int = 0
private var isLikeButtonAnimating: Bool = false
// MARK: Visibility Control
private var isCommentReplyEnabled: Bool = false {
didSet {
replyButton.isHidden = !isCommentReplyEnabled
}
}
private var isCommentLikesEnabled: Bool = false {
didSet {
likeButton.isHidden = !isCommentLikesEnabled
}
}
private var isAccessoryButtonEnabled: Bool = false {
didSet {
accessoryButton.isHidden = !isAccessoryButtonEnabled
}
}
private var isReactionBarVisible: Bool {
return isCommentReplyEnabled || isCommentLikesEnabled
}
var shouldHideSeparator = false {
didSet {
separatorView.isHidden = shouldHideSeparator
}
}
// MARK: Lifecycle
override func prepareForReuse() {
super.prepareForReuse()
// reset all highlight states.
isEmphasized = false
isReplyHighlighted = false
// reset all button actions.
accessoryButtonAction = nil
replyButtonAction = nil
likeButtonAction = nil
contentLinkTapAction = nil
onContentLoaded = nil
}
override func awakeFromNib() {
super.awakeFromNib()
configureViews()
}
// MARK: Public Methods
/// Configures the cell with a `Comment` object.
///
/// - Parameters:
/// - comment: The `Comment` object to display.
/// - renderMethod: Specifies how to display the comment body. See `RenderMethod`.
/// - onContentLoaded: Callback to be called once the content has been loaded. Provides the new content height as parameter.
func configure(with comment: Comment, renderMethod: RenderMethod = .web, onContentLoaded: ((CGFloat) -> Void)?) {
nameLabel?.setText(comment.authorForDisplay())
dateLabel?.setText(comment.dateForDisplay()?.toMediumString() ?? String())
// Always cancel ongoing image downloads, just in case. This is to prevent comment cells being displayed with the wrong avatar image,
// likely resulting from previous download operation before the cell is reused.
//
// Note that when downloading an image, any ongoing operation will be cancelled in UIImageView+Networking.
// This is more of a preventative step where the cancellation is made to happen as early as possible.
//
// Ref: https://github.com/wordpress-mobile/WordPress-iOS/issues/17972
avatarImageView.cancelImageDownload()
if let avatarURL = URL(string: comment.authorAvatarURL) {
configureImage(with: avatarURL)
} else {
configureImageWithGravatarEmail(comment.gravatarEmailForDisplay())
}
updateLikeButton(liked: comment.isLiked, numberOfLikes: comment.numberOfLikes())
// Configure feature availability.
isCommentReplyEnabled = comment.canReply()
isCommentLikesEnabled = comment.canLike()
isAccessoryButtonEnabled = comment.isApproved()
// When reaction bar is hidden, add some space between the webview and the moderation bar.
containerStackView.setCustomSpacing(contentButtonsTopSpacing, after: contentContainerView)
// Configure content renderer.
self.onContentLoaded = onContentLoaded
configureRendererIfNeeded(for: comment, renderMethod: renderMethod)
}
/// Configures the cell with a `Comment` object, to be displayed in the post details view.
///
/// - Parameters:
/// - comment: The `Comment` object to display.
/// - onContentLoaded: Callback to be called once the content has been loaded. Provides the new content height as parameter.
func configureForPostDetails(with comment: Comment, onContentLoaded: ((CGFloat) -> Void)?) {
configure(with: comment, onContentLoaded: onContentLoaded)
isCommentLikesEnabled = false
isCommentReplyEnabled = false
isAccessoryButtonEnabled = false
containerStackLeadingConstraint.constant = 0
containerStackTrailingConstraint.constant = 0
}
@objc func ensureRichContentTextViewLayout() {
guard renderMethod == .richContent,
let richContentTextView = contentContainerView.subviews.first as? WPRichContentView else {
return
}
richContentTextView.updateLayoutForAttachments()
}
}
// MARK: - CommentContentRendererDelegate
extension CommentContentTableViewCell: CommentContentRendererDelegate {
func renderer(_ renderer: CommentContentRenderer, asyncRenderCompletedWithHeight height: CGFloat) {
if renderMethod == .web {
contentContainerHeightConstraint?.constant = height
}
onContentLoaded?(height)
}
func renderer(_ renderer: CommentContentRenderer, interactedWithURL url: URL) {
contentLinkTapAction?(url)
}
}
// MARK: - Helpers
private extension CommentContentTableViewCell {
typealias Style = WPStyleGuide.CommentDetail.Content
var accessoryButtonImage: UIImage? {
switch accessoryButtonType {
case .share:
return .init(systemName: Style.shareIconImageName, withConfiguration: Style.accessoryIconConfiguration)
case .ellipsis:
return .init(systemName: Style.ellipsisIconImageName, withConfiguration: Style.accessoryIconConfiguration)
case .info:
return .init(systemName: Style.infoIconImageName, withConfiguration: Style.accessoryIconConfiguration)
}
}
var likeButtonTitle: String {
switch likeCount {
case .zero:
return .noLikes
case 1:
return String(format: .singularLikeFormat, likeCount)
default:
return String(format: .pluralLikesFormat, likeCount)
}
}
// assign base styles for all the cell components.
func configureViews() {
// Store default margin for use in content layout.
defaultLeadingMargin = containerStackLeadingConstraint.constant
selectionStyle = .none
nameLabel?.font = Style.nameFont
nameLabel?.textColor = Style.nameTextColor
badgeLabel?.font = Style.badgeFont
badgeLabel?.textColor = Style.badgeTextColor
badgeLabel?.backgroundColor = Style.badgeColor
badgeLabel?.adjustsFontForContentSizeCategory = true
badgeLabel?.adjustsFontSizeToFitWidth = true
dateLabel?.font = Style.dateFont
dateLabel?.textColor = Style.dateTextColor
accessoryButton?.tintColor = Style.buttonTintColor
accessoryButton?.setImage(accessoryButtonImage, for: .normal)
accessoryButton?.addTarget(self, action: #selector(accessoryButtonTapped), for: .touchUpInside)
replyButton?.tintColor = Style.reactionButtonTextColor
replyButton?.titleLabel?.font = Style.reactionButtonFont
replyButton?.titleLabel?.adjustsFontSizeToFitWidth = true
replyButton?.titleLabel?.adjustsFontForContentSizeCategory = true
replyButton?.setTitle(.reply, for: .normal)
replyButton?.setTitleColor(Style.reactionButtonTextColor, for: .normal)
replyButton?.setImage(Style.replyIconImage, for: .normal)
replyButton?.addTarget(self, action: #selector(replyButtonTapped), for: .touchUpInside)
replyButton?.flipInsetsForRightToLeftLayoutDirection()
replyButton?.adjustsImageSizeForAccessibilityContentSizeCategory = true
adjustImageAndTitleEdgeInsets(for: replyButton)
replyButton?.sizeToFit()
likeButton?.tintColor = Style.reactionButtonTextColor
likeButton?.titleLabel?.font = Style.reactionButtonFont
likeButton?.titleLabel?.adjustsFontSizeToFitWidth = true
likeButton?.titleLabel?.adjustsFontForContentSizeCategory = true
likeButton?.setTitleColor(Style.reactionButtonTextColor, for: .normal)
likeButton?.addTarget(self, action: #selector(likeButtonTapped), for: .touchUpInside)
likeButton?.flipInsetsForRightToLeftLayoutDirection()
likeButton?.adjustsImageSizeForAccessibilityContentSizeCategory = true
adjustImageAndTitleEdgeInsets(for: likeButton)
updateLikeButton(liked: false, numberOfLikes: 0)
likeButton?.sizeToFit()
}
private func adjustImageAndTitleEdgeInsets(for button: UIButton) {
guard let imageSize = button.imageView?.frame.size, let titleSize = button.titleLabel?.frame.size else {
return
}
let spacing: CGFloat = 3
button.titleEdgeInsets = .init(top: 0, left: -titleSize.width, bottom: -(imageSize.height + spacing), right: 0)
button.imageEdgeInsets = .init(top: -(titleSize.height + spacing), left: imageSize.width/2, bottom: 0, right: 0)
}
/// Configures the avatar image view with the provided URL.
/// If the URL does not contain any image, the default placeholder image will be displayed.
/// - Parameter url: The URL containing the image.
func configureImage(with url: URL?) {
if let someURL = url, let gravatar = Gravatar(someURL) {
avatarImageView.downloadGravatar(gravatar, placeholder: Style.placeholderImage, animate: true)
return
}
// handle non-gravatar images
avatarImageView.downloadImage(from: url, placeholderImage: Style.placeholderImage)
}
/// Configures the avatar image view from Gravatar based on provided email.
/// If the Gravatar image for the provided email doesn't exist, the default placeholder image will be displayed.
/// - Parameter gravatarEmail: The email to be used for querying the Gravatar image.
func configureImageWithGravatarEmail(_ email: String?) {
guard let someEmail = email else {
return
}
avatarImageView.downloadGravatarWithEmail(someEmail, placeholderImage: Style.placeholderImage)
}
func updateContainerLeadingConstraint() {
containerStackLeadingConstraint?.constant = (indentationWidth * CGFloat(indentationLevel)) + defaultLeadingMargin
}
/// Updates the style and text of the Like button.
/// - Parameters:
/// - liked: Represents the target state – true if the comment is liked, or should be false otherwise.
/// - numberOfLikes: The number of likes to be displayed.
/// - animated: Whether the Like button state change should be animated or not. Defaults to false.
/// - completion: Completion block called once the animation is completed. Defaults to nil.
func updateLikeButton(liked: Bool, numberOfLikes: Int, animated: Bool = false, completion: (() -> Void)? = nil) {
guard !isLikeButtonAnimating else {
return
}
isLiked = liked
likeCount = numberOfLikes
let onAnimationComplete = { [weak self] in
guard let self = self else {
return
}
self.likeButton.tintColor = liked ? Style.likedTintColor : Style.reactionButtonTextColor
self.likeButton.setImage(liked ? Style.likedIconImage : Style.unlikedIconImage, for: .normal)
self.likeButton.setTitle(self.likeButtonTitle, for: .normal)
self.adjustImageAndTitleEdgeInsets(for: self.likeButton)
self.likeButton.setTitleColor(liked ? Style.likedTintColor : Style.reactionButtonTextColor, for: .normal)
completion?()
}
guard animated else {
onAnimationComplete()
return
}
isLikeButtonAnimating = true
if isLiked {
UINotificationFeedbackGenerator().notificationOccurred(.success)
}
animateLikeButton {
onAnimationComplete()
self.isLikeButtonAnimating = false
}
}
/// Animates the Like button state change.
func animateLikeButton(completion: @escaping () -> Void) {
guard let buttonImageView = likeButton.imageView,
let overlayImage = Style.likedIconImage?.withTintColor(Style.likedTintColor) else {
completion()
return
}
let overlayImageView = UIImageView(image: overlayImage)
overlayImageView.frame = likeButton.convert(buttonImageView.bounds, from: buttonImageView)
likeButton.addSubview(overlayImageView)
let animation = isLiked ? overlayImageView.fadeInWithRotationAnimation : overlayImageView.fadeOutWithRotationAnimation
animation { _ in
overlayImageView.removeFromSuperview()
completion()
}
}
// MARK: Content Rendering
func resetRenderedContents() {
renderer = nil
contentContainerView.subviews.forEach { $0.removeFromSuperview() }
}
func configureRendererIfNeeded(for comment: Comment, renderMethod: RenderMethod) {
// skip creating the renderer if the content does not change.
// this prevents the cell to jump multiple times due to consecutive reloadData calls.
//
// note that this doesn't apply for `.richContent` method. Always reset the textView instead
// of reusing it to prevent crash. Ref: http://git.io/Jtl2U
if let renderer = renderer,
renderer.matchesContent(from: comment),
renderMethod == .web {
return
}
// clean out any pre-existing renderer just to be sure.
resetRenderedContents()
var renderer: CommentContentRenderer = {
switch renderMethod {
case .web:
return WebCommentContentRenderer(comment: comment)
case .richContent:
let renderer = RichCommentContentRenderer(comment: comment)
renderer.richContentDelegate = self.richContentDelegate
return renderer
}
}()
renderer.delegate = self
self.renderer = renderer
self.renderMethod = renderMethod
if renderMethod == .web {
// reset height constraint to handle cases where the new content requires the webview to shrink.
contentContainerHeightConstraint?.isActive = true
contentContainerHeightConstraint?.constant = 1
} else {
contentContainerHeightConstraint?.isActive = false
}
let contentView = renderer.render()
contentContainerView?.addSubview(contentView)
contentContainerView?.pinSubviewToAllEdges(contentView)
}
// MARK: Button Actions
@objc func accessoryButtonTapped() {
accessoryButtonAction?(accessoryButton)
}
@objc func replyButtonTapped() {
replyButtonAction?()
}
@objc func likeButtonTapped() {
ReachabilityUtils.onAvailableInternetConnectionDo {
updateLikeButton(liked: !isLiked, numberOfLikes: isLiked ? likeCount - 1 : likeCount + 1, animated: true) {
self.likeButtonAction?()
}
}
}
}
// MARK: - Localization
private extension String {
static let reply = NSLocalizedString("Reply", comment: "Reply to a comment.")
static let noLikes = NSLocalizedString("Like", comment: "Button title to Like a comment.")
static let singularLikeFormat = NSLocalizedString("%1$d Like", comment: "Singular button title to Like a comment. "
+ "%1$d is a placeholder for the number of Likes.")
static let pluralLikesFormat = NSLocalizedString("%1$d Likes", comment: "Plural button title to Like a comment. "
+ "%1$d is a placeholder for the number of Likes.")
// pattern that detects empty HTML elements (including HTML comments within).
static let emptyElementRegexPattern = "<[a-z]+>(<!-- [a-zA-Z0-9\\/: \"{}\\-\\.,\\?=\\[\\]]+ -->)+<\\/[a-z]+>"
}
| gpl-2.0 | a1c22fbb1fa442d35c0ad0bbdd3555ec | 37.949721 | 144 | 0.672069 | 5.320784 | false | false | false | false |
Bluthwort/Bluthwort | Example/Tests/Tests.swift | 1 | 1147 | // https://github.com/Quick/Quick
import Quick
import Nimble
import Bluthwort
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | d92525d76a939f38942434d6166f3328 | 21.82 | 60 | 0.361087 | 5.485577 | false | false | false | false |
fabioalmeida/FAAutoLayout | FAAutoLayout/Classes/UIView+Spacing.swift | 1 | 10303 | //
// UIView+Spacing.swift
// FAAutoLayout
//
// Created by Fábio Almeida on 27/06/2017.
// Copyright (c) 2017 Fábio Almeida. All rights reserved.
//
import UIKit
// MARK: - Spacing
public extension UIView {
/// Constrains the view horizontal spacing to other view that is on the same hierarchy level
///
/// This contraint is added directly to the container view and is returned for future manipulation (if needed).
/// This method should be used when you wish to define a horizontal space relation to a view that is on the same
/// hierarchy level (i.e share the same superview).
///
/// To use positive constant values, this methods should be used by adding the relation from the second view to the
/// first which means that the `toView` argument should be a view that sits physically on the left in relation with the
/// view were you are calling this method on.
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for this contraint are the same as if the constraint was created on the Interface Builder.
///
/// - Parameters:
/// - toView: The view for which we want to create the horizontal space relation. For positive `constant` values, should be on the left.
/// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added constraint between the two views.
@discardableResult
@objc(constrainHorizontalSpacingToView:constant:relation:priority:multiplier:)
func constrainHorizontalSpacing(toView view: UIView,
constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> NSLayoutConstraint {
validateViewHierarchy()
let constraint = NSLayoutConstraint.horizontalSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.superview!.addConstraint(constraint)
return constraint
}
/// Spaces out all the views horizontally with the same space between all of them.
///
/// These contraints are added directly to the container view and are returned for future manipulation (if needed).
/// This method should be used when you wish to space several views horizontally with the same dimension.
/// It can be useful, for instance, if you create an array of views dynamically and the horizontal space between
/// them should be the same.
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for these contraints are the same as if the constraints were created on the Interface Builder.
///
/// - Parameters:
/// - views: The array of views to which we want to horizontally space.
/// - constant: The constant added to the multiplied second attribute participating in the constraint.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added horizontal space constraints.
@discardableResult
@objc(constrainEqualHorizontalSpacing:constant:relation:priority:multiplier:)
class func constrainEqualHorizontalSpacing(_ views: [UIView],
constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> [NSLayoutConstraint] {
validateNumberOfViews(views)
var constraints = [NSLayoutConstraint]()
for index in 0..<(views.count-1) {
let fromView = views[index+1]
let toView = views[index]
validateViewHierarchy(fromView)
let constraint = NSLayoutConstraint.horizontalSpaceConstraint(fromView: fromView, toView: toView, relation: relation, multiplier: multiplier, constant: constant)
constraints.append(constraint)
fromView.superview!.addConstraint(constraint)
}
return constraints
}
/// Constrains the view vertical spacing to other view that is on the same hierarchy level
///
/// This contraint is added directly to the container view and is returned for future manipulation (if needed).
/// This method should be used when you wish to define a vertical space relation to a view that is on the same
/// hierarchy level (i.e share the same superview).
///
/// To use positive constant values, this methods should be used by adding the relation from the second view to the
/// first which means that the `toView` argument should be a view that sits physically above in relation with the
/// view were you are calling this method on.
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for this contraint are the same as if the constraint was created on the Interface Builder.
///
/// - Parameters:
/// - toView: The view for which we want to create the vertical space relation. For positive `constant` values, should be above.
/// - constant: The constant added to the multiplied second attribute participating in the constraint. The default value is 0.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added constraint between the two views.
@discardableResult
@objc(constrainVerticalSpacingToView:constant:relation:priority:multiplier:)
func constrainVerticalSpacing(toView view: UIView,
constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> NSLayoutConstraint {
validateViewHierarchy()
let constraint = NSLayoutConstraint.verticalSpaceConstraint(fromView: self, toView: view, relation: relation, multiplier: multiplier, constant: constant)
constraint.priority = priority
self.superview!.addConstraint(constraint)
return constraint
}
/// Spaces out all the views vertically with the same space between all of them.
///
/// These contraints are added directly to the container view and are returned for future manipulation (if needed).
/// This method should be used when you wish to space several views vertically with the same dimension.
/// It can be useful, for instance, if you create an array of views dynamically and the vertical space between
/// them should be the same.
///
/// The arguments should only be changed when the desired value is not the default value, to simplify the method readability.
/// All the **default values** for these contraints are the same as if the constraints were created on the Interface Builder.
///
/// - Parameters:
/// - views: The array of views to which we want to vertically space.
/// - constant: The constant added to the multiplied second attribute participating in the constraint.
/// - relation: The relation between the two attributes in the constraint (e.g. =, >, >=, <, <=). The default relation is Equal.
/// - priority: The priority of the constraint. The default value is 1000 (required).
/// - multiplier: The multiplier applied to the second attribute participating in the constraint. The default value is 1.
/// - Returns: The added vertical space constraints.
@discardableResult
@objc(constrainEqualVerticalSpacing:constant:relation:priority:multiplier:)
class func constrainEqualVerticalSpacing(_ views: [UIView],
constant: CGFloat = Constants.spacing,
relation: NSLayoutConstraint.Relation = Constants.relation,
priority: UILayoutPriority = Constants.priority,
multiplier: CGFloat = Constants.multiplier) -> [NSLayoutConstraint] {
validateNumberOfViews(views)
var constraints = [NSLayoutConstraint]()
for index in 0..<(views.count-1) {
let fromView = views[index+1]
let toView = views[index]
validateViewHierarchy(fromView)
let constraint = NSLayoutConstraint.verticalSpaceConstraint(fromView: fromView, toView: toView, relation: relation, multiplier: multiplier, constant: constant)
constraints.append(constraint)
fromView.superview!.addConstraint(constraint)
}
return constraints
}
}
| mit | 2b101d42e8443ea195dada93668bcc5a | 57.528409 | 173 | 0.668964 | 5.370699 | false | false | false | false |
tad-iizuka/swift-sdk | Source/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift | 1 | 3531 | /**
* Copyright IBM Corporation 2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** The detected anger, disgust, fear, joy, or sadness that is conveyed
by the content. Emotion information can be returned for detected entities,
keywords, or user-specified target phrases found in the text. */
public struct EmotionResult: JSONDecodable {
/// The returned emotion results across the document.
public let document: DocumentEmotionResults?
/// The returned emotion results per specified target.
public let targets: [TargetedEmotionResults]?
/// Used internally to initialize an `EmotionResult` model from JSON.
public init(json: JSON) throws {
document = try? json.decode(at: "document", type: DocumentEmotionResults.self)
targets = try? json.decodedArray(at: "targets", type: TargetedEmotionResults.self)
}
}
/** An object containing the emotion results of a document. */
public struct DocumentEmotionResults: JSONDecodable {
/// The returned emotion result.
public let emotion: EmotionScores?
/// Used internally to initialize a 'DocumentEmotionResults' model from JSON.
public init(json: JSON) throws {
emotion = try? json.decode(at: "emotion", type: EmotionScores.self)
}
}
/** An object containing all the emotion results in a document. */
public struct EmotionScores: JSONDecodable {
/// Anger score from 0 to 1. A higher score means that the text is more likely to convey anger.
public let anger: Double?
/// Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust.
public let disgust: Double?
/// Fear score from 0 to 1. A higher score means that the text is more likely to convey fear.
public let fear: Double?
/// Joy score from 0 to 1. A higher score means that the text is more likely to convey joy.
public let joy: Double?
/// Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness.
public let sadness: Double?
/// Used internally to intialize a 'DocumentEmotionResults' model from JSON.
public init(json: JSON) throws {
anger = try? json.getDouble(at: "anger")
disgust = try? json.getDouble(at: "disgust")
fear = try? json.getDouble(at: "fear")
joy = try? json.getDouble(at: "joy")
sadness = try? json.getDouble(at: "sadness")
}
}
/** An object containing the emotion results per target specified. */
public struct TargetedEmotionResults: JSONDecodable {
/// Targeted text.
public let text: String?
/// The emotion results of the targetted text.
public let emotion: EmotionScores?
/// Used internally to initialize a `TargetedEmotionResults` model from JSON.
public init(json: JSON) throws {
text = try? json.getString(at: "text")
emotion = try? json.decode(at: "emotion", type: EmotionScores.self)
}
}
| apache-2.0 | be06458cf97513dd46129bf3878b885c | 37.380435 | 103 | 0.694421 | 4.343173 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Controller/BaseTableViewController.swift | 1 | 1499 | //
// BaseTableViewController.swift
// DereGuide
//
// Created by zzk on 16/8/13.
// Copyright © 2016年 zzk. All rights reserved.
//
import UIKit
class BaseTableViewController: UITableViewController {
override var shouldAutorotate: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIDevice.current.userInterfaceIdiom == .pad ? .all : .portrait
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.cellLayoutMarginsFollowReadableWidth = false
clearsSelectionOnViewWillAppear = true
tableView.keyboardDismissMode = .onDrag
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
// 下面这两个方法可以让分割线左侧顶格显示 不再留15像素
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.separatorInset = UIEdgeInsets.zero
tableView.layoutMargins = UIEdgeInsets.zero
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.separatorInset = UIEdgeInsets.zero
cell.layoutMargins = UIEdgeInsets.zero
}
}
| mit | 8b895b063474e7793f7bd69b11eef5e4 | 28.55102 | 121 | 0.685083 | 5.484848 | false | false | false | false |
JohnnyHao/ForeignChat | ForeignChat/TabVCs/Messages/MessagesCell.swift | 1 | 1621 | //
// MessagesCell.swift
// ForeignChat
//
// Created by Tonny Hao on 3/3/15.
// Copyright (c) 2015 Tonny Hao. All rights reserved.
//
import UIKit
class MessagesCell: UITableViewCell {
@IBOutlet var userImage: PFImageView!
@IBOutlet var descriptionLabel: UILabel!
@IBOutlet var lastMessageLabel: UILabel!
@IBOutlet var timeElapsedLabel: UILabel!
@IBOutlet var counterLabel: UILabel!
func bindData(message: PFObject) {
userImage.layer.cornerRadius = userImage.frame.size.width / 2
userImage.layer.masksToBounds = true
let lastUser = message[PF_MESSAGES_LASTUSER] as? PFUser
userImage.file = lastUser?[PF_USER_PICTURE] as? PFFile
userImage.loadInBackground(nil)
descriptionLabel.text = message[PF_MESSAGES_DESCRIPTION] as? String
lastMessageLabel.text = message[PF_MESSAGES_LASTMESSAGE] as? String
let seconds = NSDate().timeIntervalSinceDate(message[PF_MESSAGES_UPDATEDACTION] as NSDate)
timeElapsedLabel.text = Utilities.timeElapsed(seconds)
let dateText = JSQMessagesTimestampFormatter.sharedFormatter().relativeDateForDate(message[PF_MESSAGES_UPDATEDACTION] as? NSDate)
if dateText == "Today" {
timeElapsedLabel.text = JSQMessagesTimestampFormatter.sharedFormatter().timeForDate(message[PF_MESSAGES_UPDATEDACTION] as? NSDate)
} else {
timeElapsedLabel.text = dateText
}
let counter = message[PF_MESSAGES_COUNTER].integerValue
counterLabel.text = (counter == 0) ? "" : "\(counter) new"
}
}
| apache-2.0 | e79127a25de04e9b2366fcac389b2b48 | 36.697674 | 142 | 0.681061 | 4.381081 | false | false | false | false |
ctime95/AJMListApp | AJMListApp/PlaceListController.swift | 1 | 1326 | //
// CountryListController.swift
// AJMListApp
//
// Created by Angel Jesse Morales Karam Kairuz on 10/08/17.
// Copyright © 2017 TheKairuzBlog. All rights reserved.
//
import IGListKit
class PlaceListController : ListSectionController {
var name : String!
override func sizeForItem(at index: Int) -> CGSize {
guard let context = collectionContext else { return .zero }
let width = context.containerSize.width
let height = context.containerSize.height
return CGSize(width: width, height: height)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCellFromStoryboard(withIdentifier: "cell",
for: self,
at: index) as? CountryCell else {
fatalError()
}
cell.imageView.image = UIImage(named: name)
cell.imageView.contentMode = .scaleAspectFit
return cell
}
override func didUpdate(to object: Any) {
name = object as! String
}
override func didSelectItem(at index: Int) {
}
}
| mit | 8996e7142f3364d5abfd4ae98d811dc6 | 32.125 | 111 | 0.54717 | 5.408163 | false | false | false | false |
lerigos/music-service | iOS_9/Application/LMLogin.swift | 1 | 1725 | //
// LMLogin.swift
// Application
//
// Created by Dmitriy Groschovskiy on 7/12/16.
// Copyright © 2016 Lerigos Urban Developers Limited. All rights reserved.
//
import UIKit
import Bolts
import Parse
class LMLogin: UIViewController {
@IBOutlet weak var username : UITextField!
@IBOutlet weak var password : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func authWithCredentials(sender: UIButton) {
PFUser.logInWithUsernameInBackground(username.text!, password: password.text!) {
(user: PFUser?, error: NSError?) -> Void in
if user != nil {
// Do stuff after successful login.
} else {
let alertController = UIAlertController(title: "Invalid Credentials", message: "Opps. Your password or username is incorrect. Please try again or use method bellow. Thank you!", preferredStyle: .Alert)
let firstAction = UIAlertAction(title: "Close", style: .Default) { (action) in
}
alertController.addAction(firstAction)
let secondAction = UIAlertAction(title: "Restore", style: .Default) { (action) in
let credentialsRecoveryController = LMForgotView()
self.presentViewController(credentialsRecoveryController, animated: true, completion: nil)
}
alertController.addAction(secondAction)
self.presentViewController(alertController, animated: true) { "..." }
}
}
}
}
| apache-2.0 | 34afdded702565451f671364c3f94b28 | 34.183673 | 217 | 0.609629 | 5.224242 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/QuestPurchaseNS.swift | 1 | 3217 | //
// QuestReceiptNS.swift
// AwesomeCore
//
// Created by Evandro Harrison Hoffmann on 11/7/17.
//
import Foundation
class QuestPurchaseNS {
static let shared = QuestPurchaseNS()
lazy var awesomeRequester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm)
init() {}
var lastVerifyReceiptRequest: URLSessionDataTask?
var lastAddPurchaseRequest: URLSessionDataTask?
let method: URLMethod = .POST
let url = ACConstants.shared.questsURL
func verifyReceipt(withReceipt receipt: String, response: @escaping (Bool, ErrorData?) -> Void) {
lastVerifyReceiptRequest?.cancel()
lastVerifyReceiptRequest = nil
lastVerifyReceiptRequest = awesomeRequester.performRequestAuthorized(
url, forceUpdate: true, method: method, jsonBody: QuestPurchaseGraphQLModel.mutateVerifyIAPReceipt(receipt), completion: { (data, error, responseType) in
if data != nil {
self.lastVerifyReceiptRequest = nil
if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments), let jsonObject = json as? [String: Any] {
if jsonObject.keys.contains("errors") {
response(false, nil)
} else {
response(true, nil)
}
} else {
response(false, nil)
}
} else {
self.lastVerifyReceiptRequest = nil
if let error = error {
response(false, error)
return
}
response(false, ErrorData(.unknown, "response Data could not be parsed"))
}
})
}
func addPurchase(withProductId productId: String, response: @escaping (Bool, ErrorData?) -> Void) {
lastAddPurchaseRequest?.cancel()
lastAddPurchaseRequest = nil
lastAddPurchaseRequest = awesomeRequester.performRequestAuthorized(
url, forceUpdate: true, method: method, jsonBody: QuestPurchaseGraphQLModel.mutateAddPurchase(withId: productId), completion: { (data, error, responseType) in
if data != nil {
self.lastAddPurchaseRequest = nil
if let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments), let jsonObject = json as? [String: Any] {
if jsonObject.keys.contains("errors") {
response(false, nil)
} else {
response(true, nil)
}
} else {
response(false, nil)
}
} else {
self.lastAddPurchaseRequest = nil
if let error = error {
response(false, error)
return
}
response(false, ErrorData(.unknown, "response Data could not be parsed"))
}
})
}
}
| mit | 15e85d1f3fc2cd5bd159d64a02782915 | 39.2125 | 170 | 0.52751 | 5.508562 | false | false | false | false |
WeltN24/GraphQLicious | Sample/Sample/ViewController.swift | 2 | 3953 | //
// ViewController.swift
// GraphQLicious-sample
//
// Created by Felix Dietz on 30/03/16.
// Copyright © 2016 WeltN24. All rights reserved.
//
import UIKit
import GraphQLicious
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/**
Let's assume, we have the id of an article and we want to have the
headline, body text and opener image of that article.
First, let's create a fragment to fetch the contents
of an image, namely the image `id` and the image `url`
*/
let imageContent = Fragment(
withAlias: "imageContent",
name: "Image",
fields: [
"id",
"url"
]
)
/**Next, let's embed the `Fragment` into a `Request` that gets the opener image.
Note: Argument values that are of type String, are automatically represented with quotes.
GraphQL also gives us the possibility to have custom enums as argument values.
All you have to do, is letting your enum implement ArgumentValue and you're good to go.
*/
enum customEnum: String, ArgumentValue {
case This = "this"
case That = "that"
var asGraphQLArgument: String {
return rawValue // without quotes
}
}
let customEnumArgument = Argument(
key: "enum",
values: [
customEnum.This,
customEnum.That
]
)
let imageContentRequest = Request(
name: "images",
arguments: [
Argument(key: "role", value: "opener")
],
fields: [
imageContent
]
)
/**
So now we have a request with an embedded fragment. Let's go one step further.
If we want to, we can imbed that request into another fragment.
(We can also embed fragments into fragments)
Additionally to the opener image with its id and url we also want the headline and
body text of the article.
*/
let articleContent = Fragment(
withAlias: "contentFields",
name: "Content",
fields: [
"headline",
"body",
imageContentRequest
]
)
/**
Finally, we put everything together as a query.
A query always has a top level request to get everything started,
and requires all the fragments that are used inside.
*/
let q1 = Query(request: Request(
withAlias: "test",
name: "content",
arguments: [
Argument(key: "ids", values: [153082687]),
customEnumArgument
],
fields: [
articleContent
]),
fragments: [articleContent, imageContent]
)
/**
All we have to do now is to call `create()` on our Query and we're good to go.
*/
print(q1.create())
debugPrint(q1)
/**
Let's assume, we want to change our username and our age in our backend and we want to have the new name and age back to make sure everything went right.
Let's assume further, our server provides a mutating method `editMe` for exactly that purpose.
Let us first create the actual mutating request. We can use a `MutatingRequest` for that.
As Argument values we give information about which fields should be changed and what's the actual change
*/
let mutatingRequest = Request(name: "editMe", arguments: [
Argument(key: "title", value: "hello"),
Argument(key: "groupIds", values: [1, 2, 3]),
], fields: [
"title",
Request(name: "group", fields: [
"id"
])
]
)
/**
Finally, we put everything together as a `Mutation`.
A `Mutation` works just like a `Query`
*/
let mutation = Mutation(
withAlias: "myMutation",
mutatingRequest: mutatingRequest
)
print(mutation.create())
debugPrint(mutation)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 0be57b7efff577746bd9592684e761fb | 26.830986 | 158 | 0.609312 | 4.420582 | false | false | false | false |
IBM-Swift/Kitura | Tests/KituraTests/TestServer.swift | 1 | 12865 | /**
* Copyright IBM Corporation 2016, 2017
*
* 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 Dispatch
import KituraNet
@testable import Kitura
final class TestServer: KituraTest, KituraTestSuite {
static var allTests: [(String, (TestServer) -> () throws -> Void)] {
var listOfTests: [(String, (TestServer) -> () throws -> Void)] = [
("testServerStartStop", testServerStartStop),
("testServerRun", testServerRun),
("testServerFail", testServerFail),
("testServerStartWithStatus", testServerStartWithStatus),
("testServerStartWaitStop", testServerStartWaitStop),
("testServerRestart", testServerRestart)
]
#if !SKIP_UNIX_SOCKETS
listOfTests.append(("testUnixSocketServerRestart", testUnixSocketServerRestart))
#endif
return listOfTests
}
var httpPort = 8080
let useNIO = ProcessInfo.processInfo.environment["KITURA_NIO"] != nil
override func setUp() {
super.setUp()
stopServer() // stop common server so we can run these tests
}
private func setupServerAndExpectations(expectStart: Bool, expectStop: Bool, expectFail: Bool, httpPort: Int?=nil, fastCgiPort: Int?=nil) {
let router = Router()
let httpServer = Kitura.addHTTPServer(onPort: httpPort ?? 0, onAddress: "localhost", with: router)
let fastCgiServer = useNIO ? FastCGIServer() : Kitura.addFastCGIServer(onPort: fastCgiPort ?? 0,
onAddress: "localhost", with: router)
if expectStart {
let httpStarted = expectation(description: "HTTPServer started()")
let fastCgiStarted = expectation(description: "FastCGIServer started()")
httpServer.started {
httpStarted.fulfill()
}
if useNIO {
fastCgiStarted.fulfill()
} else {
fastCgiServer.started {
fastCgiStarted.fulfill()
}
}
} else {
httpServer.started {
XCTFail("httpServer.started should not have been called")
}
if !useNIO {
fastCgiServer.started {
XCTFail("fastCgiServer.started should not have been called")
}
}
}
if expectStop {
let httpStopped = expectation(description: "HTTPServer stopped()")
let fastCgiStopped = expectation(description: "FastCGIServer stopped()")
httpServer.stopped {
httpStopped.fulfill()
}
if useNIO {
fastCgiStopped.fulfill()
} else {
fastCgiServer.stopped {
fastCgiStopped.fulfill()
}
}
}
if expectFail {
let httpFailed = expectation(description: "HTTPServer failed()")
let fastCgiFailed = expectation(description: "FastCGIServer failed()")
httpServer.failed { error in
httpFailed.fulfill()
}
if useNIO {
fastCgiFailed.fulfill()
} else {
fastCgiServer.failed { error in
fastCgiFailed.fulfill()
}
}
} else {
httpServer.failed { error in
XCTFail("\(error)")
}
if !useNIO {
fastCgiServer.failed { error in
XCTFail("\(error)")
}
}
}
}
func testServerStartStop() {
setupServerAndExpectations(expectStart: true, expectStop: true, expectFail: false)
let requestQueue = DispatchQueue(label: "Request queue")
requestQueue.async() {
Kitura.start()
Kitura.stop()
}
waitForExpectations(timeout: 10) { error in
XCTAssertNil(error)
}
}
/// Sets up two servers on the same port. One will start, and one will fail to start
/// as the address is already in use.
private func setupConflictingServers(onPort: Int) {
let router1 = Router()
let router2 = Router()
let server1 = Kitura.addHTTPServer(onPort: onPort, with: router1)
let server2 = Kitura.addHTTPServer(onPort: onPort, with: router2)
// Expect server 1 to start
let server1Started = expectation(description: "Server 1 started on port \(onPort)")
server1.started {
server1Started.fulfill()
}
// Expect server 2 to fail (same port)
let server2Failed = expectation(description: "Server 2 failed - port should already be in use")
server2.failed { error in
XCTAssertNotNil(error)
server2Failed.fulfill()
}
}
/// Tests that Kitura.startWithStatus() returns the correct number of servers
/// that failed to start.
func testServerStartWithStatus() {
setupConflictingServers(onPort: 12345)
let numFailures = Kitura.startWithStatus()
XCTAssertEqual(numFailures, 1, "Expected startWithStatus() to report 1 server fail")
waitForExpectations(timeout: 10) { error in
Kitura.stop()
XCTAssertNil(error)
}
}
/// Tests that Kitura.wait() will wait until all successful servers are stopped.
func testServerStartWaitStop() {
setupConflictingServers(onPort: 23456)
let waitComplete = DispatchSemaphore(value: 0)
let requestQueue = DispatchQueue(label: "Request queue")
requestQueue.async() {
let failures = Kitura.startWithStatus()
XCTAssertEqual(failures, 1, "Expected one server to fail to start")
// As soon as the server has started, wait for it to stop
Kitura.wait()
// Signal that Kitura.wait() has completed
waitComplete.signal()
}
waitForExpectations(timeout: 10) { error in
// Check that Kitura.wait() is still waiting
let preStopStatus = waitComplete.wait(timeout: DispatchTime.now())
XCTAssertEqual(preStopStatus, DispatchTimeoutResult.timedOut, "Kitura.wait() unexpectedly completed")
// Stop the server, allowing wait() to complete
Kitura.stop()
XCTAssertNil(error)
// Check that the Kitura.wait() call completes
let postStopStatus = waitComplete.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(10))
XCTAssertEqual(postStopStatus, DispatchTimeoutResult.success, "Timed out waiting to Kitura.wait() to complete")
}
}
func testServerRun() {
setupServerAndExpectations(expectStart: true, expectStop: false, expectFail: false)
let requestQueue = DispatchQueue(label: "Request queue")
requestQueue.async() {
Kitura.run()
}
waitForExpectations(timeout: 10) { error in
Kitura.stop()
XCTAssertNil(error)
}
}
func testServerFail() {
// setupServer startup should fail as we are passing in illegal ports
setupServerAndExpectations(expectStart: false, expectStop: false, expectFail: true,
httpPort: -1, fastCgiPort: -2)
let requestQueue = DispatchQueue(label: "Request queue")
requestQueue.async() {
Kitura.start()
}
waitForExpectations(timeout: 10) { error in
Kitura.stop()
XCTAssertNil(error)
}
}
func testServerRestart() {
var port = httpPort
let path = "/testServerRestart"
let body = "Server is running."
let router = Router()
router.get(path) { _, response, next in
response.send(body)
next()
}
let server = Kitura.addHTTPServer(onPort: 0, with: router)
server.sslConfig = KituraTest.sslConfig.config
let stopped = DispatchSemaphore(value: 0)
server.stopped {
stopped.signal()
}
Kitura.start()
port = server.port!
testResponse(port: port, path: path, expectedBody: body)
Kitura.stop(unregister: false)
stopped.wait()
XCTAssertEqual(Kitura.httpServersAndPorts.count, 1, "Kitura.httpServersAndPorts.count is \(Kitura.httpServersAndPorts.count), should be 1")
testResponse(port: port, path: path, expectedBody: nil, expectedStatus: nil)
Kitura.start()
port = server.port!
testResponse(port: port, path: path, expectedBody: body)
Kitura.stop() // default for unregister is true
XCTAssertEqual(Kitura.httpServersAndPorts.count, 0, "Kitura.httpServersAndPorts.count is \(Kitura.httpServersAndPorts.count), should be 0")
}
func testUnixSocketServerRestart() {
#if !SKIP_UNIX_SOCKETS
let path = "/testSocketServerRestart"
let body = "Server is running."
// Create a temporary socket path for this server
let socketPath = uniqueTemporaryFilePath()
defer {
removeTemporaryFilePath(socketPath)
}
let router = Router()
router.get(path) { _, response, next in
response.send(body)
next()
}
let server = Kitura.addHTTPServer(onUnixDomainSocket: socketPath, with: router)
server.sslConfig = KituraTest.sslConfig.config
let stopped = DispatchSemaphore(value: 0)
let started = DispatchSemaphore(value: 0)
server.stopped {
stopped.signal()
}
server.started {
started.signal()
}
Kitura.start()
if started.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(5)) != DispatchTimeoutResult.success {
return XCTFail("Server failed to start")
}
XCTAssertEqual(server.unixDomainSocketPath, socketPath, "Server listening on wrong path")
testResponse(socketPath: socketPath, path: path, expectedBody: body)
Kitura.stop(unregister: false)
if stopped.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(5)) != DispatchTimeoutResult.success {
return XCTFail("Server failed to stop")
}
XCTAssertEqual(Kitura.httpServersAndUnixSocketPaths.count, 1, "Kitura.httpServersAndUnixSocketPaths.count is \(Kitura.httpServersAndUnixSocketPaths.count), should be 1")
testResponse(socketPath: socketPath, path: path, expectedBody: nil, expectedStatus: nil)
Kitura.start()
if started.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(5)) != DispatchTimeoutResult.success {
return XCTFail("Server failed to start")
}
XCTAssertEqual(server.unixDomainSocketPath, socketPath, "Server listening on wrong path")
testResponse(socketPath: socketPath, path: path, expectedBody: body)
Kitura.stop() // default for unregister is true
if stopped.wait(timeout: DispatchTime.now() + DispatchTimeInterval.seconds(5)) != DispatchTimeoutResult.success {
return XCTFail("Server failed to stop")
}
XCTAssertEqual(Kitura.httpServersAndUnixSocketPaths.count, 0, "Kitura.httpServersAndUnixSocketPaths.count is \(Kitura.httpServersAndUnixSocketPaths.count), should be 0")
#endif
}
private func testResponse(port: Int? = nil, socketPath: String? = nil, method: String = "get", path: String, expectedBody: String?, expectedStatus: HTTPStatusCode? = HTTPStatusCode.OK) {
performRequest(method, path: path, port: port, socketPath: socketPath, useSSL: true, useUnixSocket: (socketPath != nil), callback: { response in
let status = response?.statusCode
XCTAssertEqual(status, expectedStatus, "status was \(String(describing: status)), expected \(String(describing: expectedStatus))")
do {
let body = try response?.readString()
XCTAssertEqual(body, expectedBody, "body was '\(String(describing: body))', expected '\(String(describing: expectedBody))'")
} catch {
XCTFail("Error reading body: \(error)")
}
})
}
}
| apache-2.0 | 71e66335c1b5d280b9c20b5d11ac6242 | 37.175074 | 190 | 0.612437 | 4.891635 | false | true | false | false |
ernieb4768/VelocityCBT | CBT Velocity/CustomPageViewController.swift | 1 | 2701 | //
// CustomPageViewController.swift
// CBT Velocity
//
// Created by Ryan Hoffman on 4/2/16.
// Copyright © 2016 Ryan Hoffman. All rights reserved.
//
import UIKit
class CustomPageViewController: UIPageViewController, UIPageViewControllerDataSource {
private(set) lazy var orderedViewControllers: [UIViewController] = {
// The view controllers will be shown in this order
return [self.newMainViewController("ActivitiesViewController"),
self.newMainViewController("AboutUsViewController")]
}()
private func newMainViewController(title: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil)
.instantiateViewControllerWithIdentifier(title)
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the data source for the PageViewController
dataSource = self
if let firstViewController = orderedViewControllers.first {
setViewControllers([firstViewController], direction: .Forward, animated: true,
completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UIPageViewControllerDataSource
func pageViewController(pageViewController: UIPageViewController,
viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard orderedViewControllers.count > previousIndex else {
return nil
}
return orderedViewControllers[previousIndex]
}
func pageViewController(pageViewController: UIPageViewController,
viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.indexOf(viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = orderedViewControllers.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return orderedViewControllers[nextIndex]
}
}
| apache-2.0 | 834dad22d10dfa83c6bfd7494457ff5e | 30.395349 | 99 | 0.642593 | 6.905371 | false | false | false | false |
liuchuo/iOS9-practise | learniostableview/learniostableview/mytableview.swift | 1 | 2047 | //
// mytableview.swift
// learniostableview
//
// Created by ChenXin on 16/3/23.
// Copyright © 2016年 ChenXin. All rights reserved.
//
import UIKit
class mytableview: UITableView, UITableViewDataSource, UITableViewDelegate {
let TAG_CELL_LABEL = 1
let dataArr = ["hehe", "haha", "hzhz"]
var data:NSDictionary!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//通过一个自己设定的 plist 文件来初始化一个 NSDictionary 字典
data = NSDictionary(contentsOfURL: NSBundle.mainBundle().URLForResource("data", withExtension: "plist")!)!
self.dataSource = self
}
internal func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("\((data.allValues[indexPath.section] as! NSArray).objectAtIndex(indexPath.row)) Clicked")
}
internal func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}// Default is 1 if not implemented
internal func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return data.allKeys[section] as? String
}
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
let label = cell?.viewWithTag(TAG_CELL_LABEL) as! UILabel
label.text = (data.allValues[indexPath.section] as! NSArray).objectAtIndex(indexPath.row) as? String
return cell!
}
internal func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (data.allValues[section] as! NSArray).count
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| gpl-3.0 | 1a4c618f4a9a6816a928bbcd8dd7fe41 | 30.84127 | 118 | 0.668993 | 4.928747 | false | false | false | false |
GianniCarlo/Audiobook-Player | BookPlayerTests/ImportOperationTests.swift | 1 | 2033 | //
// ImportOperationTests.swift
// BookPlayerTests
//
// Created by Gianni Carlo on 9/13/18.
// Copyright © 2018 Tortuga Power. All rights reserved.
//
@testable import BookPlayer
@testable import BookPlayerKit
import XCTest
// MARK: - processFiles()
class ImportOperationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
let documentsFolder = DataManager.getDocumentsFolderURL()
DataTestUtils.clearFolderContents(url: documentsFolder)
}
func testProcessOneFile() {
let filename = "file.txt"
let bookContents = "bookcontents".data(using: .utf8)!
let documentsFolder = DataManager.getDocumentsFolderURL()
// Add test file to Documents folder
let fileUrl = DataTestUtils.generateTestFile(name: filename, contents: bookContents, destinationFolder: documentsFolder)
let promise = XCTestExpectation(description: "Process file")
let promiseFile = expectation(forNotification: .processingFile, object: nil)
let operation = ImportOperation(files: [fileUrl])
operation.completionBlock = {
// Test file should no longer be in the Documents folder
XCTAssert(!FileManager.default.fileExists(atPath: fileUrl.path))
XCTAssertNotNil(operation.files.first)
XCTAssertNotNil(operation.processedFiles.first)
let file = operation.files.first!
let processedFile = operation.processedFiles.first!
// Test file exists in new location
XCTAssert(!FileManager.default.fileExists(atPath: file.path))
XCTAssert(FileManager.default.fileExists(atPath: processedFile.path))
let content = FileManager.default.contents(atPath: processedFile.path)!
XCTAssert(content == bookContents)
promise.fulfill()
}
operation.start()
wait(for: [promise, promiseFile], timeout: 15)
}
}
| gpl-3.0 | 7328afb3bf1fbd44b8bfa7fff97f5044 | 33.440678 | 128 | 0.6875 | 4.815166 | false | true | false | false |
andreyvit/ExpressiveFoundation.swift | Source/Coalescence.swift | 1 | 1840 | import Foundation
public class Coalescence {
private enum State {
case Idle
case Scheduled
case Running
case RunningAndRequestedAgain
}
public typealias AsyncBlockType = (dispatch_block_t) -> Void
public typealias MonitorBlockType = (Bool) -> Void
public let delayMs: Int64
public let serialQueue: dispatch_queue_t
public var monitorBlock: MonitorBlockType = { (b) in }
private var _state: State = .Idle
public init(delayMs: Int64 = 0) {
self.delayMs = delayMs
self.serialQueue = dispatch_get_main_queue()
}
public func perform(block: dispatch_block_t) {
performAsync({ (done) in block(); done() })
}
public func performAsync(block: AsyncBlockType) {
switch (_state) {
case .Idle:
_schedule(block)
case .Running:
_state = .RunningAndRequestedAgain
case .Scheduled:
break;
case .RunningAndRequestedAgain:
break;
}
}
private func _schedule(block: AsyncBlockType) {
assert(_state == .Idle || _state == .RunningAndRequestedAgain)
_state = .Scheduled
monitorBlock(true)
dispatch_after_ms(delayMs, queue: serialQueue) {
assert(self._state == .Scheduled)
self._state = .Running
block({
dispatch_async(self.serialQueue) {
assert(self._state == .Running || self._state == .RunningAndRequestedAgain)
if self._state == .RunningAndRequestedAgain {
self._schedule(block)
} else {
self._state = .Idle
self.monitorBlock(false)
}
}
})
}
}
}
| mit | 110e6296dabcf4058bba5220a9722f6d | 25.666667 | 95 | 0.538043 | 4.717949 | false | false | false | false |
GraphKit/GraphKit-swift | Tests/Relationship/RelationshipCodableTests.swift | 5 | 4005 | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import XCTest
import Foundation
@testable import Graph
class RelationshipCodableTests: XCTestCase {
let array: [Any] = [-1, "2", [3, "4"], Decimal(12.34)]
func testEncoder() {
let relationship = Relationship("User", graph: "CodableGraph")
relationship.name = "Orkhan"
relationship.age = 20
relationship.url = URL(string: "http://cosmicmind.com")!
relationship.array = array
relationship.dictionary = ["key": array]
relationship.add(tags: ["Swift", "iOS"])
relationship.add(to: ["Programming", "Religion"])
guard let data = try? JSONEncoder().encode(relationship) else {
XCTFail("[EntityCodableTests Error: Encoder failed to encode.]")
return
}
guard let json = GraphJSON.parse(data) else {
XCTFail("[EntityCodableTests Error: Failed to create GraphJSON.]")
return
}
XCTAssertEqual(json.type.asString, "User")
XCTAssertEqual((json.tags.object as? [String]).map { Set($0) }, Set(["Swift", "iOS"]))
XCTAssertEqual((json.groups.object as? [String]).map { Set($0) }, Set(["Programming", "Religion"]))
XCTAssertEqual(json.properties.name.asString, "Orkhan")
XCTAssertEqual(json.properties.age.asInt, 20)
XCTAssertEqual(json.properties.url.asString, "http://cosmicmind.com")
XCTAssert((json.properties.array.object as? NSArray)?.isEqual(to: array) == true)
XCTAssert((json.properties.dictionary.object as? NSDictionary)?.isEqual(to: ["key": array]) == true)
}
func testDecoder() {
let json = """
{
"type" : "User",
"groups" : [
"Programming",
"Religion"
],
"tags" : [
"Swift",
"iOS"
],
"properties" : {
"age" : 20,
"name" : "Orkhan",
"array": [-1, "2", [3, "4"], 12.34],
"dictionary": { "key": [-1, "2", [3, "4"], 12.34] }
}
}
"""
guard let data = json.data(using: .utf8) else {
XCTFail("[EntityCodableTests Error: Failed to create Data from json string.]")
return
}
let decoder = JSONDecoder()
decoder.userInfo[.graph] = "CodableGraph"
guard let relationship = try? decoder.decode(Relationship.self, from: data) else {
XCTFail("[EntityCodableTests Error: Decoder failed to decode.]")
return
}
XCTAssertEqual(relationship.type, "User")
XCTAssertTrue(relationship.has(tags: ["iOS", "Swift"]))
XCTAssertTrue(relationship.member(of: ["Programming", "Religion"]))
XCTAssertEqual(relationship.name as? String, "Orkhan")
XCTAssertEqual(relationship.age as? Int, 20)
XCTAssert((relationship.array as? NSArray)?.isEqual(to: array) == true)
XCTAssert((relationship.dictionary as? NSDictionary)?.isEqual(to: ["key": array]) == true)
}
}
| agpl-3.0 | 31ad6dc9641d8bfbe85752d4fffb7daf | 37.509615 | 104 | 0.65593 | 4.141675 | false | true | false | false |
stripe/stripe-ios | Example/UI Examples/UI Examples/CardFieldViewController.swift | 1 | 1668 | //
// CardFieldViewController.swift
// UI Examples
//
// Created by Ben Guo on 7/19/17.
// Copyright © 2017 Stripe. All rights reserved.
//
import Stripe
import UIKit
class CardFieldViewController: UIViewController {
let cardField = STPPaymentCardTextField()
var theme = STPTheme.defaultTheme
override func viewDidLoad() {
super.viewDidLoad()
title = "Card Field"
view.backgroundColor = UIColor.white
view.addSubview(cardField)
edgesForExtendedLayout = []
view.backgroundColor = theme.primaryBackgroundColor
cardField.backgroundColor = theme.secondaryBackgroundColor
cardField.textColor = theme.primaryForegroundColor
cardField.placeholderColor = theme.secondaryForegroundColor
cardField.borderColor = theme.accentColor
cardField.borderWidth = 1.0
cardField.textErrorColor = theme.errorColor
cardField.postalCodeEntryEnabled = true
navigationItem.leftBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done, target: self, action: #selector(done))
navigationController?.navigationBar.stp_theme = theme
}
@objc func done() {
dismiss(animated: true, completion: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
cardField.becomeFirstResponder()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let padding: CGFloat = 15
cardField.frame = CGRect(
x: padding,
y: padding,
width: view.bounds.width - (padding * 2),
height: 50)
}
}
| mit | 1770d0099cb83493503c638865673c6e | 29.309091 | 78 | 0.667666 | 5.258675 | false | false | false | false |
touchopia/PinchZoomImageView | PinchZoomImageView.swift | 3 | 3265 | //
// PinchZoomImageView
//
//
// Created by Phil Wright on 8/22/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
import QuartzCore
class PinchZoomImageView: UIImageView, UIGestureRecognizerDelegate {
// Required init methods
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
override init(image: UIImage?) {
super.init(image: image)
self.initialize()
}
func initialize() {
// Important for allow user interaction on images
self.userInteractionEnabled = true
self.multipleTouchEnabled = true
self.exclusiveTouch = true
// Aspect Fit the Image
self.contentMode = .ScaleAspectFit
// Important: One gesture recognizer type is required to monitor this UIImageView
// 1. Add the Tap Gesture
let tapGesture = UITapGestureRecognizer(target: self, action:Selector("handleTap:"))
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
// 2. Add the Pan Gesture
let panGesture = UIPanGestureRecognizer(target: self, action:Selector("handlePan:"))
panGesture.delegate = self
self.addGestureRecognizer(panGesture)
// 3. Add the Pinch Gesture
let pinchGesture = UIPinchGestureRecognizer(target: self, action:Selector("handlePinch:"))
pinchGesture.delegate = self
self.addGestureRecognizer(pinchGesture)
// 4. Add the Rotate Gesture
let rotateGesture = UIRotationGestureRecognizer(target: self, action:Selector("handleRotate:"))
rotateGesture.delegate = self
self.addGestureRecognizer(rotateGesture)
}
// Mark - Gesture Methods
func handleTap(recognizer: UITapGestureRecognizer) {
if let view = recognizer.view {
view.superview!.bringSubviewToFront(self)
}
}
func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translationInView(recognizer.view)
if let view = recognizer.view {
view.transform = CGAffineTransformTranslate(view.transform, translation.x, translation.y)
}
recognizer.setTranslation(CGPointZero, inView: self)
}
func handlePinch(recognizer : UIPinchGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformScale(view.transform, recognizer.scale, recognizer.scale)
recognizer.scale = 1
}
}
func handleRotate(recognizer : UIRotationGestureRecognizer) {
if let view = recognizer.view {
view.transform = CGAffineTransformRotate(view.transform, recognizer.rotation)
recognizer.rotation = 0
}
}
// Needed to allow multiple touches (i.e. zoom and pinch)
func gestureRecognizer(_: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool {
return true
}
}
| gpl-3.0 | a76a10f915a5046d46cec9a7d271e87b | 29.222222 | 103 | 0.636029 | 5.55102 | false | false | false | false |
PodRepo/firefox-ios | Utils/Extensions/NSURLExtensions.swift | 3 | 10063 | /* 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 UIKit
private struct ETLDEntry: CustomStringConvertible {
let entry: String
var isNormal: Bool { return isWild || !isException }
var isWild: Bool = false
var isException: Bool = false
init(entry: String) {
self.entry = entry
self.isWild = entry.hasPrefix("*")
self.isException = entry.hasPrefix("!")
}
private var description: String {
return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }"
}
}
private typealias TLDEntryMap = [String:ETLDEntry]
private func loadEntriesFromDisk() -> TLDEntryMap? {
if let data = NSString.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: NSBundle(identifier: "org.mozilla.Shared")!, encoding: NSUTF8StringEncoding, error: nil) {
let lines = data.componentsSeparatedByString("\n")
let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" }
var entries = TLDEntryMap()
for line in trimmedLines {
let entry = ETLDEntry(entry: line)
let key: String
if entry.isWild {
// Trim off the '*.' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(2))
} else if entry.isException {
// Trim off the '!' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(1))
} else {
key = line
}
entries[key] = entry
}
return entries
}
return nil
}
private var etldEntries: TLDEntryMap? = {
return loadEntriesFromDisk()
}()
extension NSURL {
public func withQueryParams(params: [NSURLQueryItem]) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
var items = (components.queryItems ?? [])
for param in params {
items.append(param)
}
components.queryItems = items
return components.URL!
}
public func withQueryParam(name: String, value: String) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
let item = NSURLQueryItem(name: name, value: value)
components.queryItems = (components.queryItems ?? []) + [item]
return components.URL!
}
public func getQuery() -> [String: String] {
var results = [String: String]()
let keyValues = self.query?.componentsSeparatedByString("&")
if keyValues?.count > 0 {
for pair in keyValues! {
let kv = pair.componentsSeparatedByString("=")
if kv.count > 1 {
results[kv[0]] = kv[1]
}
}
}
return results
}
public var hostPort: String? {
if let host = self.host {
if let port = self.port?.intValue {
return "\(host):\(port)"
}
return host
}
return nil
}
public func baseDomainAndPath() -> String? {
if let baseDomain = self.baseDomain() {
return baseDomain + (self.path ?? "/")
}
return nil
}
public func absoluteStringWithoutHTTPScheme() -> String? {
// If it's basic http, strip out the string but leave anything else in
if self.absoluteString.hasPrefix("http://") ?? false {
return self.absoluteString.substringFromIndex(self.absoluteString.startIndex.advancedBy(7))
} else {
return self.absoluteString
}
}
/**
Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix
with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain
would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc).
:returns: The base domain string for the given host name.
*/
public func baseDomain() -> String? {
if let host = self.host {
// If this is just a hostname and not a FQDN, use the entire hostname.
if !host.contains(".") {
return host
}
return publicSuffixFromHost(host, withAdditionalParts: 1)
} else {
return nil
}
}
/**
* Returns just the domain, but with the same scheme, and a trailing '/'.
*
* E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/
*
* Any failure? Return this URL.
*/
public func domainURL() -> NSURL {
if let normalized = self.normalizedHost() {
return NSURL(scheme: self.scheme, host: normalized, path: "/") ?? self
}
return self
}
public func normalizedHost() -> String? {
if var host = self.host {
if let range = host.rangeOfString("^(www|mobile|m)\\.", options: .RegularExpressionSearch) {
host.replaceRange(range, with: "")
}
return host
}
return nil
}
/**
Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/.
For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk.
:returns: The public suffix for within the given hostname.
*/
public func publicSuffix() -> String? {
if let host = self.host {
return publicSuffixFromHost(host, withAdditionalParts: 0)
} else {
return nil
}
}
}
//MARK: Private Helpers
private extension NSURL {
private func publicSuffixFromHost( host: String, withAdditionalParts additionalPartCount: Int) -> String? {
if host.isEmpty {
return nil
}
// Check edge case where the host is either a single or double '.'.
if host.isEmpty || NSString(string: host).lastPathComponent == "." {
return ""
}
/**
* The following algorithm breaks apart the domain and checks each sub domain against the effective TLD
* entries from the effective_tld_names.dat file. It works like this:
*
* Example Domain: test.bbc.co.uk
* TLD Entry: bbc
*
* 1. Start off by checking the current domain (test.bbc.co.uk)
* 2. Also store the domain after the next dot (bbc.co.uk)
* 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks:
* i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches
* since it satisfies the wildcard requirement.
* ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then
* currentDomain is a valid TLD
* iii. If the entry we matched is an exception case, then the base domain is the part after the next dot
*
* On the next run through the loop, we set the new domain to check as the part after the next dot,
* update the next dot reference to be the string after the new next dot, and check the TLD entries again.
* If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the
* top domain level so we use it by default.
*/
let tokens = host.componentsSeparatedByString(".")
let tokenCount = tokens.count
var suffix: String?
var previousDomain: String? = nil
var currentDomain: String = host
for offset in 0..<tokenCount {
// Store the offset for use outside of this scope so we can add additional parts if needed
let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joinWithSeparator(".") : nil
if let entry = etldEntries?[currentDomain] {
if entry.isWild && (previousDomain != nil) {
suffix = previousDomain
break;
} else if entry.isNormal || (nextDot == nil) {
suffix = currentDomain
break;
} else if entry.isException {
suffix = nextDot
break;
}
}
previousDomain = currentDomain
if let nextDot = nextDot {
currentDomain = nextDot
} else {
break
}
}
var baseDomain: String?
if additionalPartCount > 0 {
if let suffix = suffix {
// Take out the public suffixed and add in the additional parts we want.
let literalFromEnd: NSStringCompareOptions = [NSStringCompareOptions.LiteralSearch, // Match the string exactly.
NSStringCompareOptions.BackwardsSearch, // Search from the end.
NSStringCompareOptions.AnchoredSearch] // Stick to the end.
let suffixlessHost = host.stringByReplacingOccurrencesOfString(suffix, withString: "", options: literalFromEnd, range: nil)
let suffixlessTokens = suffixlessHost.componentsSeparatedByString(".").filter { $0 != "" }
let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount)
let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count]
let partsString = additionalParts.joinWithSeparator(".")
baseDomain = [partsString, suffix].joinWithSeparator(".")
} else {
return nil
}
} else {
baseDomain = suffix
}
return baseDomain
}
}
| mpl-2.0 | 92b4b72e1fd09b7217644b74963c0e23 | 37.408397 | 198 | 0.584716 | 4.726632 | false | false | false | false |
nastia05/TTU-iOS-Developing-Course | Lecture 4/MapFilterReduceDemo.playground/Contents.swift | 1 | 617 | struct Car {
enum Manufacturer {
case porsche, tesla, audi
}
let numberOfWheels: Int = 4
let manufacturer: Manufacturer
}
/// map
let cars: [Car] = [Car(manufacturer: .porsche), Car(manufacturer: .tesla), Car(manufacturer: .tesla)]
let manufacturers = cars.map { $0.manufacturer }
print(manufacturers)
/// filter
let posches = cars.filter { $0.manufacturer == .porsche }
/// first
let firstTesla = cars.first(where: { $0.manufacturer == .tesla })
/// reduce
let numberOfWheels = cars.reduce(0) { $0 + $1.numberOfWheels }
let qwer = [1, 2, 3, 4, 5]
let summ = qwer.reduce(0, +)
| mit | 19c6e88ea94bb8b209cb098a9b0b7088 | 18.903226 | 101 | 0.645057 | 3.213542 | false | false | false | false |
idomizrachi/Regen | regen/Dependencies/Stencil/Extension.swift | 2 | 3301 | open class Extension {
typealias TagParser = (TokenParser, Token) throws -> NodeType
var tags = [String: TagParser]()
var filters = [String: Filter]()
public init() {
}
/// Registers a new template tag
public func registerTag(_ name: String, parser: @escaping (TokenParser, Token) throws -> NodeType) {
tags[name] = parser
}
/// Registers a simple template tag with a name and a handler
public func registerSimpleTag(_ name: String, handler: @escaping (Context) throws -> String) {
registerTag(name) { _, token in
SimpleNode(token: token, handler: handler)
}
}
/// Registers boolean filter with it's negative counterpart
// swiftlint:disable:next discouraged_optional_boolean
public func registerFilter(name: String, negativeFilterName: String, filter: @escaping (Any?) throws -> Bool?) {
filters[name] = .simple(filter)
filters[negativeFilterName] = .simple {
guard let result = try filter($0) else { return nil }
return !result
}
}
/// Registers a template filter with the given name
public func registerFilter(_ name: String, filter: @escaping (Any?) throws -> Any?) {
filters[name] = .simple(filter)
}
/// Registers a template filter with the given name
public func registerFilter(_ name: String, filter: @escaping (Any?, [Any?]) throws -> Any?) {
filters[name] = .arguments({ value, args, _ in try filter(value, args) })
}
/// Registers a template filter with the given name
public func registerFilter(_ name: String, filter: @escaping (Any?, [Any?], Context) throws -> Any?) {
filters[name] = .arguments(filter)
}
}
class DefaultExtension: Extension {
override init() {
super.init()
registerDefaultTags()
registerDefaultFilters()
}
fileprivate func registerDefaultTags() {
registerTag("for", parser: ForNode.parse)
registerTag("if", parser: IfNode.parse)
registerTag("ifnot", parser: IfNode.parse_ifnot)
#if !os(Linux)
registerTag("now", parser: NowNode.parse)
#endif
registerTag("include", parser: IncludeNode.parse)
registerTag("extends", parser: ExtendsNode.parse)
registerTag("block", parser: BlockNode.parse)
registerTag("filter", parser: FilterNode.parse)
}
fileprivate func registerDefaultFilters() {
registerFilter("default", filter: defaultFilter)
registerFilter("capitalize", filter: capitalise)
registerFilter("uppercase", filter: uppercase)
registerFilter("lowercase", filter: lowercase)
registerFilter("join", filter: joinFilter)
registerFilter("split", filter: splitFilter)
registerFilter("indent", filter: indentFilter)
registerFilter("filter", filter: filterFilter)
}
}
protocol FilterType {
func invoke(value: Any?, arguments: [Any?], context: Context) throws -> Any?
}
enum Filter: FilterType {
case simple(((Any?) throws -> Any?))
case arguments(((Any?, [Any?], Context) throws -> Any?))
func invoke(value: Any?, arguments: [Any?], context: Context) throws -> Any? {
switch self {
case let .simple(filter):
if !arguments.isEmpty {
throw TemplateSyntaxError("Can't invoke filter with an argument")
}
return try filter(value)
case let .arguments(filter):
return try filter(value, arguments, context)
}
}
}
| mit | 3222a81c80e410e36aa497086da6507e | 32.343434 | 114 | 0.680097 | 4.12625 | false | false | false | false |
darina/omim | iphone/Maps/Classes/Components/VerticallyAlignedButton.swift | 5 | 1932 | @IBDesignable
class VerticallyAlignedButton: UIControl {
@IBInspectable
var image: UIImage? {
didSet {
imageView.image = image
}
}
@IBInspectable
var title: String? {
didSet {
if localizedText == nil {
titleLabel.text = title
}
}
}
@IBInspectable
var localizedText: String? {
didSet {
if let localizedText = localizedText {
titleLabel.text = L(localizedText)
}
}
}
@IBInspectable
var spacing: CGFloat = 4 {
didSet {
spacingConstraint.constant = spacing
}
}
@IBInspectable
var numberOfLines: Int {
get {
return titleLabel.numberOfLines
}
set {
titleLabel.numberOfLines = newValue
}
}
private lazy var spacingConstraint: NSLayoutConstraint = {
let spacingConstraint = titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: spacing)
return spacingConstraint
}()
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.translatesAutoresizingMaskIntoConstraints = false
return titleLabel
}()
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .center
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
addSubview(titleLabel)
addSubview(imageView)
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: topAnchor),
imageView.centerXAnchor.constraint(equalTo: centerXAnchor),
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor),
spacingConstraint
])
}
}
| apache-2.0 | dd770b0f482a2fa147749aa179305db3 | 21.465116 | 111 | 0.680124 | 5.044386 | false | false | false | false |
lobodart/CheatyXML | CheatyXML/CXMLTag.swift | 1 | 3876 | //
// CXMLTag.swift
// CheatyXML
//
// Created by Louis BODART on 16/07/2016.
// Copyright © 2016 Louis BODART. All rights reserved.
//
import Foundation
// MARK: - CXMLTag Class
open class CXMLTag: CXMLElement, Sequence, IteratorProtocol {
public let tagName: String!
open var attributes: [CXMLAttribute] {
get {
return self._attributes
}
}
open var count: Int {
get {
guard let _ = self._parentElement else {
return 1
}
let array: [CXMLTag] = self._parentElement.arrayOfElementsNamed(self.tagName)
return array.count
}
}
open var numberOfChildElements: Int {
get {
return self._subElements.count
}
}
internal var _subElements: [CXMLTag] = []
internal var _parentElement: CXMLTag!
internal var _attributes: [CXMLAttribute] = []
internal var _generatorIndex: Int = 0
open override var debugDescription: String { get { return self.description } }
open override var description: String {
return "CXMLTag <\(self.tagName ?? "???")>, attributes(\(self.attributes.count)): \(self.attributes), children: \(self._subElements.count)"
}
open var exists: Bool { get { return !(self is CXMLNullTag) } }
open var array: [CXMLTag] { get { return self._parentElement?.arrayOfElementsNamed(self.tagName) ?? self._subElements } }
open func makeIterator() -> CXMLTag {
self._generatorIndex = 0
return self
}
open func next() -> CXMLTag? {
if self._generatorIndex < 0 || self._generatorIndex >= self._subElements.count {
return nil
}
defer { self._generatorIndex += 1 }
return self._subElements[self._generatorIndex]
}
open func elementsNamed(_ name: String) -> [CXMLTag] {
return self.arrayOfElementsNamed(name)
}
open func attribute(_ name: String) -> CXMLAttribute {
guard let index = self._attributes.firstIndex(where: { (attribute) -> Bool in
return attribute.name == name
}) else {
return CXMLNullAttribute()
}
return self._attributes[index]
}
fileprivate final func arrayOfElementsNamed(_ tagName: String) -> [CXMLTag] {
return self._subElements.filter({(element: CXMLTag) -> Bool in
return element.tagName == tagName
})
}
internal final func addSubElement(_ subElement: CXMLTag) {
self._subElements.append(subElement)
}
init(tagName: String!) {
self.tagName = tagName
super.init(content: nil)
}
open subscript(tagName: String) -> CXMLTag! {
get {
return self[tagName, 0]
}
}
open subscript(index: Int) -> CXMLTag! {
get {
return self._parentElement[self.tagName, index]
}
}
open subscript(tagName: String, index: Int) -> CXMLTag! {
get {
if index < 0 {
return CXMLNullTag()
}
let array = self._subElements.filter({(element: CXMLTag) -> Bool in
return element.tagName == tagName
})
if index >= array.count {
return CXMLNullTag()
}
return array[index]
}
}
}
public extension Sequence where Iterator.Element: CXMLAttribute {
var dictionary: [String: String] {
get {
return self.reduce([:], { (dict: [String: String], value: CXMLAttribute) -> [String: String] in
var newDict = dict
newDict[value.name] = value._content ?? ""
return newDict
})
}
}
}
| mit | fd729dbd4f1e3caef1ec7071eab4aae3 | 27.07971 | 147 | 0.548645 | 4.448909 | false | false | false | false |
gtranchedone/AlgorithmsSwift | Algorithms.playground/Pages/Problem - 3-sum.xcplaygroundpage/Contents.swift | 1 | 1293 | /*:
[Previous](@previous)
# The 3-sum problem
### Given an array A of n numbers, let t be a number and k an integer in [1, n]. Define A to k-create t if and only if there exists k indices (not necessarily distinct) such that the sum of the values stored at those indices equals t. Design an algorithm that takes as input an array A and a number t, and determines if A 3-creates t.
*/
public func intsArray(array: [Int], hasThreeSumFor target: Int) -> Bool {
let sortedArray = array.sort()
for i in sortedArray {
if intsArray(sortedArray, hasTwoSumFor: target - i) {
return true
}
}
return false
}
private func intsArray(array: [Int], hasTwoSumFor target: Int) -> Bool {
// requires sorted array
var i = 0, j = array.count - 1
while (i <= j) {
if (array[i] + array[j] == target) {
return true
}
if (array[i] + array[j] < target) {
i++
}
else {
j--
}
}
return false
}
intsArray([3, 4, 5], hasThreeSumFor: 8)
intsArray([3, 4, 5], hasThreeSumFor: 12)
intsArray([3, 3, 3, 10, 12, 5, 7, 0], hasThreeSumFor: 12)
intsArray([3, 3, 3, 10, 12, 5, 7, 0], hasThreeSumFor: 99)
intsArray([1, 3, 5, 7, 9, 11, 13, 15], hasThreeSumFor: 30)
//: [Next](@next)
| mit | 18cc9e650b8c498c4a79d1c12040a6ca | 31.3 | 334 | 0.595201 | 3.254408 | false | false | false | false |
laszlokorte/reform-swift | ReformGraphics/ReformGraphics/Shape.swift | 1 | 915 | //
// Shape.swift
// ReformCore
//
// Created by Laszlo Korte on 13.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformMath
public struct Shape {
let background: Background
let stroke: Stroke
let area : FillArea
public init() {
background = .none
stroke = .none
area = .pathArea(Path())
}
public init(area : FillArea, background : Background = .none, stroke: Stroke = .none) {
self.area = area
self.stroke = stroke
self.background = background
}
}
public enum Aligment {
case left
case right
case center
}
public enum FillArea {
case pathArea(Path)
case textArea(Vec2d, Vec2d, alignment: Aligment, text: String, size: Double)
}
public enum Background {
case fill(Color)
case none
}
public enum Stroke {
case solid(width: Double, color: Color)
case none
}
| mit | 6fcf4b1e366247d9c5ee8703841e3eaf | 18.041667 | 91 | 0.625821 | 3.792531 | false | false | false | false |
hanhailong/practice-swift | Address Book/Retrieving and Setting a Person's Address Book Retrieving and Setting a Person's Address Book/Retrieving and Setting a Person's Address Book Retrieving and Setting a Person's Address Book/AppDelegate.swift | 2 | 5891 | //
// AppDelegate.swift
// Retrieving and Setting a Person's Address Book Retrieving and Setting a Person's Address Book
//
// Created by Domenico on 26/05/15.
// License MIT
//
import UIKit
import AddressBook
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var addressBook: ABAddressBookRef = {
var error: Unmanaged<CFError>?
return ABAddressBookCreateWithOptions(nil,
&error).takeRetainedValue() as ABAddressBookRef
}()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
switch ABAddressBookGetAuthorizationStatus(){
case .Authorized:
println("Already authorized")
performExample()
case .Denied:
println("You are denied access to address book")
case .NotDetermined:
ABAddressBookRequestAccessWithCompletion(addressBook,
{[weak self] (granted: Bool, error: CFError!) in
if granted{
let strongSelf = self!
println("Access is granted")
strongSelf.performExample()
} else {
println("Access is not granted")
}
})
case .Restricted:
println("Access is restricted")
default:
println("Unhandled")
}
return true
}
func imageForPerson(person: ABRecordRef) -> UIImage?{
let data = ABPersonCopyImageData(person).takeRetainedValue() as NSData
let image = UIImage(data: data)
return image
}
func newPersonWithFirstName(firstName: String,
lastName: String,
inAddressBook: ABAddressBookRef) -> ABRecordRef?{
let person: ABRecordRef = ABPersonCreate().takeRetainedValue()
let couldSetFirstName = ABRecordSetValue(person,
kABPersonFirstNameProperty,
firstName as CFTypeRef,
nil)
let couldSetLastName = ABRecordSetValue(person,
kABPersonLastNameProperty,
lastName as CFTypeRef,
nil)
var error: Unmanaged<CFErrorRef>? = nil
let couldAddPerson = ABAddressBookAddRecord(inAddressBook, person, &error)
if couldAddPerson{
println("Successfully added the person")
} else {
println("Failed to add the person.")
return nil
}
if ABAddressBookHasUnsavedChanges(inAddressBook){
var error: Unmanaged<CFErrorRef>? = nil
let couldSaveAddressBook = ABAddressBookSave(inAddressBook, &error)
if couldSaveAddressBook{
println("Successfully saved the address book")
} else {
println("Failed to save the address book.")
}
}
if couldSetFirstName && couldSetLastName{
println("Successfully set the first name " +
"and the last name of the person")
} else {
println("Failed to set the first name and/or " +
"the last name of the person")
}
return person
}
func setImageForPerson(person: ABRecordRef,
inAddressBook addressBook: ABAddressBookRef,
imageData: NSData) -> Bool{
var error: Unmanaged<CFErrorRef>? = nil
let couldSetPersonImage =
ABPersonSetImageData(person, imageData as CFDataRef, &error)
if couldSetPersonImage{
println("Successfully set the person's image. Saving...")
if ABAddressBookHasUnsavedChanges(addressBook){
error = nil
let couldSaveAddressBook = ABAddressBookSave(addressBook, &error)
if couldSaveAddressBook{
println("Successfully saved the address book")
return true
} else {
println("Failed to save the address book")
}
} else {
println("There are no changes to be saved!")
}
} else {
println("Failed to set the person's image")
}
return false
}
func performExample(){
let person: ABRecordRef? = newPersonWithFirstName("Richard",
lastName: "Branson", inAddressBook: addressBook)
if let richard: ABRecordRef = person{
let newImage = UIImage(named: "image")
let newImageData = UIImageJPEGRepresentation(newImage, 1.0)
if setImageForPerson(richard, inAddressBook: addressBook,
imageData: newImageData){
println("Successfully set the person's image")
let image = imageForPerson(richard)
if let currentImage = image{
println("Found the image")
} else {
println("This person has no image")
}
} else {
println("Could not set the person's image")
}
}
}
}
| mit | cdba8163973e636e9baa4ca1b1dc3916 | 32.662857 | 127 | 0.501613 | 6.396308 | false | false | false | false |
Kreattiewe/easyDegrade | gradientGenerator.swift | 1 | 863 | //
// gradientGenerator.swift
// Kreattiewe
//
// Created by angel botto on 11/01/15.
// Copyright (c) 2015 Kreattiewe. All rights reserved.
//
import Foundation
import UIKit
struct GradientGenerator {
let gradient : CAGradientLayer = CAGradientLayer()
var gradientColors : [AnyObject] = []
var generalView : UIView
var generalColors : [String] = []
init(colors : Array<String>, view : UIView) {
generalView = view
generalColors = colors
for color_index in generalColors {
var color : String = color_index
gradientColors.append(UIColor(rgba: color).CGColor)
}
}
func assignDegrade() -> Void {
gradient.frame = generalView.bounds
gradient.colors = gradientColors
generalView.layer.insertSublayer(gradient, atIndex: 0)
}
} | mit | 694385206e0cf38a4d0768e817d4ac36 | 23.685714 | 63 | 0.630359 | 4.315 | false | false | false | false |
jtbales/Face-To-Name | Face-To-Name/App/Search/SearchResultViewController.swift | 1 | 4896 | //
// SearchResultViewController.swift
// Face-To-Name
//
// Created by John Bales on 5/10/17.
// Copyright © 2017 John T Bales. All rights reserved.
//
import UIKit
import GoogleMobileAds
import AWSRekognition
import AWSDynamoDB
import AWSS3
class SearchResultViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var detailsLabel: UILabel!
@IBOutlet weak var faceImageView: UIImageView!
// @IBOutlet weak var bannerView: GADBannerView!
var matchingFaces: [AWSRekognitionFaceMatch]?
override func viewDidLoad() {
super.viewDidLoad()
//TODO results show a box around each person's face and their name
//Displays the data from the frist match in photo
displayFirstMatch(matchingFaces)
//Google AdMob
// bannerView.adUnitID = FaceToNameAds.sharedInstance.adUnitID
// bannerView.rootViewController = self
// let gadReqest = FaceToNameAds.sharedInstance.gadRequest
// bannerView.load(gadReqest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//
func displayFirstMatch(_ matches: [AWSRekognitionFaceMatch]?, _ startIndex: Int = 0) {
if let matches = matches {
//Narrow Down
var nextStartIndex = 0
var firstMatch: AWSRekognitionFaceMatch?
for i in startIndex ... matches.count {
if matches[i].face?.faceId != nil {
firstMatch = matches[i] //First valid match
nextStartIndex = i + 1
break
}
}
//Test match
if let match = firstMatch {
if let faceId = match.face?.faceId {
//Query for the face
AWSDynamoDBObjectMapper.default().queryFaceData(faceId: faceId, { (faceResults) -> Void? in
//Success
if faceResults.count == 0 {
//This indicates a stray faceId. Delete it.
AWSRekognition.default().deleteFaceIdsUNSAFE_FTN([faceId])
//Then attempt next match
self.displayFirstMatch(matches, nextStartIndex)
} else {
self.displayFace(faceResults[0], match.similarity)
}
return nil
}, { (alertParams) -> Void? in
//Failure
self.alertMessageOkay(alertParams)
return nil
})
} else {
print("faceId was nil for displayFirstMatch")
self.alertMessageOkay("No Match Found", "This person is not likely listed as an aquaintance.")
}
} else {
print("AWSRekognitionFaceMatch for displayFirstMatch was nil")
}
} else {
self.alertMessageOkay("Not Found", "Empty result. Try again with another photo.")
}
}
func displayFace(_ face: Face!, _ similarity: NSNumber?) {
DispatchQueue.main.async {
self.nameLabel.text = face.name
if let similarity = similarity {
let nf = NumberFormatter()
nf.numberStyle = .decimal
self.detailsLabel.text = "Similarity: \(nf.string(from: similarity) ?? "Unavailable")%\n"
}
self.detailsLabel.text?.append("Details: \(face.details)") //Append after confidence percentage
}
if face.s3ImageAddress == "" {
print("s3ImageAddress not provided for \(face.name)")
return
}
AWSS3.default().downloadS3Image(face.s3ImageAddress, { (downloadedFileURL) -> Void? in
//Success
//Show image
DispatchQueue.main.async { //Must modify UI on main thread
self.faceImageView.image = UIImage(fileURL: downloadedFileURL)
}
return nil
}, { (alertParams) -> Void? in
//Failure
self.alertMessageOkay(alertParams)
return nil
})
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f4b1e2fb29755a9c20367147437a9203 | 34.471014 | 114 | 0.5381 | 5.338059 | false | false | false | false |
kousun12/RxSwift | RxTests/RxSwiftTests/TestImplementations/EquatableArray.swift | 7 | 396 | //
// EquatableArray.swift
// RxTests
//
// Created by Krunoslav Zaher on 10/15/15.
//
//
import Foundation
struct EquatableArray<Element: Equatable> : Equatable {
let elements: [Element]
init(_ elements: [Element]) {
self.elements = elements
}
}
func == <E: Equatable>(lhs: EquatableArray<E>, rhs: EquatableArray<E>) -> Bool {
return lhs.elements == rhs.elements
}
| mit | c833399d5cf9f7de2d2606a6dab7d65d | 18.8 | 80 | 0.64899 | 3.633028 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.