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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
chrisamanse/Changes | Sources/Changes/Change.swift | 1 | 2383 | //
// Change.swift
// Diff
//
// Created by Chris Amanse on 09/19/2016.
//
//
/// Describes the type of change
///
/// - Insertion: A change of type insertion with an `element` that was inserted in the collection and a `destination` where the element was inserted.
/// - Deletion: A change of type deletion with an `element` that was deleted in the collection and a `destination` where the element was deleted.
/// - Substitution: A change of type substitution with an `element` as the new element in the collection and a `destination` where the element was overwritten. For example, changes of `[1,2,3]` since `[1,2,4]` (the old collection), will have a `Substitution` change with `element` 3 (the new element) and `destination` 2 (index starts at 0).
/// - Move: A change of type move with a `element` that was moved in the collection, and the element's `origin` and `destination`.
public enum Change<T: Equatable> {
case Insertion(element: T, destination: Int)
case Deletion(element: T, destination: Int)
case Substitution(element: T, destination: Int)
case Move(element: T, origin: Int, destination: Int)
}
extension Change: CustomStringConvertible {
public var description: String {
switch self {
case .Insertion(element: let element, destination: let destination):
return "Inserted \(element) at index \(destination)"
case .Deletion(element: let element, destination: let destination):
return "Deleted \(element) at index \(destination)"
case .Substitution(element: let element, destination: let destination):
return "Substituted with \(element) at index \(destination)"
case .Move(element: let element, origin: let origin, destination: let destination):
return "Moved \(element) from index \(origin) to \(destination)"
}
}
}
extension Change: Equatable {
public static func ==<T: Equatable>(lhs: Change<T>, rhs: Change<T>) -> Bool {
switch (lhs, rhs) {
case (.Insertion(let x), .Insertion(let y)):
return x == y
case (.Deletion(let x), .Deletion(let y)):
return x == y
case (.Substitution(let x), .Substitution(let y)):
return x == y
case (.Move(let x), .Move(let y)):
return x == y
default:
return false
}
}
}
| mit | 14d84942d73d5625bf30b1a82d67373b | 44.826923 | 341 | 0.644985 | 4.240214 | false | false | false | false |
MoZhouqi/KMPlaceholderTextView | Sources/KMPlaceholderTextView/KMPlaceholderTextView.swift | 1 | 6179 | //
// KMPlaceholderTextView.swift
//
// Copyright (c) 2016 Zhouqi Mo (https://github.com/MoZhouqi)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
@IBDesignable
open class KMPlaceholderTextView: UITextView {
private struct Constants {
static let defaultiOSPlaceholderColor: UIColor = {
if #available(iOS 13.0, *) {
return .systemGray3
}
return UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
}()
}
public let placeholderLabel: UILabel = UILabel()
private var placeholderLabelConstraints = [NSLayoutConstraint]()
@IBInspectable open var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable open var placeholderColor: UIColor = KMPlaceholderTextView.Constants.defaultiOSPlaceholderColor {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override open var font: UIFont! {
didSet {
if placeholderFont == nil {
placeholderLabel.font = font
}
}
}
open var placeholderFont: UIFont? {
didSet {
let font = (placeholderFont != nil) ? placeholderFont : self.font
placeholderLabel.font = font
}
}
override open var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override open var text: String! {
didSet {
textDidChange()
}
}
override open var attributedText: NSAttributedString! {
didSet {
textDidChange()
}
}
override open var textContainerInset: UIEdgeInsets {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
#if swift(>=4.2)
let notificationName = UITextView.textDidChangeNotification
#else
let notificationName = NSNotification.Name.UITextView.textDidChangeNotification
#endif
NotificationCenter.default.addObserver(self,
selector: #selector(textDidChange),
name: notificationName,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
updateConstraintsForPlaceholderLabel()
}
private func updateConstraintsForPlaceholderLabel() {
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(textContainerInset.top))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints.append(NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .greaterThanOrEqual,
toItem: placeholderLabel,
attribute: .height,
multiplier: 1.0,
constant: textContainerInset.top + textContainerInset.bottom
))
newConstraints.append(NSLayoutConstraint(
item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
))
removeConstraints(placeholderLabelConstraints)
addConstraints(newConstraints)
placeholderLabelConstraints = newConstraints
}
@objc private func textDidChange() {
placeholderLabel.isHidden = !text.isEmpty
}
open override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0
}
deinit {
#if swift(>=4.2)
let notificationName = UITextView.textDidChangeNotification
#else
let notificationName = NSNotification.Name.UITextView.textDidChangeNotification
#endif
NotificationCenter.default.removeObserver(self,
name: notificationName,
object: nil)
}
}
| mit | 2575b663ebb3306e1eb2d91c33de3008 | 33.327778 | 163 | 0.642661 | 5.663611 | false | false | false | false |
JLCdeSwift/DangTangDemo | DanTangdemo/Classes/Classify(分类)/Model/LCCollectionPost.swift | 1 | 1268 | //
// LCCollectionPost.swift
// DanTangdemo
//
// Created by 冀柳冲 on 2017/7/5.
// Copyright © 2017年 冀柳冲. All rights reserved.
//
import UIKit
class LCCollectionPost: NSObject {
var cover_image_url: String?
var id: Int?
var published_at: Int?
var created_at: Int?
var content_url: String?
var url: String?
var share_msg: String?
var title: String?
var updated_at: Int?
var short_title: String?
var liked: Bool?
var likes_count: Int?
var status: Int?
init(dict: [String: AnyObject]) {
super.init()
cover_image_url = dict["cover_image_url"] as? String
id = dict["id"] as? Int
published_at = dict["published_at"] as? Int
created_at = dict["created_at"] as? Int
content_url = dict["content_url"] as? String
url = dict["url"] as? String
share_msg = dict["share_msg"] as? String
short_title = dict["short_title"] as? String
title = dict["title"] as? String
updated_at = dict["updated_at"] as? Int
status = dict["status"] as? Int
liked = dict["liked"] as? Bool
likes_count = dict["likes_count"] as? Int
}
}
| mit | 28a4da51946cf2206327d4f91a04a38c | 20.603448 | 60 | 0.553871 | 3.600575 | false | false | false | false |
JunDang/SwiftFoundation | Sources/SwiftFoundation/POSIXRegularExpression.swift | 1 | 3442 | //
// POSIXRegularExpression.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 7/22/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin.C
#elseif os(Linux)
import Glibc
#endif
public typealias POSIXRegularExpression = regex_t
public extension POSIXRegularExpression {
public static func compile(pattern: String, options: [RegularExpression.CompileOption]) -> (ErrorCode, POSIXRegularExpression) {
var regularExpression = POSIXRegularExpression()
let flags = options.optionsBitmask()
let errorCode = regcomp(®ularExpression, pattern, flags)
return (ErrorCode(errorCode), regularExpression)
}
public mutating func free() {
regfree(&self)
}
public func firstMatch(string: String, options: [RegularExpression.MatchOption]) -> RegularExpressionMatch? {
// we are sure that that this method does not mutate the regular expression, so we make a copy
var expression = self
let numberOfMatches = re_nsub + 1 // first match is the expression itself, later matches are subexpressions
let matchesPointer = UnsafeMutablePointer<Match>.alloc(numberOfMatches)
defer { matchesPointer.destroy(numberOfMatches) }
let flags = options.optionsBitmask()
let code = regexec(&expression, string, numberOfMatches, matchesPointer, flags)
guard code == 0 else { return nil }
var matches = [Match]()
for i in 0...re_nsub {
let match = matchesPointer[i]
matches.append(match)
}
var match = RegularExpressionMatch()
do {
let expressionMatch = matches[0]
match.range = Swift.Range(start: Int(expressionMatch.rm_so), end: Int(expressionMatch.rm_eo))
}
let subexpressionsCount = re_nsub // REMOVE
if subexpressionsCount > 0 {
// Index for subexpressions start at 1, not 0
for index in 1...subexpressionsCount {
let subexpressionMatch = matches[Int(index)]
guard subexpressionMatch.rm_so != -1 else {
match.subexpressionRanges.append(RegularExpressionMatch.Range.NotFound)
continue
}
let range = Swift.Range(start: Int(subexpressionMatch.rm_so), end: Int(subexpressionMatch.rm_eo))
match.subexpressionRanges.append(RegularExpressionMatch.Range.Found(range))
}
}
return match
}
}
// MARK: - Cross-Platform Support
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public extension POSIXRegularExpression {
public typealias FlagBitmask = Int32
public typealias ErrorCode = Int32
public typealias Match = regmatch_t
}
#elseif os(Linux)
public extension POSIXRegularExpression {
public typealias FlagBitmask = Int32
public typealias ErrorCode = reg_errcode_t
public typealias Match = regmatch_t
}
#endif
| mit | 2366f22404eb72a453fd81bbc5790e58 | 28.410256 | 132 | 0.576867 | 5.237443 | false | false | false | false |
imjerrybao/SocketIO-Kit | Source/External/LumaJSON.swift | 2 | 2334 | //
// LumaJSON.swift
// LumaJSON
//
// Created by Jameson Quave on 2/28/15.
// Copyright (c) 2015 Lumarow, LLC. All rights reserved.
//
import Foundation
class LumaJSONObject: Printable {
var value: AnyObject?
subscript(index: Int) -> LumaJSONObject? {
return (value as? [AnyObject]).map { LumaJSONObject($0[index]) }
}
subscript(key: String) -> LumaJSONObject? {
return (value as? NSDictionary).map { LumaJSONObject($0[key]) }
}
subscript(key: String) -> AnyObject? {
get {
return self[key]?.value
}
}
subscript(key: Int) -> AnyObject? {
get {
return self[key]?.value
}
}
init(_ value: AnyObject?) {
self.value = value
}
var description: String {
get {
return "LumaJSONObject: \(self.value)"
}
}
}
struct LumaJSON {
static var logErrors = true
static func jsonFromObject(object: [String: AnyObject]) -> String? {
var err: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject( (object as NSDictionary) , options: nil, error: &err) {
if let jsonStr = NSString(data: jsonData, encoding: NSUTF8StringEncoding) {
return jsonStr as String
}
}
else if(err != nil) {
if LumaJSON.logErrors {
println( err?.localizedDescription )
}
}
return nil
}
static func parse(json: String) -> LumaJSONObject? {
if let jsonData = json.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){
var err: NSError?
let parsed: AnyObject? = NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableLeaves, error: &err)
if let parsedArray = parsed as? NSArray {
return LumaJSONObject(parsedArray)
}
if let parsedDictionary = parsed as? NSDictionary {
return LumaJSONObject(parsedDictionary)
}
if LumaJSON.logErrors && (err != nil) {
println(err?.localizedDescription)
}
return LumaJSONObject(parsed)
}
return nil
}
}
| mit | baefbda6a86a678cd937957ef15fef7f | 25.827586 | 123 | 0.544987 | 4.630952 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 1.playgroundbook/Contents/Chapters/Document1.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/Assessments.swift | 1 | 1994 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let success = "### Great job \nYou've solved your first challenge! \n\n[**Next Page**](@next)"
let solution: String? = nil
import PlaygroundSupport
public func assessmentPoint() -> AssessmentResults {
let checker = ContentsChecker(contents: PlaygroundPage.current.text)
var hints = [
"Start by making Byte move up the ramp. Then have Byte turn left, toggle open the switch, and walk down to the portal.",
"While moving through a portal, Byte maintains the same direction on arrival at the destination portal.",
"This puzzle is a **Challenge**. Challenges improve your coding skills by allowing you to figure out your own solutions."
]
if world.commandQueue.containsIncorrectToggleCommand() {
hints[0] = "Move Byte onto the tile with the switch before you use the `toggleSwitch()` command."
}
if checker.functionCallCount(forName: "toggleSwitch") == 0 && checker.functionCallCount(forName: "collectGem") == 0 {
hints[0] = "First, move Byte to the switch and toggle it using `toggleSwitch()`."
} else if !world.commandQueue.containsIncorrectToggleCommand() && checker.functionCallCount(forName: "collectGem") == 0 {
hints[0] = "After toggling the switch, you need to move Byte through the portal. Whichever direction Byte faces when entering the portal, Byte will face the same direction after exiting the destination portal."
} else if !world.commandQueue.containsIncorrectToggleCommand() && world.commandQueue.containsIncorrectToggleCommand() && checker.numberOfStatements < 13 {
hints[0] = "In this puzzle, you might have to move forward multiple times to get to where you want to go. For example, to move three tiles forward, you need to use three `moveForward()` commands."
}
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit | 13ccdba3968e763bf78d5a5c9cd4c264 | 45.372093 | 218 | 0.712638 | 4.511312 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/RequiredEnumCaseRule.swift | 1 | 8797 | import Foundation
import SourceKittenFramework
/// Allows for Enums that conform to a protocol to require that a specific case be present.
///
/// This is primarily for result enums where a specific case is common but cannot be inherited due to cases not being
/// inheritable.
///
/// For example: A result enum is used to define all of the responses a client must handle from a specific service call
/// in an API.
///
/// ````
/// enum MyServiceCallResponse: String {
/// case unauthorized
/// case unknownError
/// case accountCreated
/// }
///
/// // An exhaustive switch can be used so any new scenarios added cause compile errors.
/// switch response {
/// case unauthorized:
/// ...
/// case unknownError:
/// ...
/// case accountCreated:
/// ...
/// }
/// ````
///
/// If cases could be inherited you could put all of the common ones in an enum and then inherit from that enum:
///
/// ````
/// enum MyServiceResponse: String {
/// case unauthorized
/// case unknownError
/// }
///
/// enum MyServiceCallResponse: MyServiceResponse {
/// case accountCreated
/// }
/// ````
///
/// Which would result in MyServiceCallResponse having all of the cases when compiled:
///
/// ```
/// enum MyServiceCallResponse: MyServiceResponse {
/// case unauthorized
/// case unknownError
/// case accountCreated
/// }
/// ```
///
/// Since that cannot be done this rule allows you to define cases that should be present if conforming to a protocol.
///
/// `.swiftlint.yml`
/// ````
/// required_enum_case:
/// MyServiceResponse:
/// unauthorized: error
/// unknownError: error
/// ````
///
/// ````
/// protocol MyServiceResponse {}
///
/// // This will now have errors because `unauthorized` and `unknownError` are not present.
/// enum MyServiceCallResponse: String, MyServiceResponse {
/// case accountCreated
/// }
/// ````
public struct RequiredEnumCaseRule: ASTRule, OptInRule, ConfigurationProviderRule {
public typealias KindType = SwiftDeclarationKind
typealias RequiredCase = RequiredEnumCaseRuleConfiguration.RequiredCase
/// Keys needed to parse the information from the SourceKitRepresentable dictionary.
struct Keys {
static let offset = "key.offset"
static let inheritedTypes = "key.inheritedtypes"
static let name = "key.name"
static let substructure = "key.substructure"
static let kind = "key.kind"
static let enumCase = "source.lang.swift.decl.enumcase"
}
/// Simple representation of parsed information from the SourceKitRepresentable dictionary.
struct Enum {
let file: File
let location: Location
let inheritedTypes: [String]
let cases: [String]
init(from dictionary: [String: SourceKitRepresentable], in file: File) {
self.file = file
location = Enum.location(from: dictionary, in: file)
inheritedTypes = Enum.inheritedTypes(from: dictionary)
cases = Enum.cases(from: dictionary)
}
/// Determines the location of where the enum declaration starts.
///
/// - Parameters:
/// - dictionary: Parsed source for the enum.
/// - file: File that contains the enum.
/// - Returns: Location of where the enum declaration starts.
static func location(from dictionary: [String: SourceKitRepresentable], in file: File) -> Location {
guard let offset = dictionary[Keys.offset] as? Int64 else {
return Location(file: file, characterOffset: 0)
}
return Location(file: file, characterOffset: Int(offset))
}
/// Determines all of the inherited types the enum has.
///
/// - Parameter dictionary: Parsed source for the enum.
/// - Returns: All of the inherited types the enum has.
static func inheritedTypes(from dictionary: [String: SourceKitRepresentable]) -> [String] {
guard let inheritedTypes = dictionary[Keys.inheritedTypes] as? [SourceKitRepresentable] else {
return []
}
return inheritedTypes.compactMap { $0 as? [String: SourceKitRepresentable] }.compactMap {
$0[Keys.name] as? String
}
}
/// Determines the names of cases found in the enum.
///
/// - Parameter dictionary: Parsed source for the enum.
/// - Returns: Names of cases found in the enum.
static func cases(from dictionary: [String: SourceKitRepresentable]) -> [String] {
guard let elements = dictionary[Keys.substructure] as? [SourceKitRepresentable] else {
return []
}
let caseSubstructures = elements.compactMap { $0 as? [String: SourceKitRepresentable] }.filter {
$0.filter {
$0.0 == Keys.kind && $0.1 as? String == SwiftDeclarationKind.enumcase.rawValue
}.isEmpty == false
}.compactMap { $0[Keys.substructure] as? [SourceKitRepresentable] }
return caseSubstructures.flatMap { $0 }.compactMap { $0 as? [String: SourceKitRepresentable] }.compactMap {
$0[Keys.name] as? String
}
}
}
public var configuration = RequiredEnumCaseRuleConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "required_enum_case",
name: "Required Enum Case",
description: "Enums conforming to a specified protocol must implement a specific case(s).",
kind: .lint,
nonTriggeringExamples: [
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success, error, notConnected \n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success, error, notConnected(error: Error) \n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success\n" +
" case error\n" +
" case notConnected\n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success\n" +
" case error\n" +
" case notConnected(error: Error)\n" +
"}"
],
triggeringExamples: [
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success, error \n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success, error \n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success\n" +
" case error\n" +
"}",
"enum MyNetworkResponse: String, NetworkResponsable {\n" +
" case success\n" +
" case error\n" +
"}"
]
)
public func validate(file: File, kind: KindType, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .enum else {
return []
}
return violations(for: Enum(from: dictionary, in: file))
}
/// Iterates over all of the protocols in the configuration and creates violations for missing cases.
///
/// - Parameters:
/// - parsed: Enum information parsed from the SourceKitRepresentable dictionary.
/// - Returns: Violations for missing cases.
func violations(for parsed: Enum) -> [StyleViolation] {
var violations: [StyleViolation] = []
for (type, requiredCases) in configuration.protocols where parsed.inheritedTypes.contains(type) {
for requiredCase in requiredCases where !parsed.cases.contains(requiredCase.name) {
violations.append(create(violationIn: parsed, for: type, missing: requiredCase))
}
}
return violations
}
/// Creates the violation for a missing case.
///
/// - Parameters:
/// - parsed: Enum information parsed from the SourceKitRepresentable dictionary.
/// - protocolName: Name of the protocol that is missing the case.
/// - requiredCase: Information about the case and the severity of the violation.
/// - Returns: Created violation.
func create(violationIn parsed: Enum,
for protocolName: String,
missing requiredCase: RequiredCase) -> StyleViolation {
return StyleViolation(
ruleDescription: type(of: self).description,
severity: requiredCase.severity,
location: parsed.location,
reason: "Enums conforming to \"\(protocolName)\" must have a \"\(requiredCase.name)\" case")
}
}
| mit | 691ab70591f493cbeb4d3e480232a03a | 36.434043 | 120 | 0.606457 | 4.817634 | false | false | false | false |
NickKech/Iron-Wings | IronWings-iOS/GameViewController.swift | 1 | 1393 | //
// GameViewController.swift
//
// Created by Nikolaos Kechagias on 02/09/15.
// Copyright (c) 2015 Your Name. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* Configure the view */
let skView = self.view as! SKView
/* A boolean value that indicates whether the view displays the physics world */
skView.showsPhysics = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Creates, configure and present the scene in the view */
let scene = GameScene(size: skView.bounds.size)
scene.scaleMode = .aspectFill
skView.presentScene(scene)
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | 5fe33cbeb7010fb0f86bed3f8470056e | 26.86 | 90 | 0.636755 | 5.378378 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/User/SearchInFollowersRequest.swift | 1 | 2318 | //
// SearchInFollowersRequest.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class SearchInFollowersRequest: Request {
override var method: RequestMethod { return .get }
override var endpoint: String {
let user = userId
return "users/"+user+"/followers"
}
override var parameters: Dictionary<String, AnyObject> { return prepareParameters() }
fileprivate let page: Int?
fileprivate let perPage: Int?
fileprivate let userId: String
fileprivate let query: String?
init(page: Int? = nil, perPage: Int? = nil, userId: String, query: String) {
self.page = page
self.perPage = perPage
self.userId = userId
self.query = query
}
fileprivate func prepareParameters() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
if let page = page {
params["page"] = page as AnyObject?
}
if let perPage = perPage {
params["per_page"] = perPage as AnyObject?
}
if let query = query {
params["filter[username]"] = query as AnyObject?
}
return params
}
}
| mit | 384d60c4baf15e0011110d749e8729ee | 36.387097 | 89 | 0.677739 | 4.545098 | false | false | false | false |
XYXiaoYuan/Meilishuo | Meilishuo/Classes/Home/Animate/PresentAnimation.swift | 1 | 2698 | //
// PresentAnimation.swift
// Meilishuo
//
// Created by 袁小荣 on 2017/5/13.
// Copyright © 2017年 袁小荣. All rights reserved.
//
import UIKit
class PresentAnimation: NSObject {
/// ImageView用于做放大动画
fileprivate lazy var imageView = UIImageView().then {
$0.contentMode = .scaleAspectFit
}
/// 获取主界面的图片,将图片放到imageView里面
var infoTuple: (currentImage: UIImage?, superView: UIView)? {
didSet {
guard let currentImage = infoTuple?.currentImage, let supView = infoTuple?.superView else {
return
}
// 给imageView赋值图片
imageView.image = currentImage
// 将supView的位置转换到window上
imageView.frame = supView.convert(supView.bounds, to: nil)
}
}
}
extension PresentAnimation: UIViewControllerAnimatedTransitioning {
/// 动画的执行时间
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 1.0
}
/// 动画的执行过程
/// 动画执行完后必须调用 transitionContext的一个完成方法,不然不会执行成功
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
/*
思路:
1. 创建一个UIImageView
2. 获取主界面点击的图片
3. 获取主界面点击的那个cell的尺寸,并将尺寸的位置转换到window上
4. 设置UIImageView的图片以及转换到的最新位置
5. 将UIImageView添加到containerView
6. 使用UIView的动画,将UIImageView的frame放大到指定的大小(整个屏幕)
7. 动画执行完毕之后,移除UIImageView,添加toView(图片浏览器控制器的View)
8. 动画执行完调用成功方法
*/
// 将UIImageView添加到containerView
let containerView = transitionContext.containerView
containerView.addSubview(imageView)
// 使用UIView的动画,将UIImageView的frame放大到指定的大小(整个屏幕)
let duration = transitionDuration(using: transitionContext)
UIView.animate(withDuration: duration, animations: {
// 设置imageView的大小为全屏
self.imageView.frame = UIScreen.main.bounds
}, completion: { finished in
self.imageView.removeFromSuperview()
let toView = transitionContext.view(forKey: .to) ?? UIView()
containerView.addSubview(toView)
// 告诉系统动画执行完了
transitionContext.completeTransition(true)
})
}
}
| mit | ba267d98c1c385fe170384664bf3c2a0 | 30.013889 | 109 | 0.650694 | 4.47495 | false | false | false | false |
rnystrom/GitHawk | Classes/Issues/Merge/IssueMergeContextModel.swift | 1 | 1380 | //
// IssueMergeContextModel.swift
// Freetime
//
// Created by Ryan Nystrom on 2/11/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
final class IssueMergeContextModel: ListDiffable {
let id: String
let context: String
let state: StatusState
let login: String
let avatarURL: URL
let description: String
let targetURL: URL
init(
id: String,
context: String,
state: StatusState,
login: String,
avatarURL: URL,
description: String,
targetURL: URL
) {
self.id = id
self.context = context
self.state = state
self.login = login
self.avatarURL = avatarURL
self.description = description
self.targetURL = targetURL
}
// MARK: ListDiffable
func diffIdentifier() -> NSObjectProtocol {
return id as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? IssueMergeContextModel else { return false }
return context == object.context
&& state == object.state
&& login == object.login
&& avatarURL == object.avatarURL
&& description == object.description
&& targetURL == object.targetURL
}
}
| mit | 5accd23749df56fcbbb4f7d57cef9e16 | 23.192982 | 82 | 0.612763 | 4.771626 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/NCTankTableViewCell.swift | 2 | 2566 | //
// NCTankTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 08.02.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import Dgmpp
class NCTankStackView: UIStackView {
@IBOutlet weak var shieldRechargeLabel: UILabel!
@IBOutlet weak var shieldBoostLabel: UILabel!
@IBOutlet weak var armorRepairLabel: UILabel!
@IBOutlet weak var hullRepairLabel: UILabel!
@IBOutlet weak var effectiveShieldRechargeLabel: UILabel!
@IBOutlet weak var effectiveSieldBoostLabel: UILabel!
@IBOutlet weak var effectiveArmorRepairLabel: UILabel!
@IBOutlet weak var effectiveHullRepairLabel: UILabel!
}
class NCTankTableViewCell: NCTableViewCell {
@IBOutlet weak var reinforcedView: NCTankStackView!
@IBOutlet weak var sustainedView: NCTankStackView!
}
extension Prototype {
enum NCTankTableViewCell {
static let `default` = Prototype(nib: nil, reuseIdentifier: "NCTankTableViewCell")
}
}
class NCTankRow: TreeRow {
let ship: DGMShip
init(ship: DGMShip) {
self.ship = ship
super.init(prototype: Prototype.NCTankTableViewCell.default)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCTankTableViewCell else {return}
let ship = self.ship
cell.object = ship
let tank = (ship.tank, ship.effectiveTank)
let sustainableTank = (ship.sustainableTank, ship.effectiveSustainableTank)
let formatter = NCUnitFormatter(unit: .none, style: .short, useSIPrefix: false)
func fill(view: NCTankStackView, tank: (DGMTank, DGMTank)) {
view.shieldRechargeLabel.text = formatter.string(for: tank.0.passiveShield * DGMSeconds(1))
view.effectiveShieldRechargeLabel.text = formatter.string(for: tank.1.passiveShield * DGMSeconds(1))
view.shieldBoostLabel.text = formatter.string(for: tank.0.shieldRepair * DGMSeconds(1))
view.effectiveSieldBoostLabel.text = formatter.string(for: tank.1.shieldRepair * DGMSeconds(1))
view.armorRepairLabel.text = formatter.string(for: tank.0.armorRepair * DGMSeconds(1))
view.effectiveArmorRepairLabel.text = formatter.string(for: tank.1.armorRepair * DGMSeconds(1))
view.hullRepairLabel.text = formatter.string(for: tank.0.hullRepair * DGMSeconds(1))
view.effectiveHullRepairLabel.text = formatter.string(for: tank.1.hullRepair * DGMSeconds(1))
}
fill(view: cell.reinforcedView, tank: tank)
fill(view: cell.sustainedView, tank: sustainableTank)
}
override var hash: Int {
return ship.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
return (object as? NCTankRow)?.hashValue == hashValue
}
}
| lgpl-2.1 | 93b9003da8a94c783ebe8d0fa3435f7d | 32.75 | 103 | 0.760234 | 3.379447 | false | false | false | false |
swift-gtk/SwiftGTK | Sources/UIKit/AboutDialog.swift | 1 | 6021 |
public typealias AboutDialogActivateLinkCallback = (AboutDialog, String) -> Bool
public class AboutDialog: Dialog {
//internal var n_AboutDialog: UnsafeMutablePointer<GtkAboutDialog>
/*
internal init(n_AboutDialog: UnsafeMutablePointer<GtkAboutDialog>) {
self.n_AboutDialog = n_AboutDialog
super.init(n_Dialog: UnsafeMutablePointer<GtkDialog>(object.asGObject()))
}
public convenience init() {
let n_AboutDialog = UnsafeMutablePointer<GtkAboutDialog>(gtk_about_dialog_new())
self.init(n_AboutDialog: n_AboutDialog!)
}
*/
public var programName: String {
get {
return String(cString: gtk_about_dialog_get_program_name(object.asGObject()))
}
set {
gtk_about_dialog_set_program_name(object.asGObject(), newValue)
}
}
public var version: String {
get {
return String(cString: gtk_about_dialog_get_version(object.asGObject()))
}
set {
gtk_about_dialog_set_version(object.asGObject(), newValue)
}
}
public var copyright: String {
get {
return String(cString: gtk_about_dialog_get_copyright(object.asGObject()))
}
set {
gtk_about_dialog_set_copyright(object.asGObject(), newValue)
}
}
public var comments: String {
get {
return String(cString: gtk_about_dialog_get_comments(object.asGObject()))
}
set {
gtk_about_dialog_set_comments(object.asGObject(), newValue)
}
}
public var license: String {
get {
return String(cString: gtk_about_dialog_get_license(object.asGObject()))
}
set {
gtk_about_dialog_set_license(object.asGObject(), newValue)
}
}
public var wrapLicense: Bool {
get {
return gtk_about_dialog_get_wrap_license(object.asGObject()) != 0 ? true : false
}
set {
gtk_about_dialog_set_wrap_license(object.asGObject(), newValue ? 1 : 0)
}
}
public var licenseType: License {
get {
return License(rawValue: gtk_about_dialog_get_license_type(object.asGObject()))!
}
set {
gtk_about_dialog_set_license_type(object.asGObject(), newValue.rawValue)
}
}
public var website: String {
get {
return String(cString: gtk_about_dialog_get_website(object.asGObject()))
}
set {
gtk_about_dialog_set_website(object.asGObject(), newValue)
}
}
public var websiteLabel: String {
get {
return String(cString: gtk_about_dialog_get_website_label(object.asGObject()))
}
set {
gtk_about_dialog_set_website_label(object.asGObject(), newValue)
}
}
/*
// TODO: set
public var authors: [String] {
get {
var n_Authors = gtk_about_dialog_get_authors(object.asGObject())
var authors = [String]()
while n_Authors.pointee != nil {
authors.append(String(cString: n_Authors.pointee!))
n_Authors = n_Authors.advanced(by: 1)
}
return authors
}
// set {
// let authorsCount = newValue.count
//
// let n_Authors = UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>(allocatingCapacity: authorsCount)
//
// var index = 0
// for author in newValue {
// n_Authors.advanced(by: index).pointee = author
// index += 1
// }
//
// n_Authors.advanced(by: index).pointee = nil
// }
}
*/
// TODO: set
/* public var artists: [String] {
get {
var n_Artists = gtk_about_dialog_get_artists(object.asGObject())
var artists = [String]()
while n_Artists.pointee != nil {
artists.append(String(cString: n_Artists.pointee!))
n_Artists = n_Artists.advanced(by: 1)
}
return artists
}
} */
/* // TODO: set
public var documenters: [String] {
get {
var n_Documenters = gtk_about_dialog_get_documenters(object.asGObject())
var documenters = [String]()
while n_Documenters.pointee != nil {
documenters.append(String(cString: n_Documenters.pointee!))
n_Documenters = n_Documenters.advanced(by: 1)
}
return documenters
}
}
*/
public var translatorCredits: String {
get {
return String(cString: gtk_about_dialog_get_translator_credits(object.asGObject()))
}
set {
gtk_about_dialog_set_translator_credits(object.asGObject(), newValue)
}
}
// TODO: gtk_about_dialog_get_logo and gtk_about_dialog_set_logo
public var logoIconName: String {
get {
return String(cString: gtk_about_dialog_get_logo_icon_name(object.asGObject()))
}
set {
gtk_about_dialog_set_logo_icon_name(object.asGObject(), newValue)
}
}
public typealias AboutDialogActivateLinkNative = @convention(c)(UnsafeMutablePointer<GtkAboutDialog>, UnsafeMutablePointer<CChar>, gpointer) -> Void
public lazy var activateLinkSignal: Signal<AboutDialogActivateLinkCallback, AboutDialog, AboutDialogActivateLinkNative> = Signal(obj: self, signal: "activate-link", c_handler: {
(_, n_Uri, user_data) in
let data = unsafeBitCast(user_data, to: SignalData<AboutDialog, AboutDialogActivateLinkCallback>.self)
let widget = data.obj
let uri = String(cString: n_Uri)
let action = data.function
action(widget, uri)
})
}
| gpl-2.0 | 48d194423ea8f35af8c87be91601e683 | 30.689474 | 181 | 0.557382 | 4.213436 | false | false | false | false |
kean/Nuke-Alamofire-Plugin | Source/DataLoader.swift | 1 | 1758 | // The MIT License (MIT)
//
// Copyright (c) 2016-2022 Alexander Grebenyuk (github.com/kean).
import Foundation
@preconcurrency import Alamofire
import Nuke
/// Implements data loading using Alamofire framework.
public final class AlamofireDataLoader: Nuke.DataLoading {
public let session: Alamofire.Session
/// Initializes the receiver with a given Alamofire.SessionManager.
/// - parameter session: Alamofire.Session.default by default.
public init(session: Alamofire.Session = Alamofire.Session.default) {
self.session = session
}
// MARK: DataLoading
/// Loads data using Alamofire.SessionManager.
public func loadData(with request: URLRequest, didReceiveData: @escaping (Data, URLResponse) -> Void, completion: @escaping (Error?) -> Void) -> Cancellable {
// Alamofire.SessionManager automatically starts requests as soon as they are created (see `startRequestsImmediately`)
let task = self.session.streamRequest(request)
task.responseStream { [weak task] stream in
switch stream.event {
case let .stream(result):
switch result {
case let .success(data):
guard let response = task?.response else { return } // Never nil
didReceiveData(data, response)
}
case let .complete(response):
completion(response.error)
}
}
return AnyCancellable {
task.cancel()
}
}
}
private final class AnyCancellable: Nuke.Cancellable {
let closure: @Sendable () -> Void
init(_ closure: @Sendable @escaping () -> Void) {
self.closure = closure
}
func cancel() {
closure()
}
}
| mit | 8b3f075c2bfd6fc0783efa48a9cfb174 | 32.169811 | 162 | 0.632537 | 4.98017 | false | false | false | false |
nanjingboy/SwiftImageSlider | Source/ImageSliderViewController.swift | 1 | 3668 | import UIKit
open class ImageSliderViewController: UIViewController, ImageSliderViewDelegate {
open let imageSliderView: ImageSliderView
open let pageControl = UIPageControl()
public init(currentIndex: Int, imageUrls: [String]) {
imageSliderView = ImageSliderView(currntIndex: currentIndex, imageUrls: imageUrls)
super.init(nibName: nil, bundle: nil)
imageSliderViewImageSwitch(currentIndex, count: imageUrls.count, imageUrl: imageUrls[currentIndex])
}
public required init?(coder aDecoder: NSCoder) {
imageSliderView = ImageSliderView(currntIndex: 0, imageUrls: [])
super.init(coder: aDecoder)
imageSliderViewImageSwitch(0, count: 0, imageUrl: nil)
}
open override func viewDidLoad() {
super.viewDidLoad()
view.clipsToBounds = true
view.backgroundColor = UIColor.black
imageSliderView.delegate = self
imageSliderView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(imageSliderView)
setImageSliderViewConstraints()
pageControl.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pageControl)
setDisplayLabelConstraints()
}
open func setImageSliderViewConstraints() {
let imageSliderViewHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[imageSliderView]-0-|",
options: [],
metrics: nil,
views: ["imageSliderView": imageSliderView])
view.addConstraints(imageSliderViewHConstraints)
let imageSliderViewVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[imageSliderView]-0-|",
options: [],
metrics: nil,
views: ["imageSliderView": imageSliderView])
view.addConstraints(imageSliderViewVConstraints)
}
open func setDisplayLabelConstraints() {
let constraint = NSLayoutConstraint(item: pageControl,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1.0,
constant: 0.0)
view.addConstraint(constraint)
let displayLabelVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[pageControl]-20-|",
options: [],
metrics: nil,
views: ["pageControl": pageControl])
view.addConstraints(displayLabelVConstraints)
}
open func imageSliderViewSingleTap(_ tap: UITapGestureRecognizer) {
dismiss(animated: true, completion: nil)
}
open func imageSliderViewImageSwitch(_ index: Int, count: Int, imageUrl: String?) {
pageControl.numberOfPages = count
pageControl.currentPage = index
}
}
| mit | 9808e2461906725cab1d1427c52185bc | 47.906667 | 130 | 0.52181 | 7.12233 | false | false | false | false |
TalntsApp/media-picker-ios | MediaPicker/Selection/MediaPicker.swift | 1 | 11273 | import UIKit
import MediaPlayer
import AVFoundation
import Photos
import Runes
import Argo
import BABCropperView
/**
MediaPicker
----
Control that allows you to pick media from gallery.
*/
public class MediaPicker: UIView, ImageSource, VideoSource {
/// Image from gallery was selected
public var onImageReady: (UIImage -> Void)?
/// Video from gallery was selected
public var onVideoReady: (AVURLAsset -> Void)?
/// Selection was cancelled
public var onClose: (() -> Void)?
private weak var selectedAsset: PHAsset?
@IBOutlet var view: UIView?
@IBOutlet var largePreviewConstraint: NSLayoutConstraint!
@IBOutlet var largePreview: BABCropperView!
@IBOutlet var activityIndicator: UIActivityIndicatorView!
@IBOutlet var upButtonConstraint: NSLayoutConstraint!
@IBOutlet var upButton: UIButton!
@IBOutlet var upButtonIcon: UIImageView!
@IBOutlet var collectionHost: UIView!
@IBOutlet var videoPreview: UIView?
@IBOutlet var videoPlayControl: PlayControlView?
@IBInspectable var photosOnly: Bool = false
/// Overrides `UIView`'s `awakeFromNib`
override public func awakeFromNib() {
super.awakeFromNib()
let bundle = NSBundle(forClass: MediaPicker.self)
if let _ = bundle.loadNibNamed("MediaPicker", owner: self, options: nil) {
self.view?.frame = self.bounds
self.addSubview <^> self.view
setup()
}
}
private enum PreviewState: CustomStringConvertible {
case AllWayUp
case FreeScroll
mutating func flip() {
switch self {
case .FreeScroll:
self = .AllWayUp
case .AllWayUp:
self = .FreeScroll
}
}
var description: String {
switch self {
case .AllWayUp:
return "AllWayUp"
case .FreeScroll:
return "FreeScroll"
}
}
}
private var previewState = PreviewState.FreeScroll {
didSet {
if previewState != oldValue {
updatePreview()
}
}
}
func updatePreview() {
if let imageCollection = self.imageCollection {
let topPosition: CGFloat
let iconTransform: CGAffineTransform
switch self.previewState {
case .AllWayUp:
topPosition = -self.largePreview.frame.height
iconTransform = CGAffineTransformMakeScale(1.0, -1.0)
case .FreeScroll:
topPosition = 0
iconTransform = CGAffineTransformIdentity
}
Animate(duration: 0.6, options: UIViewAnimationOptions.CurveEaseInOut)
.animation {
self.largePreviewConstraint.constant = topPosition
self.upButtonIcon.transform = iconTransform
self.largePreview.layoutIfNeeded()
self.upButton.layoutIfNeeded()
imageCollection.layoutIfNeeded()
}
.fire()
}
}
/// Overrides `UIView`'s `layoutSubviews`
override public func layoutSubviews() {
super.layoutSubviews()
setupCropper()
}
private func setupCropper() {
self.largePreview.cropDisplayScale = 1.0
self.largePreview.cropSize = CGSize(width: 1242, height: 1242)
}
private lazy var imageList:MediaList = MediaList(photosOnly: self.photosOnly)
private var imageCollection: UICollectionView?
func setup() {
self.viewController?.addChildViewController(imageList)
imageCollection = imageList.collectionView
imageCollection?.frame = self.collectionHost.bounds
imageCollection?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.collectionHost.addSubview <^> imageCollection
imageList.selectionSignal.listen(self) {[weak self] (indexPath, asset) in
if let `self` = self {
self.handleSelection(indexPath, asset)
}
}
imageList.scrollSignal.listen(self) {[weak self] offset in
if let `self` = self {
self.handleScroll(offset)
}
}
upButton.onTouchDown.listen(self) { [weak self] in
if let `self` = self {
self.previewState.flip()
self.updatePreview()
}
}
}
private func handleSelection(indexPath: NSIndexPath, _ asset: PHAsset) {
self.selectedAsset = asset
self.activityIndicator.hidden = false
self.activityIndicator.startAnimating()
self.largePreview.image = nil
asset.talntsImage.listen(self) { [weak self] image in
if let `self` = self {
Animate(duration: 0.6, options: .CurveEaseInOut)
.before {
self.largePreview.image = image
}
.animation {
self.largePreviewConstraint.constant = 0
}
.after {
self.activityIndicator.stopAnimating()
self.previewState = .FreeScroll
}
.fire()
}
}
self.largePreview.synced { [weak self] in
if let `self` = self {
self.videoPreview?.removeFromSuperview()
self.videoPreview = nil
self.videoPlayControl?.removeFromSuperview()
self.videoPlayControl = nil
if asset.mediaType == .Video {
asset.urlAsset.listen(self) { [weak self] asset in
self?.setupVideoPreview <*> asset
self?.activityIndicator.stopAnimating()
}
}
}
}
}
private func handleScroll(offset: CGFloat) {
if self.previewState == .FreeScroll {
self.upButton.synced {
Animate(duration: 0.6, options: .CurveEaseOut)
.animation { [weak self] in
if let `self` = self {
self.largePreviewConstraint?.constant = offset
let verticalTransform = round((offset/self.largePreview.frame.height + 1/2) * 2)
self.upButtonIcon.transform = CGAffineTransformMakeScale(1.0, clip(low: -1.0, high: 1.0)(value: verticalTransform))
}
}
.fire()
}
}
switch self.previewState {
case .AllWayUp where offset.isZero:
Animate(duration: 0.6, options: .CurveEaseOut)
.animation { [weak self] in
self?.previewState = .FreeScroll
}
.fire()
case .FreeScroll where -offset >= self.largePreview.frame.height:
self.previewState = .AllWayUp
default:
break
}
}
private func setupVideoPreview(asset: AVURLAsset) {
let videoPreview = UIView(frame: self.largePreview.bounds)
videoPreview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
videoPreview.backgroundColor = UIColor.clearColor()
self.largePreview.addSubview(videoPreview)
self.videoPreview = videoPreview
// videoPreview.remoteURL = asset.URL.absoluteString
let statusBarHidden = UIApplication.sharedApplication().statusBarHidden
let movieController = MPMoviePlayerViewController(contentURL: asset.URL)
let player = movieController.view
videoPreview.contentMode = .ScaleAspectFill
player.contentMode = .ScaleAspectFill
player.frame = videoPreview.bounds
player.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
player.removeFromSuperview()
videoPreview.addSubview(player)
videoPreview.bringSubviewToFront(player)
if
let vc = player.viewController as? MPMoviePlayerViewController,
let mp = vc.moviePlayer
{
// mp.controlStyle = .None
mp.shouldAutoplay = false
UIApplication.sharedApplication().statusBarHidden = statusBarHidden
// let playControlView = PlayControlView(frame: player.bounds)
// playControlView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
// player.addSubview(playControlView)
//
// playControlView.onTouchDown.listen(self) { [weak playControlView] in
// if let state = playControlView?.playControlState {
// switch state {
// case .Pause:
// mp.pause()
// case .Play:
// mp.play()
// default:
// break
// }
// }
// }
// playControlView.playControlState = .Play
// playControlView.enableTouch = true
// self.videoPlayControl = playControlView
//
// NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("videoPlaybackStateChanged:"), name: MPMoviePlayerPlaybackStateDidChangeNotification, object: mp)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("videoWentFullscreen:"), name: MPMoviePlayerWillEnterFullscreenNotification, object: mp)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("videoReturnedFromFullscreen:"), name: MPMoviePlayerDidExitFullscreenNotification, object: mp)
}
}
}
func clip<T: Comparable>(low low: T, high: T)(value: T) -> T {
return max(low, min(high, value))
}
func *(lhs: CGFloat, rhs: CGSize) -> CGSize {
return CGSize(width: lhs * rhs.width, height: lhs * rhs.height)
}
func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
return rhs * lhs
}
extension UIView {
var viewController: UIViewController? {
var nextResponder: UIResponder? = self
repeat {
nextResponder = nextResponder?.nextResponder()
if let viewController = nextResponder as? UIViewController {
return viewController
}
} while (nextResponder != nil)
return nil
}
}
class PlayControlView: UIButton {
enum State {
case Wait
case Pause
case Play
}
var playControlState: State = .Pause
} | mit | ffce588782a4736fa64984950a4c3dfa | 33.371951 | 197 | 0.543688 | 5.591766 | false | false | false | false |
FuzzyHobbit/bitcoin-swift | BitcoinSwift/Models/PingMessage.swift | 1 | 1289 | //
// PingMessage.swift
// BitcoinSwift
//
// Created by James MacWhyte on 9/27/14.
// Copyright (c) 2014 DoubleSha. All rights reserved.
//
import Foundation
public func ==(left: PingMessage, right: PingMessage) -> Bool {
return left.nonce == right.nonce
}
/// The ping message is sent primarily to confirm that the TCP/IP connection is still valid. An
/// error in transmission is presumed to be a closed connection and the address is removed as a
/// current peer.
/// https://en.bitcoin.it/wiki/Protocol_specification#ping
public struct PingMessage: Equatable {
public var nonce: UInt64
public init(nonce: UInt64? = nil) {
if let nonce = nonce {
self.nonce = nonce
} else {
self.nonce = UInt64(arc4random()) | (UInt64(arc4random()) << 32)
}
}
}
extension PingMessage: MessagePayload {
public var command: Message.Command {
return Message.Command.Ping
}
public var bitcoinData: NSData {
var data = NSMutableData()
data.appendUInt64(nonce)
return data
}
public static func fromBitcoinStream(stream: NSInputStream) -> PingMessage? {
let nonce = stream.readUInt64()
if nonce == nil {
Logger.warn("Failed to parse nonce from PingMessage")
return nil
}
return PingMessage(nonce: nonce)
}
}
| apache-2.0 | 7d6f1ff72bdad82f1fd2e34504e4bff2 | 23.788462 | 95 | 0.683476 | 3.847761 | false | false | false | false |
libra/libra | diem-move/transaction-builder-generator/examples/swift/main.swift | 1 | 2737 | import DiemTypes
func demo_peer_to_peer_script() throws {
let address = DiemTypes.AccountAddress(value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
let module = DiemTypes.Identifier(value: "XDX")
let name = DiemTypes.Identifier(value: "XDX")
let type_params: [DiemTypes.TypeTag] = []
let struct_tag = DiemTypes.StructTag(
address: address,
module: module,
name: name,
type_params: type_params
)
let token = DiemTypes.TypeTag.Struct(struct_tag)
let payee = DiemTypes.AccountAddress(value: [
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
0x22,
])
let amount: UInt64 = 1234567
let script = encode_peer_to_peer_with_metadata_script(
currency: token,
payee: payee,
amount: amount,
metadata: [],
metadata_signature: []
)
switch try decode_peer_to_peer_with_metadata_script(script: script) {
case .PeerToPeerWithMetadata(_, let p, let a, _, _):
assert(p == payee, "Payee doesn't match")
assert(a == amount, "Amount doesn't match")
default: assertionFailure("Invalid scriptcall")
}
for o in try script.bcsSerialize() {
print(o, terminator: " ")
}
print()
}
func demo_peer_to_peer_script_function() throws {
let address = DiemTypes.AccountAddress(value: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
let module = DiemTypes.Identifier(value: "XDX")
let name = DiemTypes.Identifier(value: "XDX")
let type_params: [DiemTypes.TypeTag] = []
let struct_tag = DiemTypes.StructTag(
address: address,
module: module,
name: name,
type_params: type_params
)
let token = DiemTypes.TypeTag.Struct(struct_tag)
let payee = DiemTypes.AccountAddress(value: [
0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
0x22,
])
let amount: UInt64 = 1234567
let script = try PaymentScripts.encode_peer_to_peer_with_metadata_script_function(
currency: token,
payee: payee,
amount: amount,
metadata: [],
metadata_signature: []
)
switch try PaymentScripts.decode_peer_to_peer_with_metadata_script_function(payload: script) {
case .PeerToPeerWithMetadata(_, let p, let a, _, _):
assert(p == payee, "Payee doesn't match")
assert(a == amount, "Amount doesn't match")
default: assertionFailure("Invalid script function call")
}
for o in try script.bcsSerialize() {
print(o, terminator: " ")
}
print()
}
try demo_peer_to_peer_script()
try demo_peer_to_peer_script_function()
| apache-2.0 | 22d28bdb9f21eea49fe12776ddc30475 | 34.089744 | 99 | 0.60833 | 3.204918 | false | false | false | false |
himadrisj/FlickrSearch | FlickrSearch/NetworkLayer/ApiModel/GetImageListRequestModels.swift | 1 | 4708 | //
// GetImageListRequestModels.swift
// FlickrSearch
//
// Created by Himadri Sekhar Jyoti on 16/06/17.
// Copyright © 2017 Himadri Jyoti. All rights reserved.
//
import Foundation
import ObjectMapper
//MARK: Request
struct GetImageListRequestModel {
let page: Int
let itemsPerPage: Int
let searchText: String
}
extension GetImageListRequestModel: UrlRequestBuilder {
func apiMethodName() -> String {
return "flickr.photos.search"
}
func httpMethod() -> String {
return "GET"
}
func apiType() -> ApiType {
return .getImageList
}
func queryItems() -> [String: String] {
var queryParamDict = [String: String]()
queryParamDict["page"] = String(self.page)
queryParamDict["per_page"] = String(self.itemsPerPage)
queryParamDict["text"] = self.searchText
//Implicitly set query items
queryParamDict["safe_search"] = "1"
return queryParamDict
}
}
//MARK: Response
struct PhotoDetails {
var id: String?
var owner: String?
var secret: String?
var server: String?
var farm: Int?
var title: String?
}
extension PhotoDetails: StrictMappable {
var mandatoryKeys: [String] { return ["id", "secret", "server", "farm"] }
init?(map: Map) {
if(!mandatoryKeysExists(map)) {
assert(false, "Mandatory keys doesn't exist")
return nil
}
}
mutating func mapping(map: Map) {
id <- map["id"]
owner <- map["owner"]
secret <- map["secret"]
server <- map["server"]
farm <- map["farm"]
title <- map["title"]
}
}
//For testing
extension PhotoDetails: Equatable {
static func ==(lhs: PhotoDetails, rhs: PhotoDetails) -> Bool {
return
lhs.id == rhs.id &&
lhs.owner == rhs.owner &&
lhs.secret == rhs.secret &&
lhs.server == rhs.server &&
lhs.farm == rhs.farm &&
lhs.title == rhs.title
}
}
//Image URL extraction
extension PhotoDetails {
func getOriginalImageUrl() -> String? {
guard let id = self.id,
let secret = self.secret,
let server = self.server,
let farm = self.farm else {
assert(false, "Mandatory keys doesn't exist")
return nil
}
return String(format: "https://farm%d.static.flickr.com/%@/%@_%@.jpg", farm, server, id, secret)
}
//75 x 75
func getSquareImageUrl() -> String? {
guard let id = self.id,
let secret = self.secret,
let server = self.server,
let farm = self.farm else {
assert(false, "Mandatory keys doesn't exist")
return nil
}
return String(format: "https://farm%d.static.flickr.com/%@/%@_%@_s.jpg", farm, server, id, secret)
}
//150 x 150
func getLargeSquareImageUrl() -> String? {
guard let id = self.id,
let secret = self.secret,
let server = self.server,
let farm = self.farm else {
assert(false, "Mandatory keys doesn't exist")
return nil
}
return String(format: "https://farm%d.static.flickr.com/%@/%@_%@_q.jpg", farm, server, id, secret)
}
}
struct PageDetails {
var page: Int?
var pages: Int?
var perPage: Int?
var total: String?
var images: [PhotoDetails] = [PhotoDetails]()
}
extension PageDetails: Mappable {
init?(map: Map) { }
mutating func mapping(map: Map) {
page <- map["page"]
pages <- map["pages"]
perPage <- map["perpage"]
total <- map["total"]
images <- map["photo"]
}
}
//For testing
extension PageDetails: Equatable {
static func ==(lhs: PageDetails, rhs: PageDetails) -> Bool {
return
lhs.page == rhs.page &&
lhs.pages == rhs.pages &&
lhs.perPage == rhs.perPage &&
lhs.total == rhs.total &&
lhs.images == rhs.images
}
}
struct GetImageListResponse {
var photos: PageDetails?
var stat: String?
}
extension GetImageListResponse: Mappable {
init?(map: Map) { }
mutating func mapping(map: Map) {
photos <- map["photos"]
stat <- map["stat"]
}
}
//For testing
extension GetImageListResponse: Equatable {
static func ==(lhs: GetImageListResponse, rhs: GetImageListResponse) -> Bool {
return
lhs.photos == rhs.photos &&
lhs.stat == rhs.stat
}
}
| mit | 3698f6ef552498ebb34039ecd68d673b | 23.515625 | 106 | 0.545783 | 4.11811 | false | false | false | false |
zixun/GodEye | Core/AppBaseKit/Classes/Util/AppPaths.swift | 2 | 3513 | //
// AppPaths.swift
// Pods
//
// Created by zixun on 16/9/24.
//
//
import Foundation
//AppPaths用来简化对app目录的检索,
//改写自Facebook大神jverkoey的Objective-C项目Nimbus 中的NIPaths
//(https://github.com/jverkoey/nimbus/blob/master/src/core/src/NIPaths.m)
//因语法关系有略微不同 并且增加了ApplicationSupportDirectory的检索
/**
* Create a path with the given bundle and the relative path appended.
*
* @param bundle The bundle to append relativePath to. If nil, [NSBundle mainBundle]
* will be used.
* @param relativePath The relative path to append to the bundle's path.
*
* @returns The bundle path concatenated with the given relative path.
*/
public func AppPathForBundleResource(bundle: Bundle?, relativePath: String) -> String {
let resourcePath = (bundle == nil ? Bundle.main : bundle)!.resourcePath!
return (resourcePath as NSString).appendingPathComponent(relativePath)
}
/**
* Create a path with the documents directory and the relative path appended.
*
* @returns The documents path concatenated with the given relative path.
*/
public func AppPathForDocumentsResource(relativePath: String) -> String {
return documentsPath.appendingPathComponent(relativePath)
}
/**
* Create a path with the Library directory and the relative path appended.
*
* @returns The Library path concatenated with the given relative path.
*/
public func AppPathForLibraryResource(relativePath: String) -> String {
return libraryPath.appendingPathComponent(relativePath)
}
/**
* Create a path with the caches directory and the relative path appended.
*
* @returns The caches path concatenated with the given relative path.
*/
public func AppPathForCachesResource(relativePath: String) -> String {
return cachesPath.appendingPathComponent(relativePath)
}
/**
* Create a path with the ApplicationSupport directory and the relative path appended.
*
* @returns The caches path concatenated with the given relative path.
*/
public func AppPathForApplicationSupportResource(relativePath: String) -> String {
return applicationSupportPath.appendingPathComponent(relativePath)
}
/// 将document目录作为常量保存起来,提高访问性能
private let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask,
true).first! as NSString
/// 将library目录作为常量保存起来,提高访问性能
private let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
.userDomainMask,
true).first! as NSString
/// 将caches目录作为常量保存起来,提高访问性能
private let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory,
.userDomainMask,
true).first! as NSString
/// 将applicationSupport目录作为常量保存起来,提高访问性能
private let applicationSupportPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory,
.userDomainMask,
true).first! as NSString
| mit | b7288ea8207e15b07919787a596fd5e8 | 37.267442 | 102 | 0.651778 | 5.190852 | false | false | false | false |
stephentyrone/swift | test/Driver/macabi-environment.swift | 1 | 8282 | // Tests to check that the driver finds standard library in the macabi environment.
// UNSUPPORTED: windows
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios13.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-MACABI %s
// IOS13-MACABI: bin/swift
// IOS13-MACABI: -target x86_64-apple-ios13.0-macabi
// IOS13-MACABI: bin/ld
// IOS13-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]]
// IOS13-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]]
// IOS13-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]]
// IOS13-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]]
// IOS13-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]]
// IOS13-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]]
// IOS13-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]]
// IOS13-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]]
// IOS13-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0
// Adjust iOS versions < 13.0 to 13.0 for the linker's sake.
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios12.0-macabi -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS12-MACABI %s
// IOS12-MACABI: bin/swift
// IOS12-MACABI: -target x86_64-apple-ios12.0-macabi
// IOS12-MACABI: bin/ld
// IOS12-MACABI-DAG: -L [[MACCATALYST_STDLIB_PATH:[^ ]+/lib/swift/maccatalyst]]
// IOS12-MACABI-DAG: -L [[MACOSX_STDLIB_PATH:[^ ]+/lib/swift/macosx]]
// IOS12-MACABI-DAG: -L [[MACCATALYST_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/System/iOSSupport/usr/lib/swift]]
// IOS12-MACABI-DAG: -L [[MACOSX_SDK_STDLIB_PATH:[^ ]+/clang-importer-sdk/usr/lib/swift]]
// IOS12-MACABI-DAG: -rpath [[MACCATALYST_STDLIB_PATH]]
// IOS12-MACABI-DAG: -rpath [[MACOSX_STDLIB_PATH]]
// IOS12-MACABI-DAG: -rpath [[MACCATALYST_SDK_STDLIB_PATH]]
// IOS12-MACABI-DAG: -rpath [[MACOSX_SDK_STDLIB_PATH]]
// IOS12-MACABI-DAG: -platform_version mac-catalyst 13.0.0 0.0.0
// Test using target-variant to build zippered outputs
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -c -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-OBJECT %s
// ZIPPERED-VARIANT-OBJECT: bin/swift
// ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -emit-library -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -module-name foo %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-LIBRARY %s
// ZIPPERED-VARIANT-LIBRARY: bin/swift
// ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi
// ZIPPERED-VARIANT-LIBRARY: bin/ld
// ZIPPERED-VARIANT-LIBRARY: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0
// Make sure we pass the -target-variant when creating the pre-compiled header.
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=ZIPPERED-VARIANT-PCH %s
// ZIPPERED-VARIANT-PCH: bin/swift
// ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi
// ZIPPERED_VARIANT-PCH -emit-pch
// ZIPPERED-VARIANT-PCH: bin/swift
// ZIPPERED-VARIANT-PCH: -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi
// ZIPPERED-VARIANT-PCH: bin/ld
// ZIPPERED-VARIANT-PCH: -platform_version macos 10.14.0 0.0.0 -platform_version mac-catalyst 13.0.0 0.0.0
// Test using 'reverse' target-variant to build zippered outputs when the primary
// target is ios-macabi
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -c -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-OBJECT %s
// REVERSE-ZIPPERED-VARIANT-OBJECT: bin/swift
// REVERSE-ZIPPERED-VARIANT-OBJECT: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -emit-library -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -module-name foo %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-LIBRARY %s
// REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/swift
// REVERSE-ZIPPERED-VARIANT-LIBRARY: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14
// REVERSE-ZIPPERED-VARIANT-LIBRARY: bin/ld
// REVERSE-ZIPPERED-VARIANT-LIBRARY: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0
// Make sure we pass the -target-variant when creating the pre-compiled header.
// RUN: %swiftc_driver -sdk "" -sdk "" -driver-print-jobs -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14 -enable-bridging-pch -import-objc-header %S/Inputs/bridging-header.h %s | %FileCheck -check-prefix=REVERSE-ZIPPERED-VARIANT-PCH %s
// REVERSE-ZIPPERED-VARIANT-PCH: bin/swift
// REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14
// REVERSE-ZIPPERED_VARIANT-PCH -emit-pch
// REVERSE-ZIPPERED-VARIANT-PCH: bin/swift
// REVERSE-ZIPPERED-VARIANT-PCH: -target x86_64-apple-ios13.0-macabi -target-variant x86_64-apple-macosx10.14
// REVERSE-ZIPPERED-VARIANT-PCH: bin/ld
// REVERSE-ZIPPERED-VARIANT-PCH: -platform_version mac-catalyst 13.0.0 0.0.0 -platform_version macos 10.14.0 0.0.0
// RUN: not %swiftc_driver -sdk "" -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET-VARIANT %s
// RUN: not %swiftc_driver -sdk "" -target x86_64-apple-ios13.0 -target-variant x86_64-apple-macosx10.14 %s 2>&1 | %FileCheck --check-prefix=UNSUPPORTED-TARGET %s
// UNSUPPORTED-TARGET-VARIANT: error: unsupported '-target-variant' value {{.*}}; use 'ios-macabi' instead
// UNSUPPORTED-TARGET: error: unsupported '-target' value {{.*}}; use 'ios-macabi' instead
// When compiling for iOS, pass iphoneos_version_min to the linker, not maccatalyst_version_min.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target arm64-apple-ios13.0 -sdk %S/../Inputs/clang-importer-sdk %s | %FileCheck -check-prefix=IOS13-NO-MACABI -implicit-check-not=mac-catalyst %s
// IOS13-NO-MACABI: bin/swift
// IOS13-NO-MACABI: -target arm64-apple-ios13.0
// IOS13-NO-MACABI: bin/ld
// IOS13-NO-MACABI-DAG: -L {{[^ ]+/lib/swift/iphoneos}}
// IOS13-NO-MACABI-DAG: -L {{[^ ]+/clang-importer-sdk/usr/lib/swift}}
// IOS13-NO-MACABI-DAG: -platform_version ios 13.0.0
// Check reading the SDKSettings.json from an SDK and using it to map Catalyst
// SDK version information.
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_ZIPPERED %s
// MACOS_10_15_ZIPPERED: -target-sdk-version 10.15
// MACOS_10_15_ZIPPERED: -target-variant-sdk-version 13.1
// MACOS_10_15_ZIPPERED: -platform_version macos 10.14.0 10.15.0
// MACOS_10_15_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.1.0
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target x86_64-apple-macosx10.14 -target-variant x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_ZIPPERED %s
// MACOS_10_15_4_ZIPPERED: -target-sdk-version 10.15.4
// MACOS_10_15_4_ZIPPERED: -target-variant-sdk-version 13.4
// MACOS_10_15_4_ZIPPERED: -platform_version macos 10.14.0 10.15.4
// MACOS_10_15_4_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0
// RUN: %swiftc_driver -sdk "" -driver-print-jobs -target-variant x86_64-apple-macosx10.14 -target x86_64-apple-ios13.0-macabi -sdk %S/Inputs/MacOSX10.15.4.versioned.sdk %s 2>&1 | %FileCheck -check-prefix MACOS_10_15_4_REVERSE_ZIPPERED %s
// MACOS_10_15_4_REVERSE_ZIPPERED: -target-sdk-version 13.4
// MACOS_10_15_4_REVERSE_ZIPPERED: -target-variant-sdk-version 10.15.4
// MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version mac-catalyst 13.0.0 13.4.0
// MACOS_10_15_4_REVERSE_ZIPPERED: -platform_version macos 10.14.0 10.15.4
| apache-2.0 | dd3410f48d048bb5f26f234473afa8fb | 67.446281 | 265 | 0.731707 | 2.657895 | false | false | false | false |
vkochar/tweety | Tweety/Views/TweetCell.swift | 1 | 2747 | //
// TweetCell.swift
// Tweety
//
// Created by Varun on 9/30/17.
// Copyright © 2017 Varun. All rights reserved.
//
import UIKit
import AFNetworking
protocol TweetCellDelegate: NSObjectProtocol {
func tweetCell(_ tweetCell: TweetCell, didTapFavorite tweet: Tweet)
func tweetCell(_ tweetCell: TweetCell, didTapReply tweet: Tweet)
func tweetCell(_ tweetCell: TweetCell, didTapRetweet tweet: Tweet)
}
class TweetCell: UITableViewCell {
@IBOutlet weak var retweetedByLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var handleLabel: UILabel!
@IBOutlet weak var timeSinceTweetLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var replyButton: UIButton!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var favoriteButton: UIButton!
weak var delegate: TweetCellDelegate?
var tweet: Tweet! {
didSet {
if let profileUrl = tweet.user?.profileUrl {
profileImage.setImageWith(profileUrl)
}
if let handle = tweet.user?.screenname {
handleLabel.text = "@\(handle)"
}
nameLabel.text = tweet.user?.name
statusLabel.text = tweet?.text
timeSinceTweetLabel.text = Date().getTimeDifference(pastDate: tweet.timestamp)
favoriteButton.isSelected = tweet.isFavorite
retweetButton.isSelected = tweet.retweeted
}
}
override func awakeFromNib() {
super.awakeFromNib()
profileImage.layer.cornerRadius = 4
profileImage.clipsToBounds = true
favoriteButton.setImage(#imageLiteral(resourceName: "favorite"), for: UIControlState.normal)
favoriteButton.setImage(#imageLiteral(resourceName: "favorite_selected"), for: UIControlState.selected)
retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: UIControlState.normal)
retweetButton.setImage(#imageLiteral(resourceName: "retweet_selected"), for: UIControlState.selected)
}
@IBAction func onReplyButton(_ sender: UIButton) {
delegate?.tweetCell(self, didTapReply: tweet)
}
@IBAction func onRetweetButton(_ sender: UIButton) {
delegate?.tweetCell(self, didTapRetweet: tweet)
}
@IBAction func onFavoriteButton(_ sender: UIButton) {
delegate?.tweetCell(self, didTapFavorite: tweet)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 053f3d799974a81ee5bd80c54c067c01 | 32.487805 | 111 | 0.656591 | 5.09462 | false | false | false | false |
liuxuan30/ios-charts | Source/Charts/Renderers/LineChartRenderer.swift | 3 | 30352 | //
// LineChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class LineChartRenderer: LineRadarRenderer
{
// TODO: Currently, this nesting isn't necessary for LineCharts. However, it will make it much easier to add a custom rotor
// that navigates between datasets.
// NOTE: Unlike the other renderers, LineChartRenderer populates accessibleChartElements in drawCircles due to the nature of its drawing options.
/// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver.
private lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements()
@objc open weak var dataProvider: LineChartDataProvider?
@objc public init(dataProvider: LineChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
open override func drawData(context: CGContext)
{
guard let lineData = dataProvider?.lineData else { return }
for i in 0 ..< lineData.dataSetCount
{
guard let set = lineData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is ILineChartDataSet)
{
fatalError("Datasets for LineChartRenderer must conform to ILineChartDataSet")
}
drawDataSet(context: context, dataSet: set as! ILineChartDataSet)
}
}
}
@objc open func drawDataSet(context: CGContext, dataSet: ILineChartDataSet)
{
if dataSet.entryCount < 1
{
return
}
context.saveGState()
context.setLineWidth(dataSet.lineWidth)
if dataSet.lineDashLengths != nil
{
context.setLineDash(phase: dataSet.lineDashPhase, lengths: dataSet.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setLineCap(dataSet.lineCapType)
// if drawing cubic lines is enabled
switch dataSet.mode
{
case .linear: fallthrough
case .stepped:
drawLinear(context: context, dataSet: dataSet)
case .cubicBezier:
drawCubicBezier(context: context, dataSet: dataSet)
case .horizontalBezier:
drawHorizontalBezier(context: context, dataSet: dataSet)
}
context.restoreGState()
}
@objc open func drawCubicBezier(context: CGContext, dataSet: ILineChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
let intensity = dataSet.cubicIntensity
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prevDx: CGFloat = 0.0
var prevDy: CGFloat = 0.0
var curDx: CGFloat = 0.0
var curDy: CGFloat = 0.0
// Take an extra point from the left, and an extra from the right.
// That's because we need 4 points for a cubic bezier (cubic=4), otherwise we get lines moving and doing weird stuff on the edges of the chart.
// So in the starting `prev` and `cur`, go -2, -1
let firstIndex = _xBounds.min + 1
var prevPrev: ChartDataEntry! = nil
var prev: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 2, 0))
var cur: ChartDataEntry! = dataSet.entryForIndex(max(firstIndex - 1, 0))
var next: ChartDataEntry! = cur
var nextIndex: Int = -1
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in _xBounds.dropFirst() // same as firstIndex
{
prevPrev = prev
prev = cur
cur = nextIndex == j ? next : dataSet.entryForIndex(j)
nextIndex = j + 1 < dataSet.entryCount ? j + 1 : j
next = dataSet.entryForIndex(nextIndex)
if next == nil { break }
prevDx = CGFloat(cur.x - prevPrev.x) * intensity
prevDy = CGFloat(cur.y - prevPrev.y) * intensity
curDx = CGFloat(next.x - prev.x) * intensity
curDy = CGFloat(next.y - prev.y) * intensity
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y) * CGFloat(phaseY)),
control1: CGPoint(
x: CGFloat(prev.x) + prevDx,
y: (CGFloat(prev.y) + prevDy) * CGFloat(phaseY)),
control2: CGPoint(
x: CGFloat(cur.x) - curDx,
y: (CGFloat(cur.y) - curDy) * CGFloat(phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
context.restoreGState()
}
@objc open func drawHorizontalBezier(context: CGContext, dataSet: ILineChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// get the color that is specified for this position from the DataSet
let drawingColor = dataSet.colors.first!
// the path for the cubic-spline
let cubicPath = CGMutablePath()
let valueToPixelMatrix = trans.valueToPixelMatrix
if _xBounds.range >= 1
{
var prev: ChartDataEntry! = dataSet.entryForIndex(_xBounds.min)
var cur: ChartDataEntry! = prev
if cur == nil { return }
// let the spline start
cubicPath.move(to: CGPoint(x: CGFloat(cur.x), y: CGFloat(cur.y * phaseY)), transform: valueToPixelMatrix)
for j in _xBounds.dropFirst()
{
prev = cur
cur = dataSet.entryForIndex(j)
let cpx = CGFloat(prev.x + (cur.x - prev.x) / 2.0)
cubicPath.addCurve(
to: CGPoint(
x: CGFloat(cur.x),
y: CGFloat(cur.y * phaseY)),
control1: CGPoint(
x: cpx,
y: CGFloat(prev.y * phaseY)),
control2: CGPoint(
x: cpx,
y: CGFloat(cur.y * phaseY)),
transform: valueToPixelMatrix)
}
}
context.saveGState()
if dataSet.isDrawFilledEnabled
{
// Copy this path because we make changes to it
let fillPath = cubicPath.mutableCopy()
drawCubicFill(context: context, dataSet: dataSet, spline: fillPath!, matrix: valueToPixelMatrix, bounds: _xBounds)
}
context.beginPath()
context.addPath(cubicPath)
context.setStrokeColor(drawingColor.cgColor)
context.strokePath()
context.restoreGState()
}
open func drawCubicFill(
context: CGContext,
dataSet: ILineChartDataSet,
spline: CGMutablePath,
matrix: CGAffineTransform,
bounds: XBounds)
{
guard
let dataProvider = dataProvider
else { return }
if bounds.range <= 0
{
return
}
let fillMin = dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0
var pt1 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min + bounds.range)?.x ?? 0.0), y: fillMin)
var pt2 = CGPoint(x: CGFloat(dataSet.entryForIndex(bounds.min)?.x ?? 0.0), y: fillMin)
pt1 = pt1.applying(matrix)
pt2 = pt2.applying(matrix)
spline.addLine(to: pt1)
spline.addLine(to: pt2)
spline.closeSubpath()
if dataSet.fill != nil
{
drawFilledPath(context: context, path: spline, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: spline, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
private var _lineSegments = [CGPoint](repeating: CGPoint(), count: 2)
@objc open func drawLinear(context: CGContext, dataSet: ILineChartDataSet)
{
guard let dataProvider = dataProvider else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let entryCount = dataSet.entryCount
let isDrawSteppedEnabled = dataSet.mode == .stepped
let pointsPerEntryPair = isDrawSteppedEnabled ? 4 : 2
let phaseY = animator.phaseY
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
// if drawing filled is enabled
if dataSet.isDrawFilledEnabled && entryCount > 0
{
drawLinearFill(context: context, dataSet: dataSet, trans: trans, bounds: _xBounds)
}
context.saveGState()
if _lineSegments.count != pointsPerEntryPair
{
// Allocate once in correct size
_lineSegments = [CGPoint](repeating: CGPoint(), count: pointsPerEntryPair)
}
for j in _xBounds.dropLast()
{
var e: ChartDataEntry! = dataSet.entryForIndex(j)
if e == nil { continue }
_lineSegments[0].x = CGFloat(e.x)
_lineSegments[0].y = CGFloat(e.y * phaseY)
if j < _xBounds.max
{
// TODO: remove the check.
// With the new XBounds iterator, j is always smaller than _xBounds.max
// Keeping this check for a while, if xBounds have no further breaking changes, it should be safe to remove the check
e = dataSet.entryForIndex(j + 1)
if e == nil { break }
if isDrawSteppedEnabled
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: _lineSegments[0].y)
_lineSegments[2] = _lineSegments[1]
_lineSegments[3] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
else
{
_lineSegments[1] = CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY))
}
}
else
{
_lineSegments[1] = _lineSegments[0]
}
for i in 0..<_lineSegments.count
{
_lineSegments[i] = _lineSegments[i].applying(valueToPixelMatrix)
}
if !viewPortHandler.isInBoundsRight(_lineSegments[0].x)
{
break
}
// Determine the start and end coordinates of the line, and make sure they differ.
guard
let firstCoordinate = _lineSegments.first,
let lastCoordinate = _lineSegments.last,
firstCoordinate != lastCoordinate else { continue }
// make sure the lines don't do shitty things outside bounds
if !viewPortHandler.isInBoundsLeft(lastCoordinate.x) ||
!viewPortHandler.isInBoundsTop(max(firstCoordinate.y, lastCoordinate.y)) ||
!viewPortHandler.isInBoundsBottom(min(firstCoordinate.y, lastCoordinate.y))
{
continue
}
// get the color that is set for this line-segment
context.setStrokeColor(dataSet.color(atIndex: j).cgColor)
context.strokeLineSegments(between: _lineSegments)
}
context.restoreGState()
}
open func drawLinearFill(context: CGContext, dataSet: ILineChartDataSet, trans: Transformer, bounds: XBounds)
{
guard let dataProvider = dataProvider else { return }
let filled = generateFilledPath(
dataSet: dataSet,
fillMin: dataSet.fillFormatter?.getFillLinePosition(dataSet: dataSet, dataProvider: dataProvider) ?? 0.0,
bounds: bounds,
matrix: trans.valueToPixelMatrix)
if dataSet.fill != nil
{
drawFilledPath(context: context, path: filled, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: filled, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
/// Generates the path that is used for filled drawing.
private func generateFilledPath(dataSet: ILineChartDataSet, fillMin: CGFloat, bounds: XBounds, matrix: CGAffineTransform) -> CGPath
{
let phaseY = animator.phaseY
let isDrawSteppedEnabled = dataSet.mode == .stepped
let matrix = matrix
var e: ChartDataEntry!
let filled = CGMutablePath()
e = dataSet.entryForIndex(bounds.min)
if e != nil
{
filled.move(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
// create a new path
for x in stride(from: (bounds.min + 1), through: bounds.range + bounds.min, by: 1)
{
guard let e = dataSet.entryForIndex(x) else { continue }
if isDrawSteppedEnabled
{
guard let ePrev = dataSet.entryForIndex(x-1) else { continue }
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(ePrev.y * phaseY)), transform: matrix)
}
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: CGFloat(e.y * phaseY)), transform: matrix)
}
// close up
e = dataSet.entryForIndex(bounds.range + bounds.min)
if e != nil
{
filled.addLine(to: CGPoint(x: CGFloat(e.x), y: fillMin), transform: matrix)
}
filled.closeSubpath()
return filled
}
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
let dataSets = lineData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let
dataSet = dataSets[i] as? ILineChartDataSet,
shouldDrawValues(forDataSet: dataSet)
else { continue }
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if !dataSet.isDrawCirclesEnabled
{
valOffset = valOffset / 2
}
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in _xBounds
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if dataSet.isDrawValuesEnabled {
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(
x: pt.x,
y: pt.y - CGFloat(valOffset) - valueFont.lineHeight),
align: .center,
attributes: [NSAttributedString.Key.font: valueFont, NSAttributedString.Key.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
}
}
}
open override func drawExtras(context: CGContext)
{
drawCircles(context: context)
}
private func drawCircles(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
let phaseY = animator.phaseY
let dataSets = lineData.dataSets
var pt = CGPoint()
var rect = CGRect()
// If we redraw the data, remove and repopulate accessible elements to update label values and frames
accessibleChartElements.removeAll()
accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements()
// Make the chart header the first element in the accessible elements array
if let chart = dataProvider as? LineChartView {
let element = createAccessibleHeader(usingChart: chart,
andData: lineData,
withDefaultDescription: "Line Chart")
accessibleChartElements.append(element)
}
context.saveGState()
for i in 0 ..< dataSets.count
{
guard let dataSet = lineData.getDataSetByIndex(i) as? ILineChartDataSet else { continue }
if !dataSet.isVisible || dataSet.entryCount == 0
{
continue
}
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
let circleRadius = dataSet.circleRadius
let circleDiameter = circleRadius * 2.0
let circleHoleRadius = dataSet.circleHoleRadius
let circleHoleDiameter = circleHoleRadius * 2.0
let drawCircleHole = dataSet.isDrawCircleHoleEnabled &&
circleHoleRadius < circleRadius &&
circleHoleRadius > 0.0
let drawTransparentCircleHole = drawCircleHole &&
(dataSet.circleHoleColor == nil ||
dataSet.circleHoleColor == NSUIColor.clear)
for j in _xBounds
{
guard let e = dataSet.entryForIndex(j) else { break }
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
// make sure the circles don't do shitty things outside bounds
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
// Skip Circles and Accessibility if not enabled,
// reduces CPU significantly if not needed
if !dataSet.isDrawCirclesEnabled
{
continue
}
// Accessibility element geometry
let scaleFactor: CGFloat = 3
let accessibilityRect = CGRect(x: pt.x - (scaleFactor * circleRadius),
y: pt.y - (scaleFactor * circleRadius),
width: scaleFactor * circleDiameter,
height: scaleFactor * circleDiameter)
// Create and append the corresponding accessibility element to accessibilityOrderedElements
if let chart = dataProvider as? LineChartView
{
let element = createAccessibleElement(withIndex: j,
container: chart,
dataSet: dataSet,
dataSetIndex: i)
{ (element) in
element.accessibilityFrame = accessibilityRect
}
accessibilityOrderedElements[i].append(element)
}
context.setFillColor(dataSet.getCircleColor(atIndex: j)!.cgColor)
rect.origin.x = pt.x - circleRadius
rect.origin.y = pt.y - circleRadius
rect.size.width = circleDiameter
rect.size.height = circleDiameter
if drawTransparentCircleHole
{
// Begin path for circle with hole
context.beginPath()
context.addEllipse(in: rect)
// Cut hole in path
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.addEllipse(in: rect)
// Fill in-between
context.fillPath(using: .evenOdd)
}
else
{
context.fillEllipse(in: rect)
if drawCircleHole
{
context.setFillColor(dataSet.circleHoleColor!.cgColor)
// The hole rect
rect.origin.x = pt.x - circleHoleRadius
rect.origin.y = pt.y - circleHoleRadius
rect.size.width = circleHoleDiameter
rect.size.height = circleHoleDiameter
context.fillEllipse(in: rect)
}
}
}
}
context.restoreGState()
// Merge nested ordered arrays into the single accessibleChartElements.
accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 } )
accessibilityPostLayoutChangedNotification()
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
let chartXMax = dataProvider.chartXMax
context.saveGState()
for high in indices
{
guard let set = lineData.getDataSetByIndex(high.dataSetIndex) as? ILineChartDataSet
, set.isHighlightEnabled
else { continue }
guard let e = set.entryForXValue(high.x, closestToY: high.y) else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setStrokeColor(set.highlightColor.cgColor)
context.setLineWidth(set.highlightLineWidth)
if set.highlightLineDashLengths != nil
{
context.setLineDash(phase: set.highlightLineDashPhase, lengths: set.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let x = e.x // get the x-position
let y = e.y * Double(animator.phaseY)
if x > chartXMax * animator.phaseX
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
let pt = trans.pixelForValues(x: x, y: y)
high.setDraw(pt: pt)
// draw the lines
drawHighlightLines(context: context, point: pt, set: set)
}
context.restoreGState()
}
/// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements.
/// This is marked internal to support HorizontalBarChartRenderer as well.
private func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]]
{
guard let chart = dataProvider as? LineChartView else { return [] }
let dataSetCount = chart.lineData?.dataSetCount ?? 0
return Array(repeating: [NSUIAccessibilityElement](),
count: dataSetCount)
}
/// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart
/// i.e. in case of a stacked chart, this returns each stack, not the combined bar.
/// Note that it is marked internal to support subclass modification in the HorizontalBarChart.
private func createAccessibleElement(withIndex idx: Int,
container: LineChartView,
dataSet: ILineChartDataSet,
dataSetIndex: Int,
modifier: (NSUIAccessibilityElement) -> ()) -> NSUIAccessibilityElement
{
let element = NSUIAccessibilityElement(accessibilityContainer: container)
let xAxis = container.xAxis
guard let e = dataSet.entryForIndex(idx) else { return element }
guard let dataProvider = dataProvider else { return element }
// NOTE: The formatter can cause issues when the x-axis labels are consecutive ints.
// i.e. due to the Double conversion, if there are more than one data set that are grouped,
// there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution.
let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)"
let elementValueText = dataSet.valueFormatter?.stringForValue(e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler) ?? "\(e.y)"
let dataSetCount = dataProvider.lineData?.dataSetCount ?? -1
let doesContainMultipleDataSets = dataSetCount > 1
element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)"
modifier(element)
return element
}
}
| apache-2.0 | 1739166bcc7cfb623241bc435c45db07 | 37.323232 | 155 | 0.520361 | 5.851552 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/RMBTThroughput.swift | 1 | 3152 | /*****************************************************************************************************
* Copyright 2013 appscape gmbh
* Copyright 2014-2016 SPECURE GmbH
*
* 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
///
open class RMBTThroughput: NSObject {
///
var length: UInt64
///
private var _startNanos: UInt64 // nasty hack to get around endless loop with didSet
open var startNanos: UInt64 {
get {
return _startNanos
}
set {
_startNanos = newValue
_durationNanos = _endNanos - _startNanos
assert(_durationNanos >= 0, "Invalid duration")
}
}
///
private var _endNanos: UInt64 // nasty hack to get around endless loop with didSet
open var endNanos: UInt64 {
get {
return _endNanos
}
set {
_endNanos = newValue
_durationNanos = _endNanos - _startNanos
assert(_durationNanos >= 0, "Invalid duration")
}
}
///
private var _durationNanos: UInt64 // nasty hack to get around endless loop with didSet
open var durationNanos: UInt64 {
get {
return _durationNanos
}
set {
_durationNanos = newValue
_endNanos = _startNanos + _durationNanos
assert(_durationNanos >= 0, "Invalid duration")
}
}
//
convenience override init() {
self.init(length: 0, startNanos: 0, endNanos: 0)
}
///
init(length: UInt64, startNanos: UInt64, endNanos: UInt64) {
self.length = length
self._startNanos = startNanos
self._endNanos = endNanos
self._durationNanos = endNanos - startNanos
assert((endNanos - startNanos) >= 0, "Invalid duration")
}
///
func containsNanos(_ nanos: UInt64) -> Bool {
return (_startNanos <= nanos && _endNanos >= nanos)
}
///
open func kilobitsPerSecond() -> Double {
if (_durationNanos > 0) {
return Double(length) * 8.0 / (Double(_durationNanos) * Double(1e-6)) // TODO: improve
}
else {
return 0
}
}
///
open override var description: String {
return String(format: "(%@-%@, %lld bytes, %@)",
RMBTSecondsStringWithNanos(_startNanos),
RMBTSecondsStringWithNanos(_endNanos),
length,
RMBTSpeedMbpsString(kilobitsPerSecond()))
}
}
| apache-2.0 | a90ad7e565b65b164ae550e87717e8cc | 28.185185 | 103 | 0.544099 | 4.790274 | false | false | false | false |
gb-6k-house/YsSwift | Sources/Peacock/UIKit/BaseControl/YSMediaPicker.swift | 1 | 10431 | /******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: 说明
** Copyright © 2017年 尧尚信息科技(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import Foundation
import MobileCoreServices
import RxSwift
import UIKit
import AVFoundation
enum YSMediaPickerAction {
case photo(observer: AnyObserver<(UIImage, UIImage?)>)
case video(observer: AnyObserver<URL>, maxDuration: TimeInterval)
}
public enum YSMediaPickerError: Error {
case generalError
case canceled
case videoMaximumDurationExceeded
}
@objc public protocol YSMediaPickerDelegate {
func presentPicker(_ picker: UIImagePickerController)
func dismissPicker(_ picker: UIImagePickerController)
}
@objc open class YSMediaPicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
weak var delegate: YSMediaPickerDelegate?
fileprivate var currentAction: YSMediaPickerAction?
open var deviceHasCamera: Bool {
return UIImagePickerController.isSourceTypeAvailable(.camera)
}
public init(delegate: YSMediaPickerDelegate) {
self.delegate = delegate
}
open func recordVideo(device: UIImagePickerControllerCameraDevice = .rear, quality: UIImagePickerControllerQualityType = .typeMedium, maximumDuration: TimeInterval = 600, editable: Bool = false) -> Observable<URL> {
return Observable.create { observer in
self.currentAction = YSMediaPickerAction.video(observer: observer, maxDuration: maximumDuration)
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.mediaTypes = [kUTTypeMovie as String]
picker.videoMaximumDuration = maximumDuration
picker.videoQuality = quality
picker.allowsEditing = editable
picker.delegate = self
if UIImagePickerController.isCameraDeviceAvailable(device) {
picker.cameraDevice = device
}
self.delegate?.presentPicker(picker)
return Disposables.create()
}
}
open func selectVideo(_ source: UIImagePickerControllerSourceType = .photoLibrary, maximumDuration: TimeInterval = 600, editable: Bool = false) -> Observable<URL> {
return Observable.create({ observer in
self.currentAction = YSMediaPickerAction.video(observer: observer, maxDuration: maximumDuration)
let picker = UIImagePickerController()
picker.sourceType = source
picker.mediaTypes = [kUTTypeMovie as String]
picker.allowsEditing = editable
picker.delegate = self
self.delegate?.presentPicker(picker)
return Disposables.create()
})
}
/// 拍摄推按
///
/// - Parameters:
/// - device: 使用后置摄像头
/// - flashMode: 是否开启闪光灯
/// - editable: 是否允许编辑
/// - Returns: 返回的原图和被编辑的图片
open func takePhoto(device: UIImagePickerControllerCameraDevice = .rear, flashMode: UIImagePickerControllerCameraFlashMode = .auto, editable: Bool = false) -> Observable<(UIImage, UIImage?)> {
return Observable.create({ observer in
self.currentAction = YSMediaPickerAction.photo(observer: observer)
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.allowsEditing = editable
picker.delegate = self
if UIImagePickerController.isCameraDeviceAvailable(device) {
picker.cameraDevice = device
}
if UIImagePickerController.isFlashAvailable(for: picker.cameraDevice) {
picker.cameraFlashMode = flashMode
}
self.delegate?.presentPicker(picker)
return Disposables.create()
})
}
/// 从相册中选择图片
///
/// - Parameters:
/// - source: 源类型,选择图片
/// - editable: 是否可以编辑
/// - Returns: 被观察者,包含原始图片和被编辑的图片
open func selectImage(_ source: UIImagePickerControllerSourceType = .photoLibrary, editable: Bool = false) -> Observable<(UIImage, UIImage?)> {
return Observable.create { observer in
self.currentAction = YSMediaPickerAction.photo(observer: observer)
let picker = UIImagePickerController()
picker.sourceType = source
picker.allowsEditing = editable
picker.delegate = self
self.delegate?.presentPicker(picker)
return Disposables.create()
}
}
func processPhoto(_ info: [String: Any], observer: AnyObserver<(UIImage, UIImage?)>) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
let originImage = fixOrientation(image)
let editedImage: UIImage? = info[UIImagePickerControllerEditedImage] as? UIImage
observer.on(.next((originImage, editedImage)))
observer.on(.completed)
} else {
observer.on(.error(YSMediaPickerError.generalError))
}
}
/**
照片竖拍 web显示旋转解决:图片大于2M会自动旋转90度
- parameter aImage: origin image
- returns: rotate image
*/
func fixOrientation(_ aImage: UIImage) -> UIImage {
if aImage.imageOrientation == UIImageOrientation.up {
return aImage
}
var transform = CGAffineTransform.identity
switch aImage.imageOrientation {
case .down, .downMirrored:
transform = transform.translatedBy(x: aImage.size.width, y: aImage.size.height)
transform = transform.rotated(by: CGFloat(Double.pi))
break
case .left, .leftMirrored:
transform = transform.translatedBy(x: aImage.size.width, y: 0)
transform = transform.rotated(by: CGFloat(Double.pi / 2))
break
case .right, .rightMirrored:
transform = transform.translatedBy(x: 0, y: aImage.size.height)
transform = transform.rotated(by: CGFloat(-Double.pi / 2))
break
default:
break
}
switch aImage.imageOrientation {
case .upMirrored, .downMirrored:
transform = transform.translatedBy(x: aImage.size.width, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
break
case .leftMirrored, .rightMirrored:
transform = transform.translatedBy(x: aImage.size.height, y: 0)
transform = transform.scaledBy(x: -1, y: 1)
break
default:
break
}
let ctx: CGContext = CGContext(data: nil, width: Int(aImage.size.width), height: Int(aImage.size.height),
bitsPerComponent: aImage.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: aImage.cgImage!.colorSpace!,
bitmapInfo: 1)!
ctx.concatenate(transform)
switch aImage.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
ctx.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.height, height: aImage.size.width))
break
default:
ctx.draw(aImage.cgImage!, in: CGRect(x: 0, y: 0, width: aImage.size.width, height: aImage.size.height))
break
}
let cgimg: CGImage = ctx.makeImage()!
let img: UIImage = UIImage(cgImage: cgimg)
return img
}
func processVideo(_ info: [String: Any], observer: AnyObserver<URL>, maxDuration: TimeInterval, picker: UIImagePickerController) {
guard let videoURL = info[UIImagePickerControllerMediaURL] as? URL else {
observer.on(.error(YSMediaPickerError.generalError))
dismissPicker(picker)
return
}
if let editedStart = info["_UIImagePickerControllerVideoEditingStart"] as? NSNumber,
let editedEnd = info["_UIImagePickerControllerVideoEditingEnd"] as? NSNumber {
let start = Int64(editedStart.doubleValue * 1000)
let end = Int64(editedEnd.doubleValue * 1000)
let cachesDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
let editedVideoURL = URL(fileURLWithPath: cachesDirectory).appendingPathComponent("\(UUID().uuidString).mov", isDirectory: false)
let asset = AVURLAsset(url: videoURL)
if let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) {
exportSession.outputURL = editedVideoURL
exportSession.outputFileType = AVFileType.mov
exportSession.timeRange = CMTimeRange(start: CMTime(value: start, timescale: 1000), duration: CMTime(value: end - start, timescale: 1000))
exportSession.exportAsynchronously(completionHandler: {
switch exportSession.status {
case .completed:
self.processVideoURL(editedVideoURL, observer: observer, maxDuration: maxDuration, picker: picker)
case .failed: fallthrough
case .cancelled:
observer.on(.error(YSMediaPickerError.generalError))
self.dismissPicker(picker)
default: break
}
})
}
} else {
processVideoURL(videoURL, observer: observer, maxDuration: maxDuration, picker: picker)
}
}
fileprivate func processVideoURL(_ url: URL, observer: AnyObserver<URL>, maxDuration: TimeInterval, picker: UIImagePickerController) {
let asset = AVURLAsset(url: url)
let duration = CMTimeGetSeconds(asset.duration)
if duration > maxDuration {
observer.on(.error(YSMediaPickerError.videoMaximumDurationExceeded))
} else {
observer.on(.next(url))
observer.on(.completed)
}
dismissPicker(picker)
}
fileprivate func dismissPicker(_ picker: UIImagePickerController) {
delegate?.dismissPicker(picker)
}
// UIImagePickerControllerDelegate
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
if let action = currentAction {
switch action {
case .photo(let observer):
processPhoto(info as [String : AnyObject], observer: observer)
dismissPicker(picker)
case .video(let observer, let maxDuration):
processVideo(info as [String : AnyObject], observer: observer, maxDuration: maxDuration, picker: picker)
}
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismissPicker(picker)
if let action = currentAction {
switch action {
case .photo(let observer): observer.on(.error(YSMediaPickerError.canceled))
case .video(let observer, _): observer.on(.error(YSMediaPickerError.canceled))
}
}
}
}
| mit | 94b337b42104500487b47ec50a491257 | 33.066667 | 216 | 0.680626 | 4.416595 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Track/Track.swift | 1 | 1577 | //
// Track.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/12/17.
// Copyright © 2017 HungDo. All rights reserved.
//
struct Track {
let id: String
let name: String
let singer: String
let avatar: String
let lyric: String
let url: String
init(id: String, name: String, singer: String, avatar: String, lyric: String, url: String) {
self.id = id
self.name = name
self.singer = singer
self.avatar = avatar
self.lyric = lyric
self.url = url
}
init(json: [String:Any]) {
guard let id = json["id"] as? String else { fatalError("Can not get Track id") }
guard let name = json["name"] as? String else { fatalError("Can not get Track name") }
guard let singer = json["singer"] as? String else { fatalError("Can not get Track singer") }
guard let avatar = json["avatar"] as? String else { fatalError("Can not get Track avatar") }
guard let lyric = json["lyric"] as? String else { fatalError("Can not get Track lyric") }
guard let url = json["url"] as? String else { fatalError("Can not get Track url") }
self.init(id: id, name: name, singer: singer, avatar: avatar, lyric: lyric, url: url)
}
}
extension Track {
var song: Song {
return Song(id: id, name: name, singer: singer)
}
}
extension Track: Equatable {
static func == (lhs: Track, rhs: Track) -> Bool {
return lhs.id == rhs.id
}
}
| mit | c0db2a22c836fa7b21172dfbd2339672 | 28.111111 | 107 | 0.559796 | 3.9202 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/User/RealmUser.swift | 1 | 10275 | //
// RealmUser.swift
// Habitica Database
//
// Created by Phillip Thelen on 09.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
@objc
class RealmUser: Object, UserProtocol {
@objc dynamic var id: String?
@objc dynamic var balance: Float = 0
var tasksOrder: [String: [String]] = [:]
var stats: StatsProtocol? {
get {
return realmStats
}
set {
if let newStats = newValue as? RealmStats {
realmStats = newStats
return
}
if let stats = newValue {
realmStats = RealmStats(id: id, stats: stats)
}
}
}
@objc dynamic var realmStats: RealmStats?
var flags: FlagsProtocol? {
get {
return realmFlags
}
set {
if let newFlags = newValue as? RealmFlags {
realmFlags = newFlags
return
}
if let newFlags = newValue {
realmFlags = RealmFlags(id: id, flags: newFlags)
}
}
}
@objc dynamic var realmFlags: RealmFlags?
var preferences: PreferencesProtocol? {
get {
return realmPreferences
}
set {
if let newPreferences = newValue as? RealmPreferences {
realmPreferences = newPreferences
return
}
if let newPreferences = newValue {
realmPreferences = RealmPreferences(id: id, preferences: newPreferences)
}
}
}
@objc dynamic var realmPreferences: RealmPreferences?
var profile: ProfileProtocol? {
get {
return realmProfile
}
set {
if let newProfile = newValue as? RealmProfile {
realmProfile = newProfile
return
}
if let profile = newValue {
realmProfile = RealmProfile(id: id, profile: profile)
}
}
}
@objc dynamic var realmProfile: RealmProfile?
var contributor: ContributorProtocol? {
get {
return realmContributor
}
set {
if let newContributor = newValue as? RealmContributor {
realmContributor = newContributor
return
}
if let newContributor = newValue {
realmContributor = RealmContributor(id: id, contributor: newContributor)
}
}
}
@objc dynamic var realmContributor: RealmContributor?
var backer: BackerProtocol? {
get {
return realmBacker
}
set {
if let newBacker = newValue as? RealmBacker {
realmBacker = newBacker
return
}
if let newBacker = newValue {
realmBacker = RealmBacker(id: id, backer: newBacker)
}
}
}
@objc dynamic var realmBacker: RealmBacker?
var items: UserItemsProtocol? {
get {
return realmItems
}
set {
if let newItems = newValue as? RealmUserItems {
realmItems = newItems
return
}
if let newItems = newValue {
realmItems = RealmUserItems(id: id, userItems: newItems)
}
}
}
@objc dynamic var realmItems: RealmUserItems?
var tags: [TagProtocol] {
get {
return realmTags.map({ (tag) -> TagProtocol in
return tag
})
}
set {
realmTags.removeAll()
newValue.forEach { (tag) in
if let realmTag = tag as? RealmTag {
realmTags.append(realmTag)
} else {
realmTags.append(RealmTag(userID: id, tagProtocol: tag))
}
}
}
}
var inbox: InboxProtocol? {
get {
return realmInbox
}
set {
if let newItems = newValue as? RealmInbox {
realmInbox = newItems
return
}
if let newItems = newValue {
realmInbox = RealmInbox(id: id, inboxProtocol: newItems)
}
}
}
@objc dynamic var realmInbox: RealmInbox?
var authentication: AuthenticationProtocol? {
get {
return realmAuthentication
}
set {
if let value = newValue as? RealmAuthentication {
realmAuthentication = value
return
}
if let value = newValue {
realmAuthentication = RealmAuthentication(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmAuthentication: RealmAuthentication?
var purchased: PurchasedProtocol? {
get {
return realmPurchased
}
set {
if let value = newValue as? RealmPurchased {
realmPurchased = value
return
}
if let value = newValue {
realmPurchased = RealmPurchased(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmPurchased: RealmPurchased?
var party: UserPartyProtocol? {
get {
return realmParty
}
set {
if let value = newValue as? RealmUserParty {
realmParty = value
return
}
if let value = newValue {
realmParty = RealmUserParty(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmParty: RealmUserParty?
var achievements: UserAchievementsProtocol? {
get {
return realmAchievements
}
set {
if let value = newValue as? RealmUserAchievements {
realmAchievements = value
return
}
if let value = newValue {
realmAchievements = RealmUserAchievements(userID: id, protocolObject: value)
}
}
}
@objc dynamic var realmAchievements: RealmUserAchievements?
var realmTags = List<RealmTag>()
var challenges: [ChallengeMembershipProtocol] {
get {
return realmChallenges.map({ (tag) -> ChallengeMembershipProtocol in
return tag
})
}
set {
realmChallenges.removeAll()
newValue.forEach { (challenge) in
if let realmChallenge = challenge as? RealmChallengeMembership {
realmChallenges.append(realmChallenge)
} else {
realmChallenges.append(RealmChallengeMembership(userID: id, protocolObject: challenge))
}
}
}
}
var realmChallenges = List<RealmChallengeMembership>()
var hasNewMessages: [UserNewMessagesProtocol] {
get {
return realmNewMessages.map({ (tag) -> UserNewMessagesProtocol in
return tag
})
}
set {
realmNewMessages.removeAll()
newValue.forEach { (newMessages) in
if let realmNewMessage = newMessages as? RealmUserNewMessages {
realmNewMessages.append(realmNewMessage)
} else {
realmNewMessages.append(RealmUserNewMessages(userID: id, protocolObject: newMessages))
}
}
}
}
var realmNewMessages = List<RealmUserNewMessages>()
var invitations: [GroupInvitationProtocol] {
get {
return realmInvitations.map({ (invitation) -> GroupInvitationProtocol in
return invitation
})
}
set {
realmInvitations.removeAll()
newValue.forEach { (invitation) in
if let realmInvitation = invitation as? RealmGroupInvitation {
realmInvitations.append(realmInvitation)
} else {
realmInvitations.append(RealmGroupInvitation(userID: id, protocolObject: invitation))
}
}
}
}
var realmInvitations = List<RealmGroupInvitation>()
var pushDevices: [PushDeviceProtocol] {
get {
return realmPushDevices.map({ (pushDevice) -> PushDeviceProtocol in
return pushDevice
})
}
set {
realmPushDevices.removeAll()
newValue.forEach { (pushDevice) in
if let realmPushDevice = pushDevice as? RealmPushDevice {
realmPushDevices.append(realmPushDevice)
} else {
realmPushDevices.append(RealmPushDevice(userID: id, protocolObject: pushDevice))
}
}
}
}
var realmPushDevices = List<RealmPushDevice>()
var needsCron: Bool = false
var lastCron: Date?
var isValid: Bool {
return !isInvalidated
}
override static func primaryKey() -> String {
return "id"
}
override static func ignoredProperties() -> [String] {
return ["flags", "preferences", "stats", "profile", "contributor", "backer", "tasksOrder", "items", "tags", "inbox", "authentication", "purchased", "party", "invitations", "pushDevices"]
}
convenience init(_ user: UserProtocol) {
self.init()
id = user.id
stats = user.stats
flags = user.flags
preferences = user.preferences
profile = user.profile
contributor = user.contributor
balance = user.balance
items = user.items
tags = user.tags
needsCron = user.needsCron
lastCron = user.lastCron
inbox = user.inbox
authentication = user.authentication
purchased = user.purchased
party = user.party
challenges = user.challenges
hasNewMessages = user.hasNewMessages
invitations = user.invitations
pushDevices = user.pushDevices
achievements = user.achievements
}
}
| gpl-3.0 | 75382d4734f3eee86894055b97402a03 | 29.39645 | 194 | 0.530271 | 5.279548 | false | false | false | false |
hhyyg/Miso.Gistan | Gistan/APIClient/GitHub/GitHubAPI.swift | 1 | 1644 | //
// GitHubAPI.swift
// Gistan
//
// Created by Hiroka Yago on 2017/10/01.
// Copyright © 2017 miso. All rights reserved.
//
final class GitHubAPI {
/// Userのgistを取得
struct GetUsersGists: GitHubRequest {
typealias Response = [GistItem]
let userName: String
var method: HTTPMethod {
return .get
}
var path: String {
return "users/\(userName)/gists"
}
var parameters: Any? {
return nil
}
}
/// Userのフォローしている人を取得
struct GetUsersFollowing: GitHubRequest {
typealias Response = [User]
let userName: String
var method: HTTPMethod {
return .get
}
var path: String {
return "users/\(userName)/following"
}
var parameters: Any? {
return nil
}
}
/// get user info
struct GetUser: GitHubRequest {
typealias Response = User
let userName: String
var method: HTTPMethod {
return .get
}
var path: String {
return "users/\(userName)"
}
var parameters: Any? {
return nil
}
}
struct GetMe: GitHubRequest {
typealias Response = User
var method: HTTPMethod {
return .get
}
var path: String {
return "user"
}
var parameters: Any? {
return nil
}
}
/*
struct SearchUsers: GitHubRequest {
typealias Response = [User]
var method: HTTPMethod
}*/
}
| mit | 9dda38a3772d9ec0a970053e007c3236 | 16.877778 | 48 | 0.505904 | 4.746313 | false | false | false | false |
4taras4/totp-auth | TOTP/ViperModules/MainList/Module/Presenter/MainListPresenter.swift | 1 | 7809 | //
// MainListMainListPresenter.swift
// TOTP
//
// Created by Tarik on 10/10/2020.
// Copyright © 2020 Taras Markevych. All rights reserved.
//
import UIKit
final class MainListPresenter: NSObject, MainListViewOutput {
// MARK: -
// MARK: Properties
weak var view: MainListViewInput!
var interactor: MainListInteractorInput!
var router: MainListRouterInput!
fileprivate var codeList = [Code]()
fileprivate var favouriteList = [Code]()
fileprivate var folders = [Folder]()
private var refreshTimer: Timer?
private var interval = 30.0
private var updated: Int = 0
// MARK: -
// MARK: MainListViewOutput
func viewIsReady() {
updated = 0
let calendar = Calendar.current
let time = calendar.dateComponents([.second], from: Date()).second!
if time > 30 {
interval = Double(60 - time)
} else {
interval = Double(30 - time)
}
print("init:", interval)
refreshTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(refreshData), userInfo: nil, repeats: true)
}
func settingsButtonPressed() {
router.openSettings()
}
func addItemButtonPressed() {
router.addItem()
}
func favItemButtonPressed() {
view.changeIsEdit()
}
@objc func refreshData() {
interactor.converUserData(users: RealmManager.shared.fetchCodesList() ?? [])
}
func updateTimerIfNeeded() {
updated += 1
if interval != 30.0, updated == 2 {
print("set new time")
self.interval = 30
refreshTimer?.invalidate()
refreshTimer = nil
refreshTimer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(refreshData), userInfo: nil, repeats: true)
}
}
func reloadFolders() {
interactor.getFolders()
}
}
// MARK: -
// MARK: MainListInteractorOutput
extension MainListPresenter: MainListInteractorOutput {
func listOfFolders(array: [Folder]) {
folders = array
if array.count == 0 {
view.changeCollectionView(isHidden: true)
} else {
view.changeCollectionView(isHidden: false)
view.reloadFoldersCollectionView()
}
}
func dataBaseOperationFinished() {
refreshData()
}
func listOfCodes(codes: [Code], favourites: [Code]) {
favouriteList = favourites
codeList = codes
view.reloadTable()
updateTimerIfNeeded()
}
}
// MARK: -
// MARK: MainListModuleInput
extension MainListPresenter: MainListModuleInput {
}
extension MainListPresenter: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return favouriteList.isEmpty ? 1 : 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if favouriteList.isEmpty {
return codeList.count
} else {
switch section {
case 0:
return favouriteList.count
default:
return codeList.count
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MainListTableViewCell", for: indexPath) as! MainListTableViewCell
if favouriteList.isEmpty {
cell.setup(cell: codeList[indexPath.row], timeInterval: interval)
} else {
switch indexPath.section {
case 0:
cell.setup(cell: favouriteList[indexPath.row], timeInterval: interval)
default:
cell.setup(cell: codeList[indexPath.row], timeInterval: interval)
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
UIPasteboard.general.string = codeList[indexPath.row].code
UIManager.shared.showAlert(title: nil, message: "Code \(codeList[indexPath.row].code) copied!")
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if favouriteList.isEmpty {
switch editingStyle {
case .delete:
interactor.deleteRow(with: codeList[indexPath.row].token)
case .insert:
interactor.updateRow(with: codeList[indexPath.row].token, isFavourite: true)
default:
break
}
} else {
switch indexPath.section {
case 0:
switch editingStyle {
case .delete:
interactor.updateRow(with: codeList[indexPath.row].token, isFavourite: false)
case .insert:
interactor.updateRow(with: codeList[indexPath.row].token, isFavourite: true)
default:
break
}
case 1:
switch editingStyle {
case .delete:
interactor.deleteRow(with: codeList[indexPath.row].token)
case .insert:
interactor.updateRow(with: codeList[indexPath.row].token, isFavourite: true)
default:
break
}
default:
break
}
}
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if favouriteList.isEmpty {
return tableView.isEditing ? .insert : .delete
} else {
switch indexPath.section {
case 0:
return .delete
case 1:
return tableView.isEditing ? .insert : .delete
default:
return tableView.isEditing ? .insert : .delete
}
}
}
//added for ADDS baner spacing when you have a lot of items in the list
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
switch section {
case 0:
return 10
default:
return 90
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return UIView(frame: .zero)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if favouriteList.isEmpty {
return Constants.text.fullListTableTitle
} else {
switch section {
case 0:
return Constants.text.favouritesTableTitle
default:
return Constants.text.fullListTableTitle
}
}
}
}
extension MainListPresenter: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return folders.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FolderItemCollectionViewCell", for: indexPath) as! FolderItemCollectionViewCell
cell.setup(item: folders[indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
router.openFolder(item: folders[indexPath.row])
}
}
| mit | d7f31efae74f4aeb25326f33fb6aeaaf | 31.669456 | 155 | 0.599513 | 5.240268 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Objects/scripts/XD/XDSMacroTypes.swift | 1 | 12389 | //
// XDSMacroTypes.swift
// GoD Tool
//
// Created by The Steez on 03/06/2018.
//
import Foundation
func ==(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index == rhs.index
}
func !=(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index != rhs.index
}
func <(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index < rhs.index
}
func >(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index > rhs.index
}
func <=(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index <= rhs.index
}
func >=(lhs: XDSMacroTypes, rhs: XDSMacroTypes) -> Bool {
return lhs.index >= rhs.index
}
indirect enum XDSMacroTypes {
case invalid
case null
// Types that can be replaced with macros
case pokemon
case item
case model
case move
case room
case flag
case talk
case ability
case msgVar
case battleResult
case shadowStatus
case pokespot
case battleID
case shadowID
case treasureID
case battlefield
case partyMember
case integerMoney
case integerCoupons
case integerQuantity
case integerIndex
case vectorDimension // x,y or z
case giftPokemon
case region
case language
case PCBox
case transitionID
case yesNoIndex
case scriptFunction
case sfxID
case storyProgress
case buttonInput
case array(XDSMacroTypes)
// replaced with special macro but not added as a define statement
case msg
case bool
// Types simply used for documentation but are printed as raw values
case integer
case float
case number // accepts either an integer, a float or a string representation of a number
case integerAngleDegrees
case floatAngleDegrees
case floatAngleRadians
case floatFraction // between 0.0 and 1.0
case integerByte
case integerUnsignedByte
case integerUnsigned
case integerBitMask
case datsIdentifier // id for a .dats model archive]
case camIdentifier // id for a .cam file
case cameraType
case vector
case arrayIndex
case string // not msgs, raw strings used mainly by printf for debugging
case list(XDSMacroTypes) // multiple parameters of an unspecified number
case anyType // rare but some functions can take any value as parameter, usually when it is unused
case variableType // the type may vary depending on the other parameters
case optional(XDSMacroTypes) // may be included or discluded
case object(Int) // value of class type 33 or higher, same type as the class calling the function
case objectName(String) // same as object but specified by its name instead of index for convenience
var index : Int {
switch self {
case .invalid: return -1
case .null: return 0
case .pokemon: return 1
case .item: return 2
case .model: return 3
case .move: return 4
case .room: return 5
case .flag: return 6
case .talk: return 7
case .ability: return 8
case .msgVar: return 9
case .battleResult: return 10
case .shadowStatus: return 11
case .pokespot: return 12
case .battleID: return 13
case .shadowID: return 14
case .treasureID: return 15
case .battlefield: return 16
case .partyMember: return 17
case .integerMoney: return 18
case .integerCoupons: return 19
case .integerQuantity: return 20
case .integerIndex: return 21
case .vectorDimension: return 22
case .giftPokemon: return 23
case .region: return 24
case .language: return 25
case .PCBox: return 26
case .transitionID: return 27
case .yesNoIndex: return 28
case .scriptFunction: return 29
case .sfxID: return 30
case .storyProgress: return 31
case .buttonInput: return 32
// leave a gap in case of future additions
case .array: return 99
case .msg: return 100
case .bool: return 101
// another gap for same reason
case .integer: return 200
case .float: return 201
case .number: return 202
case .integerAngleDegrees: return 203
case .floatAngleDegrees: return 204
case .floatAngleRadians: return 205
case .floatFraction: return 206
case .integerByte: return 207
case .integerUnsignedByte: return 208
case .integerUnsigned: return 209
case .integerBitMask: return 210
case .datsIdentifier: return 211
case .camIdentifier: return 212
case .cameraType: return 213
// more gaps
case .vector: return 300
case .arrayIndex: return 301
case .string: return 302
case .list: return 303
// I hope you like gaps
case .optional: return 497
case .variableType: return 498
case .anyType: return 499
case .object(let cid): return 500 + cid
case .objectName(let s):
if let type = XGScriptClass.getClassNamed(s) {
return XDSMacroTypes.object(type.index).index
} else {
printg("Unknown macro type class: \(s)")
return -2
}
}
}
var macroType : XDSMacroTypes {
switch self {
case .array(let t):
return t
case .optional(let t):
return t
default:
return self
}
}
var needsDefine : Bool {
return self < XDSMacroTypes.msg && self > XDSMacroTypes.null && self != .scriptFunction
}
var printsAsMacro : Bool {
return self < XDSMacroTypes.integer && self > XDSMacroTypes.null
}
var printsAsHexadecimal : Bool {
switch self {
case .room:
fallthrough
case .battlefield:
fallthrough
case .scriptFunction:
fallthrough
case .integerUnsigned:
fallthrough
case .datsIdentifier:
fallthrough
case .camIdentifier:
fallthrough
case .flag:
fallthrough
case .integerBitMask:
fallthrough
case .buttonInput:
fallthrough
case .invalid:
fallthrough
case .model:
return true
case .optional(let t):
return t.printsAsHexadecimal
case .list(let t):
return t.printsAsHexadecimal
case .array(let t):
return t.printsAsHexadecimal
default:
return false
}
}
var typeName : String {
switch self {
case .invalid:
return "Invalid"
case .null:
return "Null"
case .pokemon:
return "PokemonID"
case .item:
return "ItemID"
case .model:
return "ModelID"
case .move:
return "MoveID"
case .room:
return "RoomID"
case .flag:
return "FlagID"
case .talk:
return "SpeechType"
case .ability:
return "AbilityID"
case .msgVar:
return "MessageVariable"
case .battleResult:
return "BattleResult"
case .shadowStatus:
return "ShadowPokemonStatus"
case .pokespot:
return "PokespotID"
case .battleID:
return "BattleID"
case .shadowID:
return "ShadowPokemonID"
case .treasureID:
return "TreasureID"
case .battlefield:
return "RoomID"
case .partyMember:
return "NPCPartyMemberID"
case .integerMoney:
return "Pokedollars"
case .integerCoupons:
return "Pokecoupons"
case .integerQuantity:
return "Quantity"
case .integerIndex:
return "Index"
case .yesNoIndex:
return "YesNoIndex"
case .scriptFunction:
return "ScriptFunction"
case .sfxID:
return "SoundEffectID"
case .storyProgress:
return "StoryProgress"
case .vectorDimension:
return "VectorDimension"
case .giftPokemon:
return "GiftID"
case .region:
return "RegionID"
case .language:
return "LanguageID"
case .PCBox:
return "PCBoxID"
case .transitionID:
return "TransitionID"
case .buttonInput:
return "ButtonInput"
case .msg:
return "StringID"
case .bool:
return "YesOrNo"
case .integer:
return "Integer"
case .float:
return "Decimal"
case .number:
return "AnyNumber"
case .integerAngleDegrees:
return "Degrees"
case .floatAngleDegrees:
return "DecimalDegrees"
case .floatAngleRadians:
return "Radians"
case .floatFraction:
return "DecimalFromZeroToOne"
case .integerByte:
return "Signed8BitInteger"
case .integerUnsignedByte:
return "Unsigned8BitInteger"
case .integerUnsigned:
return "Unsigned32BitInteger"
case .integerBitMask:
return "IntegerBitMask"
case .datsIdentifier:
return "DatsID"
case .camIdentifier:
return "CameraRoutineID"
case .cameraType:
return "CameraType"
case .vector:
return "Vector"
case .array(let t):
return "Array[\(t.typeName)]"
case .arrayIndex:
return "ArrayIndex"
case .string:
return "String"
case .list(let t):
return "\(t.typeName) ..."
case .variableType:
return "TypeVaries"
case .optional(let t):
return "Optional(\(t.typeName))"
case .anyType:
return "AnyType"
case .object(let id):
let name = XGScriptClass.classes(id).name
return "\(name)Object"
case .objectName(let name):
return "\(name)Object"
}
}
static var autocompletableTypes: [XDSMacroTypes] {
return [
.pokemon, .item, .model, .move, .room, .flag, .talk, .ability, .msgVar, .battleResult, .shadowStatus, .pokespot, .shadowID, .battlefield, .partyMember, .vectorDimension, .giftPokemon, .region, .language, .PCBox, .transitionID, .scriptFunction, .sfxID, .storyProgress, .buttonInput
]
}
var autocompleteValues: [Int] {
switch self {
case .pokemon: return allPokemonArray().map{ $0.index }
case .item: return allItemsArray().map{ $0.index }
case .model: return XGFsys(file: .fsys("people_archive")).identifiers
case .move: return allPokemonArray().map{ $0.index }
case .room: return XGRoom.allValues.map{ $0.roomID }.sorted()
case .flag: return XDSFlags.allCases.map{ $0.rawValue }
case .talk: return XDSTalkTypes.allCases.map{ $0.rawValue }
case .ability: return Array(0 ..< kNumberOfAbilities)
case .msgVar: return XGSpecialCharacters.allCases.map { $0.rawValue }
case .battleResult: return Array(0 ... 3)
case .shadowStatus: return Array(0 ... 4)
case .pokespot: return XGPokeSpots.allCases.map{ $0.rawValue }
case .shadowID: return XGDecks.DeckDarkPokemon.allActivePokemon.map{ $0.shadowID }
case .battlefield: return Array(0 ..< CommonIndexes.NumberOfBattleFields.value)
case .partyMember: return Array(0 ... 3)
case .vectorDimension: return Array(0 ... 2)
case .giftPokemon: return Array(0 ..< kNumberOfGiftPokemon)
case .region: return Array(0 ... 2)
case .language: return XGLanguages.allCases.map{ $0.rawValue }
case .transitionID: return Array(2 ... 5)
case .scriptFunction: return (0 ..< XGFiles.common_rel.scriptData.ftbl.count).map { 0x596_0000 + $0 }
case .sfxID: return Array(0 ..< CommonIndexes.NumberOfSounds.value)
case .storyProgress: return XGStoryProgress.allCases.map{ $0.rawValue }
case .buttonInput: return (0 ..< 12).map{ Int(pow(2.0, Double($0))) }.filter{ $0 != 0x80 }
default: return []
}
}
}
let kNumberOfTalkTypes = 22
enum XDSTalkTypes: Int, CaseIterable {
case none = 0
case normal = 1
case approachThenSpeak = 2
case promptYesNoBool = 3 // yes = 1, no = 0
case battle1 = 6
case promptYesNoIndex = 8 // yes = 0, no = 1
case battle2 = 9
case silentItem = 14
case speciesCry = 15
case silentText = 16
var extraMacro : XDSMacroTypes? {
switch self {
case .silentItem: return .item
case .speciesCry: return .pokemon
case .battle1: return .battleID
case .battle2: return .battleID
default: return nil
}
}
var extraMacro2 : XDSMacroTypes? {
switch self {
case .silentItem: return .integerQuantity
case .speciesCry: return .msg
default: return nil
}
}
var string : String {
switch self {
case .none : return "none"
case .normal : return "normal"
case .approachThenSpeak : return "approach"
case .promptYesNoBool : return "yes_no"
case .battle1 : return "battle_alt"
case .battle2 : return "battle"
case .silentItem : return "get_item"
case .speciesCry : return "species_cry"
case .silentText : return "silent"
case .promptYesNoIndex : return "yes_no_index"
}
}
}
enum XDSMSGVarTypes : Int {
// incomplete but unnecessary. full list in xgspecialstringcharacter
case pokemon = 0x4e
case item = 0x2d
static func macroForVarType(_ type: Int) -> XDSMacroTypes? {
switch type {
case 0x0f: fallthrough
case 0x10: fallthrough
case 0x11: fallthrough
case 0x12: fallthrough
case 0x16: fallthrough
case 0x17: fallthrough
case 0x18: fallthrough
case 0x19: return .pokemon
case 0x1a: fallthrough
case 0x1b: fallthrough
case 0x1c: fallthrough
case 0x1d: return .ability
case 0x1e: fallthrough
case 0x20: fallthrough
case 0x21: return .pokemon
case 0x28: return .move
case 0x29: fallthrough
case 0x2d: fallthrough
case 0x2e: return .item
case 0x2f: return nil // item quantity
case 0x4d: return .msg
case 0x4e: return .pokemon
default: return nil
}
}
}
| gpl-2.0 | d058fc63cfdfb5db8ab76646507a6d6b | 24.283673 | 284 | 0.707321 | 3.218758 | false | false | false | false |
YQqiang/Nunchakus | Pods/BMPlayer/BMPlayer/Classes/BMPlayerControlView.swift | 1 | 25266 | //
// BMPlayerControlView.swift
// Pods
//
// Created by BrikerMan on 16/4/29.
//
//
import UIKit
import NVActivityIndicatorView
@objc public protocol BMPlayerControlViewDelegate: class {
/**
call when control view choose a definition
- parameter controlView: control view
- parameter index: index of definition
*/
func controlView(controlView: BMPlayerControlView, didChooseDefition index: Int)
/**
call when control view pressed an button
- parameter controlView: control view
- parameter button: button type
*/
func controlView(controlView: BMPlayerControlView, didPressButton button: UIButton)
/**
call when slider action trigged
- parameter controlView: control view
- parameter slider: progress slider
- parameter event: action
*/
func controlView(controlView: BMPlayerControlView, slider: UISlider, onSliderEvent event: UIControlEvents)
/**
call when needs to change playback rate
- parameter controlView: control view
- parameter rate: playback rate
*/
@objc optional func controlView(controlView: BMPlayerControlView, didChangeVideoPlaybackRate rate: Float)
}
open class BMPlayerControlView: UIView {
open weak var delegate: BMPlayerControlViewDelegate?
// MARK: Variables
open var resource: BMPlayerResource?
open var selectedIndex = 0
open var isFullscreen = false
open var isMaskShowing = true
open var totalDuration:TimeInterval = 0
open var delayItem: DispatchWorkItem?
var playerLastState: BMPlayerState = .notSetURL
fileprivate var isSelectecDefitionViewOpened = false
// MARK: UI Components
/// main views which contains the topMaskView and bottom mask view
open var mainMaskView = UIView()
open var topMaskView = UIView()
open var bottomMaskView = UIView()
/// Image view to show video cover
open var maskImageView = UIImageView()
/// top views
open var backButton = UIButton(type : UIButtonType.custom)
open var titleLabel = UILabel()
open var chooseDefitionView = UIView()
/// bottom view
open var currentTimeLabel = UILabel()
open var totalTimeLabel = UILabel()
/// Progress slider
open var timeSlider = BMTimeSlider()
/// load progress view
open var progressView = UIProgressView()
/* play button
playButton.isSelected = player.isPlaying
*/
open var playButton = UIButton(type: UIButtonType.custom)
/* fullScreen button
fullScreenButton.isSelected = player.isFullscreen
*/
open var fullscreenButton = UIButton(type: UIButtonType.custom)
open var subtitleLabel = UILabel()
open var subtitleBackView = UIView()
open var subtileAttrabute: [String : Any]?
/// Activty Indector for loading
open var loadingIndector = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
open var seekToView = UIView()
open var seekToViewImage = UIImageView()
open var seekToLabel = UILabel()
open var replayButton = UIButton(type: UIButtonType.custom)
/// Gesture used to show / hide control view
open var tapGesture: UITapGestureRecognizer!
// MARK: - handle player state change
/**
call on when play time changed, update duration here
- parameter currentTime: current play time
- parameter totalTime: total duration
*/
open func playTimeDidChange(currentTime: TimeInterval, totalTime: TimeInterval) {
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
totalTimeLabel.text = BMPlayer.formatSecondsToString(totalTime)
timeSlider.value = Float(currentTime) / Float(totalTime)
if let subtitle = resource?.subtitle {
showSubtile(from: subtitle, at: currentTime)
}
}
/**
call on load duration changed, update load progressView here
- parameter loadedDuration: loaded duration
- parameter totalDuration: total duration
*/
open func loadedTimeDidChange(loadedDuration: TimeInterval , totalDuration: TimeInterval) {
progressView.setProgress(Float(loadedDuration)/Float(totalDuration), animated: true)
}
open func playerStateDidChange(state: BMPlayerState) {
switch state {
case .readyToPlay:
hideLoader()
case .buffering:
showLoader()
case .bufferFinished:
hideLoader()
case .playedToTheEnd:
playButton.isSelected = false
showPlayToTheEndView()
controlViewAnimation(isShow: true)
cancelAutoFadeOutAnimation()
default:
break
}
playerLastState = state
}
/**
Call when User use the slide to seek function
- parameter toSecound: target time
- parameter totalDuration: total duration of the video
- parameter isAdd: isAdd
*/
open func showSeekToView(to toSecound: TimeInterval, total totalDuration:TimeInterval, isAdd: Bool) {
seekToView.isHidden = false
seekToLabel.text = BMPlayer.formatSecondsToString(toSecound)
let rotate = isAdd ? 0 : CGFloat(Double.pi)
seekToViewImage.transform = CGAffineTransform(rotationAngle: rotate)
let targetTime = BMPlayer.formatSecondsToString(toSecound)
timeSlider.value = Float(toSecound / totalDuration)
currentTimeLabel.text = targetTime
}
// MARK: - UI update related function
/**
Update UI details when player set with the resource
- parameter resource: video resouce
- parameter index: defualt definition's index
*/
open func prepareUI(for resource: BMPlayerResource, selectedIndex index: Int) {
self.resource = resource
self.selectedIndex = index
titleLabel.text = resource.name
prepareChooseDefinitionView()
autoFadeOutControlViewWithAnimation()
}
open func playStateDidChange(isPlaying: Bool) {
autoFadeOutControlViewWithAnimation()
playButton.isSelected = isPlaying
}
/**
auto fade out controll view with animtion
*/
open func autoFadeOutControlViewWithAnimation() {
cancelAutoFadeOutAnimation()
delayItem = DispatchWorkItem {
self.controlViewAnimation(isShow: false)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + BMPlayerConf.animateDelayTimeInterval,
execute: delayItem!)
}
/**
cancel auto fade out controll view with animtion
*/
open func cancelAutoFadeOutAnimation() {
delayItem?.cancel()
}
/**
Implement of the control view animation, override if need's custom animation
- parameter isShow: is to show the controlview
*/
open func controlViewAnimation(isShow: Bool) {
let alpha: CGFloat = isShow ? 1.0 : 0.0
self.isMaskShowing = isShow
UIApplication.shared.setStatusBarHidden(!isShow, with: .fade)
UIView.animate(withDuration: 0.3, animations: {
self.topMaskView.alpha = alpha
self.bottomMaskView.alpha = alpha
self.mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: isShow ? 0.4 : 0.0)
if isShow {
if self.isFullscreen { self.chooseDefitionView.alpha = 1.0 }
} else {
self.replayButton.isHidden = true
self.chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(35)
}
self.chooseDefitionView.alpha = 0.0
}
self.layoutIfNeeded()
}) { (_) in
if isShow {
self.autoFadeOutControlViewWithAnimation()
}
}
}
/**
Implement of the UI update when screen orient changed
- parameter isForFullScreen: is for full screen
*/
open func updateUI(_ isForFullScreen: Bool) {
isFullscreen = isForFullScreen
fullscreenButton.isSelected = isForFullScreen
chooseDefitionView.isHidden = !isForFullScreen
if isForFullScreen {
if BMPlayerConf.topBarShowInCase.rawValue == 2 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
} else {
if BMPlayerConf.topBarShowInCase.rawValue >= 1 {
topMaskView.isHidden = true
} else {
topMaskView.isHidden = false
}
}
}
/**
Call when video play's to the end, override if you need custom UI or animation when played to the end
*/
open func showPlayToTheEndView() {
replayButton.isHidden = false
}
open func hidePlayToTheEndView() {
replayButton.isHidden = true
}
open func showLoader() {
loadingIndector.isHidden = false
loadingIndector.startAnimating()
}
open func hideLoader() {
loadingIndector.isHidden = true
}
open func hideSeekToView() {
seekToView.isHidden = true
}
open func showCoverWithLink(_ cover:String) {
self.showCover(url: URL(string: cover))
}
open func showCover(url: URL?) {
if let url = url {
DispatchQueue.global(qos: .default).async {
let data = try? Data(contentsOf: url)
DispatchQueue.main.async(execute: {
if let data = data {
self.maskImageView.image = UIImage(data: data)
} else {
self.maskImageView.image = nil
}
self.hideLoader()
});
}
}
}
open func hideCoverImageView() {
self.maskImageView.isHidden = true
}
open func prepareChooseDefinitionView() {
guard let resource = resource else {
return
}
for item in chooseDefitionView.subviews {
item.removeFromSuperview()
}
for i in 0..<resource.definitions.count {
let button = BMPlayerClearityChooseButton()
if i == 0 {
button.tag = selectedIndex
} else if i <= selectedIndex {
button.tag = i - 1
} else {
button.tag = i
}
button.setTitle("\(resource.definitions[button.tag].definition)", for: UIControlState())
chooseDefitionView.addSubview(button)
button.addTarget(self, action: #selector(self.onDefinitionSelected(_:)), for: UIControlEvents.touchUpInside)
button.snp.makeConstraints({ (make) in
make.top.equalTo(chooseDefitionView.snp.top).offset(35 * i)
make.width.equalTo(50)
make.height.equalTo(25)
make.centerX.equalTo(chooseDefitionView)
})
if resource.definitions.count == 1 {
button.isEnabled = false
}
}
}
// MARK: - Action Response
/**
Call when some action button Pressed
- parameter button: action Button
*/
open func onButtonPressed(_ button: UIButton) {
autoFadeOutControlViewWithAnimation()
if let type = ButtonType(rawValue: button.tag) {
switch type {
case .play, .replay:
if playerLastState == .playedToTheEnd {
hidePlayToTheEndView()
}
default:
break
}
}
delegate?.controlView(controlView: self, didPressButton: button)
}
/**
Call when the tap gesture tapped
- parameter gesture: tap gesture
*/
open func onTapGestureTapped(_ gesture: UITapGestureRecognizer) {
if playerLastState == .playedToTheEnd {
return
}
controlViewAnimation(isShow: !isMaskShowing)
}
// MARK: - handle UI slider actions
@objc func progressSliderTouchBegan(_ sender: UISlider) {
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchDown)
}
@objc func progressSliderValueChanged(_ sender: UISlider) {
hidePlayToTheEndView()
cancelAutoFadeOutAnimation()
let currentTime = Double(sender.value) * totalDuration
currentTimeLabel.text = BMPlayer.formatSecondsToString(currentTime)
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .valueChanged)
}
@objc func progressSliderTouchEnded(_ sender: UISlider) {
autoFadeOutControlViewWithAnimation()
delegate?.controlView(controlView: self, slider: sender, onSliderEvent: .touchUpInside)
}
// MARK: - private functions
fileprivate func showSubtile(from subtitle: BMSubtitles, at time: TimeInterval) {
if let group = subtitle.search(for: time) {
subtitleBackView.isHidden = false
subtitleLabel.attributedText = NSAttributedString(string: group.text,
attributes: subtileAttrabute)
} else {
subtitleBackView.isHidden = true
}
}
@objc fileprivate func onDefinitionSelected(_ button:UIButton) {
let height = isSelectecDefitionViewOpened ? 35 : resource!.definitions.count * 40
chooseDefitionView.snp.updateConstraints { (make) in
make.height.equalTo(height)
}
UIView.animate(withDuration: 0.3, animations: {
self.layoutIfNeeded()
})
isSelectecDefitionViewOpened = !isSelectecDefitionViewOpened
if selectedIndex != button.tag {
selectedIndex = button.tag
delegate?.controlView(controlView: self, didChooseDefition: button.tag)
}
prepareChooseDefinitionView()
}
@objc fileprivate func onReplyButtonPressed() {
replayButton.isHidden = true
}
// MARK: - Init
override public init(frame: CGRect) {
super.init(frame: frame)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUIComponents()
addSnapKitConstraint()
customizeUIComponents()
}
/// Add Customize functions here
open func customizeUIComponents() {
}
func setupUIComponents() {
// Subtile view
subtitleLabel.numberOfLines = 0
subtitleLabel.textAlignment = .center
subtitleLabel.textColor = UIColor.white
subtitleLabel.adjustsFontSizeToFitWidth = true
subtitleLabel.minimumScaleFactor = 0.5
subtitleLabel.font = UIFont.systemFont(ofSize: 13)
subtitleBackView.layer.cornerRadius = 2
subtitleBackView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
subtitleBackView.addSubview(subtitleLabel)
subtitleBackView.isHidden = true
addSubview(subtitleBackView)
// Main mask view
addSubview(mainMaskView)
mainMaskView.addSubview(topMaskView)
mainMaskView.addSubview(bottomMaskView)
mainMaskView.insertSubview(maskImageView, at: 0)
mainMaskView.clipsToBounds = true
mainMaskView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4 )
// Top views
topMaskView.addSubview(backButton)
topMaskView.addSubview(titleLabel)
addSubview(chooseDefitionView)
backButton.tag = BMPlayerControlView.ButtonType.back.rawValue
backButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_back"), for: .normal)
backButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
titleLabel.textColor = UIColor.white
titleLabel.text = ""
titleLabel.font = UIFont.systemFont(ofSize: 16)
chooseDefitionView.clipsToBounds = true
// Bottom views
bottomMaskView.addSubview(playButton)
bottomMaskView.addSubview(currentTimeLabel)
bottomMaskView.addSubview(totalTimeLabel)
bottomMaskView.addSubview(progressView)
bottomMaskView.addSubview(timeSlider)
bottomMaskView.addSubview(fullscreenButton)
playButton.tag = BMPlayerControlView.ButtonType.play.rawValue
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_play"), for: .normal)
playButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_pause"), for: .selected)
playButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
currentTimeLabel.textColor = UIColor.white
currentTimeLabel.font = UIFont.systemFont(ofSize: 12)
currentTimeLabel.text = "00:00"
currentTimeLabel.textAlignment = NSTextAlignment.center
totalTimeLabel.textColor = UIColor.white
totalTimeLabel.font = UIFont.systemFont(ofSize: 12)
totalTimeLabel.text = "00:00"
totalTimeLabel.textAlignment = NSTextAlignment.center
timeSlider.maximumValue = 1.0
timeSlider.minimumValue = 0.0
timeSlider.value = 0.0
timeSlider.setThumbImage(BMImageResourcePath("Pod_Asset_BMPlayer_slider_thumb"), for: .normal)
timeSlider.maximumTrackTintColor = UIColor.clear
timeSlider.minimumTrackTintColor = BMPlayerConf.tintColor
timeSlider.addTarget(self, action: #selector(progressSliderTouchBegan(_:)),
for: UIControlEvents.touchDown)
timeSlider.addTarget(self, action: #selector(progressSliderValueChanged(_:)),
for: UIControlEvents.valueChanged)
timeSlider.addTarget(self, action: #selector(progressSliderTouchEnded(_:)),
for: [UIControlEvents.touchUpInside,UIControlEvents.touchCancel, UIControlEvents.touchUpOutside])
progressView.tintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6 )
progressView.trackTintColor = UIColor ( red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3 )
fullscreenButton.tag = BMPlayerControlView.ButtonType.fullscreen.rawValue
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_fullscreen"), for: .normal)
fullscreenButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_portialscreen"), for: .selected)
fullscreenButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
mainMaskView.addSubview(loadingIndector)
loadingIndector.type = BMPlayerConf.loaderType
loadingIndector.color = BMPlayerConf.tintColor
// View to show when slide to seek
addSubview(seekToView)
seekToView.addSubview(seekToViewImage)
seekToView.addSubview(seekToLabel)
seekToLabel.font = UIFont.systemFont(ofSize: 13)
seekToLabel.textColor = UIColor ( red: 0.9098, green: 0.9098, blue: 0.9098, alpha: 1.0 )
seekToView.backgroundColor = UIColor ( red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7 )
seekToView.layer.cornerRadius = 4
seekToView.layer.masksToBounds = true
seekToView.isHidden = true
seekToViewImage.image = BMImageResourcePath("Pod_Asset_BMPlayer_seek_to_image")
addSubview(replayButton)
replayButton.isHidden = true
replayButton.setImage(BMImageResourcePath("Pod_Asset_BMPlayer_replay"), for: .normal)
replayButton.addTarget(self, action: #selector(onButtonPressed(_:)), for: .touchUpInside)
replayButton.tag = ButtonType.replay.rawValue
tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapGestureTapped(_:)))
addGestureRecognizer(tapGesture)
}
func addSnapKitConstraint() {
// Main mask view
mainMaskView.snp.makeConstraints { (make) in
make.edges.equalTo(self)
}
maskImageView.snp.makeConstraints { (make) in
make.edges.equalTo(mainMaskView)
}
topMaskView.snp.makeConstraints { (make) in
make.top.left.right.equalTo(mainMaskView)
make.height.equalTo(65)
}
bottomMaskView.snp.makeConstraints { (make) in
make.bottom.left.right.equalTo(mainMaskView)
make.height.equalTo(50)
}
// Top views
backButton.snp.makeConstraints { (make) in
make.width.height.equalTo(50)
make.left.bottom.equalTo(topMaskView)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(backButton.snp.right)
make.centerY.equalTo(backButton)
}
chooseDefitionView.snp.makeConstraints { (make) in
make.right.equalTo(topMaskView.snp.right).offset(-20)
make.top.equalTo(titleLabel.snp.top).offset(-4)
make.width.equalTo(60)
make.height.equalTo(30)
}
// Bottom views
playButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.left.bottom.equalTo(bottomMaskView)
}
currentTimeLabel.snp.makeConstraints { (make) in
make.left.equalTo(playButton.snp.right)
make.centerY.equalTo(playButton)
make.width.equalTo(40)
}
timeSlider.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(currentTimeLabel.snp.right).offset(10).priority(750)
make.height.equalTo(30)
}
progressView.snp.makeConstraints { (make) in
make.centerY.left.right.equalTo(timeSlider)
make.height.equalTo(2)
}
totalTimeLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(timeSlider.snp.right).offset(5)
make.width.equalTo(40)
}
fullscreenButton.snp.makeConstraints { (make) in
make.width.equalTo(50)
make.height.equalTo(50)
make.centerY.equalTo(currentTimeLabel)
make.left.equalTo(totalTimeLabel.snp.right)
make.right.equalTo(bottomMaskView.snp.right)
}
loadingIndector.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX).offset(0)
make.centerY.equalTo(mainMaskView.snp.centerY).offset(0)
}
// View to show when slide to seek
seekToView.snp.makeConstraints { (make) in
make.center.equalTo(self.snp.center)
make.width.equalTo(100)
make.height.equalTo(40)
}
seekToViewImage.snp.makeConstraints { (make) in
make.left.equalTo(seekToView.snp.left).offset(15)
make.centerY.equalTo(seekToView.snp.centerY)
make.height.equalTo(15)
make.width.equalTo(25)
}
seekToLabel.snp.makeConstraints { (make) in
make.left.equalTo(seekToViewImage.snp.right).offset(10)
make.centerY.equalTo(seekToView.snp.centerY)
}
replayButton.snp.makeConstraints { (make) in
make.centerX.equalTo(mainMaskView.snp.centerX)
make.centerY.equalTo(mainMaskView.snp.centerY)
make.width.height.equalTo(50)
}
subtitleBackView.snp.makeConstraints {
$0.bottom.equalTo(snp.bottom).offset(-5)
$0.centerX.equalTo(snp.centerX)
$0.width.lessThanOrEqualTo(snp.width).offset(-10).priority(750)
}
subtitleLabel.snp.makeConstraints {
$0.left.equalTo(subtitleBackView.snp.left).offset(10)
$0.right.equalTo(subtitleBackView.snp.right).offset(-10)
$0.top.equalTo(subtitleBackView.snp.top).offset(2)
$0.bottom.equalTo(subtitleBackView.snp.bottom).offset(-2)
}
}
fileprivate func BMImageResourcePath(_ fileName: String) -> UIImage? {
let bundle = Bundle(for: BMPlayer.self)
let image = UIImage(named: fileName, in: bundle, compatibleWith: nil)
return image
}
}
| mit | c2ee5e00c9b458dab912bea4c918099b | 34.436185 | 126 | 0.610465 | 4.969709 | false | false | false | false |
daltonclaybrook/music-room-ios | MusicRoom/RoomCell.swift | 1 | 791 | //
// RoomCell.swift
// MusicRoom
//
// Created by Dalton Claybrook on 11/1/16.
// Copyright © 2016 Claybrook Software. All rights reserved.
//
import UIKit
class RoomCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var ownerLabel: UILabel!
@IBOutlet weak var peopleCountLabel: UILabel!
@IBOutlet weak var nowPlayingLabel: UILabel!
static var reuseID: String {
return String(describing: RoomCell.self)
}
func configure(with room: Room) {
nameLabel.text = room.name
ownerLabel.text = room.owner
peopleCountLabel.text = room.participantCount == 1 ? "1 person inside" : "\(room.participantCount) people inside"
nowPlayingLabel.text = "now playing \(room.nowPlaying)"
}
}
| mit | 45c269623b55ead30a0fc737973e3b60 | 27.214286 | 121 | 0.672152 | 4.136126 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/Model/AuthInfo.swift | 2 | 1897 | //
// AuthInfo.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/05/19.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
import LUKeychainAccess
class AuthInfo: NSObject {
var username = ""
var password = ""
var endpoint = ""
var basicAuthUsername = ""
var basicAuthPassword = ""
func save() {
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(username, forKey: "username")
userDefaults.setObject(endpoint, forKey: "endpoint")
userDefaults.setObject(basicAuthUsername, forKey: "basicAuthUsername")
userDefaults.synchronize()
let keychainAccess = LUKeychainAccess.standardKeychainAccess()
keychainAccess.setString(password, forKey: "password")
keychainAccess.setString(basicAuthPassword, forKey: "basicAuthPassword")
}
func load() {
var value: String?
let userDefaults = NSUserDefaults.standardUserDefaults()
value = userDefaults.objectForKey("username") as? String
username = (value != nil) ? value! : ""
value = userDefaults.objectForKey("endpoint") as? String
endpoint = (value != nil) ? value! : ""
value = userDefaults.objectForKey("basicAuthUsername") as? String
basicAuthUsername = (value != nil) ? value! : ""
let keychainAccess = LUKeychainAccess.standardKeychainAccess()
value = keychainAccess.stringForKey("password")
password = (value != nil) ? value! : ""
value = keychainAccess.stringForKey("basicAuthPassword")
basicAuthPassword = (value != nil) ? value! : ""
}
func clear() {
username = ""
password = ""
endpoint = ""
basicAuthUsername = ""
basicAuthPassword = ""
}
func logout() {
self.clear()
self.save()
}
}
| mit | 62e31556479d5430890eb429181ec8ff | 30.065574 | 80 | 0.621636 | 4.690594 | false | false | false | false |
amraboelela/swift | benchmark/utils/TestsUtils.swift | 1 | 8940 | //===--- TestsUtils.swift -------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
public enum BenchmarkCategory : String {
// Validation "micro" benchmarks test a specific operation or critical path that
// we know is important to measure.
case validation
// subsystems to validate and their subcategories.
case api, Array, String, Dictionary, Codable, Set, Data
case sdk
case runtime, refcount, metadata
// Other general areas of compiled code validation.
case abstraction, safetychecks, exceptions, bridging, concurrency, existential
// Algorithms are "micro" that test some well-known algorithm in isolation:
// sorting, searching, hashing, fibonaci, crypto, etc.
case algorithm
// Miniapplications are contrived to mimic some subset of application behavior
// in a way that can be easily measured. They are larger than micro-benchmarks,
// combining multiple APIs, data structures, or algorithms. This includes small
// standardized benchmarks, pieces of real applications that have been extracted
// into a benchmark, important functionality like JSON parsing, etc.
case miniapplication
// Regression benchmarks is a catch-all for less important "micro"
// benchmarks. This could be a random piece of code that was attached to a bug
// report. We want to make sure the optimizer as a whole continues to handle
// this case, but don't know how applicable it is to general Swift performance
// relative to the other micro-benchmarks. In particular, these aren't weighted
// as highly as "validation" benchmarks and likely won't be the subject of
// future investigation unless they significantly regress.
case regression
// Most benchmarks are assumed to be "stable" and will be regularly tracked at
// each commit. A handful may be marked unstable if continually tracking them is
// counterproductive.
case unstable
// CPU benchmarks represent instrinsic Swift performance. They are useful for
// measuring a fully baked Swift implementation across different platforms and
// hardware. The benchmark should also be reasonably applicable to real Swift
// code--it should exercise a known performance critical area. Typically these
// will be drawn from the validation benchmarks once the language and standard
// library implementation of the benchmark meets a reasonable efficiency
// baseline. A benchmark should only be tagged "cpubench" after a full
// performance investigation of the benchmark has been completed to determine
// that it is a good representation of future Swift performance. Benchmarks
// should not be tagged if they make use of an API that we plan on
// reimplementing or call into code paths that have known opportunities for
// significant optimization.
case cpubench
// Explicit skip marker
case skip
}
extension BenchmarkCategory : CustomStringConvertible {
public var description: String {
return self.rawValue
}
}
extension BenchmarkCategory : Comparable {
public static func < (lhs: BenchmarkCategory, rhs: BenchmarkCategory) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
public struct BenchmarkPlatformSet : OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let darwin = BenchmarkPlatformSet(rawValue: 1 << 0)
public static let linux = BenchmarkPlatformSet(rawValue: 1 << 1)
public static var currentPlatform: BenchmarkPlatformSet {
#if os(Linux)
return .linux
#else
return .darwin
#endif
}
public static var allPlatforms: BenchmarkPlatformSet {
return [.darwin, .linux]
}
}
public struct BenchmarkInfo {
/// The name of the benchmark that should be displayed by the harness.
public var name: String
/// Shadow static variable for runFunction.
private var _runFunction: (Int) -> ()
/// A function that invokes the specific benchmark routine.
public var runFunction: ((Int) -> ())? {
if !shouldRun {
return nil
}
return _runFunction
}
/// A set of category tags that describe this benchmark. This is used by the
/// harness to allow for easy slicing of the set of benchmarks along tag
/// boundaries, e.x.: run all string benchmarks or ref count benchmarks, etc.
public var tags: Set<BenchmarkCategory>
/// The platforms that this benchmark supports. This is an OptionSet.
private var unsupportedPlatforms: BenchmarkPlatformSet
/// Shadow variable for setUpFunction.
private var _setUpFunction: (() -> ())?
/// An optional function that if non-null is run before benchmark samples
/// are timed.
public var setUpFunction : (() -> ())? {
if !shouldRun {
return nil
}
return _setUpFunction
}
/// Shadow static variable for computed property tearDownFunction.
private var _tearDownFunction: (() -> ())?
/// An optional function that if non-null is run after samples are taken.
public var tearDownFunction: (() -> ())? {
if !shouldRun {
return nil
}
return _tearDownFunction
}
public var legacyFactor: Int?
public init(name: String, runFunction: @escaping (Int) -> (), tags: [BenchmarkCategory],
setUpFunction: (() -> ())? = nil,
tearDownFunction: (() -> ())? = nil,
unsupportedPlatforms: BenchmarkPlatformSet = [],
legacyFactor: Int? = nil) {
self.name = name
self._runFunction = runFunction
self.tags = Set(tags)
self._setUpFunction = setUpFunction
self._tearDownFunction = tearDownFunction
self.unsupportedPlatforms = unsupportedPlatforms
self.legacyFactor = legacyFactor
}
/// Returns true if this benchmark should be run on the current platform.
var shouldRun: Bool {
return !unsupportedPlatforms.contains(.currentPlatform)
}
}
extension BenchmarkInfo : Comparable {
public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool {
return lhs.name < rhs.name
}
public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool {
return lhs.name == rhs.name
}
}
extension BenchmarkInfo : Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
}
}
// Linear function shift register.
//
// This is just to drive benchmarks. I don't make any claim about its
// strength. According to Wikipedia, it has the maximal period for a
// 32-bit register.
struct LFSR {
// Set the register to some seed that I pulled out of a hat.
var lfsr : UInt32 = 0xb78978e7
mutating func shift() {
lfsr = (lfsr >> 1) ^ (UInt32(bitPattern: -Int32((lfsr & 1))) & 0xD0000001)
}
mutating func randInt() -> Int64 {
var result : UInt32 = 0
for _ in 0..<32 {
result = (result << 1) | (lfsr & 1)
shift()
}
return Int64(bitPattern: UInt64(result))
}
}
var lfsrRandomGenerator = LFSR()
// Start the generator from the beginning
public func SRand() {
lfsrRandomGenerator = LFSR()
}
public func Random() -> Int64 {
return lfsrRandomGenerator.randInt()
}
@inlinable // FIXME(inline-always)
@inline(__always)
public func CheckResults(
_ resultsMatch: Bool,
file: StaticString = #file,
function: StaticString = #function,
line: Int = #line
) {
guard _fastPath(resultsMatch) else {
print("Incorrect result in \(function), \(file):\(line)")
abort()
}
}
public func False() -> Bool { return false }
/// This is a dummy protocol to test the speed of our protocol dispatch.
public protocol SomeProtocol { func getValue() -> Int }
struct MyStruct : SomeProtocol {
init() {}
func getValue() -> Int { return 1 }
}
public func someProtocolFactory() -> SomeProtocol { return MyStruct() }
// Just consume the argument.
// It's important that this function is in another module than the tests
// which are using it.
@inline(never)
public func blackHole<T>(_ x: T) {
}
// Return the passed argument without letting the optimizer know that.
@inline(never)
public func identity<T>(_ x: T) -> T {
return x
}
// Return the passed argument without letting the optimizer know that.
// It's important that this function is in another module than the tests
// which are using it.
@inline(never)
public func getInt(_ x: Int) -> Int { return x }
// The same for String.
@inline(never)
public func getString(_ s: String) -> String { return s }
// The same for Substring.
@inline(never)
public func getSubstring(_ s: Substring) -> Substring { return s }
| apache-2.0 | c5c10dd54d3ff8e5bdc2f2aa69e6bb5d | 31.747253 | 90 | 0.696532 | 4.476715 | false | false | false | false |
toco1001/Sources | Sources/SearchTableViewCell.swift | 1 | 1570 | //
// SearchTableViewCell.swift
// Sources
//
// Created by toco on 25/02/17.
// Copyright © 2017 tocozakura. All rights reserved.
//
import UIKit
import SDWebImage
class SearchTableViewCell: UITableViewCell {
static let nibName = "SearchTableViewCell"
static let identifier = nibName
static let Height = CGFloat(80.0)
static var avatorURL: String?
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
iconImageView?.layer.cornerRadius = SearchTableViewCell.Height/2
iconImageView?.layer.masksToBounds = true
iconImageView?.layer.borderColor = Settings.Colors.systemGrayColor.cgColor
iconImageView?.layer.borderWidth = 2.0
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension SearchTableViewCell {
func configure(repository: Repository, row: Int) {
self.nameLabel?.text = repository.fullName
let avatorUrlString = repository.owner.avatar_url
let avatorURL = NSURL(string: avatorUrlString)
self.iconImageView?.sd_setImage(with: avatorURL as URL?, placeholderImage: nil, options: .lowPriority
, completed: {
image, error, cacheType, imageUrl in
if error != nil {
return
}
if image != nil && cacheType == .none {
self.iconImageView?.fadeIn(duration: FadeType.Slow.rawValue)
}
})
}
}
| mit | 252e1d7ea08edcd7899ff7dca293ea77 | 28.603774 | 105 | 0.699809 | 4.508621 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/SwiftMoment/SwiftMoment/SwiftMoment/TimeUnit.swift | 2 | 713 | //
// TimeUnit.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
/// Represents different time units.
///
/// - Years: Represents year units.
/// - Quarters: Represents quarter units.
/// - Months: Represents month units.
/// - Weeks: Represents week units.
/// - Days: Represents day units.
/// - Hours: Represents hour units.
/// - Minutes: Represents minute units.
/// - Seconds: Represents second units.
public enum TimeUnit: String {
case Years = "y"
case Quarters = "Q"
case Months = "M"
case Weeks = "w"
case Days = "d"
case Hours = "H"
case Minutes = "m"
case Seconds = "s"
}
| mit | 03afc49ade72619702dbe1c71bf851ce | 24.464286 | 64 | 0.618513 | 3.512315 | false | false | false | false |
ello/ello-ios | Sources/Networking/LoadingToken.swift | 1 | 587 | ////
/// LoadingToken.swift
//
struct LoadingToken {
private var loadInitialPageLoadingToken: String = ""
var cancelLoadingClosure: Block = {}
mutating func resetInitialPageLoadingToken() -> String {
let newToken = UUID().uuidString
loadInitialPageLoadingToken = newToken
return newToken
}
func isValidInitialPageLoadingToken(_ token: String) -> Bool {
return loadInitialPageLoadingToken == token
}
mutating func cancelInitialPage() {
_ = resetInitialPageLoadingToken()
self.cancelLoadingClosure()
}
}
| mit | 09bdd0c3c646c247cdafbf1b1ae8cbe0 | 24.521739 | 66 | 0.67121 | 4.974576 | false | false | false | false |
Norod/Filterpedia | Filterpedia/customFilters/metalFilters/MetalFilters.swift | 1 | 16044 | //
// MetalFilters.swift
// Filterpedia
//
// Created by Simon Gladman on 24/01/2016.
// Copyright © 2016 Simon Gladman. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
import CoreImage
#if !arch(i386) && !arch(x86_64)
import Metal
import MetalKit
// MARK: MetalPixellateFilter
class MetalPixellateFilter: MetalImageFilter
{
init()
{
super.init(functionName: "pixellate")
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var inputPixelWidth: CGFloat = 50
var inputPixelHeight: CGFloat = 25
override func setDefaults()
{
inputPixelWidth = 50
inputPixelHeight = 25
}
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Metal Pixellate",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputPixelWidth": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 50,
kCIAttributeDisplayName: "Pixel Width",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPixelHeight": [kCIAttributeIdentity: 1,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 25,
kCIAttributeDisplayName: "Pixel Height",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar]
]
}
}
// MARK: Perlin Noise
class MetalPerlinNoise: MetalGeneratorFilter
{
init()
{
super.init(functionName: "perlin")
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var inputReciprocalScale = CGFloat(50)
var inputOctaves = CGFloat(2)
var inputPersistence = CGFloat(0.5)
var inputColor0 = CIColor(red: 0.5, green: 0.25, blue: 0)
var inputColor1 = CIColor(red: 0, green: 0, blue: 0.15)
var inputZ = CGFloat(0)
override func setDefaults()
{
inputReciprocalScale = 50
inputOctaves = 2
inputPersistence = 0.5
inputColor0 = CIColor(red: 0.5, green: 0.25, blue: 0)
inputColor1 = CIColor(red: 0, green: 0, blue: 0.15)
}
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Metal Perlin Noise",
"inputReciprocalScale": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 50,
kCIAttributeDisplayName: "Scale",
kCIAttributeMin: 10,
kCIAttributeSliderMin: 10,
kCIAttributeSliderMax: 100,
kCIAttributeType: kCIAttributeTypeScalar],
"inputOctaves": [kCIAttributeIdentity: 1,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 2,
kCIAttributeDisplayName: "Octaves",
kCIAttributeMin: 1,
kCIAttributeSliderMin: 1,
kCIAttributeSliderMax: 16,
kCIAttributeType: kCIAttributeTypeScalar],
"inputPersistence": [kCIAttributeIdentity: 2,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 0.5,
kCIAttributeDisplayName: "Persistence",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1,
kCIAttributeType: kCIAttributeTypeScalar],
"inputColor0": [kCIAttributeIdentity: 3,
kCIAttributeClass: "CIColor",
kCIAttributeDefault: CIColor(red: 0.5, green: 0.25, blue: 0),
kCIAttributeDisplayName: "Color One",
kCIAttributeType: kCIAttributeTypeColor],
"inputColor1": [kCIAttributeIdentity: 4,
kCIAttributeClass: "CIColor",
kCIAttributeDefault: CIColor(red: 0, green: 0, blue: 0.15),
kCIAttributeDisplayName: "Color Two",
kCIAttributeType: kCIAttributeTypeColor],
"inputZ": [kCIAttributeIdentity: 5,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 1,
kCIAttributeDisplayName: "Z Position",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 1024,
kCIAttributeType: kCIAttributeTypeScalar],
"inputWidth": [kCIAttributeIdentity: 2,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Width",
kCIAttributeMin: 100,
kCIAttributeSliderMin: 100,
kCIAttributeSliderMax: 2048,
kCIAttributeType: kCIAttributeTypeScalar],
"inputHeight": [kCIAttributeIdentity: 2,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 640,
kCIAttributeDisplayName: "Height",
kCIAttributeMin: 100,
kCIAttributeSliderMin: 100,
kCIAttributeSliderMax: 2048,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
}
// MARK: MetalKuwaharaFilter
class MetalKuwaharaFilter: MetalImageFilter
{
init()
{
super.init(functionName: "kuwahara")
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
var inputRadius: CGFloat = 15
override func setDefaults()
{
inputRadius = 15
}
override var attributes: [String : Any]
{
return [
kCIAttributeFilterDisplayName: "Metal Kuwahara",
"inputImage": [kCIAttributeIdentity: 0,
kCIAttributeClass: "CIImage",
kCIAttributeDisplayName: "Image",
kCIAttributeType: kCIAttributeTypeImage],
"inputRadius": [kCIAttributeIdentity: 0,
kCIAttributeClass: "NSNumber",
kCIAttributeDefault: 15,
kCIAttributeDisplayName: "Radius",
kCIAttributeMin: 0,
kCIAttributeSliderMin: 0,
kCIAttributeSliderMax: 30,
kCIAttributeType: kCIAttributeTypeScalar],
]
}
}
// MARK: MetalFilter types
class MetalGeneratorFilter: MetalFilter
{
var inputWidth: CGFloat = 640
var inputHeight: CGFloat = 640
override func textureInvalid() -> Bool
{
if let textureDescriptor = textureDescriptor ,
textureDescriptor.width != Int(inputWidth) ||
textureDescriptor.height != Int(inputHeight)
{
return true
}
return false
}
}
class MetalImageFilter: MetalFilter
{
var inputImage: CIImage?
override func textureInvalid() -> Bool
{
if let textureDescriptor = textureDescriptor,
let inputImage = inputImage ,
textureDescriptor.width != Int(inputImage.extent.width) ||
textureDescriptor.height != Int(inputImage.extent.height)
{
return true
}
return false
}
}
// MARK: Base class
/// `MetalFilter` is a Core Image filter that uses a Metal compute function as its engine.
/// This version supports a single input image and an arbritrary number of `NSNumber`
/// parameters. Numeric parameters require a properly set `kCIAttributeIdentity` which
/// defines their buffer index into the Metal kernel.
class MetalFilter: CIFilter, MetalRenderable
{
let device: MTLDevice = MTLCreateSystemDefaultDevice()!
let colorSpace = CGColorSpaceCreateDeviceRGB()
lazy var ciContext: CIContext =
{
[unowned self] in
return CIContext(mtlDevice: self.device)
}()
lazy var commandQueue: MTLCommandQueue =
{
[unowned self] in
return self.device.makeCommandQueue()
}()
lazy var defaultLibrary: MTLLibrary =
{
[unowned self] in
return self.device.newDefaultLibrary()!
}()
var pipelineState: MTLComputePipelineState!
let functionName: String
var threadsPerThreadgroup: MTLSize!
var threadgroupsPerGrid: MTLSize?
var textureDescriptor: MTLTextureDescriptor?
var kernelInputTexture: MTLTexture?
var kernelOutputTexture: MTLTexture?
override var outputImage: CIImage!
{
if textureInvalid()
{
self.textureDescriptor = nil
}
if let imageFilter = self as? MetalImageFilter,
let inputImage = imageFilter.inputImage
{
return imageFromComputeShader(width: inputImage.extent.width,
height: inputImage.extent.height,
inputImage: inputImage)
}
if let generatorFilter = self as? MetalGeneratorFilter
{
return imageFromComputeShader(width: generatorFilter.inputWidth,
height: generatorFilter.inputHeight,
inputImage: nil)
}
return nil
}
init(functionName: String)
{
self.functionName = functionName
super.init()
let kernelFunction = defaultLibrary.makeFunction(name: self.functionName)!
do
{
pipelineState = try self.device.makeComputePipelineState(function: kernelFunction)
let maxTotalThreadsPerThreadgroup = Double(pipelineState.maxTotalThreadsPerThreadgroup)
let threadExecutionWidth = Double(pipelineState.threadExecutionWidth)
let threadsPerThreadgroupSide = stride(
from: 0,
to: Int(sqrt(maxTotalThreadsPerThreadgroup)),
by: 1).reduce(16)
{
return (Double($1 * $1) / threadExecutionWidth).truncatingRemainder(dividingBy:1) == 0 ? $1 : $0
}
threadsPerThreadgroup = MTLSize(width:threadsPerThreadgroupSide,
height:threadsPerThreadgroupSide,
depth:1)
}
catch
{
fatalError("Unable to create pipeline state for kernel function \(functionName)")
}
if !(self is MetalImageFilter) && !(self is MetalGeneratorFilter)
{
fatalError("MetalFilters must subclass either MetalImageFilter or MetalGeneratorFilter")
}
}
required init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
func textureInvalid() -> Bool
{
fatalError("textureInvalid() not implemented in MetalFilter")
}
func imageFromComputeShader(width: CGFloat, height: CGFloat, inputImage: CIImage?) -> CIImage
{
if textureDescriptor == nil
{
if ((width < 1.0) || (height <= 1.0)) {
return CIImage();
}
textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
width: Int(width),
height: Int(height),
mipmapped: false)
kernelInputTexture = device.makeTexture(descriptor: textureDescriptor!)
kernelOutputTexture = device.makeTexture(descriptor: textureDescriptor!)
threadgroupsPerGrid = MTLSizeMake(
textureDescriptor!.width / threadsPerThreadgroup.width,
textureDescriptor!.height / threadsPerThreadgroup.height, 1)
}
let commandBuffer = commandQueue.makeCommandBuffer()
if let imageFilter = self as? MetalImageFilter,
let inputImage = imageFilter.inputImage
{
ciContext.render(inputImage,
to: kernelInputTexture!,
commandBuffer: commandBuffer,
bounds: inputImage.extent,
colorSpace: colorSpace)
}
let commandEncoder = commandBuffer.makeComputeCommandEncoder()
commandEncoder.setComputePipelineState(pipelineState)
// populate float buffers using kCIAttributeIdentity as buffer index
for inputKey in inputKeys
{
let attribute = attributes[inputKey] as! [String : Any]
let attributeClass = attribute[kCIAttributeClass] as! String
if (attributeClass == "NSNumber") {
if let bufferIndex = (attributes[inputKey] as! [String:AnyObject])[kCIAttributeIdentity] as? Int,
var bufferValue = value(forKey: inputKey) as? Float
{
let buffer = device.makeBuffer(bytes: &bufferValue,
length: MemoryLayout<Float>.size,
options: [])
commandEncoder.setBuffer(buffer, offset: 0, at: bufferIndex)
}
}
if (attributeClass == "CIColor") {
if let bufferIndex = (attributes[inputKey] as! [String:AnyObject])[kCIAttributeIdentity] as? Int,
let bufferValue = value(forKey: inputKey) as? CIColor
{
var color = float4(Float(bufferValue.red),
Float(bufferValue.green),
Float(bufferValue.blue),
Float(bufferValue.alpha))
let buffer = device.makeBuffer(bytes: &color,
length: MemoryLayout<float4>.size,
options: [])
commandEncoder.setBuffer(buffer, offset: 0, at: bufferIndex)
}
}
}
if self is MetalImageFilter
{
commandEncoder.setTexture(kernelInputTexture, at: 0)
commandEncoder.setTexture(kernelOutputTexture, at: 1)
}
else if self is MetalGeneratorFilter
{
commandEncoder.setTexture(kernelOutputTexture, at: 0)
}
commandEncoder.dispatchThreadgroups(threadgroupsPerGrid!,
threadsPerThreadgroup: threadsPerThreadgroup)
commandEncoder.endEncoding()
commandBuffer.commit()
return CIImage(mtlTexture: kernelOutputTexture!,
options: [kCIImageColorSpace: colorSpace])!
}
}
#else
class MetalFilter: CIFilter
{
}
#endif
protocol MetalRenderable {
}
| gpl-3.0 | 55ef8d5b860a763faf305f9ae7e306ab | 31.410101 | 113 | 0.569968 | 5.80217 | false | false | false | false |
akhilraj-rajkumar/swift-code-gen | example/Pods/ObjectMapper/Sources/Map.swift | 43 | 6408 | //
// Map.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// MapContext is available for developers who wish to pass information around during the mapping process.
public protocol MapContext {
}
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
public internal(set) var JSON: [String: Any] = [:]
public internal(set) var isKeyPresent = false
public internal(set) var currentValue: Any?
public internal(set) var currentKey: String?
var keyIsNested = false
public internal(set) var nestedKeyDelimiter: String = "."
public var context: MapContext?
public var shouldIncludeNilValues = false /// If this is set to true, toJSON output will include null values for any variables that are not set.
public let toObject: Bool // indicates whether the mapping is being applied to an existing object
public init(mappingType: MappingType, JSON: [String: Any], toObject: Bool = false, context: MapContext? = nil, shouldIncludeNilValues: Bool = false) {
self.mappingType = mappingType
self.JSON = JSON
self.toObject = toObject
self.context = context
self.shouldIncludeNilValues = shouldIncludeNilValues
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
return self[key, delimiter: ".", ignoreNil: false]
}
public subscript(key: String, delimiter delimiter: String) -> Map {
let nested = key.contains(delimiter)
return self[key, nested: nested, delimiter: delimiter, ignoreNil: false]
}
public subscript(key: String, nested nested: Bool) -> Map {
return self[key, nested: nested, delimiter: ".", ignoreNil: false]
}
public subscript(key: String, nested nested: Bool, delimiter delimiter: String) -> Map {
return self[key, nested: nested, delimiter: delimiter, ignoreNil: false]
}
public subscript(key: String, ignoreNil ignoreNil: Bool) -> Map {
return self[key, delimiter: ".", ignoreNil: ignoreNil]
}
public subscript(key: String, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map {
let nested = key.contains(delimiter)
return self[key, nested: nested, delimiter: delimiter, ignoreNil: ignoreNil]
}
public subscript(key: String, nested nested: Bool, ignoreNil ignoreNil: Bool) -> Map {
return self[key, nested: nested, delimiter: ".", ignoreNil: ignoreNil]
}
public subscript(key: String, nested nested: Bool, delimiter delimiter: String, ignoreNil ignoreNil: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
nestedKeyDelimiter = delimiter
if mappingType == .fromJSON {
// check if a value exists for the current key
// do this pre-check for performance reasons
if nested == false {
let object = JSON[key]
let isNSNull = object is NSNull
isKeyPresent = isNSNull ? true : object != nil
currentValue = isNSNull ? nil : object
} else {
// break down the components of the key that are separated by .
(isKeyPresent, currentValue) = valueFor(ArraySlice(key.components(separatedBy: delimiter)), dictionary: JSON)
}
// update isKeyPresent if ignoreNil is true
if ignoreNil && currentValue == nil {
isKeyPresent = false
}
}
return self
}
public func value<T>() -> T? {
return currentValue as? T
}
}
/// Fetch value from JSON dictionary, loop through keyPathComponents until we reach the desired object
private func valueFor(_ keyPathComponents: ArraySlice<String>, dictionary: [String: Any]) -> (Bool, Any?) {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return (false, nil)
}
if let keyPath = keyPathComponents.first {
let object = dictionary[keyPath]
if object is NSNull {
return (true, nil)
} else if keyPathComponents.count > 1, let dict = object as? [String: Any] {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else if keyPathComponents.count > 1, let array = object as? [Any] {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, array: array)
} else {
return (object != nil, object)
}
}
return (false, nil)
}
/// Fetch value from JSON Array, loop through keyPathComponents them until we reach the desired object
private func valueFor(_ keyPathComponents: ArraySlice<String>, array: [Any]) -> (Bool, Any?) {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return (false, nil)
}
//Try to convert keypath to Int as index
if let keyPath = keyPathComponents.first,
let index = Int(keyPath) , index >= 0 && index < array.count {
let object = array[index]
if object is NSNull {
return (true, nil)
} else if keyPathComponents.count > 1, let array = object as? [Any] {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, array: array)
} else if keyPathComponents.count > 1, let dict = object as? [String: Any] {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, dictionary: dict)
} else {
return (true, object)
}
}
return (false, nil)
}
| apache-2.0 | a896f08e84822df5edf3ddf36fa1eca2 | 34.403315 | 151 | 0.715824 | 3.878935 | false | false | false | false |
DrabWeb/Komikan | Komikan/Komikan/KMMigrationImporter.swift | 1 | 7873 | //
// KMMigrationImporter.swift
// Komikan
//
// Created by Seth on 2016-03-13.
//
import Cocoa
/// Used for importing your collection that you exported for migration
class KMMigrationImporter {
/// The manga grid controller to add the imported manga to
var mangaGridController : KMMangaGridController = KMMangaGridController();
/// Imports all the manga in the passed folder and all it's subfolders. Only imports ones that have metadata exported
func importFolder(_ path : String) {
// Print to the log that we are importing
print("KMMigrationImporter: Trying to import files in \(path)");
/// The file enumerator for the import folder
let importFolderFileEnumerator : FileManager.DirectoryEnumerator = FileManager.default.enumerator(atPath: path)!;
// For every item in all the contents of the import path and its subfolders...
for(_, currentFilePath) in importFolderFileEnumerator.enumerated() {
/// The full path to the current file on the system
let currentFileFullPath : String = path + String(describing: currentFilePath);
/// The extension of the current file
let currentFileExtension : String = NSString(string: currentFileFullPath).pathExtension;
// If the current file is a CBZ, CBR, ZIP, RAR or Folder...
if(currentFileExtension == "cbz" || currentFileExtension == "cbr" || currentFileExtension == "zip" || currentFileExtension == "rar" || KMFileUtilities().isFolder(currentFileFullPath)) {
// If the current file has a Komikan JSON file...
if(KMFileUtilities().mangaFileHasJSON(currentFileFullPath)) {
// Print to the log that we are importing the current manga
print("KMMigrationImporter: Importing file \(currentFileFullPath)");
/// The manga we will add
let manga : KMManga = KMManga();
/// The SwiftyJSON object for the manga's JSON info
let mangaJson = JSON(data: FileManager.default.contents(atPath: KMFileUtilities().mangaFileJSONPath(currentFileFullPath))!);
// If the title value from the JSON is not "auto" or blank...
if(mangaJson["title"].stringValue != "auto" && mangaJson["title"].stringValue != "") {
// Set the manga's title to the value in the JSON
manga.title = mangaJson["title"].stringValue;
}
// If the title value is "auto"...
else if(mangaJson["title"].stringValue == "auto") {
// Set the manga's title to the file's name without the extension
manga.title = KMFileUtilities().getFileNameWithoutExtension(currentFileFullPath);
}
// If the cover image value from the JSON is not "auto" or blank...
if(mangaJson["cover-image"].stringValue != "auto" && mangaJson["cover-image"].stringValue != "") {
// If the first character is not a "/"...
if(mangaJson["cover-image"].stringValue.substring(to: mangaJson["cover-image"].stringValue.characters.index(after: mangaJson["cover-image"].stringValue.startIndex)) == "/") {
// Set the cover for this manga to the image file at cover-image
manga.coverImage = NSImage(contentsOf: URL(fileURLWithPath: mangaJson["cover-image"].stringValue))!;
}
// If the cover-image value was local...
else {
// Get the relative image
manga.coverImage = NSImage(contentsOf: URL(fileURLWithPath: KMFileUtilities().folderPathForFile(currentFileFullPath) + "Komikan/" + mangaJson["cover-image"].stringValue))!;
}
}
// Set the series, artist, and writer
manga.series = mangaJson["series"].stringValue;
manga.artist = mangaJson["artist"].stringValue;
manga.writer = mangaJson["writer"].stringValue;
// For every tag in the JSON's tags array...
for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() {
// Add the current tag to the manga's tags
manga.tags.append(currentTag.stringValue);
}
// Set the group
manga.group = mangaJson["group"].stringValue;
// Set if this manga is a favourite
manga.favourite = mangaJson["favourite"].boolValue;
// Set if this manga is l-lewd...
manga.lewd = mangaJson["lewd"].boolValue;
// If all the internal values are present...
if(mangaJson["current-page"].exists() && mangaJson["page-count"].exists() && mangaJson["saturation"].exists() && mangaJson["brightness"].exists() && mangaJson["contrast"].exists() && mangaJson["sharpness"].exists()) {
// Set the current page
manga.currentPage = mangaJson["current-page"].intValue - 1;
// Set the page count
manga.pageCount = mangaJson["page-count"].intValue;
// Set the color and sharpness values
manga.saturation = CGFloat(mangaJson["saturation"].floatValue);
manga.brightness = CGFloat(mangaJson["brightness"].floatValue);
manga.contrast = CGFloat(mangaJson["contrast"].floatValue);
manga.sharpness = CGFloat(mangaJson["sharpness"].floatValue);
// Update the percent
manga.updatePercent();
}
// Set the manga's directory
manga.directory = currentFileFullPath;
/// The grid item we will add
let mangaGridItem : KMMangaGridItem = KMMangaGridItem();
// Update the grid item's manga
mangaGridItem.changeManga(manga);
// Add this manga
mangaGridController.addGridItem(mangaGridItem);
// Update the filters
mangaGridController.updateFilters();
// Create the new notification to tell the user the import has finished
let finishedNotification = NSUserNotification();
// Set the title
finishedNotification.title = "Komikan";
// Set the informative text
finishedNotification.informativeText = "Finished importing manga from \"" + currentFileFullPath + "\"";
// Set the notifications identifier to be an obscure string, so we can show multiple at once
finishedNotification.identifier = UUID().uuidString;
// Show the notification
NSUserNotificationCenter.default.deliver(finishedNotification);
}
}
}
}
}
| gpl-3.0 | 15282f3115185e5cffc606dec319e1b8 | 55.235714 | 237 | 0.521148 | 5.755117 | false | false | false | false |
stormpath/stormpath-sdk-swift | Stormpath/Social Login/FacebookLoginProvider.swift | 1 | 1907 | //
// FacebookLoginProvider.swift
// Stormpath
//
// Created by Edward Jiang on 3/7/16.
// Copyright © 2016 Stormpath. All rights reserved.
//
import Foundation
class FacebookLoginProvider: NSObject, LoginProvider {
var urlSchemePrefix = "fb"
var state = arc4random_uniform(10000000)
func authenticationRequestURL(_ application: StormpathSocialProviderConfiguration) -> URL {
let scopes = application.scopes ?? "email"
// Auth_type is re-request since we need to ask for email scope again if
// people decline the email permission. If it gets annoying because
// people keep asking for more scopes, we can change this.
let queryString = "client_id=\(application.appId)&redirect_uri=\(application.urlScheme)://authorize&response_type=token&scope=\(scopes)&state=\(state)&auth_type=rerequest".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
return URL(string: "https://www.facebook.com/dialog/oauth?\(queryString)")!
}
func getResponseFromCallbackURL(_ url: URL, callback: @escaping LoginProviderCallback) {
if(url.queryDictionary["error"] != nil) {
// We are not even going to callback, because the user never started
// the login process in the first place. Error is always because
// people cancelled the FB login according to https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
return
}
// Get the access token, and check that the state is the same
guard let accessToken = url.fragmentDictionary["access_token"], url.fragmentDictionary["state"] == "\(state)" else {
callback(nil, StormpathError.InternalSDKError)
return
}
callback(LoginProviderResponse(data: accessToken, type: .accessToken), nil)
}
}
| apache-2.0 | 9387e17a9e8978e2bc9a34b1d163e784 | 44.380952 | 255 | 0.676285 | 4.729529 | false | false | false | false |
realtime-framework/RealtimeMessaging-iOS-Swift | Pod/Classes/Balancer.swift | 1 | 2426 | //
// Balancer
//
// Balancer.swift
// Balancer
//
// Created by João Caixinha.
//
//
import Foundation
let BALANCER_RESPONSE_PATTERN: String = "^var SOCKET_SERVER = \\\"(.*?)\\\";$"
/**
* Request's balancer for connection url
*/
class Balancer: NSObject {
var theCallabck: ((String?) -> ())?
init(cluster aCluster: String?, serverUrl url: String?, isCluster: Bool?, appKey anAppKey: String?, callback aCallback: (aBalancerResponse: String?) -> Void) {
super.init()
theCallabck = aCallback
var parsedUrl: String? = aCluster
if isCluster == false {
aCallback(aBalancerResponse: url)
}
else {
parsedUrl = parsedUrl?.stringByAppendingString("?appkey=")
parsedUrl = parsedUrl?.stringByAppendingString(anAppKey!)
let request: NSURLRequest = NSURLRequest(URL: NSURL(string: parsedUrl!)!)
NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {
(receivedData:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error != nil{
self.theCallabck!(nil)
return
}
else if receivedData != nil {
do{
let myString: NSString? = String(data: receivedData!, encoding: NSUTF8StringEncoding)
let resRegex: NSRegularExpression = try NSRegularExpression(pattern: BALANCER_RESPONSE_PATTERN, options: NSRegularExpressionOptions.CaseInsensitive)
let resMatch: NSTextCheckingResult? = resRegex.firstMatchInString(myString! as String, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, myString!.length))
if resMatch != nil {
let strRange: NSRange? = resMatch!.rangeAtIndex(1)
if strRange != nil && strRange?.length <= myString?.length {
self.theCallabck!(myString!.substringWithRange(strRange!) as String)
return
}
}
}catch{
self.theCallabck!(nil)
return
}
}
self.theCallabck!(nil)
}).resume()
}
}
}
| mit | 5848be930dcf3ac26679cae5fd877b18 | 38.129032 | 194 | 0.534021 | 5.260304 | false | false | false | false |
dongdongSwift/guoke | gouke/果壳/DetailCell1.swift | 1 | 1459 | //
// DetailCell2.swift
// 果壳
//
// Created by qianfeng on 2016/10/27.
// Copyright © 2016年 张冬. All rights reserved.
//
import UIKit
class DetailCell1: UITableViewCell {
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var sourcename: UILabel!
@IBOutlet weak var content: UILabel!
// var data:[resultModel]?{
// didSet{
// showData()
// }
// }
// func showData(){
//// self.content.text=data
// }
class func createDeatilCell1(tableView:UITableView,atIndexPath indexPath:NSIndexPath,sourceData:sourceDataModel?)->DetailCell1{
let cell=tableView.dequeueReusableCellWithIdentifier("DetailCell1", forIndexPath: indexPath) as! DetailCell1
// let sourcedata=dataAll?.result[indexPath.section].source_data
cell.content.text=sourceData!.summary
cell.sourcename.text=sourceData!.title
cell.icon.kf_setImageWithURL(NSURL(string: (sourceData?.image)!))
return cell
}
override func awakeFromNib() {
super.awakeFromNib()
self.icon.layer.cornerRadius=38.5
self.icon.layer.borderWidth=1
self.layer.borderColor=UIColor.grayColor().CGColor
self.icon.clipsToBounds=true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 9390b69b77df78eaeb1722876f175250 | 25.814815 | 131 | 0.651243 | 4.113636 | false | false | false | false |
ndevenish/KerbalHUD | KerbalHUD/SphericalPoint.swift | 1 | 6945 | //
// SphericalPoint.swift
// KerbalHUD
//
// Created by Nicholas Devenish on 29/08/2015.
// Copyright © 2015 Nicholas Devenish. All rights reserved.
//
import Foundation
import GLKit
//typealias SphericalPoint = (theta: GLfloat, phi: GLfloat, r: GLfloat)
//
public struct SphericalPoint : Equatable {
public var theta : GLfloat
public var phi : GLfloat
public var r : GLfloat
var lat : GLfloat { return (π/2 - phi) * 180/π }
var long : GLfloat { return theta * 180/π }
public init(fromCartesian from: GLKVector3) {
theta = atan2(from.y, from.x)
r = GLKVector3Length(from)
phi = acos(from.z/r)
}
public init(theta: GLfloat, phi: GLfloat, r: GLfloat) {
self.theta = theta
self.phi = phi
self.r = r
}
public init(lat: GLfloat, long: GLfloat, r: GLfloat) {
self.theta = long * π/180
self.phi = π/2 - (lat * π/180)
self.r = r
}
}
public func ==(left: SphericalPoint, right: SphericalPoint) -> Bool {
return left.theta == right.theta && left.phi == right.phi && left.r == right.r
}
public func GLKVector3Make(fromSpherical from: SphericalPoint) -> GLKVector3 {
return GLKVector3Make(
from.r*cos(from.theta)*sin(from.phi),
from.r*sin(from.theta)*sin(from.phi),
from.r*cos(from.phi))
}
public extension SphericalPoint {
var unitVectorPhi : GLKVector3 {
return GLKVector3Make(
cos(theta)*cos(phi),
sin(theta)*cos(phi),
-sin(phi))
}
var unitVectorTheta : GLKVector3 {
return GLKVector3Make(-sin(theta), cos(theta), 0)
}
var unitVectorR : GLKVector3 {
return GLKVector3Make(
cos(theta)*sin(phi),
sin(theta)*sin(phi),
cos(phi))
}
}
func modSq(of: GLKVector3) -> GLfloat
{
return GLKVector3DotProduct(of, of)
}
/// Casts an orthographic ray along the -r axis of the spherical point + 2D offset, and
/// returns the closest point of intersection (if there is one). Assumes a sphere
/// of radius 1 at the origin.
public func pointOffsetRayIntercept(sphericalPoint point: SphericalPoint, offset: Point2D, radius : Float = 1.0)
-> SphericalPoint?
{
// l = line direction
// o = line origin
// c = center point of sphere
// r = radius of sphere
let l = -point.unitVectorR
let o = GLKVector3Make(fromSpherical: point)
+ offset.x*point.unitVectorTheta
- offset.y*point.unitVectorPhi
let c = GLKVector3Make(0, 0, 0)
let r : GLfloat = radius
let sqrtPart = pow(l•(o-c), 2) - modSq(o-c) + r*r
if sqrtPart < 0 {
return nil
}
// We have at least one intersection. Calculate the smallest.
let dBoth = -(l•(o-c)) ± sqrt(sqrtPart)
let d = min(dBoth.0, dBoth.1)
// Calculate the point on the sphere of this point
let intersect = SphericalPoint(fromCartesian: o + d*l)
return SphericalPoint(theta: intersect.theta, phi: intersect.phi, r: r)
}
private enum BulkSpherePosition {
case Left
case Right
case Middle
}
extension DrawingTools {
func drawProjectedGridOntoSphere(
position position : SphericalPoint,
left: Float, bottom: Float, right: Float, top: Float,
xSteps : UInt, ySteps : UInt, slicePoint : Float)
{
// Work out if we are near the slice point
let shiftedPosition = position.theta == π ? π : cyc_mod(position.theta - slicePoint + π, m: 2*π) - π
let sphereDomain : BulkSpherePosition
if shiftedPosition < -120 * π/180 {
sphereDomain = .Left
} else if shiftedPosition > 120*π/180 {
sphereDomain = .Right
} else {
sphereDomain = .Middle
}
// Generate the grid projected onto the sphere
let geometry = projectGridOntoSphere(position: position, left: left, bottom: bottom, right: right, top: top, xSteps: xSteps, ySteps: ySteps)
// Flatten this into a data array, handling the slice shift
var data = geometry.flatMap { (pos: Point2D, uv: Point2D) -> [GLfloat] in
let theta : GLfloat
let shiftedThetaA = cyc_mod(pos.x - slicePoint + 180, m: 360)-180
let shiftedTheta = pos.x > 179 && shiftedThetaA == -180 ? 180 : shiftedThetaA
if sphereDomain == .Left && shiftedTheta > 120 {
theta = pos.x - 360
} else if sphereDomain == .Right && shiftedTheta < -120 {
theta = pos.x + 360
} else {
theta = pos.x
}
return [theta, pos.y, uv.x, uv.y]
}
// Load into a buffer object!
let array = createVertexArray(positions: 2, textures: 2)
glBufferData(
GLenum(GL_ARRAY_BUFFER), sizeof(GLfloat)*data.count,
&data, GLenum(GL_DYNAMIC_DRAW))
// Draw!
glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, GLsizei(geometry.count))
// Delete the array and buffer
bind(VertexArray.Empty)
deleteVertexArray(array)
}
}
func projectGridOntoSphere(position basePosition : SphericalPoint,
left: Float, bottom: Float, right: Float, top: Float,
xSteps : UInt, ySteps : UInt) -> [(pos: Point2D, uv: Point2D)]
{
let position = SphericalPoint(theta: basePosition.theta, phi: basePosition.phi, r: 60)
let bounds = FixedBounds(left: left, bottom: bottom, right: right, top: top)
let data = generateTriangleStripGrid(bounds, xSteps: xSteps, ySteps: ySteps)
let geometry = data.map { (pos : Point2D, uv: Point2D) -> (pos : Point2D, uv: Point2D) in
// let sphePos : SphericalPoint
guard let sphePos = pointOffsetRayIntercept(sphericalPoint: position,
offset: pos, radius: 59) else {
// let sphePos = pointOffsetRayIntercept(sphericalPoint: position,
// offset: pos, radius: 59)
fatalError()
}
return (Point2D(sphePos.long, sphePos.lat), uv)
}
return geometry
}
func generateTriangleStripGrid(bounds : Bounds, xSteps : UInt, ySteps : UInt)
-> [(pos: Point2D, uv: Point2D)]
{
var data : [(pos: Point2D, uv: Point2D)] = []
// Generate all the points on a grid for this
for iY in 0..<ySteps {
for iX in 0...xSteps {
let xFrac = Float(iX)/Float(xSteps)
let yFrac = Float(iY)/Float(ySteps)
// The offset points of this index specifically
let xOffset = bounds.size.w * xFrac + bounds.left
let yOffset = bounds.size.h * yFrac + bounds.bottom
let uv = Point2D(x: xFrac, y: yFrac)
// If we have data already, double-up the first vertex as we will
// need to do so for a triangle strip
if iX == 0 && data.count > 0 {
data.append((pos: Point2D(x: xOffset, y: yOffset), uv: uv))
}
data.append((Point2D(x: xOffset, y: yOffset), uv))
// Calculate the y of the next one up
let nextYFrac = Float(iY+1)/Float(ySteps)
let yOffset2 = bounds.size.h * nextYFrac + bounds.bottom
let uvUp = Point2D(x: xFrac, y: nextYFrac)
data.append((Point2D(x: xOffset, y: yOffset2), uvUp))
}
// Finish the triangle strip line
data.append(data.last!)
}
// Remove the last item as it will double up otherwise (empty triangle)
data.removeLast()
return data
}
| mit | 7fd73f6116ba1f51296572ce51cc2664 | 30.339367 | 144 | 0.650448 | 3.415187 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Idiomatic/ReturnValueFromVoidFunctionRuleExamples.swift | 1 | 6122 | internal struct ReturnValueFromVoidFunctionRuleExamples {
static let nonTriggeringExamples = [
Example("""
func foo() {
return
}
"""),
Example("""
func foo() {
return /* a comment */
}
"""),
Example("""
func foo() -> Int {
return 1
}
"""),
Example("""
func foo() -> Void {
if condition {
return
}
bar()
}
"""),
Example("""
func foo() {
return;
bar()
}
"""),
Example("func test() {}"),
Example("""
init?() {
guard condition else {
return nil
}
}
"""),
Example("""
init?(arg: String?) {
guard arg != nil else {
return nil
}
}
"""),
Example("""
func test() {
guard condition else {
return
}
}
"""),
Example("""
func test() -> Result<String, Error> {
func other() {}
func otherVoid() -> Void {}
}
"""),
Example("""
func test() -> Int? {
return nil
}
"""),
Example("""
func test() {
if bar {
print("")
return
}
let foo = [1, 2, 3].filter { return true }
return
}
"""),
Example("""
func test() {
guard foo else {
bar()
return
}
}
"""),
Example("""
func spec() {
var foo: Int {
return 0
}
"""),
Example(#"""
final class SearchMessagesDataSource: ValueCellDataSource {
internal enum Section: Int {
case emptyState
case messageThreads
}
internal func load(messageThreads: [MessageThread]) {
self.set(
values: messageThreads,
cellClass: MessageThreadCell.self,
inSection: Section.messageThreads.rawValue
)
}
internal func emptyState(isVisible: Bool) {
self.set(
cellIdentifiers: isVisible ? ["SearchMessagesEmptyState"] : [],
inSection: Section.emptyState.rawValue
)
}
internal override func configureCell(tableCell cell: UITableViewCell, withValue value: Any) {
switch (cell, value) {
case let (cell as MessageThreadCell, value as MessageThread):
cell.configureWith(value: value)
case (is StaticTableViewCell, is Void):
return
default:
assertionFailure("Unrecognized combo: \(cell), \(value).")
}
}
}
"""#, excludeFromDocumentation: true)
]
static let triggeringExamples = [
Example("""
func foo() {
↓return bar()
}
"""),
Example("""
func foo() {
↓return self.bar()
}
"""),
Example("""
func foo() -> Void {
↓return bar()
}
"""),
Example("""
func foo() -> Void {
↓return /* comment */ bar()
}
"""),
Example("""
func foo() {
↓return
self.bar()
}
"""),
Example("""
func foo() {
variable += 1
↓return
variable += 1
}
"""),
Example("""
func initThing() {
guard foo else {
↓return print("")
}
}
"""),
Example("""
// Leading comment
func test() {
guard condition else {
↓return assertionfailure("")
}
}
"""),
Example("""
func test() -> Result<String, Error> {
func other() {
guard false else {
↓return assertionfailure("")
}
}
func otherVoid() -> Void {}
}
"""),
Example("""
func test() {
guard conditionIsTrue else {
sideEffects()
return // comment
}
guard otherCondition else {
↓return assertionfailure("")
}
differentSideEffect()
}
"""),
Example("""
func test() {
guard otherCondition else {
↓return assertionfailure(""); // comment
}
differentSideEffect()
}
"""),
Example("""
func test() {
if x {
↓return foo()
}
bar()
}
"""),
Example("""
func test() {
switch x {
case .a:
↓return foo() // return to skip baz()
case .b:
bar()
}
baz()
}
"""),
Example("""
func test() {
if check {
if otherCheck {
↓return foo()
}
}
bar()
}
"""),
Example("""
func test() {
↓return foo()
}
"""),
Example("""
func test() {
↓return foo({
return bar()
})
}
"""),
Example("""
func test() {
guard x else {
↓return foo()
}
bar()
}
"""),
Example("""
func test() {
let closure: () -> () = {
return assert()
}
if check {
if otherCheck {
return // comments are fine
}
}
↓return foo()
}
""")
]
}
| mit | ed344e61e56b404f2fe47b119eeba1bb | 21.794007 | 103 | 0.355899 | 5.752363 | false | true | false | false |
ken0nek/MaterialKit | Example/MaterialKit/TableViewController.swift | 3 | 1455 | //
// TableViewController.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/16/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var labels = ["MKButton", "MKTextField", "MKTableViewCell", "MKTextView", "MKColor", "MKLayer", "MKAlert", "MKCheckBox"]
var rippleLocations: [MKRippleLocation] = [.TapLocation, .TapLocation, .Center, .Left, .Right, .TapLocation, .TapLocation, .TapLocation]
var circleColors = [UIColor.MKColor.LightBlue, UIColor.MKColor.Grey, UIColor.MKColor.LightGreen]
override func viewDidLoad() {
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("MyCell") as! MyCell
cell.setMessage(labels[indexPath.row % labels.count])
cell.rippleLocation = rippleLocations[indexPath.row % labels.count]
let index = indexPath.row % circleColors.count
cell.rippleLayerColor = circleColors[index]
return cell
}
} | mit | d77cebc6ab5bd34c4c89e8f354687816 | 37.315789 | 140 | 0.700344 | 4.739414 | false | false | false | false |
jeremiahyan/ResearchKit | ResearchKitTests/ORKSignatureResultTests.swift | 2 | 2632 | /*
Copyright (c) 2019, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import XCTest
class ORKSignatureResultTests: XCTestCase {
var result: ORKSignatureResult!
var image: UIImage!
var path: UIBezierPath!
let date = Date()
override func setUp() {
super.setUp()
let bundle = Bundle(identifier: "org.researchkit.ResearchKit")
image = UIImage(named: "heartbeat", in: bundle, compatibleWith: .none)
path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 50, height: 50))
result = ORKSignatureResult(signatureImage: image, signaturePath: [path])
}
func testProperties() {
XCTAssertEqual(result.signatureImage, image)
XCTAssertEqual(result.signaturePath, [path])
}
func testIsEqual() {
result.startDate = date
result.endDate = date
let newResult = ORKSignatureResult(signatureImage: image, signaturePath: [path])
newResult.startDate = date
newResult.endDate = date
XCTAssert(result.isEqual(newResult))
}
}
| bsd-3-clause | 2ddc08f56878d99dfbcea82ce9265961 | 41.451613 | 88 | 0.738222 | 4.838235 | false | true | false | false |
mhplong/Projects | iOS/ServiceTracker/ServiceTimeTracker/ViewController.swift | 1 | 11803 | //
// ViewController.swift
// ServiceTimeTracker
//
// Created by Mark Long on 5/11/16.
// Copyright © 2016 Mark Long. All rights reserved.
//
import UIKit
import CoreData
import MessageUI
class ViewController: UIViewController, UITableViewDelegate, MFMailComposeViewControllerDelegate {
//MARK: Variables
@IBOutlet var timeLabel : UILabel!
@IBOutlet var momentTimeLabel : UILabel!
@IBOutlet var momentTable : MomentTableView!
var timer = NSTimer()
var lastStart = NSTimeInterval()
var lastMoment = NSTimeInterval()
var inSession = false
var sessionNumber = 1
var sessionNamePrefix = "Session"
var sessionId = "Session 1"
//MARK: Class Overrides
override func viewDidLoad() {
super.viewDidLoad()
//loadState()
setupDefaults()
//setupNotifications()
// Do any additional setup after loading the view, typically from a nib.
}
func setupDefaults() {
let prefs = NSUserDefaults.standardUserDefaults()
let resetDatabase = prefs.boolForKey("reset_data_pref")
let namePrefix = prefs.stringForKey("session_name_prefix_pref")
if resetDatabase {
databaseDeleteSessions()
saveDatabase()
prefs.setBool(false, forKey: "reset_data_pref")
}
if namePrefix != nil {
sessionNamePrefix = namePrefix!
}
}
func setupNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(saveState), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
func saveState() {
if inSession {
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(lastStart, forKey: "saved_start")
prefs.setBool(true, forKey: "inSession")
prefs.setObject(sessionId, forKey: "session_id")
}
saveDatabase()
}
func loadState() {
let prefs = NSUserDefaults.standardUserDefaults()
lastStart = prefs.objectForKey("saved_start") as? NSTimeInterval ?? lastStart
inSession = prefs.boolForKey("inSession")
if inSession {
sessionId = prefs.objectForKey("session_id") as? String ?? "Session 1"
startTimer()
}
}
//MARK: IBActions
@IBAction func start(sender: UIButton) {
if !inSession {
beginSession()
startTimer()
}
}
@IBAction func newMoment(sender: UIButton) {
if inSession {
stopTimer()
beginNewMoment()
startTimer()
}
}
@IBAction func stop(sender: UIButton) {
if inSession {
stopTimer()
beginNewMoment()
momentTable.reloadData()
endSession()
}
}
@IBAction func export(sender: UIButton) {
if let sessions = getSessions() {
var bodyMessage = ""
for session in sessions {
let lastMent = session.moments?.lastObject as! Moment
let lastInterval = lastMent.end_time!.timeIntervalSinceDate(session.date!)
let elapsedDate = NSDate(timeIntervalSinceReferenceDate: lastInterval)
bodyMessage += "\n\(session.name!):\t\(dateToString(elapsedDate, elapsed: true))\n"
bodyMessage += "-----------------------------------------------------------------------\n"
bodyMessage += "Start\tEnd\tElapsed\tName\n"
bodyMessage += "-----------------------------------------------------------------------\n"
for elem in session.moments! {
let ment = elem as! Moment
let start = ment.start_time!
let end = ment.end_time!
let startText = dateToString(dateToElapsedDate(session.date!, end: start), elapsed: true)
let stopText = dateToString(dateToElapsedDate(session.date!, end: end), elapsed: true)
let elapsed = dateToString(dateToElapsedDate(start, end: end), elapsed: true)
bodyMessage += "\(startText)\t\(stopText)\t\(elapsed)\t\(ment.name!)\n"
}
}
let mailCompose = MFMailComposeViewController()
mailCompose.setSubject("ServiceTimeTracker Report")
mailCompose.setMessageBody(bodyMessage, isHTML: false)
mailCompose.mailComposeDelegate = self
self.presentViewController(mailCompose, animated: true, completion: nil)
}
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: NSTimer methods
func update() {
let offsetNow = NSDate().timeIntervalSinceReferenceDate
timeLabel.text = elapsedTime(fromInterval: lastStart, toInterval: offsetNow)
momentTimeLabel.text = elapsedTime(fromInterval: lastMoment, toInterval: offsetNow)
}
func startTimer() {
if !timer.valid {
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}
}
func stopTimer() {
timer.invalidate()
}
//MARK: Session/Moment Methds
func beginSession() {
inSession = true
lastStart = NSDate.timeIntervalSinceReferenceDate()
lastMoment = NSDate.timeIntervalSinceReferenceDate()
self.databaseBeginSession()
}
func endSession() {
inSession = false
saveDatabase()
}
func beginNewMoment() {
insertMoment()
momentTable.reloadData()
lastMoment = NSDate.timeIntervalSinceReferenceDate()
}
//MARK: momentTableView Methods
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(12.0)
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.font = UIFont.systemFontOfSize(12)
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let dbContext = getDatabaseContext() {
do {
let sessionFetch = NSFetchRequest(entityName: "Session")
let sortDescripter = NSSortDescriptor(key: "id", ascending: false)
sessionFetch.sortDescriptors = [sortDescripter]
if let modelSessions = try dbContext.executeFetchRequest(sessionFetch) as? [Session] {
if var momentsArray = modelSessions[indexPath.section].moments?.array as? [Moment] {
momentsArray = momentsArray.reverse()
let moment = momentsArray[indexPath.row]
askForMomentName(moment)
}
}
} catch {
print("Error: \(error)")
}
}
}
func askForMomentName(moment: Moment) {
let alert = UIAlertController(title: "Moment", message: "Enter Name", preferredStyle: .Alert)
let changeNameAction = UIAlertAction(title: "Ok", style: .Destructive) {
action in
if alert.textFields!.first!.text! != "" {
moment.name = alert.textFields!.first!.text!
self.momentTable.reloadData()
}
}
alert.addAction(changeNameAction)
alert.addTextFieldWithConfigurationHandler(nil)
self.presentViewController(alert, animated: true, completion: nil)
}
//MARK: Change Session Name
func askForSessionName() {
let alert = UIAlertController(title: "Session", message: "Enter Name", preferredStyle: .Alert)
let changeNameAction = UIAlertAction(title: "Ok", style: .Destructive) {
action in
if alert.textFields!.first!.text! != "" {
self.sessionId = alert.textFields!.first!.text!
}
}
alert.addAction(changeNameAction)
alert.addTextFieldWithConfigurationHandler(nil)
self.presentViewController(alert, animated: true, completion: nil)
}
//MARK: Database methods
func setSessionId() {
if let dbContext = getDatabaseContext() {
do {
let sessionFetch = NSFetchRequest(entityName: "Session")
let results = try dbContext.executeFetchRequest(sessionFetch)
sessionNumber = results.count
sessionId = "\(sessionNamePrefix) \(sessionNumber)"
} catch {
print("Error accessing database: \(error)")
}
}
}
func databaseBeginSession() {
if let dbContext = getDatabaseContext() {
if let session1 = Session(insertIntoManagedObjectContext: dbContext) {
setSessionId()
askForSessionName()
session1.id = NSNumber(integer: sessionNumber)
session1.date = NSDate(timeIntervalSinceReferenceDate: lastStart)
}
}
}
func databaseDeleteSessions() {
if let dbContext = getDatabaseContext() {
if let sessions = getSessions() {
for session in sessions {
dbContext.deleteObject(session)
}
}
}
}
func getDatabaseContext() -> NSManagedObjectContext? {
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
return delegate.managedObjectContext
} else {
return nil
}
}
func insertMoment() {
if let dbContext = getDatabaseContext() {
let sessionFetch = NSFetchRequest(entityName: "Session")
sessionFetch.predicate = NSPredicate(format: "id == %i", sessionNumber)
let results = getSessions(sessionFetch)
if let session = results!.first {
session.name = sessionId
if let ment = Moment(insertIntoManagedObjectContext: dbContext) {
ment.name = "initial"
ment.start_time = NSDate(timeIntervalSinceReferenceDate: lastMoment)
ment.end_time = NSDate()
session.addMoment(ment)
}
}
}
}
func getSessions(fetchRequest: NSFetchRequest? = nil) -> [Session]? {
if let dbContext = getDatabaseContext() {
do {
var request = fetchRequest
if request == nil {
request = NSFetchRequest(entityName: "Session")
}
let results = try dbContext.executeFetchRequest(request!)
if let sessions = results as? [Session] {
return sessions
}
} catch {
print("Error: \(error)")
}
}
return nil
}
func saveDatabase() {
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
delegate.saveContext()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | fd92c2d59e07dac195e7d87a6b3866bc | 33.508772 | 158 | 0.567361 | 5.443727 | false | false | false | false |
caxco93/peliculas | DemoWS/WS/CDMWebTranslator.swift | 1 | 1595 | //
// CDMWebTranslator.swift
// Survey
//
// Created by Benjamin Eyzaguirre on 8/04/16.
// Copyright © 2016 Core Data Media. All rights reserved.
//
import UIKit
class CDMWebTranslator: NSObject {
class func translateSucursalBE(diccionario objDiccionario : NSDictionary) -> SucursalBE{
let objSucursal = SucursalBE()
objSucursal.sucursal_id = objDiccionario["idSucursal"] as? String
objSucursal.sucursal_nombre = objDiccionario["nombreSucursal"] as? String
return objSucursal
}
class func translateHorarioBE(diccionario objDiccionario : NSDictionary) -> HorarioBE{
let objHorario = HorarioBE()
objHorario.horario_idSucursal = objDiccionario["idSucursal"] as? String
objHorario.horario_idPelicula = objDiccionario["idPelicula"] as? String
objHorario.horario_horario = objDiccionario["horario"] as? String
return objHorario
}
class func translatePeliculaBE(diccionario objDiccionario : NSDictionary) -> PeliculaBE{
let objPelicula = PeliculaBE()
objPelicula.pelicula_id = objDiccionario["idPelicula"] as? String
objPelicula.pelicula_nombre = objDiccionario["nombreComercial"] is NSNull ? "-" : objDiccionario["nombreComercial"] as? String
objPelicula.pelicula_resumen = objDiccionario["resumen"] as? String
objPelicula.pelicula_urlImagen = objDiccionario["aficheOficial"] as? String
return objPelicula
}
}
| mit | e90771595b584c86efdd3c270b7b1dea | 32.208333 | 143 | 0.653701 | 3.573991 | false | false | false | false |
khizkhiz/swift | stdlib/public/core/Unmanaged.swift | 1 | 3730 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type for propagating an unmanaged object reference.
///
/// When you use this type, you become partially responsible for
/// keeping the object alive.
public struct Unmanaged<Instance : AnyObject> {
internal unowned(unsafe) var _value: Instance
@_transparent
internal init(_private: Instance) { _value = _private }
/// Unsafely turn an opaque C pointer into an unmanaged
/// class reference.
///
/// This operation does not change reference counts.
///
/// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue()
@_transparent
@warn_unused_result
public static func fromOpaque(value: OpaquePointer) -> Unmanaged {
// Null pointer check is a debug check, because it guards only against one
// specific bad pointer value.
_stdlibAssert(
value != nil,
"attempt to create an Unmanaged instance from a null pointer")
return Unmanaged(_private: unsafeBitCast(value, to: Instance.self))
}
/// Create an unmanaged reference with an unbalanced retain.
/// The object will leak if nothing eventually balances the retain.
///
/// This is useful when passing an object to an API which Swift
/// does not know the ownership rules for, but you know that the
/// API expects you to pass the object at +1.
@_transparent
@warn_unused_result
public static func passRetained(value: Instance) -> Unmanaged {
return Unmanaged(_private: value).retain()
}
/// Create an unmanaged reference without performing an unbalanced
/// retain.
///
/// This is useful when passing a reference to an API which Swift
/// does not know the ownership rules for, but you know that the
/// API expects you to pass the object at +0.
///
/// CFArraySetValueAtIndex(.passUnretained(array), i,
/// .passUnretained(object))
@_transparent
@warn_unused_result
public static func passUnretained(value: Instance) -> Unmanaged {
return Unmanaged(_private: value)
}
/// Get the value of this unmanaged reference as a managed
/// reference without consuming an unbalanced retain of it.
///
/// This is useful when a function returns an unmanaged reference
/// and you know that you're not responsible for releasing the result.
@warn_unused_result
public func takeUnretainedValue() -> Instance {
return _value
}
/// Get the value of this unmanaged reference as a managed
/// reference and consume an unbalanced retain of it.
///
/// This is useful when a function returns an unmanaged reference
/// and you know that you're responsible for releasing the result.
@warn_unused_result
public func takeRetainedValue() -> Instance {
let result = _value
release()
return result
}
/// Perform an unbalanced retain of the object.
@_transparent
public func retain() -> Unmanaged {
Builtin.retain(_value)
return self
}
/// Perform an unbalanced release of the object.
@_transparent
public func release() {
Builtin.release(_value)
}
#if _runtime(_ObjC)
/// Perform an unbalanced autorelease of the object.
@_transparent
public func autorelease() -> Unmanaged {
Builtin.autorelease(_value)
return self
}
#endif
}
| apache-2.0 | 85ce38b70cc84f146c445f3996d6c01d | 32.603604 | 80 | 0.667828 | 4.769821 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseGenericBlockTableViewCell.swift | 1 | 2312 | //
// CourseHTMLTableViewCell.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 14/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
class CourseGenericBlockTableViewCell : UITableViewCell, CourseBlockContainerCell {
private let content = CourseOutlineItemView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(content)
content.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(contentView)
}
}
var block : CourseBlock? = nil {
didSet {
content.setTitleText(block?.displayName)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseHTMLTableViewCell: CourseGenericBlockTableViewCell {
static let identifier = "CourseHTMLTableViewCellIdentifier"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style : style, reuseIdentifier : reuseIdentifier)
content.setContentIcon(Icon.CourseHTMLContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseProblemTableViewCell : CourseGenericBlockTableViewCell {
static let identifier = "CourseProblemTableViewCellIdentifier"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style : style, reuseIdentifier : reuseIdentifier)
content.setContentIcon(Icon.CourseProblemContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class CourseUnknownTableViewCell: CourseGenericBlockTableViewCell {
static let identifier = "CourseUnknownTableViewCellIdentifier"
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
content.leadingIconColor = OEXStyles.sharedStyles().neutralBase()
content.setContentIcon(Icon.CourseUnknownContent)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | a6b274ee205397bb570cccef044e6b48 | 29.421053 | 83 | 0.704152 | 5.137778 | false | false | false | false |
hirohisa/RxSwift | RxSwift/RxSwift/Observables/Implementations/Debug.swift | 11 | 1646 | //
// Debug.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Debug_<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = Debug<Element>
let parent: Parent
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
let maxEventTextLength = 40
let ellipsis = "..."
let eventText = "\(event)"
let eventNormalized = count(eventText) > maxEventTextLength
? prefix(eventText, maxEventTextLength / 2) + "..." + suffix(eventText, maxEventTextLength / 2)
: eventText
println("[\(parent.identifier)] -> Event \(eventNormalized)")
trySend(observer, event)
}
override func dispose() {
println("[\(parent.identifier)] dispose")
super.dispose()
}
}
class Debug<Element> : Producer<Element> {
let identifier: String
let source: Observable<Element>
init(identifier: String, source: Observable<Element>) {
self.identifier = identifier
self.source = source
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
println("[\(identifier)] subscribed")
let sink = Debug_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribeSafe(sink)
}
} | mit | 89be10c77746db23b071a28826fa0c2a | 28.410714 | 145 | 0.617861 | 4.389333 | false | false | false | false |
oettam/camera-controls-demo | Camera/ExposureViewController.swift | 1 | 3178 | //
// ExposureViewController.swift
// Camera
//
// Created by Matteo Caldari on 05/02/15.
// Copyright (c) 2015 Matteo Caldari. All rights reserved.
//
import UIKit
import CoreMedia
class ExposureViewController: UIViewController, CameraControlsViewControllerProtocol, CameraSettingValueObserver {
@IBOutlet var modeSwitch:UISwitch!
@IBOutlet var biasSlider:UISlider!
@IBOutlet var durationSlider:UISlider!
@IBOutlet var isoSlider:UISlider!
var cameraController:CameraController? {
willSet {
if let cameraController = cameraController {
cameraController.unregisterObserver(observer: self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.unregisterObserver(observer: self, property: CameraControlObservableSettingExposureDuration)
cameraController.unregisterObserver(observer: self, property: CameraControlObservableSettingISO)
}
}
didSet {
if let cameraController = cameraController {
cameraController.registerObserver(observer: self, property: CameraControlObservableSettingExposureTargetOffset)
cameraController.registerObserver(observer: self, property: CameraControlObservableSettingExposureDuration)
cameraController.registerObserver(observer: self, property: CameraControlObservableSettingISO)
}
}
}
override func viewDidLoad() {
setInitialValues()
}
@IBAction func modeSwitchValueChanged(sender:UISwitch) {
if sender.isOn {
cameraController?.enableContinuousAutoExposure()
}
else {
cameraController?.setCustomExposureWithDuration(duration: durationSlider.value)
}
updateSliders()
}
@IBAction func sliderValueChanged(sender:UISlider) {
switch sender {
case biasSlider:
cameraController?.setExposureTargetBias(bias: sender.value)
case durationSlider:
cameraController?.setCustomExposureWithDuration(duration: sender.value)
case isoSlider:
cameraController?.setCustomExposureWithISO(iso: sender.value)
default: break
}
}
func cameraSetting(setting: String, valueChanged value: AnyObject) {
if setting == CameraControlObservableSettingExposureDuration {
if let durationValue = value as? NSValue {
let duration = CMTimeGetSeconds(durationValue.timeValue)
durationSlider.value = Float(duration)
}
}
else if setting == CameraControlObservableSettingISO {
if let iso = value as? Float {
isoSlider.value = Float(iso)
}
}
}
func setInitialValues() {
if isViewLoaded && cameraController != nil {
if let autoExposure = cameraController?.isContinuousAutoExposureEnabled() {
modeSwitch.isOn = autoExposure
updateSliders()
}
if let currentDuration = cameraController?.currentExposureDuration() {
durationSlider.value = currentDuration
}
if let currentISO = cameraController?.currentISO() {
isoSlider.value = currentISO
}
if let currentBias = cameraController?.currentExposureTargetOffset() {
biasSlider.value = currentBias
}
}
}
func updateSliders() {
for slider in [durationSlider, isoSlider] as [UISlider] {
slider.isEnabled = !modeSwitch.isOn
}
}
}
| mit | 0a6cba07696ddf952795eba96bbfdfa5 | 28.425926 | 117 | 0.746067 | 4.639416 | false | false | false | false |
ruter/Strap-in-Swift | SocialMedia/SocialMedia/DetailViewController.swift | 1 | 2358 | //
// DetailViewController.swift
// SocialMedia
//
// Created by Ruter on 16/4/14.
// Copyright © 2016年 Ruter. All rights reserved.
//
import UIKit
import Social
class DetailViewController: UIViewController {
@IBOutlet weak var detailImageView: UIImageView!
var didTapped = false
var detailItem: String? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
self.title = detail
if let imageView = self.detailImageView {
imageView.image = UIImage(named: detail)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
// Can set selector as shareToFB
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: #selector(shareTapped))
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
self.view.addGestureRecognizer(tapGestureRecognizer)
}
func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
if didTapped {
didTapped = false
self.view.backgroundColor = UIColor.whiteColor()
navigationController?.navigationBarHidden = false
} else {
didTapped = true
self.view.backgroundColor = UIColor.blackColor()
navigationController?.navigationBarHidden = true
}
}
}
func shareTapped() {
let vc = UIActivityViewController(activityItems: [detailImageView.image!], applicationActivities: [])
vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
presentViewController(vc, animated: true, completion: nil)
}
func shareToFB() {
let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
vc.setInitialText("Hey! This picture is great!")
vc.addImage(detailImageView.image!)
vc.addURL(NSURL(string: "http://www.photolib.noaa.gov/nssl"))
presentViewController(vc, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | f9c9d6f6c4c7526bbf92f5eab1f5de64 | 27.719512 | 131 | 0.691295 | 4.947479 | false | false | false | false |
kareman/FileSmith | Sources/FileSmith/Paths.swift | 1 | 19652 | //
// Paths.swift
// FileSmith
//
// Created by Kåre Morstøl on 29/11/2016.
//
import Foundation
public let pathseparator = "/"
let homedir = NSHomeDirectoryForUser(NSUserName())!
let homedircomponents = homedir.components(separatedBy: pathseparator)
/// The location of an item _which may or may not exist_ in the local file system.
/// It is either a DirectoryPath or a FilePath.
public protocol Path: CustomStringConvertible {
/// The individual parts of the absolute version of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
var components: [String] { get }
/// The individual parts of the relative part (if any) of this path.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do baseComponents.
var relativeComponents: [String]? { get }
/// The individual parts of the base part (if any) of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do relativeComponents.
var baseComponents: [String]? { get }
init(absolute components: [String])
init(base: [String], relative: [String])
init(_ stringpath: String)
init?(_ url: URL)
}
// MARK: Structs.
/// The path to a file system item of unknown type.
public struct AnyPath: Path {
private let _components: [String]
private let _relativestart: Array<String>.Index?
/// Creates an absolute path to an item from (but not including) the root folder through all the
/// directories listed in the array.
/// - Parameter components: The names of the directories in the path, ending with the item name. Each name must not be empty or contain only a '.', and any '..' must be at the beginning. Cannot be empty.
public init(absolute components: [String]) {
self._components = components
_relativestart = nil
}
/// Creates a relative path to an item, from the provided base.
/// Each name in the parameter arrays must not be empty or contain only a '.', and any '..' must be at the beginning.
/// - Parameter base: The names of the directories in the base, in order.
/// - Parameter relative: The names of the directories in the relative part, ending with the item name. Cannot be empty.
public init(base: [String], relative: [String]) {
_components = base + relative
_relativestart = base.endIndex
}
/// The individual parts of the relative part (if any) of this path.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do baseComponents.
public var relativeComponents: [String]? {
return _relativestart.map { Array(_components.suffix(from: $0)) }
}
/// The individual parts of the base part (if any) of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do relativeComponents.
public var baseComponents: [String]? {
return _relativestart.map { Array(_components.prefix(upTo: $0)) }
}
/// The individual parts of the absolute version of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
public var components: [String] {
if let rel = _relativestart, rel != _components.endIndex, _components[rel] == ".." {
return fixDotDots(_components)
}
return _components
}
}
/// The path to either a directory or the symbolic link to a directory.
public struct DirectoryPath: Path {
private let _path: AnyPath
/// Creates an absolute path to a directory from (but not including) the root folder through all the
/// directories listed in the array.
/// - Parameter components: The names of the directories in the path, in order. Each name must not be empty or contain only a '.', and any '..' must be at the beginning.
public init(absolute components: [String]) {
_path = AnyPath(absolute: components)
}
/// Creates a relative path to a directory, from the provided base.
/// Each name in the parameter arrays must not be empty or contain only a '.', and any '..' must be at the beginning.
/// - Parameter base: The names of the directories in the base, in order.
/// - Parameter relative: The names of the directories in the relative part, in order. If empty the path refers to the base directory.
public init(base: [String], relative: [String]) {
_path = AnyPath(base: base, relative: relative)
}
/// The individual parts of the relative part (if any) of this path.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do baseComponents.
public var relativeComponents: [String]? {
return _path.relativeComponents
}
/// The individual parts of the base part (if any) of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do relativeComponents.
public var baseComponents: [String]? {
return _path.baseComponents
}
/// The individual parts of the absolute version of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
public var components: [String] {
return _path.components
}
}
/// The path to a file system item which is not a directory or the symbolic link to a directory.
public struct FilePath: Path {
private let _path: AnyPath
/// Creates an absolute path to a file from (but not including) the root folder through all the
/// directories listed in the array.
/// - Parameter components: The names of the directories in the path, ending with the file name. Each name must not be empty or contain only a '.', and any '..' must be at the beginning. Cannot be empty.
public init(absolute components: [String]) {
_path = AnyPath(absolute: components)
}
/// Creates a relative path to a file, from the provided base.
/// Each name in the parameter arrays must not be empty or contain only a '.', and any '..' must be at the beginning.
/// - Parameter base: The names of the directories in the base, in order.
/// - Parameter relative: The names of the directories in the relative part, ending with the file name. Cannot be empty.
public init(base: [String], relative: [String]) {
_path = AnyPath(base: base, relative: relative)
}
/// The individual parts of the relative part (if any) of this path.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do baseComponents.
public var relativeComponents: [String]? {
return _path.relativeComponents
}
/// The individual parts of the base part (if any) of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
/// If this exists, then so do relativeComponents.
public var baseComponents: [String]? {
return _path.baseComponents
}
/// The individual parts of the absolute version of this path, from (but not including) the root folder.
/// Any '..' not at the beginning have been resolved, and there are no empty parts or only '.'.
public var components: [String] {
return _path.components
}
}
// MARK: Initialise from String.
/// Removes any pair of [<directory name>, '..'].
/// - Returns: an array where any '..' are only at the beginning.
func fixDotDots(_ components: [String]) -> [String] {
guard let firstdotdot = components.firstIndex(of: "..") else { return components }
var components = components
var i = max(1,firstdotdot)
while i < components.endIndex {
if i > 0 && components[i] == ".." && components[i-1] != ".." {
components.removeSubrange((i-1)...i)
i -= 1
} else {
i += 1
}
}
return components
}
/// Creates an array of path components from a string.
func parseComponents(_ stringpath: String) -> (components: [String], isRelative: Bool) {
func prepareComponents<C: Collection>(_ components: C) -> [String]
where C.Element == String {
return fixDotDots(components.filter { !$0.isEmpty && $0 != "." })
}
let stringpath = stringpath.isEmpty ? "." : stringpath
let components = stringpath.components(separatedBy: pathseparator)
if components.first == "" {
return (prepareComponents(components), false)
} else if components.first == "~" {
return (prepareComponents(homedircomponents + components.dropFirst()), false)
}
return (prepareComponents(components), true)
}
extension Path {
/// Creates a relative path from two strings.
///
/// - Parameters:
/// - base: The path to the directory this path is relative to. If it does not begin with a '/' it will be appended to the current working directory.
/// - relative: The relative path. It doesn't matter if this begins with a '/'.
public init(base: String, relative: String) {
let rel = Self("/"+relative)
let base = DirectoryPath(base)
self.init(base: base.components, relative: rel.components)
}
/// Creates a path from a string.
/// If the string begins with a '/' it is absolute, otherwise it is relative to the current working directory.
public init(_ stringpath: String) {
let (components, isrelative) = parseComponents(stringpath)
if isrelative {
let current = FileManager().currentDirectoryPath.components(separatedBy: pathseparator).dropFirst().array
self.init(base: current, relative: components)
} else {
self.init(absolute: components)
}
if self is FilePath {
precondition(!stringpath.hasSuffix(pathseparator),
"Trying to create a FilePath from \(stringpath) (ending in '\(pathseparator)'). If this is a directory, use DirectoryPath instead. If it is a file, remove the trailing \(pathseparator). If it is unknown, use AnyPath")
}
}
}
extension AnyPath: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(stringLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
extension FilePath: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(stringLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
extension DirectoryPath: ExpressibleByStringLiteral {
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
public init(stringLiteral value: String) {
self.init(value)
}
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
/// Tries to create a new Path by detecting if it is a directory or a file.
///
/// If the path ends in a '/', it is a directory.
/// If the path exists, check in the file system.
/// Otherwise return nil.
public func path(detectTypeOf stringpath: String) -> Path? {
guard !stringpath.hasSuffix(pathseparator) else {
return DirectoryPath(stringpath)
}
guard let type = FileType(stringpath) else {
return nil
}
return type == .directory ? DirectoryPath(stringpath) : FilePath(stringpath)
}
// MARK: Common methods.
extension Path {
/// Creates a new path from another path.
public init(_ inpath: Path) {
if let base = inpath.baseComponents, let rel = inpath.relativeComponents {
self.init(base: base, relative: rel)
} else {
self.init(absolute: inpath.components)
}
}
/// The relative or absolute string representation of this path.
public var string: String {
return relativeString ?? absoluteString
}
/// The relative or absolute string representation of this path.
public var description: String {
return string
}
/// The base of this path, if it is relative. Otherwise nil.
public var base: DirectoryPath? {
return baseComponents.map { DirectoryPath(absolute: $0) }
}
/// The string representation of the relative part of this path, if any.
public var relativeString: String? {
let result = relativeComponents?.joined(separator: pathseparator)
return result?.isEmpty == true ? "." : result
}
/// The string representation of the absolute version of this path.
public var absoluteString: String {
return pathseparator + components.joined(separator: pathseparator)
}
/// The main part of this path (the last component).
public var name: String {
return components.last ?? "/"
}
/// The extension of the name (as in "file.extension").
public var `extension`: String? {
guard let lastdot = name.lastIndex(of: "."),
lastdot != name.startIndex,
lastdot != name.index(before: name.endIndex)
else { return nil }
return String(name[name.index(after: lastdot)...])
}
/// The name without any extension.
public var nameWithoutExtension: String {
if let lastdot = name.lastIndex(of: "."), lastdot != name.startIndex {
return String(name[..<lastdot])
}
return name
}
/// If relative, joins base and relative together. Otherwise returns self.
public var absolute: Self {
return Self(absolute: components)
}
/// Go up `nr` directories.
/// - parameter nr: How many directories to go up the file tree. Defaults to 1.
public func parent(nr levels: Int = 1) -> DirectoryPath {
precondition(levels > 0, "Cannot go up less than one level of parent directories")
if let relative = relativeComponents, levels < relative.count, relative[relative.count - levels] != ".." {
return DirectoryPath(base: baseComponents!, relative: Array(relative.dropLast(levels)))
}
return DirectoryPath(absolute: Array(self.components.dropLast(levels)))
}
/// A new path pointing to the same item as this path, and whose base path is `base`.
///
/// - Parameter base: The base of the new path.
public func relativeTo(_ base: DirectoryPath) -> Self {
let i = components.indexOfFirstDifference(base.components)
let nrofdotdots = base.components.count - (i ?? components.count)
return Self(base: base.components, relative: Array(repeating: "..", count: nrofdotdots) + components.suffix(from: i ?? components.endIndex))
}
// MARK: Accesses the filesystem.
/// Checks if this path points to an existing item in the local filesystem.
/// - Note: Does not check if this path points to the correct type of item (file or directory).
///
/// If this is a symbolic link which points to a non-existing path, then the result is false.
public func exists() -> Bool {
return FileManager().fileExists(atPath: absoluteString)
}
/// A path referring to the same item in the file system, where all symbolic links have been resolved.
/// Components of this path which do not exist are returned unchanged.
public func resolvingSymlinks() -> Self {
return Self(self.url.resolvingSymlinksInPath())!
}
}
// MARK: DirectoryPath methods.
extension DirectoryPath {
/// The path to the current working directory.
public static var current: DirectoryPath {
get {
return DirectoryPath(FileManager().currentDirectoryPath)
}
set {
guard FileManager().changeCurrentDirectoryPath(newValue.absoluteString) else {
fatalError("Could not change current directory to \(newValue.absoluteString)")
}
}
}
/// The path to the current user's home directory.
public static var home: DirectoryPath {
return DirectoryPath(NSHomeDirectoryForUser(NSUserName())!)
}
/// The path to the root directory in the local file system.
public static var root: DirectoryPath {
return DirectoryPath(absolute:[])
}
internal func append<P: Path>(_ newcomponents: [String]) -> P {
if let relativeComponents = self.relativeComponents {
return P(base: self.baseComponents!, relative: fixDotDots(relativeComponents + newcomponents))
}
return P(absolute: fixDotDots(self.components + newcomponents))
}
internal func append<P: Path>(_ appendix: String, relative: Bool = false) -> P {
let (newcomponents, _) = parseComponents(appendix)
return relative ? P(base: components, relative: newcomponents) : append(newcomponents)
}
/// Creates a new path by adding a file path to the end of this directory path.
///
/// - Parameters:
/// - stringpath: The path to add.
/// - relative: If true, this path will be the base, and `stringpath` will be the relative part.
/// If false and this path is relative, the new path will be relative too. Otherwise it is absolute.
/// The default is false.
public func append(file stringpath: String, relative: Bool = false) -> FilePath {
return append(stringpath, relative: relative)
}
/// Creates a new path by adding a directory path to the end of this directory path.
///
/// - Parameters:
/// - stringpath: The path to add.
/// - relative: If true, this path will be the base, and `stringpath` will be the relative part.
/// If false and this path is relative, the new path will be relative too. Otherwise it is absolute.
/// The default is false.
public func append(directory stringpath: String, relative: Bool = false) -> DirectoryPath {
return append(stringpath, relative: relative)
}
public static func + <P: Path>(leftdir: DirectoryPath, rightpath: P) -> P {
let rightcomponents = rightpath.relativeComponents ?? rightpath.components
return leftdir.append(rightcomponents)
}
/// Checks if the absolute version of the provided path begins with the absolute version of this path.
public func isAParentOf<P: Path>(_ path: P) -> Bool {
return path.absolute.components.starts(with: self.absolute.components) && path.components.count != self.components.count
}
}
// MARK: Equatable
public func == <P:Path>(left: P, right: P) -> Bool where P:Equatable {
return left == right
}
extension AnyPath: Equatable, Hashable {
public static func == (left: AnyPath, right: AnyPath) -> Bool {
guard (left.relativeComponents == nil) == (right.relativeComponents == nil) else {
return false
}
if let leftrel = left.relativeComponents, let rightrel = right.relativeComponents {
return (leftrel == rightrel) && (left.baseComponents! == right.baseComponents!)
}
return left.components == right.components
}
}
extension FilePath: Equatable, Hashable {
public static func ==(left: FilePath, right: FilePath) -> Bool {
return AnyPath(left) == AnyPath(right)
}
}
extension DirectoryPath: Equatable, Hashable {
public static func ==(left: DirectoryPath, right: DirectoryPath) -> Bool {
return AnyPath(left) == AnyPath(right)
}
}
// MARK: URL
extension Path {
/// If relative, converts this path to a Foundation.URL.
public var relativeURL: URL? {
return relativeString.map { URL(fileURLWithPath: $0) }
}
/// Converts this path to a Foundation.URL.
public var url: URL {
return URL(fileURLWithPath: absoluteString)
}
/// Creates a path from a URL.
///
/// - returns: Path if URL is a file URL. Otherwise nil.
public init?(_ url: URL) {
guard url.isFileURL else { return nil }
self.init(absolute: url.standardizedFileURL.pathComponents.dropFirst().array)
}
}
extension FilePath {
/// Creates a path from a URL.
///
/// - returns: Path if URL is a file URL and does not have a directory path. Otherwise nil.
public init?(_ url: URL) {
if #available(OSX 10.11, iOS 9.0, tvOS 10.0, watchOS 3.0, *) {
guard url.isFileURL && !url.hasDirectoryPath else { return nil }
} else {
guard url.isFileURL && !url.path.hasSuffix(pathseparator) else { return nil }
}
self.init(absolute: url.standardizedFileURL.pathComponents.dropFirst().array)
}
}
| mit | ae21f2abeb23f8bea31196656f4f91ee | 36.643678 | 221 | 0.709008 | 3.725118 | false | false | false | false |
box/box-ios-sdk | Sources/Logger/ConsoleLogDestination.swift | 1 | 2979 | //
// ConsoleLogDestination.swift
// BoxSDK
//
// Created by Abel Osorio on 5/10/19.
// Copyright © 2019 Box. All rights reserved.
//
import Foundation
import os.log
/// Defines logging into a console
public class ConsoleLogDestination: LogDestination {
private var sdkLogger = OSLog(subsystem: LogSubsystem.boxSwiftSDK, category: LogCategory.sdk.description)
private var networkAgentLogger = OSLog(subsystem: LogSubsystem.boxSwiftSDK, category: LogCategory.networkAgent.description)
private var clientLogger = OSLog(subsystem: LogSubsystem.boxSwiftSDK, category: LogCategory.client.description)
private var modulesLogger = OSLog(subsystem: LogSubsystem.boxSwiftSDK, category: LogCategory.modules.description)
// swiftlint:disable cyclomatic_complexity
/// Logs a message into the console
///
/// - Parameters:
/// - message: Message to be written into the console log
/// - level: Log level defining type of log
/// - category: Log category defining type of data logged
/// - args: Log arguments
public func write(_ message: StaticString, level: LogLevel, category: LogCategory, _ args: [CVarArg]) {
let type = level.osLogType
var logger: OSLog
switch category {
case .sdk:
logger = sdkLogger
case .client:
logger = clientLogger
case .modules:
logger = modulesLogger
case .networkAgent:
logger = networkAgentLogger
}
// The Swift overlay of os_log prevents from accepting an unbounded number of args
// http://www.openradar.me/33203955
// https://stackoverflow.com/questions/50937765/why-does-wrapping-os-log-cause-doubles-to-not-be-logged-correctly
assert(args.count <= 9)
switch args.count {
case 9:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8])
case 8:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])
case 7:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3], args[4], args[5], args[6])
case 6:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3], args[4], args[5])
case 5:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3], args[4])
case 4:
os_log(message, log: logger, type: type, args[0], args[1], args[2], args[3])
case 3:
os_log(message, log: logger, type: type, args[0], args[1], args[2])
case 2:
os_log(message, log: logger, type: type, args[0], args[1])
case 1:
os_log(message, log: logger, type: type, args[0])
default:
os_log(message, log: logger, type: type)
}
}
// swiftlint:enable cyclomatic_complexity
}
| apache-2.0 | f77b23ed57b9dc15bf1feb680eb1bf7f | 40.361111 | 133 | 0.619208 | 3.755359 | false | false | false | false |
optimizely/swift-sdk | Sources/Implementation/Datastore/DataStoreUserDefaults.swift | 1 | 3243 | //
// Copyright 2019-2022, Optimizely, Inc. and 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
/// Implementation of OPTDataStore using standard UserDefaults.
/// This class should be used as a singleton.
public class DataStoreUserDefaults: OPTDataStore {
// A hardcoded max for user defaults. Since there is a max on iostv
#if os(tvOS)
static let MAX_DS_SIZE = 128000
#else
static let MAX_DS_SIZE = 1000000
#endif
static let dispatchQueue = DispatchQueue(label: "OPTDataStoreQueueUserDefaults")
// thread-safe lazy logger load (after HandlerRegisterService ready)
private let threadSafeLogger = ThreadSafeLogger()
var logger: OPTLogger {
return threadSafeLogger.logger
}
public func getItem(forKey: String) -> Any? {
return DataStoreUserDefaults.dispatchQueue.sync {
return UserDefaults.standard.object(forKey: forKey)
}
}
public func saveItem(forKey: String, value: Any) {
DataStoreUserDefaults.dispatchQueue.async {
if let value = value as? Data {
if value.count > DataStoreUserDefaults.MAX_DS_SIZE {
self.logger.e("Save to User Defaults error: \(forKey) is too big to save size(\(value.count))")
return
}
} else if let value = value as? String {
if value.count > DataStoreUserDefaults.MAX_DS_SIZE {
self.logger.e("Save to User Defaults error: \(forKey) is too big to save size(\(value.count))")
return
}
} else if let value = value as? [Data] {
var l: Int = 0
l = value.reduce(into: l, { (res, data) in
res += data.count
})
if l > DataStoreUserDefaults.MAX_DS_SIZE {
self.logger.e("Save to User Defaults error: \(forKey) is too big to save size(\(value.count))")
return
}
} else if let value = value as? [String] {
var l: Int = 0
l = value.reduce(into: l, { (res, data) in
res += data.count
})
if l > DataStoreUserDefaults.MAX_DS_SIZE {
self.logger.e("Save to User Defaults error: \(forKey) is too big to save size(\(value.count))")
return
}
}
UserDefaults.standard.set(value, forKey: forKey)
UserDefaults.standard.synchronize()
}
}
public func removeItem(forKey: String) {
UserDefaults.standard.removeObject(forKey: forKey)
}
}
| apache-2.0 | 12dbdee0c95742da6e59ea9abbb3317c | 37.607143 | 115 | 0.591736 | 4.652798 | false | false | false | false |
wangxin20111/WXWeiBo | WXWeibo/WXWeibo/Classes/Home/View/WXStatusCell.swift | 1 | 11152 | //
// WXStatusCell.swift
// WXWeibo
//
// Created by 王鑫 on 16/7/18.
// Copyright © 2016年 王鑫. All rights reserved.
//
import UIKit
import PureLayout
import SDWebImage
//通用的边距
let WXCommonMargin:CGFloat = 10.0
class WXStatusCell: UITableViewCell {
//MARK: - 对外开放一个接口
class func cellWithTableView(tableview : UITableView) -> UITableViewCell
{
let ident = "WXStatusCell"
var cell = tableview.dequeueReusableCellWithIdentifier(ident)
if (cell == nil) {
cell = WXStatusCell.init(style: UITableViewCellStyle.Default, reuseIdentifier: ident)
}
return cell!
}
//MARK: - 对外的属性
var statusM : WXStatusModel?{
didSet{
//更新UI
//头像
iconView.sd_setImageWithURL(statusM?.user?.imageURL, placeholderImage: UIImage(named: "avatar_default"))
//时间
timeLab.text = NSDate.dateWithTimeStamp("\(statusM?.createAt)!").descDate
//来源
sourceLab.text = statusM?.source
//内容
contentLab.text = statusM?.text
//名字
nameLab.text = statusM?.user?.name
//会员几级
vertifiedView.image = statusM?.user?.verifiedImage
//更新vip的级别图片
vipView.image = statusM?.user?.vipRankImage
//更新照片的尺寸
flowLayout.itemSize = calculateImageSize().imgSize
picsViewWidht?.constant = calculateImageSize().picsViewSize.width
picsViewHeight?.constant = calculateImageSize().picsViewSize.height
picsView .reloadData()
updateConstraintsIfNeeded()
}
}
//collectionView的size
var picsViewHeight:NSLayoutConstraint?
var picsViewWidht:NSLayoutConstraint?
//MARK: - 懒加载数据
/// 头像
private lazy var iconView: UIImageView = {
let iv = UIImageView()
return iv
}()
/// 认证图标
private lazy var vertifiedView : UIImageView = UIImageView(image: UIImage(named:"avatar_enterprise_vip"))
/// 名字
private lazy var nameLab : UILabel = UILabel.createLable("名字", fontSize: 17, color: UIColor.blackColor())
/// 时间
private lazy var timeLab : UILabel = UILabel.createLable("time", fontSize: 17, color: UIColor.blackColor())
/// 来源
private lazy var sourceLab : UILabel = UILabel.createLable("time", fontSize: 17, color: UIColor.blackColor())
/// 级数,黄色皇冠
private lazy var vipView : UIImageView = {
let vv = UIImageView(image:UIImage(named:"common_icon_membership"))
return vv
}()
//重写Frame:CollectionViewLayout 方法
private lazy var flowLayout : UICollectionViewFlowLayout = {
let fly = UICollectionViewFlowLayout()
fly.minimumLineSpacing = WXCommonMargin
fly.minimumInteritemSpacing = WXCommonMargin
return fly
}()
//照片们
private lazy var picsView:WXPicsCollectionView = {
let pV = WXPicsCollectionView(frame:CGRectZero,collectionViewLayout: self.flowLayout)
return pV
}()
/// 内容
private lazy var contentLab : UILabel = UILabel.createLable("time", fontSize: 16, color: UIColor.darkGrayColor())
private lazy var footerView : WXStatusFooterView = {
let ft = WXStatusFooterView()
return ft
}()
//MARK: - 初始化代码
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(iconView)
contentView.addSubview(nameLab)
contentView.addSubview(vertifiedView)
contentView.addSubview(sourceLab)
contentView.addSubview(contentLab)
contentLab.numberOfLines = 0;
contentView.addSubview(vipView)
contentView.addSubview(timeLab)
contentView.addSubview(footerView)
picsView.backgroundColor = UIColor.redColor()
contentView.addSubview(picsView)
picsView.delegate = self
picsView.dataSource = self
// updateConstraintsIfNeeded()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 布局子控件
override func updateConstraints() {
super.updateConstraints()
//头像
iconView.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: WXCommonMargin)
iconView.autoPinEdgeToSuperviewEdge(ALEdge.Top, withInset: WXCommonMargin)
//名字
nameLab.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: iconView,withOffset: WXCommonMargin)
nameLab.autoPinEdgeToSuperviewEdge(ALEdge.Top,withInset: WXCommonMargin)
//timeLab
timeLab.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: nameLab,withOffset: WXCommonMargin)
timeLab.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: iconView,withOffset: WXCommonMargin)
//认证
vertifiedView.autoPinEdge(ALEdge.Right, toEdge: ALEdge.Right, ofView: iconView, withOffset:0)
vertifiedView.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: iconView, withOffset: 0)
//来源
sourceLab.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: timeLab, withOffset: WXCommonMargin)
sourceLab.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Bottom, ofView: iconView)
//vip头像
vipView.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: nameLab,withOffset: WXCommonMargin)
vipView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Top, ofView: nameLab)
//内容
contentLab.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset: WXCommonMargin)
contentLab.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: iconView,withOffset: WXCommonMargin)
contentLab.autoPinEdgeToSuperviewEdge(ALEdge.Right,withInset: WXCommonMargin)
//布局多个照片的时候所产生的照片view
picsView.autoPinEdgeToSuperviewEdge(ALEdge.Left, withInset:WXCommonMargin)
picsView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: contentLab, withOffset: WXCommonMargin)
picsViewHeight = picsView.autoSetDimension(ALDimension.Height, toSize: 15)
picsViewWidht = picsView.autoSetDimension(ALDimension.Width, toSize: 15)
//底部操作栏
footerView.autoPinEdge(ALEdge.Top, toEdge: ALEdge.Bottom, ofView: picsView,withOffset:WXCommonMargin)
footerView.autoPinEdgeToSuperviewEdge(ALEdge.Right)
footerView.autoPinEdgeToSuperviewEdge(ALEdge.Left)
footerView.autoSetDimension(ALDimension.Height, toSize: WXStatusFooterViewHeight)
footerView.autoPinEdgeToSuperviewEdge(ALEdge.Bottom)
}
//计算将要显示图片的尺寸
private func calculateImageSize() -> (picsViewSize:CGSize,imgSize:CGSize)
{
//1.取出配图的个数
let count = statusM?.picULRs.count
//2.如果没有配图的话,返回zero
if(count == 0 || count == nil)
{
return (CGSizeZero,CGSizeZero)
}
//3.如果有一张配图,返回配图实际的大小
if count == 1 {
let key = statusM?.picULRs.first?.absoluteString
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
return (image.size,image.size)
}
//4.如果有四张配图,就计算一下田字格的大小
let margin = 10
let width = 90
if count == 4
{
let imgWidth = width * 2 + margin
return (CGSizeMake(CGFloat(imgWidth), CGFloat(imgWidth)),CGSizeMake(CGFloat(width), CGFloat(width)))
}
//5.如果他是其他数量的,计算九宫格的大小
// 5.如果是其它(多张), 计算九宫格的大小
/*
2/3
5/6
7/8/9
*/
// 5.1计算列数
let colNumber = 3
// 5.2计算行数
//(8 - 1) / 3 + 1
let rowNumber = (count! - 1) / 3 + 1
// 宽度 = 列数 * 图片的宽度 + (列数 - 1) * 间隙
let viewWidth = colNumber * width + (colNumber - 1) * margin
// 高度 = 行数 * 图片的高度 + (行数 - 1) * 间隙
let viewHeight = rowNumber * width + (rowNumber - 1) * margin
return (CGSizeMake(CGFloat(viewWidth), CGFloat(viewHeight)),CGSizeMake(CGFloat(width), CGFloat(width)))
}
}
//MARK: - 实现collectionView代理方法和数据源方法
extension WXStatusCell:UICollectionViewDelegate,UICollectionViewDataSource
{
//数据源方法
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return statusM?.picULRs.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = WXSingleImgCell.cellWithCollectionView(collectionView, indexPath: indexPath) as! WXSingleImgCell
cell.imgURL = statusM?.picULRs[indexPath.item]
return cell
}
}
//MARK: - 自定义一个底部的操作栏
//底部操作栏的高度
let WXStatusFooterViewHeight:CGFloat = 44.0
class WXStatusFooterView : UIView
{
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(retweetBtn)
addSubview(unlikeBtn)
addSubview(commentBtn)
backgroundColor = UIColor.lightGrayColor()
updateConstraintsIfNeeded()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - 创建底部的btn
private lazy var retweetBtn : UIButton = UIButton.createBtn("timeline_icon_retweet", title: "转发")
private lazy var unlikeBtn : UIButton = UIButton.createBtn("timeline_icon_unlike", title: "赞")
//评论
private lazy var commentBtn : UIButton = UIButton.createBtn("timeline_icon_comment", title: "评论")
//MARK: - 布局
override func updateConstraints() {
super.updateConstraints()
let btnWidth = WXScreenWidth/3.0
retweetBtn.autoPinEdgeToSuperviewEdge(ALEdge.Top)
retweetBtn.autoPinEdgeToSuperviewEdge(ALEdge.Bottom)
retweetBtn.autoPinEdgeToSuperviewEdge(ALEdge.Left)
retweetBtn.autoSetDimension(ALDimension.Width, toSize: btnWidth)
unlikeBtn.autoPinEdgeToSuperviewEdge(ALEdge.Top)
unlikeBtn.autoPinEdgeToSuperviewEdge(ALEdge.Bottom)
unlikeBtn.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: retweetBtn)
unlikeBtn.autoSetDimension(ALDimension.Width, toSize: btnWidth)
commentBtn.autoPinEdgeToSuperviewEdge(ALEdge.Top)
commentBtn.autoPinEdgeToSuperviewEdge(ALEdge.Bottom)
commentBtn.autoPinEdgeToSuperviewEdge(ALEdge.Right)
commentBtn.autoPinEdge(ALEdge.Left, toEdge: ALEdge.Right, ofView: unlikeBtn)
}
}
| mit | f08a1db5a301026e18bb65a79aa03606 | 37.412409 | 130 | 0.658147 | 4.522991 | false | false | false | false |
eBardX/XestiMonitors | Sources/Core/CoreMotion/AltimeterMonitor.swift | 1 | 2471 | //
// AltimeterMonitor.swift
// XestiMonitors
//
// Created by J. G. Pusey on 2017-04-14.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
#if os(iOS) || os(watchOS)
import CoreMotion
import Foundation
///
/// An `AltimeterMonitor` instance monitors the device for changes in
/// relative altitude.
///
public class AltimeterMonitor: BaseMonitor {
///
/// Encapsulates changes to the relative altitude.
///
public enum Event {
///
/// The relative altitude has been updated.
///
case didUpdate(Info)
}
///
/// Encapsulates the relative change in altitude.
///
public enum Info {
///
/// The relative change in altitude data.
///
case data(CMAltitudeData)
///
/// The error encountered in attempting to obtain the relative
/// change in altitude.
///
case error(Error)
///
/// No altitude data is available.
///
case unknown
}
///
/// Initializes a new `AltimeterMonitor`.
///
/// - Parameters:
/// - queue: The operation queue on which the handler executes.
/// - handler: The handler to call when new altitude data is
/// available.
///
public init(queue: OperationQueue,
handler: @escaping (Event) -> Void) {
self.altimeter = AltimeterInjector.inject()
self.handler = handler
self.queue = queue
}
///
/// A Boolean value indicating whether the device supports generating
/// data for relative altitude changes.
///
public var isAvailable: Bool {
return type(of: altimeter).isRelativeAltitudeAvailable()
}
private let altimeter: AltimeterProtocol
private let handler: (Event) -> Void
private let queue: OperationQueue
override public func cleanupMonitor() {
altimeter.stopRelativeAltitudeUpdates()
super.cleanupMonitor()
}
override public func configureMonitor() {
super.configureMonitor()
altimeter.startRelativeAltitudeUpdates(to: .main) { [unowned self] data, error in
var info: Info
if let error = error {
info = .error(error)
} else if let data = data {
info = .data(data)
} else {
info = .unknown
}
self.handler(.didUpdate(info))
}
}
}
#endif
| mit | 19a9cc539dbbeac07fa10142758ea9e6 | 22.980583 | 89 | 0.566397 | 4.651601 | false | false | false | false |
gaintext/gaintext-engine | Sources/Engine/ResultCache.swift | 1 | 2068 | //
// GainText parser
// Copyright Martin Waitz
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
/// Key to identify parser results.
struct CacheKey {
let cache: ObjectIdentifier
let position: Position
let startOfWord: Bool
}
extension CacheKey: Hashable {
var hashValue: Int {
return cache.hashValue ^ position.hashValue
}
static func ==(lhs: CacheKey, rhs: CacheKey) -> Bool {
return lhs.position == rhs.position
&& lhs.cache == rhs.cache
&& lhs.startOfWord == rhs.startOfWord
}
}
/// Stored parser result.
enum CachedResult {
case cached(nodes: [Node], cursor: Cursor)
case error(error: ParserError)
}
private class Wrapper {
let parser: Parser<[Node]>
init(_ parser: Parser<[Node]>) { self.parser = parser }
var id: ObjectIdentifier { return ObjectIdentifier(self) }
}
/// Cache the result of a delegate parser.
/// Any further `parse` calls will return the exact same result.
public func cached(_ parser: Parser<[Node]>) -> Parser<[Node]> {
let wrapper = Wrapper(parser)
return Parser { input in
let key = CacheKey(cache: wrapper.id,
position: input.position,
startOfWord: input.atStartOfWord)
let scope = input.block
if let found = scope.cache[key] {
switch found {
case .cached(let nodes, let cursor):
return (nodes, cursor)
case .error(let error):
throw error
}
}
do {
let (nodes, cursor) = try wrapper.parser.parse(input)
scope.cache[key] = .cached(nodes: nodes, cursor: cursor)
return (nodes, cursor)
} catch let error as ParserError {
scope.cache[key] = .error(error: error)
throw error
}
}
}
| gpl-3.0 | 4b6706e890e1dcbfd9ac7dcefd9cae7a | 29.865672 | 71 | 0.604932 | 4.344538 | false | false | false | false |
VikingDen/actor-platform | actor-apps/app-ios/ActorCore/Providers/CocoaFileSystemRuntime.swift | 9 | 6023 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
// Public methods for working with files
class CocoaFiles {
class func pathFromDescriptor(path: String) -> String {
var manager = NSFileManager.defaultManager();
var documentsFolders = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)!;
if (documentsFolders.count > 0) {
var appPath = (documentsFolders[0] as! String).stringByDeletingLastPathComponent
return appPath + path
} else {
fatalError("Unable to load Application path")
}
}
}
// Implementation of FileSystem storage
@objc class CocoaFileSystemRuntime : NSObject, ARFileSystemRuntime {
var appPath: String = ""
override init() {
super.init()
var manager = NSFileManager.defaultManager();
var documentsFolders = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)!;
if (documentsFolders.count > 0) {
appPath = (documentsFolders[0] as! String).stringByDeletingLastPathComponent
} else {
fatalError("Unable to load Application path")
}
}
func createTempFile() -> ARFileSystemReference! {
var fileName = "/tmp/\(NSUUID().UUIDString)"
NSFileManager.defaultManager().createFileAtPath(appPath + fileName, contents: NSData(), attributes: nil);
return CocoaFile(path: fileName);
}
func commitTempFile(sourceFile: ARFileSystemReference!, withFileId fileId: jlong, withFileName fileName: String!) -> ARFileSystemReference! {
var manager = NSFileManager.defaultManager();
var baseName = fileName;
var index = 0;
while(manager.fileExistsAtPath("\(appPath)/Documents/\(index)_\(baseName)")) {
index = index + 1;
}
var resultPath = "/Documents/\(index)_\(baseName)";
var error : NSError?;
manager.moveItemAtPath(appPath + sourceFile.getDescriptor()!, toPath: appPath + resultPath, error: &error)
if (error == nil) {
return CocoaFile(path: resultPath)
}
return nil
}
func fileFromDescriptor(descriptor: String!) -> ARFileSystemReference! {
return CocoaFile(path: descriptor);
}
func isFsPersistent() -> Bool {
return true;
}
}
class CocoaFile : NSObject, ARFileSystemReference {
let path: String;
let realPath: String;
init(path:String) {
self.path = path
self.realPath = CocoaFiles.pathFromDescriptor(path)
}
func getDescriptor() -> String! {
return path;
}
func isExist() -> Bool {
return NSFileManager().fileExistsAtPath(realPath);
}
func getSize() -> jint {
var error:NSError?;
var attrs = NSFileManager().attributesOfItemAtPath(realPath, error: &error);
if (error != nil) {
return 0;
}
return jint(NSDictionary.fileSize(attrs!)());
}
func openWriteWithSize(size: jint) -> AROutputFile! {
var fileHandle = NSFileHandle(forWritingAtPath: realPath);
if (fileHandle == nil) {
return nil
}
fileHandle!.seekToFileOffset(UInt64(size))
fileHandle!.seekToFileOffset(0)
return CocoaOutputFile(fileHandle: fileHandle!);
}
func openRead() -> ARInputFile! {
var fileHandle = NSFileHandle(forReadingAtPath: realPath);
if (fileHandle == nil) {
return nil
}
return CocoaInputFile(fileHandle: fileHandle!);
}
}
class CocoaOutputFile : NSObject, AROutputFile {
let fileHandle: NSFileHandle;
init(fileHandle:NSFileHandle){
self.fileHandle = fileHandle;
}
func writeWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset dataOffset: jint, withLength dataLen: jint) -> Bool {
var toWrite = NSMutableData(length: Int(dataLen))!;
var srcBuffer = UnsafeMutablePointer<UInt8>(data.buffer());
var destBuffer = UnsafeMutablePointer<UInt8>(toWrite.bytes);
for i in 0..<dataLen {
destBuffer.memory = srcBuffer.memory;
destBuffer++;
srcBuffer++;
}
fileHandle.seekToFileOffset(UInt64(fileOffset));
fileHandle.writeData(toWrite)
return true;
}
func close() -> Bool {
self.fileHandle.synchronizeFile()
self.fileHandle.closeFile()
return true;
}
}
class CocoaInputFile :NSObject, ARInputFile {
let fileHandle:NSFileHandle;
init(fileHandle:NSFileHandle){
self.fileHandle = fileHandle;
}
func readWithOffset(fileOffset: jint, withData data: IOSByteArray!, withDataOffset offset: jint, withLength len: jint, withCallback callback: ARFileReadCallback!) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
self.fileHandle.seekToFileOffset(UInt64(fileOffset));
var readed:NSData = self.fileHandle.readDataOfLength(Int(len));
var srcBuffer = UnsafeMutablePointer<UInt8>(readed.bytes);
var destBuffer = UnsafeMutablePointer<UInt8>(data.buffer());
var len = min(Int(len), Int(readed.length));
for i in offset..<offset+len {
destBuffer.memory = srcBuffer.memory;
destBuffer++;
srcBuffer++;
}
callback.onFileReadWithOffset(fileOffset, withData: data, withDataOffset: offset, withLength: jint(len))
}
}
func close() -> Bool {
self.fileHandle.closeFile()
return true;
}
} | mit | aa55a7bb4c1ef7801f386892178d5eda | 29.892308 | 168 | 0.609497 | 5.297274 | false | false | false | false |
CPRTeam/CCIP-iOS | Pods/CryptoSwift/Sources/CryptoSwift/BlockMode/PCBC.swift | 3 | 2581 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// Propagating Cipher Block Chaining (PCBC)
//
public struct PCBC: BlockMode {
public enum Error: Swift.Error {
/// Invalid IV
case invalidInitializationVector
}
public let options: BlockModeOption = [.initializationVectorRequired, .paddingRequired]
private let iv: Array<UInt8>
public init(iv: Array<UInt8>) {
self.iv = iv
}
public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> CipherModeWorker {
if self.iv.count != blockSize {
throw Error.invalidInitializationVector
}
return PCBCModeWorker(blockSize: blockSize, iv: self.iv.slice, cipherOperation: cipherOperation)
}
}
struct PCBCModeWorker: BlockModeWorker {
let cipherOperation: CipherOperationOnBlock
var blockSize: Int
let additionalBufferSize: Int = 0
private let iv: ArraySlice<UInt8>
private var prev: ArraySlice<UInt8>?
init(blockSize: Int, iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) {
self.blockSize = blockSize
self.iv = iv
self.cipherOperation = cipherOperation
}
mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let ciphertext = cipherOperation(xor(prev ?? iv, plaintext)) else {
return Array(plaintext)
}
self.prev = xor(plaintext, ciphertext.slice)
return ciphertext
}
mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> {
guard let plaintext = cipherOperation(ciphertext) else {
return Array(ciphertext)
}
let result: Array<UInt8> = xor(prev ?? self.iv, plaintext)
self.prev = xor(plaintext.slice, ciphertext)
return result
}
}
| gpl-3.0 | 8a1a449a4b387d41701b6de0151d6f08 | 35.857143 | 217 | 0.736434 | 4.410256 | false | false | false | false |
austinzheng/swift | stdlib/public/core/StringCreate.swift | 2 | 5636 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// String Creation Helpers
//===----------------------------------------------------------------------===//
internal func _allASCII(_ input: UnsafeBufferPointer<UInt8>) -> Bool {
// NOTE: Avoiding for-in syntax to avoid bounds checks
//
// TODO(String performance): Vectorize and/or incorporate into validity
// checking, perhaps both.
//
let ptr = input.baseAddress._unsafelyUnwrappedUnchecked
var i = 0
while i < input.count {
guard ptr[i] <= 0x7F else { return false }
i &+= 1
}
return true
}
extension String {
@usableFromInline
internal static func _fromASCII(
_ input: UnsafeBufferPointer<UInt8>
) -> String {
_internalInvariant(_allASCII(input), "not actually ASCII")
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let storage = _StringStorage.create(initializingFrom: input, isASCII: true)
return storage.asString
}
@usableFromInline
internal static func _tryFromUTF8(
_ input: UnsafeBufferPointer<UInt8>
) -> String? {
guard case .success(let extraInfo) = validateUTF8(input) else {
return nil
}
return String._uncheckedFromUTF8(input, isASCII: extraInfo.isASCII)
}
@usableFromInline
internal static func _fromUTF8Repairing(
_ input: UnsafeBufferPointer<UInt8>
) -> (result: String, repairsMade: Bool) {
switch validateUTF8(input) {
case .success(let extraInfo):
return (String._uncheckedFromUTF8(
input, asciiPreScanResult: extraInfo.isASCII
), false)
case .error(let initialRange):
return (repairUTF8(input, firstKnownBrokenRange: initialRange), true)
}
}
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>
) -> String {
return _uncheckedFromUTF8(input, isASCII: _allASCII(input))
}
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>,
isASCII: Bool
) -> String {
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let storage = _StringStorage.create(
initializingFrom: input, isASCII: isASCII)
return storage.asString
}
// If we've already pre-scanned for ASCII, just supply the result
@usableFromInline
internal static func _uncheckedFromUTF8(
_ input: UnsafeBufferPointer<UInt8>, asciiPreScanResult: Bool
) -> String {
if let smol = _SmallString(input) {
return String(_StringGuts(smol))
}
let isASCII = asciiPreScanResult
let storage = _StringStorage.create(
initializingFrom: input, isASCII: isASCII)
return storage.asString
}
@usableFromInline
internal static func _uncheckedFromUTF16(
_ input: UnsafeBufferPointer<UInt16>
) -> String {
// TODO(String Performance): Attempt to form smol strings
// TODO(String performance): Skip intermediary array, transcode directly
// into a StringStorage space.
var contents: [UInt8] = []
contents.reserveCapacity(input.count)
let repaired = transcode(
input.makeIterator(),
from: UTF16.self,
to: UTF8.self,
stoppingOnError: false,
into: { contents.append($0) })
_internalInvariant(!repaired, "Error present")
return contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) }
}
internal func _withUnsafeBufferPointerToUTF8<R>(
_ body: (UnsafeBufferPointer<UTF8.CodeUnit>) throws -> R
) rethrows -> R {
return try self.withUnsafeBytes { rawBufPtr in
let rawPtr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked
return try body(UnsafeBufferPointer(
start: rawPtr.assumingMemoryBound(to: UInt8.self),
count: rawBufPtr.count))
}
}
@usableFromInline @inline(never) // slow-path
internal static func _fromCodeUnits<
Input: Collection,
Encoding: Unicode.Encoding
>(
_ input: Input,
encoding: Encoding.Type,
repair: Bool
) -> (String, repairsMade: Bool)?
where Input.Element == Encoding.CodeUnit {
// TODO(String Performance): Attempt to form smol strings
// TODO(String performance): Skip intermediary array, transcode directly
// into a StringStorage space.
var contents: [UInt8] = []
contents.reserveCapacity(input.underestimatedCount)
let repaired = transcode(
input.makeIterator(),
from: Encoding.self,
to: UTF8.self,
stoppingOnError: false,
into: { contents.append($0) })
guard repair || !repaired else { return nil }
let str = contents.withUnsafeBufferPointer { String._uncheckedFromUTF8($0) }
return (str, repaired)
}
public // @testable
static func _fromInvalidUTF16(
_ utf16: UnsafeBufferPointer<UInt16>
) -> String {
return String._fromCodeUnits(utf16, encoding: UTF16.self, repair: true)!.0
}
@usableFromInline
internal static func _fromSubstring(
_ substring: __shared Substring
) -> String {
if substring._offsetRange == substring._wholeString._offsetRange {
return substring._wholeString
}
return substring._withUTF8 { return String._uncheckedFromUTF8($0) }
}
}
| apache-2.0 | 7b4e10069235c1d01e6efa0d967af002 | 29.630435 | 80 | 0.659155 | 4.541499 | false | false | false | false |
NoodleOfDeath/PastaParser | runtime/swift/GrammarKit/Classes/model/grammar/scanner/Parser.swift | 1 | 11708 | //
// The MIT License (MIT)
//
// Copyright © 2020 NoodleOfDeath. All rights reserved.
// NoodleOfDeath
//
// 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.
/// Grammatical scanner for scanning token streams.
open class Parser: BaseGrammaticalScanner {
/// Parses a token stream.
///
/// - Parameters:
/// - tokenStream:
/// - offset:
/// - length:
/// - parentChain:
public func parse(_ tokenStream: TokenStream<Token>?, from offset: Int, length: Int? = nil, rules: [GrammarRule]? = nil) {
if let length = length {
parse(tokenStream, within: NSMakeRange(offset, length), rules: rules)
} else {
parse(tokenStream, within: tokenStream?.range.shiftingLocation(by: offset), rules: rules)
}
}
/// Parses a token stream.
///
/// - Parameters:
/// - tokenStream:
/// - streamRange:
/// - parentChain:
public func parse(_ tokenStream: TokenStream<Token>?, within streamRange: NSRange? = nil, rules: [GrammarRule]? = nil) {
guard let tokenStream = tokenStream else { return }
let characterStream = tokenStream.characterStream
var streamRange = streamRange ?? NSMakeRange(0, tokenStream.tokenCount)
while streamRange.location < tokenStream.tokenCount {
var matchChain = MatchChain()
for rule in (rules ?? grammar.parserRules) {
matchChain = parse(tokenStream, rule: rule, within: streamRange)
if matchChain.matches {
matchChain.rule = rule
break
}
}
if matchChain.matches && !matchChain.has(option: .skip) {
delegate?.scanner(self, didGenerate: matchChain,
characterStream: characterStream,
tokenStream: tokenStream)
} else {
let token = tokenStream[streamRange.location]
delegate?.scanner(self, didSkip: token, characterStream: characterStream)
}
streamRange.shiftLocation(by: matchChain.matches ? matchChain.tokenCount : 1)
}
delegate?.scanner(self, didFinishScanning: characterStream, tokenStream: tokenStream)
}
///
///
/// - Parameters:
/// - tokenStream:
/// - rule:
/// - streamRange:
/// - matchChain:
/// - parentChain:
/// - metadata:
/// - Returns:
public func parse(_ tokenStream: TokenStream<Token>, rule: GrammarRule, within streamRange: NSRange, matchChain: MatchChain? = nil, captureGroups: [String: MatchChain]? = nil, iteration: Int = 0) -> MatchChain {
let matchChain = matchChain ?? MatchChain(rule: rule)
var captureGroups = captureGroups ?? [:]
guard rule.isValid, streamRange.length > 0, streamRange.location < tokenStream.tokenCount else {
return matchChain
}
var subchain = MatchChain(rule: rule)
var tmpChain = MatchChain(rule: rule)
var matchCount = 0
var dx = 0
switch rule.type {
case .parserRuleReference:
guard let ruleRef = grammar[rule.value] else {
print(String(format: "No parser rule was defined for id \"%@\"", rule.value))
return matchChain
}
tmpChain = parse(tokenStream, rule: ruleRef, within: streamRange,
captureGroups: captureGroups,
iteration: iteration + (rule.rootAncestor?.id == ruleRef.id ? 1 : 0))
while rule.inverted != tmpChain.absoluteMatch {
if rule.inverted {
let token = tokenStream[streamRange.location + dx]
tmpChain = MatchChain(rule: rule)
tmpChain.rule = rule
tmpChain.add(token: token)
}
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
matchCount += 1
dx += tmpChain.tokenCount
if !rule.quantifier.greedy { break }
tmpChain = parse(tokenStream, rule: ruleRef,
within: streamRange.shiftingLocation(by: dx),
captureGroups: captureGroups, iteration: iteration)
}
case .lexerRuleReference:
var isRef = false
if let ruleRef = grammar.rules[rule.value], ruleRef.isFragment {
isRef = true
tmpChain = parse(tokenStream, rule: ruleRef, within: streamRange,
captureGroups: captureGroups, iteration: iteration)
}
var token = tokenStream[streamRange.location]
var matches = token.matches(rule.value) || tmpChain.matches
while rule.inverted != matches {
if !isRef { tmpChain.add(token: token) }
matchCount += 1
dx += tmpChain.tokenCount
if !rule.quantifier.greedy || streamRange.location + dx >= tokenStream.tokenCount { break }
isRef = false
if let ruleRef = grammar.rules[rule.value], ruleRef.isFragment {
isRef = true
tmpChain = parse(tokenStream, rule: ruleRef, within: streamRange)
}
token = tokenStream[streamRange.location + dx]
matches = token.matches(rule.value) || tmpChain.matches
}
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
case .parserRule, .lexerRule, .composite:
if rule.subrules.count > 0 {
for subrule in rule.subrules {
tmpChain = parse(tokenStream, rule: subrule, within: streamRange, captureGroups: captureGroups, iteration: iteration)
if rule.inverted != tmpChain.absoluteMatch { break }
}
var subtokens = [Token]()
while rule.inverted != tmpChain.absoluteMatch {
if rule.inverted {
let token = tokenStream[streamRange.location + dx]
tmpChain = MatchChain(rule: rule)
tmpChain.rule = rule
tmpChain.add(token: token)
}
if rule.isRule {
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
} else {
subtokens.append(contentsOf: tmpChain.tokens)
}
matchCount += 1
dx += tmpChain.tokenCount
if !rule.quantifier.greedy { break }
for subrule in rule.subrules {
tmpChain = parse(tokenStream, rule: subrule,
within: streamRange.shiftingLocation(by: dx),
captureGroups: captureGroups, iteration: iteration)
if rule.inverted != tmpChain.absoluteMatch { break }
}
}
if rule.type == .composite {
tmpChain = MatchChain(rule: rule, tokens: subtokens)
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
}
}
case .captureGroupReference:
let key = "\(iteration).\(rule.value)"
if let captureGroup = captureGroups[key] {
var range = streamRange
var match = captureGroup.string.format(using: .escapeRegex).firstMatch(in: tokenStream.reduce(over: range), options: ([], .anchored))
var subtokens = [Token]()
while rule.inverted != (match != nil) {
if !rule.inverted, let _ = match {
dx += range.length
} else {
dx += 1
}
matchCount += 1
subtokens.append(contentsOf: tokenStream[range.bridgedRange])
if !rule.quantifier.greedy { break }
range = NSMakeRange(dx, range.length - dx)
match = captureGroup.string.format(using: .escapeRegex).firstMatch(in: tokenStream.reduce(over: range), options: ([], .anchored))
}
tmpChain = MatchChain(rule: rule, tokens: subtokens)
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
}
default:
// .literal, .expression
var pattern = rule.value
if "^\\w+$".doesMatch(rule.value) {
pattern = String(format: "\\b%@\\b", rule.value)
}
var token = tokenStream[streamRange.location]
var matches = pattern.doesMatch(token.value, options: .anchored)
while rule.inverted != matches {
tmpChain.add(token: token)
matchCount += 1
dx += 1
if !rule.quantifier.greedy || streamRange.location + dx >= tokenStream.tokenCount { break }
token = tokenStream[streamRange.location + dx]
matches = pattern.doesMatch(token.value, options: .anchored)
}
subchain.add(subchain: tmpChain)
subchain.add(tokens: tmpChain.tokens)
}
subchain ?= matchChain.add(subchains: subchain.subchains)
matchChain.add(tokens: subchain.tokens)
if let groupName = rule.groupName, subchain.length > 0 {
let key = "\(iteration).\(groupName)"
captureGroups[key] = subchain
}
if (!rule.quantifier.hasRange && matchCount > 0) || rule.quantifier.optional || rule.quantifier.matches(matchCount) {
if let next = rule.next {
let remainingRange = streamRange.shiftingLocation(by: dx)
if remainingRange.length > 0 {
return parse(tokenStream, rule: next, within: remainingRange, matchChain: matchChain, captureGroups: captureGroups, iteration: iteration)
}
if !next.quantifier.optional {
return matchChain
}
}
matchChain.matches = true
}
return matchChain
}
}
| mit | 571e613f10d93dbba2fdc3aaf2da6173 | 42.682836 | 215 | 0.545827 | 4.950106 | false | false | false | false |
apple/swift | validation-test/compiler_crashers_2_fixed/0207-issue-49919.swift | 2 | 1080 | // RUN: %target-swift-frontend -emit-ir %s
// https://github.com/apple/swift/issues/49919
public protocol TypedParserResultTransferType {
// Remove type constraint
associatedtype Result: ParserResult
}
public struct AnyTypedParserResultTransferType<P: ParserResult>: TypedParserResultTransferType {
public typealias Result = P
// Remove property
public let result: P
}
public protocol ParserResult {}
public protocol StaticParser: ParserResult {}
// Change comformance to ParserResult
public protocol TypedStaticParser: StaticParser {
// Remove type constraint
associatedtype ResultTransferType: TypedParserResultTransferType
}
// Remove where clause
public protocol MutableSelfStaticParser: TypedStaticParser where ResultTransferType == AnyTypedParserResultTransferType<Self> {
func parseTypeVar() -> AnyTypedParserResultTransferType<Self>
}
extension MutableSelfStaticParser {
public func anyFunction() -> () {
let t = self.parseTypeVar
// Remove this and below
_ = t()
_ = self.parseTypeVar()
}
}
| apache-2.0 | 1e9e1d20211485692e64041bbcf98457 | 27.421053 | 127 | 0.746296 | 4.886878 | false | false | false | false |
hooman/swift | test/Concurrency/async_task_groups.swift | 2 | 5871 | // RUN: %target-typecheck-verify-swift -disable-availability-checking
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
@available(SwiftStdlib 5.5, *)
func asyncFunc() async -> Int { 42 }
@available(SwiftStdlib 5.5, *)
func asyncThrowsFunc() async throws -> Int { 42 }
@available(SwiftStdlib 5.5, *)
func asyncThrowsOnCancel() async throws -> Int {
// terrible suspend-spin-loop -- do not do this
// only for purposes of demonstration
while Task.isCancelled {
try? await Task.sleep(nanoseconds: 1_000_000_000)
}
throw CancellationError()
}
@available(SwiftStdlib 5.5, *)
func test_taskGroup_add() async throws -> Int {
try await withThrowingTaskGroup(of: Int.self) { group in
group.addTask {
await asyncFunc()
}
group.addTask {
await asyncFunc()
}
var sum = 0
while let v = try await group.next() {
sum += v
}
return sum
} // implicitly awaits
}
// ==== ------------------------------------------------------------------------
// MARK: Example group Usages
struct Boom: Error {}
@available(SwiftStdlib 5.5, *)
func work() async -> Int { 42 }
@available(SwiftStdlib 5.5, *)
func boom() async throws -> Int { throw Boom() }
@available(SwiftStdlib 5.5, *)
func first_allMustSucceed() async throws {
let first: Int = try await withThrowingTaskGroup(of: Int.self) { group in
group.addTask { await work() }
group.addTask { await work() }
group.addTask { try await boom() }
if let first = try await group.next() {
return first
} else {
fatalError("Should never happen, we either throw, or get a result from any of the tasks")
}
// implicitly await: boom
}
_ = first
// Expected: re-thrown Boom
}
@available(SwiftStdlib 5.5, *)
func first_ignoreFailures() async throws {
@Sendable func work() async -> Int { 42 }
@Sendable func boom() async throws -> Int { throw Boom() }
let first: Int = try await withThrowingTaskGroup(of: Int.self) { group in
group.addTask { await work() }
group.addTask { await work() }
group.addTask {
do {
return try await boom()
} catch {
return 0 // TODO: until try? await works properly
}
}
var result: Int = 0
while let v = try await group.next() {
result = v
if result != 0 {
break
}
}
return result
}
_ = first
// Expected: re-thrown Boom
}
// ==== ------------------------------------------------------------------------
// MARK: Advanced Custom Task Group Usage
@available(SwiftStdlib 5.5, *)
func test_taskGroup_quorum_thenCancel() async {
// imitates a typical "gather quorum" routine that is typical in distributed systems programming
enum Vote {
case yay
case nay
}
struct Follower: Sendable {
init(_ name: String) {}
func vote() async throws -> Vote {
// "randomly" vote yes or no
return .yay
}
}
/// Performs a simple quorum vote among the followers.
///
/// - Returns: `true` iff `N/2 + 1` followers return `.yay`, `false` otherwise.
func gatherQuorum(followers: [Follower]) async -> Bool {
try! await withThrowingTaskGroup(of: Vote.self) { group in
for follower in followers {
group.addTask { try await follower.vote() }
}
defer {
group.cancelAll()
}
var yays: Int = 0
var nays: Int = 0
let quorum = Int(followers.count / 2) + 1
while let vote = try await group.next() {
switch vote {
case .yay:
yays += 1
if yays >= quorum {
// cancel all remaining voters, we already reached quorum
return true
}
case .nay:
nays += 1
if nays >= quorum {
return false
}
}
}
return false
}
}
_ = await gatherQuorum(followers: [Follower("A"), Follower("B"), Follower("C")])
}
// FIXME: this is a workaround since (A, B) today isn't inferred to be Sendable
// and causes an error, but should be a warning (this year at least)
@available(SwiftStdlib 5.5, *)
struct SendableTuple2<A: Sendable, B: Sendable>: Sendable {
let first: A
let second: B
init(_ first: A, _ second: B) {
self.first = first
self.second = second
}
}
@available(SwiftStdlib 5.5, *)
extension Collection where Self: Sendable, Element: Sendable, Self.Index: Sendable {
/// Just another example of how one might use task groups.
func map<T: Sendable>(
parallelism requestedParallelism: Int? = nil/*system default*/,
// ordered: Bool = true, /
_ transform: @Sendable (Element) async throws -> T
) async throws -> [T] { // TODO: can't use rethrows here, maybe that's just life though; rdar://71479187 (rethrows is a bit limiting with async functions that use task groups)
let defaultParallelism = 2
let parallelism = requestedParallelism ?? defaultParallelism
let n = self.count
if n == 0 {
return []
}
return try await withThrowingTaskGroup(of: SendableTuple2<Int, T>.self) { group in
var result = ContiguousArray<T>()
result.reserveCapacity(n)
var i = self.startIndex
var submitted = 0
func submitNext() async throws {
group.addTask { [submitted,i] in
let value = try await transform(self[i])
return SendableTuple2(submitted, value)
}
submitted += 1
formIndex(after: &i)
}
// submit first initial tasks
for _ in 0..<parallelism {
try await submitNext()
}
while let tuple = try await group.next() {
let index = tuple.first
let taskResult = tuple.second
result[index] = taskResult
try Task.checkCancellation()
try await submitNext()
}
assert(result.count == n)
return Array(result)
}
}
}
| apache-2.0 | e6bb42e02f0fc7e82de62b8b8e53bc84 | 25.445946 | 177 | 0.599046 | 4.091289 | false | false | false | false |
MidnightPulse/Tabman | Example/Tabman-Example/PresetAppearanceConfigs.swift | 1 | 2498 | //
// PresetAppearanceConfigs.swift
// Tabman-Example
//
// Created by Merrick Sapsford on 10/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import Foundation
import Tabman
class PresetAppearanceConfigs: Any {
static func forStyle(_ style: TabmanBar.Style, currentAppearance: TabmanBar.Appearance?) -> TabmanBar.Appearance? {
let appearance = currentAppearance ?? TabmanBar.Appearance.defaultAppearance
appearance.indicator.bounces = false
appearance.indicator.compresses = false
switch style {
case .bar:
appearance.style.background = .solid(color: UIColor.white.withAlphaComponent(0.3))
appearance.indicator.color = .white
appearance.indicator.lineWeight = .thick
case .scrollingButtonBar:
appearance.state.color = UIColor.white.withAlphaComponent(0.6)
appearance.state.selectedColor = UIColor.white
appearance.style.background = .blur(style: .light)
appearance.indicator.color = UIColor.white
appearance.layout.itemVerticalPadding = 16.0
appearance.indicator.bounces = true
appearance.indicator.lineWeight = .normal
appearance.layout.edgeInset = 16.0
appearance.layout.interItemSpacing = 20.0
case .buttonBar:
appearance.state.color = UIColor.white.withAlphaComponent(0.6)
appearance.state.selectedColor = UIColor.white
appearance.style.background = .blur(style: .light)
appearance.indicator.color = UIColor.white
appearance.indicator.lineWeight = .thin
appearance.indicator.compresses = true
appearance.layout.edgeInset = 8.0
appearance.layout.interItemSpacing = 0.0
case .blockTabBar:
appearance.state.color = UIColor.white.withAlphaComponent(0.6)
appearance.state.selectedColor = UIColor(red:0.92, green:0.20, blue:0.29, alpha:1.0)
appearance.style.background = .solid(color: UIColor.white.withAlphaComponent(0.3))
appearance.indicator.color = UIColor.white.withAlphaComponent(0.8)
appearance.layout.edgeInset = 0.0
appearance.layout.interItemSpacing = 0.0
appearance.indicator.bounces = true
default:
appearance.style.background = .blur(style: .light)
}
return appearance
}
}
| mit | 6040a5c3fd429072db3e43066b87f458 | 39.274194 | 119 | 0.647978 | 4.774379 | false | false | false | false |
zmeyc/GRDB.swift | DemoApps/GRDBDemoiOS/GRDBDemoiOS/Database.swift | 1 | 2047 | import GRDB
import UIKit
// The shared database queue
var dbQueue: DatabaseQueue!
func setupDatabase(_ application: UIApplication) throws {
// Setup database error log: it's very useful for debugging
// See https://github.com/groue/GRDB.swift/#error-log
Database.logError = { (resultCode, message) in
NSLog("%@", "SQLite error \(resultCode): \(message)")
}
// Connect to the database
// See https://github.com/groue/GRDB.swift/#database-connections
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
dbQueue = try DatabaseQueue(path: databasePath)
// Be a nice iOS citizen, and don't consume too much memory
// See https://github.com/groue/GRDB.swift/#memory-management
dbQueue.setupMemoryManagement(in: application)
// Use DatabaseMigrator to setup the database
// See https://github.com/groue/GRDB.swift/#migrations
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
// Create a table
// See https://github.com/groue/GRDB.swift#create-tables
try db.create(table: "persons") { t in
// An integer primary key auto-generates unique IDs
t.column("id", .integer).primaryKey()
// Sort person names in a localized case insensitive fashion by default
// See https://github.com/groue/GRDB.swift/#unicode
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
t.column("score", .integer).notNull()
}
}
migrator.registerMigration("addPersons") { db in
// Populate the persons table with random data
for _ in 0..<8 {
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
}
}
try migrator.migrate(dbQueue)
}
| mit | 74f37f300242d1b9af9b048b55ad198b | 33.694915 | 121 | 0.639961 | 4.82783 | false | false | false | false |
buguanhu/THLiveSmart | THLiveSmart/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Observer.swift | 8 | 2584 | //
// Observer.swift
// ReactiveCocoa
//
// Created by Andy Matuschak on 10/2/15.
// Copyright © 2015 GitHub. All rights reserved.
//
/// A protocol for type-constrained extensions of `Observer`.
public protocol ObserverType {
associatedtype Value
associatedtype Error: ErrorType
/// Puts a `Next` event into `self`.
func sendNext(value: Value)
/// Puts a `Failed` event into `self`.
func sendFailed(error: Error)
/// Puts a `Completed` event into `self`.
func sendCompleted()
/// Puts an `Interrupted` event into `self`.
func sendInterrupted()
}
/// An Observer is a simple wrapper around a function which can receive Events
/// (typically from a Signal).
public struct Observer<Value, Error: ErrorType> {
public typealias Action = Event<Value, Error> -> Void
/// An action that will be performed upon arrival of the event.
public let action: Action
/// An initializer that accepts a closure accepting an event for the
/// observer.
///
/// - parameters:
/// - action: A closure to lift over received event.
public init(_ action: Action) {
self.action = action
}
/// An initializer that accepts closures for different event types.
///
/// - parameters:
/// - failed: Optional closure that accepts an `Error` parameter when a
/// `Failed` event is observed.
/// - completed: Optional closure executed when a `Completed` event is
/// observed.
/// - interruped: Optional closure executed when an `Interrupted` event is
/// observed.
/// - next: Optional closure executed when a `Next` event is observed.
public init(failed: (Error -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, next: (Value -> Void)? = nil) {
self.init { event in
switch event {
case let .Next(value):
next?(value)
case let .Failed(error):
failed?(error)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
}
}
}
extension Observer: ObserverType {
/// Puts a `Next` event into `self`.
///
/// - parameters:
/// - value: A value sent with the `Next` event.
public func sendNext(value: Value) {
action(.Next(value))
}
/// Puts a `Failed` event into `self`.
///
/// - parameters:
/// - error: An error object sent with `Failed` event.
public func sendFailed(error: Error) {
action(.Failed(error))
}
/// Puts a `Completed` event into `self`.
public func sendCompleted() {
action(.Completed)
}
/// Puts an `Interrupted` event into `self`.
public func sendInterrupted() {
action(.Interrupted)
}
}
| apache-2.0 | 005e47792649ac85dd9269711725d4d1 | 25.090909 | 142 | 0.651955 | 3.59249 | false | false | false | false |
algolia/algoliasearch-client-swift | Tests/AlgoliaSearchClientTests/Doc/APIParameters/APIParameters+Pagination.swift | 1 | 2174 | //
// APIParameters+Pagination.swift
//
//
// Created by Vladislav Fitc on 07/07/2020.
//
import Foundation
import AlgoliaSearchClient
extension APIParameters {
//MARK: - Pagination
func pagination() {
func page() {
/*
page = page_number
*/
let query = Query("query")
.set(\.page, to: 0)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func hitsPerPage() {
/*
hitsPerPage = number_of_hits
*/
func set_default_hits_per_page() {
let settings = Settings()
.set(\.hitsPerPage, to: 20)
index.setSettings(settings) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func override_default_hits_per_page() {
let query = Query("query")
.set(\.hitsPerPage, to: 10)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
func offset() {
/*
offset = record_number
*/
let query = Query("query")
.set(\.offset, to: 4)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func length() {
/*
length = number_of_records
*/
let query = Query("query")
.set(\.length, to: 4)
index.search(query: query) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
func paginationLimitedTo() {
/*
paginationLimitedTo: number_of_records
*/
let settings = Settings()
.set(\.paginationLimitedTo, to: 1000)
index.setSettings(settings) { result in
if case .success(let response) = result {
print("Response: \(response)")
}
}
}
}
}
| mit | 10cbea01b82bf5944d5e1c14d089936b | 19.903846 | 51 | 0.49494 | 4.287968 | false | false | false | false |
lanjing99/RxSwiftDemo | 03-subjects-and-variable/challenge/Challenge2-Starter/RxSwift.playground/Contents.swift | 1 | 2344 | //: Please build the scheme 'RxSwiftPlayground' first
import RxSwift
example(of: "Variable") {
enum UserSession {
case loggedIn, loggedOut
}
enum LoginError: Error {
case invalidCredentials
}
let disposeBag = DisposeBag()
// Create userSession Variable of type UserSession with initial value of .loggedOut
// Subscribe to receive next events from userSession
func logInWith(username: String, password: String, completion: (Error?) -> Void) {
guard username == "[email protected]",
password == "appleseed"
else {
completion(LoginError.invalidCredentials)
return
}
// Update userSession
}
func logOut() {
// Update userSession
}
func performActionRequiringLoggedInUser(_ action: () -> Void) {
// Ensure that userSession is loggedIn and then execute action()
}
for i in 1...2 {
let password = i % 2 == 0 ? "appleseed" : "password"
logInWith(username: "[email protected]", password: password) { error in
guard error == nil else {
print(error!)
return
}
print("User logged in.")
}
performActionRequiringLoggedInUser {
print("Successfully did something only a logged in user can do.")
}
}
}
/*:
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.
*/
| mit | 1ff06bdc316aaf8caa35438e1ab7cf01 | 26.904762 | 85 | 0.712457 | 4.725806 | false | false | false | false |
JsonBin/WBAlamofire | Source/WBAlCache.swift | 1 | 11777 | //
// WBAlCache.swift
// WBAlamofire
//
// Created by zwb on 2017/12/27.
// Copyright © 2017年 HengSu Technology. All rights reserved.
//
import Foundation
/// WBAlCache is a cache handler class
public struct WBAlCache {
public static let shared = WBAlCache()
public typealias CacheSizeCompleteClosure = (_ size: UInt) -> Void
public typealias CacheSizeCleanClosure = (_ complete: Bool) -> Void
private let manager = FileManager.default
// MARK: - Cache and Download Files Size
///=============================================================================
/// @name Cache and Download Files Size
///=============================================================================
/// 所有下载文件的大小.
/// The download files size.
///
/// - Parameter complete: calculate the download file size with closure
public func downloadCacheSize(_ complete: @escaping CacheSizeCompleteClosure) {
DispatchQueue.wbCurrent.async {
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
path = (path as NSString).appendingPathComponent(WBAlConfig.shared.downFileName)
let size = self.travelCacheFiles(path)
DispatchQueue.main.async {
complete(size)
}
}
}
/// 所有缓存文件的大小.
/// The cache files size.
///
/// - Parameter complte: calculate the response cache file size with closure
public func responseCacheFilesSize(_ complte: @escaping CacheSizeCompleteClosure) {
DispatchQueue.wbCurrent.async {
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
path = (path as NSString).appendingPathComponent(WBAlConfig.shared.cacheFileName)
let size = self.travelCacheFiles(path)
DispatchQueue.main.async {
complte(size)
}
}
}
// MARK: - Remove Cache and Download Files
///=============================================================================
/// @name Remove Cache and Download Files
///=============================================================================
/// Remove all the downloaded file, or the name of the specified file
///
/// - Parameters:
/// - name: need to remove the name of the file. Don't pass parameters, to remove all the downloaded file by default
/// - complete: when remove completed, closure will be used. if not set, the files will remove in background.
public func removeDownloadFiles(with name: String? = nil, complete: CacheSizeCleanClosure? = nil) {
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
path = (path as NSString).appendingPathComponent(WBAlConfig.shared.downFileName)
if let name = name {
do {
let path = (path as NSString).appendingPathComponent(name)
try manager.removeItem(atPath: path)
complete?(true)
} catch { complete?(false) }
return
}
do {
try manager.removeItem(atPath: path)
try manager.createDirectory(atPath: path, withIntermediateDirectories: true)
complete?(true)
} catch { complete?(false) }
}
/// To remove a single or all the cache files
///
/// - Parameters:
/// - request: need to remove the cache file request. Don't pass this parameter, the default to remove all the cache files
/// - complete: when remove completed, closure will be used. if not set, the files will remove in background.
public func removeCacheFiles(for request: WBAlRequest? = nil, complete: CacheSizeCleanClosure? = nil) {
if let request = request {
let cachePath = cacheFilePath(request)
let metadataPath = cacheMetadataFilePath(request)
do {
try manager.removeItem(atPath: cachePath)
try manager.removeItem(atPath: metadataPath)
complete?(true)
} catch { complete?(false) }
return
}
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
path = (path as NSString).appendingPathComponent(WBAlConfig.shared.cacheFileName)
do {
try manager.removeItem(atPath: path)
try manager.createDirectory(atPath: path, withIntermediateDirectories: true)
complete?(true)
} catch { complete?(false) }
}
/// Remove all files
///
/// - Parameter complte: when remove completed, closure will be used. if not set, the files will remove in background.
public func removeAllFiles(_ complte: @escaping CacheSizeCleanClosure) {
removeDownloadFiles { (finised) in
if finised {
self.removeCacheFiles(complete: complte)
} else {
complte(false)
}
}
}
// MARK: - Cache File Path
///=============================================================================
/// @name Cache File Path
///=============================================================================
/// Access to the path of the cache file
///
/// - Parameter request: Need to get the cache the request of the path
/// - Returns: The cache file path
public func cacheFilePath(_ request: WBAlRequest) -> String {
let cacheName = self.cacheFileName(request)
let cachePath = self.cacheBasePath(request) as NSString
return cachePath.appendingPathComponent(cacheName)
}
/// Take the path of the metadata file
///
/// - Parameter request: Need to get the metadata file path of the request
/// - Returns: The path of the metadata file
public func cacheMetadataFilePath(_ request: WBAlRequest) -> String {
let metaName = self.cacheFileName(request) + ".metadata"
let metaPath = self.cacheBasePath(request) as NSString
return metaPath.appendingPathComponent(metaName)
}
// MARK: - Private
///=============================================================================
/// @name Private
///=============================================================================
/// The name of the cache file
private func cacheFileName(_ request: WBAlRequest) -> String {
let requestURL = request.requestURL
let baseURL = WBAlConfig.shared.baseURL
var requestInfo = String(format: "Host:%@, Url:%@, Method:%@", baseURL, requestURL, request.requestMethod.rawValue.rawValue)
if let params = request.requestParams {
let params = request.cacheFileNameFilterForRequestParams(params)
requestInfo = requestInfo.appendingFormat(", Params:%@", params)
}
let cacheFileName = WBAlUtils.md5WithString(requestInfo)
return cacheFileName
}
/// The path of the cache file
private func cacheBasePath(_ request: WBAlRequest) -> String {
let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
var cachePath = (path as NSString).appendingPathComponent(WBAlConfig.shared.cacheFileName)
// Filter cache dirPath if needed
let filters = WBAlConfig.shared.cacheDirPathFilters
if !filters.isEmpty {
for filter in filters {
cachePath = filter.filterCacheDirPath(cachePath, baseRequest: request)
}
}
let manager = FileManager.default
var isDirectory:ObjCBool = true
if !manager.fileExists(atPath: cachePath, isDirectory: &isDirectory) {
isDirectory = false
// create
createBaseCachePath(cachePath)
} else {
if !isDirectory.boolValue {
try? manager.removeItem(atPath: cachePath)
createBaseCachePath(cachePath)
}
}
return cachePath
}
private func createBaseCachePath(_ path: String) {
do {
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
WBAlUtils.addNotBackupAttribute(path)
} catch {
WBAlog("Create cache directory failed, reason = \(error)")
}
}
/// Remove the entire contents of a folder
///
/// - Parameters:
/// - filePath: need to remove the folder
/// - complete: whether remove complete
private func removeForder(with filePath: String, complete: CacheSizeCleanClosure?) {
let manager = FileManager.default
if !manager.fileExists(atPath: filePath, isDirectory: nil) {
DispatchQueue.main.async {
complete?(false)
}
return
}
DispatchQueue.wbCurrent.async {
let filePaths = manager.subpaths(atPath: filePath)
filePaths?.forEach {
let fileAbsoluePath = (filePath as NSString).appendingPathComponent($0)
do {
try manager.removeItem(atPath: fileAbsoluePath)
} catch {
WBAlog("Remove Failed! remove file failed from \(fileAbsoluePath) with reason is: \(error)")
}
}
DispatchQueue.main.async {
complete?(true)
}
}
}
/// Calculate the size of the folder
///
/// - Parameters:
/// - filePath: the folder path
/// - complete: all the file's size
private func forderSize(with filePath: String, complete: @escaping CacheSizeCompleteClosure) -> Void {
let manager = FileManager.default
if !manager.fileExists(atPath: filePath, isDirectory: nil) {
complete(0)
return
}
DispatchQueue.wbCurrent.async {
let filePaths = manager.subpaths(atPath: filePath)
var size: Double = 0
filePaths?.forEach {
let fileAbsoluePath = (filePath as NSString).appendingPathComponent($0)
size += self.sizeOfFilePath(path: fileAbsoluePath)
}
DispatchQueue.main.async {
complete(UInt(size))
}
}
}
/// A single file size
///
/// - Parameter path: The file path
/// - Returns: Access to the file size
private func sizeOfFilePath(path: String) -> Double {
let manager = FileManager.default
if !manager.fileExists(atPath: path) { return 0 }
do {
let dic = try manager.attributesOfItem(atPath: path)
if let size = dic[.size] as? Double { return size }
return 0
} catch { return 0 }
}
private func travelCacheFiles(_ path: String) -> UInt {
let url = URL(fileURLWithPath: path)
let resourceKeys: Set<URLResourceKey> = [.isDirectoryKey, .contentAccessDateKey, .totalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0
var urls = [URL]()
do {
urls = try manager.contentsOfDirectory(at: url, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)
} catch { }
for fileURL in urls {
do {
let resourceValues = try fileURL.resourceValues(forKeys: resourceKeys)
if resourceValues.isDirectory == true {
continue
}
if let size = resourceValues.totalFileAllocatedSize {
diskCacheSize += UInt(size)
}
} catch {}
}
return diskCacheSize
}
}
| mit | 7a01fef893defdda44895109ec838cad | 36.501597 | 136 | 0.576504 | 5.240179 | false | false | false | false |
softdevstory/yata | yataTests/Sources/Models/NodeElementTests.swift | 1 | 3834 | //
// NodeElementTests.swift
// yata
//
// Created by HS Song on 2017. 6. 14..
// Copyright © 2017년 HS Song. All rights reserved.
//
import Foundation
import XCTest
class NodeElementTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testNoJsonString() {
let nodeElement = NodeElement(JSONString: "test")
XCTAssertNil(nodeElement)
}
func testMappingSimple() {
let jsonObject: [String: Any] = [
"tag": "p",
"attrs": [
"id": "Big-text",
"target": "_blank"
],
"children": [ "This is a test" ]
]
let jsonString = convertJSONString(from: jsonObject)
XCTAssertNotNil(jsonString)
let nodeElement = NodeElement(JSONString: jsonString!)
XCTAssertNotNil(nodeElement)
XCTAssertEqual(nodeElement?.tag, "p")
XCTAssertEqual(nodeElement?.attrs?.id, "Big-text")
XCTAssertEqual(nodeElement?.children?.count, 1)
if let node = nodeElement?.children?[0] {
switch node.type {
case .string:
XCTAssertEqual(node.value, "This is a test")
default:
XCTAssert(false)
}
} else {
XCTAssert(false)
}
}
func testMappingComplex() {
let jsonObject: [String: Any] = [
"tag": "figure",
"attrs": [
"id": "Big-text"
],
"children": [
[
"tag": "img",
"attrs": [
"src": "/file/15e6f3a9880edd9ef2436.png",
"id": "test"
],
"children": [
[
"tag": "img",
"attrs": [
"src": "/file/15e6f3a9880edd9ef2436.png",
"id": "test"
],
"children": [
"테스트 이미지"
]
]
]
],
[
"tag": "figcaption",
"children": [
"테스트 이미지"
]
]
]
]
let jsonString = convertJSONString(from: jsonObject)
XCTAssertNotNil(jsonString)
let nodeElement = NodeElement(JSONString: jsonString!)
XCTAssertNotNil(nodeElement)
XCTAssertEqual(nodeElement?.tag, jsonObject["tag"] as? String)
XCTAssertEqual(nodeElement?.attrs?.id, "Big-text")
if let children = nodeElement?.children {
for item in children {
switch item.element.tag! {
case "img":
XCTAssertEqual(item.element.attrs?.id, "test")
if let subChild = item.element.children?[0] {
XCTAssertEqual(subChild.element.tag, "img")
XCTAssertEqual(subChild.element.attrs?.id, "test")
XCTAssertEqual(subChild.element.children?[0].value, "테스트 이미지")
} else {
XCTAssert(false)
}
case "figcaption":
XCTAssertEqual(item.element.children?[0].value, "테스트 이미지")
default:
XCTAssert(false)
}
}
}
}
}
| mit | d406a9feca67cdf65b5012621a5173d7 | 29.264 | 111 | 0.435369 | 5.084677 | false | true | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Platform/iOS/Controllers/EmptyDetailsViewController.swift | 1 | 1854 | //
// EmptyDetailsViewController.swift
// Bluefruit Connect
//
// Created by Antonio García on 06/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import UIKit
class EmptyDetailsViewController: ModuleViewController {
// UI
@IBOutlet weak var emptyLabel: UILabel!
// Data
private var isConnnecting = false
private var isAnimating = false
private var scanningAnimationVieWController: ScanningAnimationViewController?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
setConnecting(isConnnecting)
}
func setConnecting(isConnecting : Bool) {
self.isConnnecting = isConnecting
let localizationManager = LocalizationManager.sharedInstance
emptyLabel?.text = localizationManager.localizedString(isConnecting ? "peripheraldetails_connecting" : "peripheraldetails_select")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ScanningAnimationViewControllerSegue" {
scanningAnimationVieWController = (segue.destinationViewController as! ScanningAnimationViewController)
if isAnimating { // check if startAnimating was called before preprareForSegue was executed
startAnimating()
}
}
}
func startAnimating() {
isAnimating = true
scanningAnimationVieWController?.startAnimating()
}
func stopAnimating() {
isAnimating = false
scanningAnimationVieWController?.stopAnimating()
}
}
| mit | 1833c32f4e73da93d294529a94adb1a0 | 28.396825 | 138 | 0.678186 | 5.595166 | false | false | false | false |
noppefoxwolf/ZappingKit | ZappingKit/Classes/ZappableViewController.swift | 1 | 10709 | //
// ZappableViewController.swift
// Pods
//
// Created by Tomoya Hirano on 2016/10/11.
//
//
import UIKit
import RxSwift
import RxCocoa
public protocol ZappableViewControllerDataSource: class {
func zappableViewController(_ zappableViewController: ZappableViewController, viewControllerBefore viewController: UIViewController?) -> UIViewController?
func zappableViewController(_ zappableViewController: ZappableViewController, viewControllerAfter viewController: UIViewController?) -> UIViewController?
}
public protocol ZappableViewControllerDelegate: class { }
open class ZappableViewController: UIViewController {
enum DirectionType {
case before
case idle
case after
static func type(translationY: CGFloat) -> DirectionType {
switch translationY {
case (let y) where y > 0: return .after
case (let y) where y < 0: return .before
default: return .idle
}
}
}
public enum HandlingMode {
case velocity
case translation
case mix
}
weak public var delegate: ZappableViewControllerDelegate? = nil
weak public var dataSource: ZappableViewControllerDataSource? = nil
private var peekContainerView = ContainerView()
private var contentView = ContainerView()
//options
public var disableBounceIfNotingNext = true
private var lockIdentity = false
public var validVelocityOffset: CGFloat = 0.0
public var validTranslationOffset: CGFloat = 0.0
//temp
private var directionHandler = PublishSubject<DirectionType>()
private var peekContentType = BehaviorSubject<DirectionType>(value: .idle)
private var pushPublisher = PublishSubject<CGFloat>()
private var isScrollEnable = false
private var isNeedEndAppearanceContentView = false
private var disposeBag = DisposeBag()
public var handlingMode: HandlingMode = .velocity
open override func viewDidLoad() {
super.viewDidLoad()
setup()
setupSubscriber()
}
private func setup() {
peekContainerView.translatesAutoresizingMaskIntoConstraints = false
contentView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(peekContainerView)
view.addSubview(contentView)
view.addConstraints(FillConstraintsPair(of: peekContainerView, name: "peekContainerView"))
view.addConstraints(FillConstraintsPair(of: contentView, name: "contentView"))
let pan = UIPanGestureRecognizer(target: self, action: #selector(panAction(_:)))
pan.delegate = self
view.addGestureRecognizer(pan)
}
private func setupSubscriber() {
directionHandler.distinctUntilChanged().asDriver(onErrorJustReturn: .idle).drive(onNext: { [weak self] (type) in
self?.preparePeekContentView(with: type)
}).addDisposableTo(disposeBag)
pushPublisher.map { [weak self] (velocityY) -> (DirectionType, CGFloat) in
guard let value = try? self?.peekContentType.value(), let currentDirection = value else { return (.idle, velocityY) }
switch currentDirection {
case .after where velocityY <= 0: return (.idle, velocityY)
case .before where velocityY >= 0: return (.idle, velocityY)
default: return (currentDirection, velocityY)
}
}.filter({ [weak self] (type, velocityY) -> Bool in
guard let value = try? self?.peekContentType.value(), let currentDirection = value else { return false }
return !(currentDirection == .idle && type == .idle && !self!.isNeedEndAppearanceContentView)
}).asDriver(onErrorJustReturn: (.idle, 0.0)).drive(onNext: { [weak self] (type, velocityY) in
guard let _self = self else { return }
var toY: CGFloat = 0.0
switch type {
case .after: toY = _self.view.bounds.height
case .before: toY = -_self.view.bounds.height
default: break
}
let rangeY = abs(_self.contentView.frame.origin.y - toY)
let duration = min(rangeY / velocityY, 0.75)
switch type {
case .after, .before:
self?.view.isUserInteractionEnabled = false
UIView.animate(withDuration: TimeInterval(duration), delay: 0.0, options: .allowAnimatedContent, animations: {
self?.contentView.transform = CGAffineTransform(translationX: 0, y: toY)
}, completion: { [weak self] (_) in
self?.peekContainerView.viewController?.endAppearanceTransition()
self?.isNeedEndAppearanceContentView = false
self?.contentView.viewController?.endAppearanceTransition()
self?.contentView.viewController?.willMove(toParentViewController: nil)
self?.contentView.viewController?.view.removeFromSuperview()
self?.contentView.viewController?.removeFromParentViewController()
self?.contentView.viewController = nil
if let vc = self?.peekContainerView.viewController {
self?.peekContainerView.viewController = nil
vc.view.removeFromSuperview()
self?.contentView.viewController = vc
self?.contentView.addSubview(vc.view)
self?.contentView.addConstraints(FillConstraintsPair(of: vc.view))
self?.contentView.viewController?.endAppearanceTransition()
self?.contentView.transform = CGAffineTransform.identity
self?.directionHandler.onNext(.idle)
}
self?.view.isUserInteractionEnabled = true
})
default:
self?.view.isUserInteractionEnabled = false
UIView.animate(withDuration: TimeInterval(duration), delay: 0.0, options: .allowAnimatedContent, animations: {
self?.contentView.transform = CGAffineTransform.identity
}, completion: { (_) in
self?.peekContainerView.viewController?.beginAppearanceTransition(false, animated: false)
self?.peekContainerView.viewController?.endAppearanceTransition()
self?.peekContainerView.viewController?.willMove(toParentViewController: nil)
self?.peekContainerView.viewController?.view.removeFromSuperview()
self?.peekContainerView.viewController?.removeFromParentViewController()
self?.peekContainerView.viewController = nil
self?.isNeedEndAppearanceContentView = false
self?.contentView.viewController?.beginAppearanceTransition(true, animated: true)
self?.contentView.viewController?.endAppearanceTransition()
self?.directionHandler.onNext(.idle)
self?.view.isUserInteractionEnabled = true
})
}
}).addDisposableTo(disposeBag)
}
private func preparePeekContentView(with type: DirectionType) {
var vc: UIViewController? = nil
switch type {
case .after:
vc = dataSource?.zappableViewController(self, viewControllerAfter: contentView.viewController)
case .before:
vc = dataSource?.zappableViewController(self, viewControllerBefore: contentView.viewController)
default: break
}
isScrollEnable = (vc != nil)
peekContainerView.viewController?.beginAppearanceTransition(false, animated: false)
peekContainerView.viewController?.endAppearanceTransition()
peekContainerView.viewController?.willMove(toParentViewController: nil)
peekContainerView.viewController?.view.removeFromSuperview()
peekContainerView.viewController?.removeFromParentViewController()
peekContainerView.viewController = nil
if let vc = vc {
isNeedEndAppearanceContentView = true
peekContentType.onNext(type)
contentView.viewController?.beginAppearanceTransition(false, animated: true)
vc.beginAppearanceTransition(true, animated: false)
vc.view.translatesAutoresizingMaskIntoConstraints = false
addChildViewController(vc)
peekContainerView.viewController = vc
peekContainerView.addSubview(vc.view)
peekContainerView.addConstraints(FillConstraintsPair(of: vc.view))
vc.didMove(toParentViewController: self)
} else {
peekContentType.onNext(.idle)
}
}
@objc private func panAction(_ sender: UIPanGestureRecognizer) {
let translationY = sender.translation(in: self.view).y
let velocityY = sender.velocity(in: self.view).y
switch sender.state {
case .began, .changed:
directionHandler.onNext(DirectionType.type(translationY: translationY))
if isScrollEnable {
contentView.transform = CGAffineTransform(translationX: 0, y: translationY)
}
case .ended:
pushPublisher.onNext(velocityY)
default: break
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
contentView.viewController?.beginAppearanceTransition(true, animated: animated)
contentView.viewController?.endAppearanceTransition()
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
contentView.viewController?.beginAppearanceTransition(false, animated: animated)
contentView.viewController?.endAppearanceTransition()
}
//Must call in viewDidLoad
public func first(_ viewController: UIViewController) {
//viewController.beginAppearanceTransition(true, animated: false)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
addChildViewController(viewController)
contentView.viewController = viewController
contentView.addSubview(viewController.view)
contentView.addConstraints(FillConstraintsPair(of: viewController.view))
viewController.didMove(toParentViewController: self)
//viewController.endAppearanceTransition()
}
//viewWillAppearとかの制御権を握る
open override var shouldAutomaticallyForwardAppearanceMethods: Bool { return false }
}
extension ZappableViewController: UIGestureRecognizerDelegate {
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let recog = gestureRecognizer as? UIPanGestureRecognizer {
switch handlingMode {
case .velocity:
let velocity = recog.velocity(in: self.view)
if abs(velocity.y) > abs(velocity.x) && validVelocityOffset < abs(velocity.y) {
return true
}
case .translation:
let translate = recog.translation(in: self.view)
if abs(translate.y) > abs(translate.x) && validTranslationOffset < abs(translate.y) {
return true
}
case .mix:
let velocity = recog.velocity(in: self.view)
let translate = recog.translation(in: self.view)
if abs(velocity.y) > abs(velocity.x) && validVelocityOffset < abs(velocity.y) && abs(translate.y) > abs(translate.x) && validTranslationOffset < abs(translate.y) {
return true
}
}
}
return false
}
}
| mit | 409431cb871d4113115d303d4cceee9c | 40.119231 | 171 | 0.712468 | 5.142376 | false | false | false | false |
nyin005/Forecast-App | Forecast/Forecast/Class/Summary/SummaryViewController.swift | 1 | 2614 | //
// SummaryViewController.swift
// Forecast
//
// Created by appledev110 on 11/22/16.
// Copyright © 2016 appledev110. All rights reserved.
//
import UIKit
class SummaryViewController: BaseViewController {
var scrollViewSet: ScrollViewSet?
var summaryView: SummaryTableView?
var onBenchVC: OnBenchViewController?
private var summaryModel: SummaryListModel? = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.initNavView(title: "Summary", bolBack: false, bolRefresh: false)
fetchSummaryData()
}
func fetchSummaryData() {
let path = Bundle.main.path(forResource: "summary", ofType: "json")
do {
let content = try String(contentsOfFile: path!)
self.summaryModel = SummaryListModel(JSONString: content)!
} catch _ {
}
if self.summaryModel != nil {
initUI()
}
}
func initUI() {
scrollViewSet = ScrollViewSet.init(frame: CGRect(x: 0, y: 32, width: LCDW, height: LCDH - 32))
self.view.addSubview(scrollViewSet!)
initSummaryView()
}
func initSummaryView() {
for i in 0..<Int((self.summaryModel?.data.count)!) {
summaryView = SummaryTableView.init(frame: CGRect(x: CGFloat(i) * LCDW, y: 0, width: LCDW, height: LCDH - 64), style: .plain)
summaryView?.reports = (self.summaryModel?.data[i].reports)!
summaryView?.cellClickedHandler = {(obj) -> Void in
let index : Int = Int(obj as! NSNumber)
self.openOnBenchVC(titleStr: (self.summaryModel?.data[index].reports[index].date)!)
}
self.scrollViewSet?.scrollView?.addSubview(summaryView!)
}
}
func openOnBenchVC(titleStr: String) {
onBenchVC = OnBenchViewController()
onBenchVC?.titleStr = titleStr
self.navigationController?.pushViewController(onBenchVC!, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | a936eb1f0b6e1aabd1c526679dae2554 | 30.481928 | 137 | 0.619977 | 4.592267 | false | false | false | false |
allen-zeng/PromiseKit | Tests/A+ Specs/0.0.0.swift | 2 | 2956 | import PromiseKit
import XCTest
// we reject with this when we don't intend to test against it
enum Error: ErrorType { case Dummy }
func later(ticks: Int = 1, _ body: () -> Void) {
let ticks = Double(NSEC_PER_SEC) / (Double(ticks) * 50.0 * 1000.0)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(ticks)), dispatch_get_main_queue(), body)
}
extension XCTestCase {
func testFulfilled(numberOfExpectations: Int = 1, body: (Promise<Int>, [XCTestExpectation], Int) -> Void) {
let specify = mkspecify(numberOfExpectations, generator: { Int(arc4random()) }, body: body)
specify("already-fulfilled") { value in
return (Promise(value), {})
}
specify("immediately-fulfilled") { value in
let (promise, fulfill, _) = Promise<Int>.pendingPromise()
return (promise, {
fulfill(value)
})
}
specify("eventually-fulfilled") { value in
let (promise, fulfill, _) = Promise<Int>.pendingPromise()
return (promise, {
later {
fulfill(value)
}
})
}
}
func testRejected(numberOfExpectations: Int = 1, body: (Promise<Int>, [XCTestExpectation], ErrorType) -> Void) {
let specify = mkspecify(numberOfExpectations, generator: { _ -> ErrorType in
return NSError(domain: PMKErrorDomain, code: Int(arc4random()), userInfo: nil)
}, body: body)
specify("already-rejected") { error in
return (Promise(error: error), {})
}
specify("immediately-rejected") { error in
let (promise, _, reject) = Promise<Int>.pendingPromise()
return (promise, {
reject(error)
})
}
specify("eventually-rejected") { error in
let (promise, _, reject) = Promise<Int>.pendingPromise()
return (promise, {
later {
reject(error)
}
})
}
}
/////////////////////////////////////////////////////////////////////////
private func mkspecify<T>(numberOfExpectations: Int, generator: () -> T, body: (Promise<Int>, [XCTestExpectation], T) -> Void) -> (String, feed: (T) -> (Promise<Int>, () -> Void)) -> Void {
return { desc, feed in
let floater = self.expectationWithDescription("")
later(2, floater.fulfill)
let value = generator()
let (promise, after) = feed(value)
let expectations = (1...numberOfExpectations).map {
self.expectationWithDescription("\(desc) (\($0))")
}
body(promise, expectations, value)
after()
self.waitForExpectationsWithTimeout(1, handler: nil)
}
}
}
func XCTAssertEqual(e1: ErrorType, _ e2: ErrorType) {
XCTAssert(e1 as NSError == e2 as NSError)
}
| mit | 2bcc96ae72b44b1a6c3fc3b80a3e2ddb | 32.213483 | 193 | 0.536198 | 4.561728 | false | true | false | false |
Eonil/Channel.Swift | Workbench/main.swift | 1 | 2794 | //
// main.swift
// Replicate
//
// Created by Hoon H. on 2015/04/08.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import Channel
//let e = Emitter<Int>()
//let m = Monitor<Int>(println)
//e.register(m)
//e.signal(222)
let e = Dispatcher<Int>()
let r = Relay<Int>()
let m = Monitor<Int>(println)
e.register(r)
r.register(m)
e.signal(333)
//class Gate<T,U> {
// typealias IncomingSignal = T
// typealias OutgoingSignal = U
//
// func register(m: Monitor<T>) {
//
// }
// func deregister(m: Monitor<T>) {
//
// }
//
// private let transform: T->U
// private init(_ transform: T->U) {
// self.transform = transform
// }
// private func signal(s: IncomingSignal) {
//
// }
//}
//class ArrayRepository<T> {
// private(set) var state: [T] = []
// func signal(t: ArrayTransaction<T>) {
// }
// func register(r: ArrayReplication<T>) {
// assert(r.session == nil)
// r.session = ArrayReplicationSession(source: self)
// }
// func deregister(r: ArrayReplication<T>) {
// assert(r.session != nil)
// assert(r.session!.source === self)
// r.session = nil
// }
//}
//
//class ArrayReplication<T> {
//
// init() {
// }
//
// var state: [T]? {
// get {
// return session?.localcopy
// }
// }
//
// private var session: ArrayReplicationSession<T>?
//
// private func signal(s: ArrayTransaction<T>) {
// assert(session != nil)
// }
//}
//
//private final class ArrayReplicationSession<T> {
// unowned let source: ArrayRepository<T>
// private(set) var localcopy: [T]
// init(source: ArrayRepository<T>) {
// self.source = source
// localcopy = source.state
// }
// deinit {
// }
//}
//
//class ArrayMonitor<T> {
//
// init() {
// }
// var state: [T]? {
// get {
// return session?.source.state
// }
// }
//
// private var session: ArrayMonitoringSession<T>?
//
// private func signal(s: ArrayTransaction<T>) {
// assert(session != nil)
// }
//}
//
//private final class ArrayMonitoringSession<T> {
// unowned let source: ArrayRepository<T>
// init(source: ArrayRepository<T>) {
// self.source = source
// }
// deinit {
// }
//}
//
//
//class Spot<T> {
// func register(r: Replication<T>) {
// assert(r.session == nil)
// r.session = ReplicationSession(source: self)
// }
// func deregister(r: Replication<T>) {
// assert(r.session != nil)
// assert(r.session!.source === self)
// r.session = nil
// }
//}
//class Replication<T> {
// init() {
// }
//
// private var session: ReplicationSession<T>?
//
// private func signal(T) {
// assert(session != nil)
// }
//}
//
//private final class ReplicationSession<T> {
// unowned let source: Spot<T>
// init(source: Spot<T>) {
// self.source = source
// }
// deinit {
// }
//}
//
| mit | 93ea2903af42bdae79f2aa8e7f01252b | 9.956863 | 53 | 0.579456 | 2.618557 | false | false | false | false |
mitchtreece/Spider | Spider/Classes/Core/SSE/EventParser.swift | 1 | 2754 | //
// EventParser.swift
// Spider-Web
//
// Created by Mitch Treece on 10/6/20.
//
import Foundation
internal class EventParser {
// Events are separated by end of line. End of line can be:
// \r = CR (Carriage Return) → Used as a new line character in Mac OS before X
// \n = LF (Line Feed) → Used as a new line character in Unix/Mac OS X
// \r\n = CR + LF → Used as a new line character in Windows
private let newlineCharacters = [
"\r\n",
"\n",
"\r"
]
private let buffer: EventBuffer
init() {
self.buffer = EventBuffer(newlineCharacters: self.newlineCharacters)
}
func parse(data: Data?) -> [Event] {
return self.buffer
.append(data: data)
.map { self.event(from: $0) }
}
private func event(from string: String) -> Event {
var event = [String: String?]()
for line in string.components(separatedBy: CharacterSet.newlines) as [String] {
guard let (key, value) = parseLine(line) else { continue }
if let value = value, let lastValue = event[key] ?? nil {
event[key] = "\(lastValue)\n\(value)"
}
else if let value = value {
event[key] = value
}
else {
event[key] = nil
}
}
var retryTime: Int?
if let retryString = (event["retry"] ?? nil) {
retryTime = Int(retryString.trimmingCharacters(in: CharacterSet.whitespaces))
}
return Event(
id: event["id"] ?? nil,
type: event["event"] ?? nil,
data: event["data"] ?? nil,
retryTime: retryTime
)
}
private func parseLine(_ line: String) -> (key: String, value: String?)? {
var nsKey: NSString?
var nsValue: NSString?
let scanner = Scanner(string: line)
scanner.scanUpTo(":", into: &nsKey)
scanner.scanString(":", into: nil)
for character in self.newlineCharacters {
if scanner.scanUpTo(character, into: &nsValue) {
break
}
}
// If theres no key, abort.
guard let _nsKey = nsKey,
_nsKey.length > 0 else { return nil }
// For id & data, if they come empty
// they should return an empty string not nil.
if _nsKey != "event" && nsValue == nil {
nsValue = ""
}
return (
_nsKey as String,
nsValue as String?
)
}
}
| mit | 5b084d5119b95fbae4e5d69a775126e9 | 25.171429 | 89 | 0.486172 | 4.439418 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/4.3HW.playground/Contents.swift | 1 | 8236 | import UIKit
//1. Прочитайте главы Enumerations и Classes and Structures в книге «The Swift Programming Language».
//Done
//2. Если бы в вашей программе была работа с игральными картами, как бы вы организовали их хранение? Приведите пример.
enum CardValue {
case king, queen, jack, ace, one, two, three, four, five, six, seven, eight, nine, ten
}
enum Card {
case hearts(value: CardValue)
case diamonds(value: CardValue)
case spades(value: CardValue)
case clubs(value: CardValue)
}
var card:Card
card = .clubs(value: .two)
//3. Каких типов могут быть raw значения кейсов enum’а?
//String, Character, Int, Float, Double
//4. Напишите класс и структуру для хранения информации (положение, размер) о круге, прямоугольнике.
struct Figure {
var coordinateCircle: (Int, Int, String) = (2, 0, "Large")
var coordinateRectangle: (Int, Int, String) = (-1, 6, "Medium")
}
var fig = Figure()
fig.coordinateCircle
class FigureClass {
var coordinateCircle: (Int, Int, String) = (2, 0, "Large")
var coordinateRectangle: (Int, Int, String) = (-1, 6, "Medium")
}
var figClass = FigureClass()
figClass.coordinateCircle
//5. Для следующего кода, выполнение каких строчек закончится ошибкой и почему:
//
//class ClassUser1{
// let name: String
// init(name: String) {
// self.name = name
// }
//}
//
//
//class ClassUser2{
// var name: String
// init(name: String) {
// self.name = name
// }
//}
//
//
//struct StructUser1{
// let name: String
// init(name: String) {
// self.name = name
// }
//}
//
//
//struct StructUser2{
// var name: String
// init(name: String) {
// self.name = name
// }
//}
//
//
//let user1 = ClassUser1(name: "Nikita")
//user1.name = "Anton" //name объявлена в классе как константа
//
//
//let user2 = ClassUser2(name: "Nikita")
//user2.name = "Anton"
//
//
//let user3 = StructUser1(name: "Nikita")
//user3.name = "Anton" //name3 объявлена как константа
//
//
//let user4 = StructUser2(name: "Nikita")
//user4.name = "Anton" //name4 объявлена как константа
//
//
//var user5 = ClassUser1(name: "Nikita")
//user5.name = "Anton" //name объявлена в классе как константа
//
//
//var user6 = ClassUser2(name: "Nikita")
//user6.name = "Anton"
//
//
//var user7 = StructUser1(name: "Nikita")
//user7.name = "Anton" //name объявлена в структуре как константа
//
//
//var user8 = StructUser2(name: "Nikita")
//user8.name = "Anton"
//6. Напишите пример класса автомобиля (какие поля ему нужны – на ваше усмотрение) с конструктором, в котором часть полей будет иметь значение по умолчанию.
class Automobile {
let type: String = "light"
let power: Int = 100
var doors: Int
var transmission: String
init(doors: Int, transmission: String) {
self.doors = doors
self.transmission = transmission
}
}
var auto = Automobile(doors: 4, transmission: "Auto")
auto.power
//7. Напишите класс для калькулятора с функциями для сложения, вычитания, умножения и деления цифр, которые в нем хранятся как свойства.
enum Operators {
case plus, minus, division, multiplication
}
class Calculator {
let typeOperator: Operators
init(typeOperator: Operators) {
self.typeOperator = typeOperator
}
func calculate(num1: Double, num2: Double) -> Double {
switch typeOperator {
case .plus:
return num1 + num2
case .minus:
return num1 - num2
case .division:
return num1 / num2
case .multiplication:
return num1 * num2
}
}
}
var sum = Calculator(typeOperator: .plus)
sum.calculate(num1: 1, num2: 3)
//8. В каких случаях следует использовать ключевое слово static?
//В случаях, когда нам необходимо, чтобы свойство или функция принадлежала не экземпляру класса, а самому классу и не могла быть вызвана напрямую.
//9. Могут ли иметь наследников:
//1. Классы
//Да, т.к. это тип ссылка, а ссылки можно наследовать, в отличие от типа значение, которое не наследуется, а копируется
//2. Структуры
//Нет, т.к. это тип значение, а не ссылка
//3. Enum’ы
//Нет, как и структуры.
//10. Представим, что вы создаете rpg игру. Напишите структуру для хранения координаты игрока, enum для направлений (восток, сервер, запад, юг) и функцию, которая берет к себе на вход позицию и направление и возвращает новую координату (после того как игрок походил на одну клетку в соответствующую сторону). Вызовите эту функцию несколько раз, «походив» своим игроком
struct Coordinates {
var coordinate = (0, 0)
}
enum Routes {
case east, north, west, south
}
func calculationCoordinates(position: Coordinates, route: Routes) -> Coordinates {
switch route {
case .east:
return .init(coordinate: (position.coordinate.0 + 1, position.coordinate.1))
case .north:
return .init(coordinate: (position.coordinate.0, position.coordinate.1 + 1))
case .south:
return .init(coordinate: (position.coordinate.0 + 1, position.coordinate.1 - 1))
case .west:
return .init(coordinate: (position.coordinate.0 - 1, position.coordinate.1))
// default:
// return .init(coordinate: (position.coordinate.0, position.coordinate.1))
}
}
var eastStep = calculationCoordinates(position: Coordinates.init(coordinate: (4, 6)), route: .east)
eastStep.coordinate
var northStep = calculationCoordinates(position: Coordinates.init(coordinate: (2, 7)), route: .north)
northStep.coordinate
//Бонусные задания к урокам:
//
//Енамы
//Можно ли в enum’е хранить дополнительные данные?
/*Не понял вопрос. Что подразумавается под дополнительными данными?
Перечисления могут в себе группировать, помимо самих членов перечсисления, другие перечисления, методы, свойства. В этом суть вопроса?
*/
//Классы
//В каких случаях удобнее структурировать данные и функции в класс?
//Не знаю. Прошу объяснить. Сейчас эта тема мне не совсем понятна.
//Структуры
//В каких случаях лучше использовать класс, а в каких – структуру?
/*Структура - типы-значения. Классы - типы-ссылка. Т.е. при работе в экземпляром структуры проиходит его копирование, а при работе с экземпляром класса просто ссылается на него.
Но я не понимаю в каких случах что использовать. Можете объяснить? Сейчас не сильно наблюдаю разницу между страктурами и классами.
*/
| apache-2.0 | 6e0ac0c27657175f545baf57e0be3d70 | 30.928934 | 368 | 0.692051 | 2.607794 | false | false | false | false |
nlgb/VVSPageView | VVSPageView/VVSPageView/VVSPageView/VVSTitleView.swift | 1 | 5677 | //
// VVSTitleView.swift
// VVSPageView
//
// Created by sw on 17/4/19.
// Copyright © 2017年 sw. All rights reserved.
//
import UIKit
protocol VVSTitleViewDelegate : class {
func titleView(titleView : VVSTitleView, didCilckIndex index : Int)
}
class VVSTitleView: UIView {
// delegate 用weak修饰 代理遵守协议不再用<>,改用 :
weak var delegate : VVSTitleViewDelegate?
fileprivate var currentIndex : Int = 0
fileprivate var style : VVSPageStyle
fileprivate var titles : [String]
fileprivate var titleLabels : [UILabel] = [UILabel]()
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame = self.bounds
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
return scrollView
}()
// MARK:- 构造函数
// init(frame: CGRect, style : VVSPageStyle, titles : Array<String>) {
init(frame: CGRect, style : VVSPageStyle, titles : [String]) {
self.style = style
self.titles = titles
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- UI
extension VVSTitleView {
fileprivate func setupUI() {
// 添加一个scrollView
addSubview(scrollView)
// 添加label
setupTitleLabels()
// 设置label的frame
setupLabelFrame()
}
private func setupLabelFrame() {
var labelW : CGFloat = 0
let labelH : CGFloat = frame.height
var labelX : CGFloat = 0
let labelY : CGFloat = 0
for (i, titleLabel) in titleLabels.enumerated() {
if style.titleIsScrollEnable {// 可以滚动
labelW = (titles[i] as NSString).boundingRect(with: CGSize(width:CGFloat.greatestFiniteMagnitude, height : 0) , options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName : titleLabel.font], context: nil).width
labelX = titleLabel.tag == 0 ? style.titleMargin * 0.5 : (titleLabels[i - 1].frame.maxX + style.titleMargin)
} else {// 不可以滚动
labelW = frame.width / CGFloat(titleLabels.count)
labelX = labelW * CGFloat(i)
}
titleLabel.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
}
// 如果标题是可以滚动的,那么需要设置scrollView的contentSize
if style.titleIsScrollEnable {
guard let lastLabel = titleLabels.last else {
return
}
scrollView.contentSize = CGSize(width: lastLabel.frame.maxX + style.titleMargin * 0.5, height: 0)
}
}
private func setupTitleLabels() {
for (i,title) in titles.enumerated() {
let label = UILabel()
label.tag = i
label.text = title
label.textAlignment = .center
label.textColor = i == 0 ? style.selectColor : style.normalColor
label.font = UIFont.systemFont(ofSize: style.fontSize)
scrollView.addSubview(label)
titleLabels.append(label)
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_:)))
label.addGestureRecognizer(tapGes)
label.isUserInteractionEnabled = true
}
}
}
// MARK:- 事件监听
extension VVSTitleView {
@objc fileprivate func titleLabelClick(_ tapGes:UITapGestureRecognizer) {
guard let targetLabel = tapGes.view as? UILabel else {
return
}
print(targetLabel.tag)
// 点击了同一个标签
if targetLabel.tag == currentIndex {
return
}
// 修改上个标签的状态
let lastLabel = titleLabels[currentIndex]
lastLabel.textColor = style.normalColor
// 修改当前标签的状态
let currentLabel = targetLabel
currentLabel.textColor = style.selectColor
currentIndex = currentLabel.tag
// 居中显示
if style.titleIsScrollEnable {
adjustLabelPosition(label: currentLabel)
}
// 通知delegate
delegate?.titleView(titleView: self, didCilckIndex: currentIndex)
}
fileprivate func adjustLabelPosition(label : UILabel) {
// 1.计算一下offsetX
var offsetX = label.center.x - bounds.width * 0.5
// 2.临界值的判断
if offsetX < 0 {
offsetX = 0
}
if offsetX > scrollView.contentSize.width - scrollView.bounds.width {
offsetX = scrollView.contentSize.width - scrollView.bounds.width
}
// 3.设置scrollView的contentOffset
scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
}
}
extension VVSTitleView : VVSContentViewDelegate {
func contentView(contentView: VVSContentView, didScrollToIndex index: Int) {
if style.titleIsScrollEnable {
adjustLabelPosition(label: titleLabels[index])
}
// 如果titleView支持渐变
if style.titleIsTransitionEnable {
} else {
// 如果titleView不支持渐变
let lastLabel = titleLabels[currentIndex]
let currentLabel = titleLabels[index]
lastLabel.textColor = style.normalColor
currentLabel.textColor = style.selectColor
}
currentIndex = index
}
}
| apache-2.0 | e518d5c9316187efa9501326e9b3f72b | 31 | 257 | 0.602574 | 4.865832 | false | false | false | false |
SakuragiTen/DYTV | DYTV/DYTV/Classes/Home/ViewModel/RecommentViewModel.swift | 1 | 1858 | //
// RecommentViewModel.swift
// DYTV
//
// Created by gongsheng on 2016/12/17.
// Copyright © 2016年 gongsheng. All rights reserved.
//
import UIKit
class RecommentViewModel : BaseViewModel{
//MARK: - 懒加载属性
// lazy var cycleModels : []
fileprivate lazy var bigDataGroup : AnchorGroupModel = AnchorGroupModel()
fileprivate lazy var prettyGroup : AnchorGroupModel = AnchorGroupModel()
}
//MARK: - 发送网络请求
extension RecommentViewModel {
func requestData(finishedCallback : @escaping () -> ()) {
//定义参数
// let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
//创建group
//1.请求第一部分推荐数据
NetworkTools.requestData(url: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", type: .GET, parameters: ["time" : Date.getCurrentTime()]) { (result) in
print(result)
//将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
//根据"data"这个key获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
//遍历字典数组 转换成模型对象
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
//获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict : dict)
self.bigDataGroup.anchors.append(anchor)
}
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishedCallback()
}
//2.请求第二部分颜值数据
//3.请求后面部分游戏数据
}
}
| mit | e106bc2872b3f5cab02d15146bfa0672 | 27.15 | 158 | 0.553582 | 4.589674 | false | false | false | false |
OctMon/OMExtension | OMExtension/OMExtension/Source/Foundation/OMDictionary.swift | 1 | 3862 | //
// OMDictionary.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public extension Dictionary {
func omRandom() -> (Key, Value) {
let index = Int(arc4random_uniform(UInt32(self.count)))
return (Array(keys)[index], Array(values)[index])
}
func omContainsKey(_ key: Key) -> Bool {
return index(forKey: key) != nil
}
func omUnion(_ dictionary: Dictionary...) -> Dictionary {
var result = self
dictionary.forEach { (dict) in
dict.forEach { (key, value) in
result.updateValue(value, forKey: key)
}
}
return result
}
func omMapFilter<K, V>(_ map: (Key, Value) -> (K, V)?) -> [K: V] {
var result = [K: V]()
forEach {
if let value = map($0, $1) {
result[value.0] = value.1
}
}
return result
}
func omFilter(_ valid: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if valid(key, value) {
result[key] = value
}
}
return result
}
func omIntersection<K, V>(_ dictionary: [K: V]...) -> [K: V] where V: Equatable {
let filter = omMapFilter { (key, value) -> (K, V)? in
if let key = key as? K, let value = value as? V {
return (key, value)
}
return nil
}
return filter.omFilter { (key: K, value: V) -> Bool in
dictionary.omFilter { $0.omContainsKey(key) && $0[key] == value }
}
}
}
public extension Dictionary where Value: Equatable {
func omDifference(_ dictionary: [Key: Value]...) -> [Key: Value] {
var result = self
for dict in dictionary {
for (key, value) in dict {
if result.omContainsKey(key) && result[key] == value {
result.removeValue(forKey: key)
}
}
}
return result
}
}
public extension Dictionary {
var omToString: String? {
if let data = try? JSONSerialization.data(withJSONObject: self) {
let string = String(data: data, encoding: .utf8)
return string
}
return nil
}
}
| mit | 6741cc2b18848e07efac36a4178f7604 | 26.197183 | 85 | 0.519938 | 4.647413 | false | false | false | false |
jixuhui/HJHeartSwift | HJHeartSwift/HJHeartSwift/VOPDemo.swift | 1 | 1644 | //
// VOPDemo.swift
// HJSteed
//
// Created by jixuhui on 16/1/7.
// Copyright © 2016年 Hubbert. All rights reserved.
//
import Foundation
protocol Inner {
var value:String {get set}
}
struct InnerValueType:Inner {
var value = "InnerValueType"
}
class InnerReferenceType:Inner {
var value = "InnerReferenceType"
}
protocol OuterPrintMe {
func printMe(name:String)
}
protocol OuterChangeMe {
mutating func changeMe(text:String)
}
protocol Outer: OuterPrintMe,OuterChangeMe {
var value:String {get set}
var innerValue:Inner {get set}
var innerReference:Inner {get set}
var computerValue:String {get}
}
extension Outer {
// var value:String {
// return ""
// }
//
// var innerValue:Inner {
// return InnerValueType()
// }
//
// var innerReference:Inner {
// return InnerReferenceType()
// }
var computerValue:String {
return "yes"
}
func printMe(name:String) {
print("\(name).value = \(self.value)\n\(name).innerValue.value = \(self.innerValue.value)\n\(name).innerReference.value = \(self.innerReference.value)")
}
mutating func changeMe(text:String) {
self.value = text
self.innerValue.value = text
self.innerReference.value = text
}
}
class OuterReferenceType:Outer {
var value = "OuterReferenceType"
var innerValue:Inner = InnerValueType()
var innerReference:Inner = InnerReferenceType()
}
struct OuterValueType:Outer {
var value = "OuterValueType"
var innerValue:Inner = InnerValueType()
var innerReference:Inner = InnerReferenceType()
}
| mit | b8308064db9b911a2d81bd4899f69873 | 20.311688 | 160 | 0.65387 | 3.662946 | false | false | false | false |
danielsaidi/KeyboardKit | Demo/Demo/Demo/DemoListButton.swift | 1 | 879 | //
// DemoListButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-02-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
struct DemoListButton: View {
init(
_ image: Image? = nil,
_ text: String,
_ rightImage: Image? = nil,
_ isNavigation: Bool = false,
action: @escaping () -> Void) {
self.item = DemoListItem(image, text, rightImage)
self.action = action
}
private let item: DemoListItem
private let action: () -> Void
var body: some View {
Button(action: action) {
item
}.buttonStyle(PlainButtonStyle())
}
}
struct DemoListButton_Previews: PreviewProvider {
static var previews: some View {
List {
DemoListButton(.alert, "This is a list item", .alert, action: {})
}
}
}
| mit | b89804c875f866fbaffae7cca256f99b | 21.512821 | 77 | 0.574032 | 4.122066 | false | false | false | false |
uberbruns/CompareTools | DeltaCamera/DeltaCamera/BaseComponents/TableViewController/TableViewSectionItem.swift | 1 | 1121 | //
// TableViewSectionItem.swift
//
// Created by Karsten Bruns on 28/08/15.
// Copyright © 2015 bruns.me. All rights reserved.
//
import Foundation
import UBRDelta
public struct TableViewSectionItem : ComparableSectionItem {
public var uniqueIdentifier: Int { return id.hash }
public var items: [ComparableItem] = []
public let id: String
public var title: String?
public var footer: String? = nil
public var userInfo: [String:AnyObject]? = nil
public init(id: String, title: String?) {
self.id = id
self.title = title
}
public func compareTo(other: ComparableItem) -> ComparisonLevel {
guard let other = other as? TableViewSectionItem else { return .Different }
guard other.id == self.id else { return .Different }
let titleChanged = other.title != title
let footerChanged = other.footer != footer
if !titleChanged && !footerChanged {
return .Same
} else {
return .Changed(["title":titleChanged, "footer": footerChanged])
}
}
} | mit | dd63c37461978568c00769fd31e6c75f | 25.690476 | 83 | 0.616964 | 4.426877 | false | false | false | false |
Perfect-Server-Swift-LearnGuide/Today-News-Admin | Sources/Handler/DeleteArticleHandler.swift | 1 | 1262 | //
// DeleteArticleHandler.swift
// Today-News-Admin
//
// Created by Mac on 17/7/13.
//
//
import PerfectLib
import PerfectHTTP
import PerfectMustache
import DataBase
import PerfectMongoDB
import Model
public struct DeleteArticleHandler: MustachePageHandler {
/// DeleteArticle
public static func delete(req: HTTPRequest, res: HTTPResponse) -> String {
var data = [String]()
for param in req.postParams {
data.append(param.1)
}
let db = DeleteArticleModel()
return db.deletes(data)
}
/// Mustache handler
public func extendValuesForResponse(context contxt: MustacheWebEvaluationContext, collector: MustacheEvaluationOutputCollector) {
var values = MustacheEvaluationContext.MapType()
let obj = DeleteArticleModel()
values["articles"] = obj.articles()
values["total"] = obj.total
contxt.extendValues(with: values)
do {
try contxt.requestCompleted(withCollector: collector)
} catch {
let response = contxt.webResponse
response.status = .internalServerError
response.appendBody(string: "\(error)")
response.completed()
}
}
}
| apache-2.0 | c5a797b26c4cb0913c4a076daed83706 | 24.755102 | 133 | 0.634707 | 4.853846 | false | false | false | false |
suragch/aePronunciation-iOS | aePronunciation/StudyTimer.swift | 1 | 1253 | import Foundation
class StudyTimer {
// singleton
static let sharedInstance = StudyTimer()
private init() {}
private var startTime: Date?
private var studyType: StudyType?
enum StudyType {
case learnSingle
case learnDouble
case practiceSingle
case practiceDouble
case testSingle
case testDouble
}
var isTiming: Bool {
get {
return startTime != nil
}
}
func start(type: StudyType) {
// no need to restart the timer for the same type
if self.studyType == type {
return
}
// stop and record time for previous type (if any)
stop()
// start time for this type
self.startTime = Date()
self.studyType = type
}
func stop() {
guard let currentType = self.studyType else {return}
guard let start = self.startTime else {return}
let elapsedTime = abs(start.timeIntervalSinceNow)
MyUserDefaults.addTime(for: currentType, time: elapsedTime)
// set to nil so that not saving multiple times
self.studyType = nil
self.startTime = nil
}
}
| unlicense | b4e70b344b2d3bf18715d1034003ccf1 | 22.641509 | 67 | 0.561053 | 5.032129 | false | false | false | false |
pigigaldi/Pock | Pock/UI/TouchBar/EmptyTouchBarController/EmptyTouchBarController.swift | 1 | 3569 | //
// EmptyTouchBarController.swift
// Pock
//
// Created by Pierluigi Galdi on 07/05/21.
//
import Cocoa
import PockKit
internal class EmptyTouchBarController: PKTouchBarMouseController {
internal enum State {
case empty, installDefault
}
internal var state: State = .empty
// MARK: UI Elements
@IBOutlet private weak var titleLabel: NSTextField!
@IBOutlet private weak var subtitleLabel: NSTextField!
@IBOutlet private weak var informativeLabel: NSTextField!
@IBOutlet private weak var actionIconView: NSImageView!
@IBOutlet private weak var actionButton: NSButton!
// MARK: Mouse Support
private var buttonWithMouseOver: NSButton?
private var touchBarView: NSView? {
guard let views = NSFunctionRow._topLevelViews() as? [NSView], let view = views.last else {
Roger.debug("Touch Bar is not available.")
return nil
}
return view
}
public override var parentView: NSView! {
get {
return touchBarView
} set {
super.parentView = newValue
}
}
override func present() {
super.present()
updateUIState()
}
private func updateUIState() {
switch state {
case .empty:
informativeLabel.stringValue = "widgets.empty.add-widgets-to-pock".localized
actionButton.tag = 0
actionButton.title = "general.action.customize".localized
case .installDefault:
informativeLabel.stringValue = "widgets.defaults.tap-to-install".localized
actionButton.tag = 1
actionButton.title = "general.action.install".localized
}
titleLabel.stringValue = "general.welcome-to-pock".localized
subtitleLabel.stringValue = "general.pock-widgets-manager".localized
async(after: 0.5) { [weak self] in
self?.addIconViewAnimation()
}
}
@IBAction private func actionButtonPressed(_ button: NSButton) {
defer {
dismiss()
}
switch button.tag {
case 0:
AppController.shared.openPockCustomizationPalette()
case 1:
AppController.shared.reInstallDefaultWidgets()
default:
return
}
}
// MARK: Mouse stuff
public override func screenEdgeController(_ controller: PKScreenEdgeController, mouseClickAtLocation location: NSPoint, in view: NSView) {
guard let button = button(at: location) else {
return
}
actionButtonPressed(button)
}
public override func updateCursorLocation(_ location: NSPoint?) {
super.updateCursorLocation(location)
buttonWithMouseOver?.isHighlighted = false
buttonWithMouseOver = nil
buttonWithMouseOver = button(at: location)
buttonWithMouseOver?.isHighlighted = true
}
private func button(at location: NSPoint?) -> NSButton? {
guard let view = parentView.subview(in: parentView, at: location, of: "NSTouchBarItemContainerView") else {
return nil
}
return view.findViews(subclassOf: NSButton.self).first
}
}
// MARK: Icon bounce animation
extension EmptyTouchBarController {
private func addIconViewAnimation() {
actionIconView.superview?.layout()
let slideAnimation = CABasicAnimation(keyPath: "position.x")
slideAnimation.duration = 0.475
slideAnimation.fromValue = (actionIconView.superview?.frame.origin.x ?? 0) + 3.3525
slideAnimation.toValue = (actionIconView.superview?.frame.origin.x ?? 0) - 1.3525
slideAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
slideAnimation.autoreverses = true
slideAnimation.repeatCount = .greatestFiniteMagnitude
actionIconView.superview?.layer?.add(slideAnimation, forKey: "bounce_animation")
}
private func removeIconViewAnimation() {
actionIconView.superview?.layer?.removeAnimation(forKey: "bounce_animation")
}
}
| mit | a4ccf0a7b19d5e295c694ec9503974b5 | 28.254098 | 139 | 0.743906 | 3.821199 | false | false | false | false |
otanistudio/SwipeUp | SwipeUp/SwipeUpCell.swift | 1 | 4571 | //
// SwipeUpCell.swift
// SwipeUp
//
// Created by Robert Otani on 6/5/15.
// Copyright (c) 2015 Robert Otani. All rights reserved.
//
import UIKit
protocol SwipeUpCellDelegate {
func swipeUpDidFinish(tag: NSNumber)
}
class SwipeUpCell: UICollectionViewCell, UIGestureRecognizerDelegate {
var panUpGestureRecognizer: UIPanGestureRecognizer!
var delegate: SwipeUpCellDelegate!
var itemTag: NSNumber!
@IBOutlet weak var swipeableView: UIImageView!
@IBOutlet weak var tagLabel: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
panUpGestureRecognizer = nil
delegate = nil
itemTag = nil
tagLabel.text = ""
swipeableView!.frame = contentView.frame
swipeableView!.alpha = 1.0
}
class func cellID() -> String {
return "SwipeUpCollectionCellID"
}
func configure(delegate: SwipeUpCellDelegate, tag: NSNumber) {
panUpGestureRecognizer = UIPanGestureRecognizer(target: self, action: "didPanUp:");
panUpGestureRecognizer?.delegate = self
swipeableView!.image = UIImage(named: "derp.jpg")
addGestureRecognizer(panUpGestureRecognizer!)
self.delegate = delegate
itemTag = tag
tagLabel.text = tag.stringValue
}
internal func didPanUp(gesture: UIGestureRecognizer) {
if (gesture == panUpGestureRecognizer
&& gesture.numberOfTouches() == 1
&& gesture.state == UIGestureRecognizerState.Changed) {
contentView.clipsToBounds = false
let location = gesture.locationInView(contentView);
var frame = contentView.frame;
frame.origin.y = location.y;
if (frame.origin.y >= 0) {
frame.origin.y = 0;
}
swipeableView.frame = frame;
let denom = contentView.bounds.size.height + fabs(location.y);
let percent = contentView.bounds.size.height / denom;
swipeableView.alpha = percent;
} else if (gesture == panUpGestureRecognizer && gesture.state == UIGestureRecognizerState.Ended) {
let swipableRect = swipeableView.frame;
let velocity = panUpGestureRecognizer.velocityInView(contentView)
/*
Naïve solution: If the bottom edge of the swipeableRect needs to cross
the top of the bounding contentView and also needs to be
fast enough for the swipe to work.
*/
if ((-1.0 * swipableRect.origin.y < contentView.frame.size.height) && (velocity.y > -1500.0)) {
UIView.animateWithDuration(0.5,
delay: 0,
usingSpringWithDamping: 0.33,
initialSpringVelocity: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { [weak self]() -> Void in
self!.swipeableView.frame = self!.contentView.frame
self!.swipeableView.alpha = 1.0
}, completion: nil)
} else {
let fadeAwayLine = -1.0 * UIScreen.mainScreen().bounds.size.height / 1.5;
UIView.animateWithDuration(
0.33,
delay: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations: { [weak self]() -> Void in
self!.swipeableView.frame = CGRectMake(swipableRect.origin.x,
fadeAwayLine,
swipableRect.size.width,
swipableRect.size.height)
self!.swipeableView.alpha = 0.0
}, completion:{ [weak self](finished: Bool) -> Void in
self!.delegate.swipeUpDidFinish(self!.itemTag!)
} )
}
}
}
// UIGestureRecognizerDelegate
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if (!gestureRecognizer.isKindOfClass(UIPanGestureRecognizer.self)) {
return false
}
let panRecognizer = gestureRecognizer as! UIPanGestureRecognizer
let translation = panRecognizer.translationInView(contentView)
return abs(translation.x) < abs(translation.y)
}
}
| mit | 2462cf27b379575289bcdd12446a2c52 | 38.059829 | 107 | 0.573085 | 5.36385 | false | false | false | false |
buyiyang/iosstar | iOSStar/Scenes/Market/CustomView/MarketDetailCell.swift | 3 | 4771 |
//
// MarketDetailCell.swift
// iOSStar
//
// Created by J-bb on 17/5/16.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import Charts
class MarketDetailCell: UITableViewCell,ChartViewDelegate{
var currentView:UIView?
@IBOutlet weak var currentPriceLabel: UILabel!
var datas:[TimeLineModel]?
@IBOutlet weak var lineView: LineChartView!
@IBOutlet weak var changeLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
changeLabel.layer.cornerRadius = 3
changeLabel.clipsToBounds = true
lineView.legend.setCustom(entries: [])
lineView.noDataText = "暂无数据"
lineView.xAxis.labelPosition = .bottom
lineView.xAxis.drawGridLinesEnabled = false
lineView.xAxis.drawAxisLineEnabled = false
lineView.xAxis.axisMinimum = 0
lineView.xAxis.axisMaximum = 30
lineView.leftAxis.axisMinimum = 0
lineView.xAxis.labelFont = UIFont.systemFont(ofSize: 0)
lineView.leftAxis.labelFont = UIFont.systemFont(ofSize: 10)
lineView.leftAxis.gridColor = UIColor.init(rgbHex: 0xf2f2f2)
lineView.rightAxis.labelFont = UIFont.systemFont(ofSize: 0)
lineView.delegate = self
lineView.chartDescription?.text = ""
lineView.rightAxis.forceLabelsEnabled = false
lineView.animate(xAxisDuration: 1)
}
func setStarModel(starModel:MarketListModel) {
iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + starModel.pic_tail))
}
func setBannerModel(bannerModel:BannerDetaiStarModel) {
iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + bannerModel.pic_url_tail))
}
func setRealTimeData(realTimeModel:RealTimeModel) {
let percent = (realTimeModel.change / realTimeModel.currentPrice) * 100
currentPriceLabel.text = "\(realTimeModel.currentPrice)"
var colorString = AppConst.Color.up
if realTimeModel.change < 0 {
changeLabel.text = String(format: "%.2f/%.2f%%", realTimeModel.change, -percent)
colorString = AppConst.Color.down
}else{
changeLabel.text = String(format: "%.2f/+%.2f%%",realTimeModel.change,percent)
}
currentPriceLabel.textColor = UIColor(hexString: colorString)
changeLabel.backgroundColor = UIColor(hexString: colorString)
}
func setData(datas:[TimeLineModel]) {
var entrys: [ChartDataEntry] = []
for (index,model) in datas.enumerated() {
let entry = ChartDataEntry(x: Double(index), y: model.currentPrice)
entrys.append(entry)
}
self.datas = datas
let set = LineChartDataSet(values: entrys, label: "分时图")
set.colors = [UIColor.red]
set.circleRadius = 0
set.form = .empty
set.circleHoleRadius = 0
set.mode = .cubicBezier
set.valueFont = UIFont.systemFont(ofSize: 0)
set.drawFilledEnabled = true
set.fillColor = UIColor(red: 203.0 / 255, green: 66.0 / 255, blue: 50.0 / 255, alpha: 0.5)
let data: LineChartData = LineChartData.init(dataSets: [set])
lineView.data = data
lineView.data?.notifyDataChanged()
lineView.setNeedsDisplay()
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
if let model:TimeLineModel = datas?[Int(entry.x)] {
let markerView = WPMarkerLineView.init(frame: CGRect.init(x: 0, y: 0, width: 100, height: 50))
markerView.titleLabel.text = markerLineText(model: model)
let marker = MarkerImage.init()
marker.chartView = chartView
marker.image = imageFromUIView(markerView)
chartView.marker = marker
}
}
func markerLineText(model: TimeLineModel) -> String {
let time = Date.yt_convertDateToStr(Date.init(timeIntervalSince1970: TimeInterval(model.priceTime)), format: "MM-dd HH:mm")
let price = String.init(format: "%.2f", model.currentPrice)
return "\(time)\n最新价\(price)"
}
func imageFromUIView(_ view: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let viewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return viewImage!
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | fae85fa12dc6b66df1810dfe5a0b9e9f | 39.237288 | 131 | 0.66091 | 4.47081 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/AppDelegate+DebugWindow.swift | 1 | 834 | import UIKit
extension AppDelegate {
func installDebugModule() {
guard let window = window else { return }
let complicatedGesture = UITapGestureRecognizer(target: self, action: #selector(showDebugMenu))
complicatedGesture.numberOfTouchesRequired = 2
complicatedGesture.numberOfTapsRequired = 5
window.addGestureRecognizer(complicatedGesture)
}
@objc private func showDebugMenu(_ sender: UIGestureRecognizer) {
let storyboard = UIStoryboard(name: "Debug", bundle: .main)
guard let viewController = storyboard.instantiateInitialViewController() else { return }
let host = UINavigationController(rootViewController: viewController)
host.modalPresentationStyle = .formSheet
window?.rootViewController?.present(host, animated: true)
}
}
| mit | 43a2b0511831b0d618a2ccb7dde29c2f | 35.26087 | 103 | 0.721823 | 5.751724 | false | false | false | false |
webelectric/AspirinKit | AspirinKit/Sources/UIKit/UIApplication+Extensions.swift | 1 | 2463 | //
// Thread.swift
// AspirinKit
//
// Copyright © 2014 - 2017 The Web Electric Corp.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
public extension UIApplication {
public class func findTopViewController(_ baseVC: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navController = baseVC as? UINavigationController {
return self.findTopViewController(navController.visibleViewController)
}
if let tabBarVC = baseVC as? UITabBarController {
let moreNavigationController = tabBarVC.moreNavigationController
if let topVC = moreNavigationController.topViewController, topVC.view.window != nil {
return self.findTopViewController(topVC)
}
else if let selectedViewController = tabBarVC.selectedViewController {
return self.findTopViewController(selectedViewController)
}
}
if let splitVC = baseVC as? UISplitViewController, splitVC.viewControllers.count == 1 {
return self.findTopViewController(splitVC.viewControllers[0])
}
if let presentedVC = baseVC?.presentedViewController {
return self.findTopViewController(presentedVC)
}
return baseVC
}
}
| mit | 479e017c6df9a3d921b4032c5efd5b95 | 39.360656 | 148 | 0.694151 | 5.129167 | false | false | false | false |
gribozavr/swift | test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2conformance-1distinct_use.swift | 1 | 3705 | // RUN: %swift -target %module-target-future -emit-ir -prespecialize-generic-metadata %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type
// CHECK: @"$s4main5ValueVySiGMf" = internal constant <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i8**,
// CHECK-SAME: i8**,
// CHECK-SAME: i32{{(, \[4 x i8\])?}},
// CHECK-SAME: i64
// CHECK-SAME: }> <{
// i8** @"$sB[[INT]]_WV",
// i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0),
// CHECK-SAME: [[INT]] 512,
// CHECK-SAME: %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, i32, i32, i32, i32 }>* @"$s4main5ValueVMn" to %swift.type_descriptor*),
// CHECK-SAME: %swift.type* @"$sSiN",
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0),
// CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1QAAWP", i32 0, i32 0),
// CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}},
// CHECK-SAME: i64 3
// CHECK-SAME: }>, align [[ALIGNMENT]]
protocol P {}
protocol Q {}
extension Int : P {}
extension Int : Q {}
struct Value<First : P & Q> {
let first: First
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13) )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]], %swift.type*, i8**, i8**) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TABLE_1:%[0-9]+]] = bitcast i8** %2 to i8*
// CHECK: [[ERASED_TABLE_2:%[0-9]+]] = bitcast i8** %3 to i8*
// CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_LABEL]]:
// CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE]]
// CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]]
// CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE]], i8* [[ERASED_TABLE_1]], i8* [[ERASED_TABLE_2]], %swift.type_descriptor* bitcast (<{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, i32, i32, i32, i32 }>* @"$s4main5ValueVMn" to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 62246014d907b9c11c53a5dbe0bb1af9 | 53.485294 | 391 | 0.60027 | 2.834736 | false | false | false | false |
benbahrenburg/PDFUtilities | PDFUtilities/Classes/PDFDocumentPasswordInfo.swift | 1 | 2074 | //
// PDFUtilities - Tools for working with PDFs
// PDFDocumentPasswordInfo.swift
//
// Created by Ben Bahrenburg
// Copyright © 2016 bencoding.com. All rights reserved.
//
import Foundation
/**
PDF Password Struct, used to unlock or add a password to a PDF
Provides the ability to set the User and/or Owner Passwords
If you init using just a single password the User password will be used.
*/
public struct PDFDocumentPasswordInfo {
/// User Password (optional)
var userPassword: String? = nil
/// Owner Password (optional)
var ownerPassword: String? = nil
/**
Creates a new instance of the PDFDocumentPasswordInfo object
- Parameter userPassword: The User password
- Parameter ownerPassword: The Owner password
*/
public init(userPassword: String, ownerPassword: String) {
self.userPassword = userPassword
self.ownerPassword = ownerPassword
}
/**
Creates a new instance of the PDFDocumentPasswordInfo object
- Parameter password: The password provided will be used as the User Password
*/
public init(userPassword: String) {
self.userPassword = userPassword
}
/**
Creates a new instance of the PDFDocumentPasswordInfo object
- Parameter password: The password provided will be used as the User Password
*/
public init(ownerPassword: String) {
self.ownerPassword = ownerPassword
}
/**
The toInfo method is used to create meta data for unlocking or locking pdfs.
- Returns: An Array of items used when locking or unlocking PDFs.
*/
func toInfo() -> [AnyHashable : Any] {
var info: [AnyHashable : Any] = [:]
if let userPassword = self.userPassword {
info[String(kCGPDFContextUserPassword)] = userPassword as AnyObject?
}
if let ownerPassword = self.ownerPassword {
info[String(kCGPDFContextOwnerPassword)] = ownerPassword as AnyObject?
}
return info
}
}
| mit | 6c99565e0e955ba58f8c4dab7992437e | 26.64 | 82 | 0.654607 | 4.889151 | false | false | false | false |
AnRanScheme/magiGlobe | magi/magiGlobe/Pods/RxSwift/RxSwift/Observables/Sequence.swift | 78 | 3377 | //
// Sequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension Observable {
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: elements, scheduler: scheduler)
}
}
extension Observable {
/**
Converts an array to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
}
final fileprivate class ObservableSequenceSink<S: Sequence, O: ObserverType> : Sink<O> where S.Iterator.Element == O.E {
typealias Parent = ObservableSequence<S>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.scheduleRecursive((_parent._elements.makeIterator(), _parent._elements)) { (iterator, recurse) in
var mutableIterator = iterator
if let next = mutableIterator.0.next() {
self.forwardOn(.next(next))
recurse(mutableIterator)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
}
}
final fileprivate class ObservableSequence<S: Sequence> : Producer<S.Iterator.Element> {
fileprivate let _elements: S
fileprivate let _scheduler: ImmediateSchedulerType
init(elements: S, scheduler: ImmediateSchedulerType) {
_elements = elements
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 3a87c2597a6f78e1de5b2ff3dc529515 | 36.932584 | 173 | 0.680095 | 4.788652 | false | false | false | false |
melling/SwiftCookBook | SwiftCookBook.playground/Pages/Arrays.xcplaygroundpage/Contents.swift | 1 | 3572 | //: [Previous](@previous)
/*:
Swift Cookbook Array Functions
Copy and Paste into a Swift Playground
Version: 20151019.01
Some ideas came from [Perl](http://pleac.sourceforge.net/pleac_perl/arrays.html) and [Python](http://pleac.sourceforge.net/pleac_python/arrays.html) Pleacs
*/
import Foundation
//: Array Creation
var anArray = ["one", "two", "three","one"] // Mutable
let anImmutableArray = ["four", "five"] // Immutable
let numbers = Array(1...10) // 1 through 10
let numbers9 = Array(1..<10) // 1 through 9
let numbers0_9 = [Int](0..<10)
//let total = numbers0_9.reduce(0, +)
let multDim:[[Int]] = [[1,2,3], [4,5,6], [7,8,9]]
//: First element of array
anArray.first // a Swift solution. nil if empty
anArray[0] // Classic solution. Error if empty
//: Last element of array
anArray.last // a Swift solution. nil if empty
anArray[anArray.count-1] // Classic solution. Error if empty
//: Empty Array
var emptyArray:[String] = []
if emptyArray.isEmpty {
print("Empty Array")
}
emptyArray.first // Returns nil
emptyArray.last // Returns nil
//: Does value exist in array?
if anArray.contains("three") {
print("Array contains value")
}
//: How to filter array to get unique items?
// Create a Set then build array from it. Set guarantees uniqueness
var aSet:Set<String> = []
anArray.forEach{aSet.insert($0)} // Could do this: aSet = Set(anArray)
aSet.count
anArray = Array(aSet)
anArray.count
//: How to merge arrays?
// Just like prior solution. Uses Set's union function
// Also skip closure
anArray = ["one", "two", "three","one"]
aSet = Set(anArray)
aSet.formUnion(anImmutableArray)
aSet.count
anArray = Array(aSet)
anArray.count
//: Sort Array
anArray = ["one", "two", "three","one"]
let sortedArray = anArray.sorted() // Returns a new sorted array
let sortedArrayReverse = anArray.sorted(by: >) // Reverse order
sortedArray
sortedArrayReverse
anArray
anArray.sort() // Update the array in place
anArray
anArray.removeLast()
anArray.removeFirst()
//: Find the index of an element in an Array
anArray = ["one", "two", "three","one"]
anArray.index(of: "two")
//: indexOf() can also be used to search an array
let aNumericArray = [1, 2, 10, 20, 100]
let x = aNumericArray.index(where: {$0 > 10}) // Find the index of first value greater than 10
print(x ?? 0)
//: Array.reduce
/*:
A series of functions that use the Array.reduce method
anArray.reduce(initialValue) { (finalValue, elementValue) in PERFORM_CALCULATION }
1. finalValue is assigned initialValue
2. Calculation is performed
3. finalValue is returned for assignment
*/
//: Sum values in an Array
let smallArray = Array(1...3)
let arraySum = smallArray.reduce(0) { (total, i) in total + i }
arraySum
let average = arraySum / smallArray.count
//: Maximum Value in an Array
let maxNum = smallArray.reduce(0) { (total, i) in max(total, i) } // Decrease initial value 0 if max is less than that
maxNum
//: Minimum Value in an Array
let minNum = smallArray.reduce(100) { (total, i) in min(total, i) } // Increase initial value 100 if min is greater than that
minNum
//: Product
let tmpArray0 = Array(1...5)
let product = tmpArray0.reduce(1) { (total, i) in total * i }
product
//: Summation and Product without closure
let tmpSummation = Array(1...100).reduce(0, +)
let tmpProduct = Array(1...10).reduce(1, *)
//: Reverse Array with reduce()
let reverseIntArray = Array(1...10).reduce([Int](), { [$1] + $0 })
reverseIntArray
let reverseStringArray = ["dog","cat", "bird", "rabbit"].reduce([String](), { [$1] + $0 })
reverseStringArray
//: [Next](@next)
| cc0-1.0 | 787370c18d934a7291535884b9b885c1 | 25.656716 | 156 | 0.693729 | 3.369811 | false | false | false | false |
malcommac/SwiftDate | Sources/SwiftDate/Date/Date.swift | 2 | 5565 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
internal enum AssociatedKeys: String {
case customDateFormatter = "SwiftDate.CustomDateFormatter"
}
extension Date: DateRepresentable {
/// Just return itself to be compliant with `DateRepresentable` protocol.
public var date: Date { return self }
/// For absolute Date object the default region is obtained from the global `defaultRegion` variable.
public var region: Region {
SwiftDate.defaultRegion
}
/// Assign a custom formatter if you need a special behaviour during formatting of the object.
/// Usually you will not need to do it, SwiftDate uses the local thread date formatter in order to
/// optimize the formatting process. By default is `nil`.
public var customFormatter: DateFormatter? {
get {
let formatter: DateFormatter? = getAssociatedValue(key: AssociatedKeys.customDateFormatter.rawValue, object: self as AnyObject)
return formatter
}
set {
set(associatedValue: newValue, key: AssociatedKeys.customDateFormatter.rawValue, object: self as AnyObject)
}
}
/// Extract the date components.
public var dateComponents: DateComponents {
region.calendar.dateComponents(DateComponents.allComponentsSet, from: self)
}
/// Initialize a new date object from string expressed in given region.
///
/// - Parameters:
/// - string: date expressed as string.
/// - format: format of the date (`nil` uses provided list of auto formats patterns.
/// Pass it if you can in order to optimize the parse task).
/// - region: region in which the date is expressed. `nil` uses the `SwiftDate.defaultRegion`.
public init?(_ string: String, format: String? = nil, region: Region = SwiftDate.defaultRegion) {
guard let dateInRegion = DateInRegion(string, format: format, region: region) else { return nil }
self = dateInRegion.date
}
/// Initialize a new date from the number of seconds passed since Unix Epoch.
///
/// - Parameter interval: seconds
/// Initialize a new date from the number of seconds passed since Unix Epoch.
///
/// - Parameters:
/// - interval: seconds from Unix epoch time.
/// - region: region in which the date, `nil` uses the default region at UTC timezone
public init(seconds interval: TimeInterval, region: Region = Region.UTC) {
self = DateInRegion(seconds: interval, region: region).date
}
/// Initialize a new date corresponding to the number of milliseconds since the Unix Epoch.
///
/// - Parameters:
/// - interval: seconds since the Unix Epoch timestamp.
/// - region: region in which the date must be expressed, `nil` uses the default region at UTC timezone
public init(milliseconds interval: Int, region: Region = Region.UTC) {
self = DateInRegion(milliseconds: interval, region: region).date
}
/// Initialize a new date with the opportunity to configure single date components via builder pattern.
/// Date is therfore expressed in passed region (`DateComponents`'s `timezone`,`calendar` and `locale` are ignored
/// and overwritten by the region if not `nil`).
///
/// - Parameters:
/// - configuration: configuration callback
/// - region: region in which the date is expressed. Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components configuration: ((inout DateComponents) -> Void), region: Region? = SwiftDate.defaultRegion) {
guard let date = DateInRegion(components: configuration, region: region)?.date else { return nil }
self = date
}
/// Initialize a new date with given components.
///
/// - Parameters:
/// - components: components of the date.
/// - region: region in which the date is expressed.
/// Ignore to use `SwiftDate.defaultRegion`, `nil` to use `DateComponents` data.
public init?(components: DateComponents, region: Region?) {
guard let date = DateInRegion(components: components, region: region)?.date else { return nil }
self = date
}
/// Initialize a new date with given components.
public init(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int = 0, nanosecond: Int = 0, region: Region = SwiftDate.defaultRegion) {
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
components.nanosecond = nanosecond
components.timeZone = region.timeZone
components.calendar = region.calendar
self = region.calendar.date(from: components)!
}
/// Express given absolute date in the context of the default region.
///
/// - Returns: `DateInRegion`
public func inDefaultRegion() -> DateInRegion {
DateInRegion(self, region: SwiftDate.defaultRegion)
}
/// Express given absolute date in the context of passed region.
///
/// - Parameter region: destination region.
/// - Returns: `DateInRegion`
public func `in`(region: Region) -> DateInRegion {
DateInRegion(self, region: region)
}
/// Return a date in the distant past.
///
/// - Returns: Date instance.
public static func past() -> Date {
Date.distantPast
}
/// Return a date in the distant future.
///
/// - Returns: Date instance.
public static func future() -> Date {
Date.distantFuture
}
}
| mit | 1135ed9b91048ab482efe6d21d3f83c0 | 36.594595 | 151 | 0.713875 | 4.067251 | false | false | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Mapping/DictConvertable.swift | 1 | 13254 | //
// DictConvertable.swift
// MoyskladNew
//
// Created by Andrey Parshakov on 26.10.16.
// Copyright © 2016 Andrey Parshakov. All rights reserved.
//
//import Money
import Foundation
import UIKit
extension Dictionary where Key : ExpressibleByStringLiteral, Value : Any {
public func value<T>(_ key: Key) -> T? {
return self[key] as? T
}
public func msArray(_ key: Key) -> [Dictionary<String, Any>] {
return (self[key] as? Array<Any> ?? []).map {
$0 as? Dictionary<String, Any>
}.compactMap { $0 }
}
}
public protocol MSRequestEntity {
func requestUrl() -> MSApiRequest?
func pathComponents() -> [String]
func deserializationError() -> MSError
var id: MSID { get }
}
public protocol DictConvertable {
associatedtype Element : Metable
static func from(dict : Dictionary<String, Any>) -> MSEntity<Element>?
func dictionary(metaOnly: Bool) -> Dictionary<String, Any>
}
extension MSID: Equatable {
public convenience init(dict: Dictionary<String, Any>) {
self.init(msID: UUID(uuidString: dict.value("id") ?? ""),
syncID: UUID(uuidString: dict.value("syncId") ?? ""))
}
public func dictionary() -> Dictionary<String, Any> {
var dict = [String:Any]()
if let id = msID?.uuidString {
dict["id"] = id
}
if let sId = syncID?.uuidString {
dict["syncId"] = sId
}
return dict
}
public static func ==(left: MSID, right: MSID) -> Bool {
return left.msID == right.msID && left.syncID == right.syncID
}
}
extension MSInfo {
public init(dict: Dictionary<String, Any>) {
self.name = dict.value("name") ?? ""
self.description = dict.value("description") ?? ""
self.version = dict.value("version") ?? 0
self.updated = Date.fromMSDate(dict.value("updated") ?? "")
self.deleted = nil
}
public func dictionary() -> Dictionary<String, Any> {
var dict = ["name":name]
if let description = description {
dict["description"] = description
}
return dict
}
}
extension UIColor {
public convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
public convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
}
extension MSState : DictConvertable {
public static func from(dict: Dictionary<String, Any>) -> MSEntity<MSState>? {
guard let meta = MSMeta.from(dict: dict["meta"] as? [String: Any] ?? [:], parent: dict) else { return nil }
guard let name: String = dict.value("name"), name.count > 0 else { return MSEntity.meta(meta) }
guard let color: Int = dict.value("color") else { return MSEntity.meta(meta) }
return MSEntity.entity(MSState(meta: meta,
id: MSID(dict: dict),
accountId: dict.value("accountId") ?? "",
name: name,
color: UIColor(netHex:color)))
}
public func dictionary(metaOnly: Bool = true) -> Dictionary<String, Any> {
var dict = [String: Any]()
dict["meta"] = meta.dictionary()
guard !metaOnly else { return dict }
// тут должны быть остальные поля объекта, если они понадобятся
return dict
}
}
extension MSRate {
public static func from(dict: Dictionary<String, Any>) -> MSRate? {
guard let currency = MSCurrency.from(dict: dict.msValue("currency")) else {
return nil
}
return MSRate(currency: currency, value: dict.value("value"))
}
public func dictionary(metaOnly: Bool = true) -> Dictionary<String, Any> {
var dict = [String: Any]()
dict["value"] = value
dict["currency"] = serialize(entity: currency, metaOnly: metaOnly)
return dict
}
}
extension MSMeta {
public static func from(dict: Dictionary<String, Any>, parent: Dictionary<String, Any>) -> MSMeta? {
guard let type = MSObjectType(rawValue: dict["type"] as? String ?? "") else {
return nil
}
return MSMeta(name: parent["name"] as? String ?? "", href: dict["href"] as? String ?? "", metadataHref: dict["metadataHref"] as? String ?? "", type: type)
}
public func dictionary() -> Dictionary<String, Any> {
return ["href":href.withoutParameters(), "mediaType":mediaType, "metadataHref":metadataHref, "type":type.rawValue]
}
}
extension MSPrice {
public static func from(dict: Dictionary<String, Any>, priceTypeOverride: String? = nil) -> MSPrice? {
guard dict.keys.count > 0 else {
return nil
}
let priceType: String? = {
guard let priceTypeOverride = priceTypeOverride else { return dict.value("priceType") }
return priceTypeOverride
}()
return MSPrice(priceType: priceType, value: (dict.value("value") ?? 0.0).toMoney(), currency: MSCurrency.from(dict: dict.msValue("currency")))
}
}
extension MSImage {
public static func from(dict: Dictionary<String, Any>) -> MSImage? {
guard let miniature: String = dict.msValue("miniature").value("href") else { return nil }
guard let miniatureUrl = URL(string: miniature) else { return nil }
return MSImage(title: dict.value("title") ?? "",
filename: dict.value("filename") ?? "",
size: dict.value("size") ?? 0,
miniatureUrl: miniatureUrl,
tinyUrl: URL(string: dict.msValue("tiny").value("href") ?? ""))
}
}
extension MSRegistrationResult {
public static func from(dict: Dictionary<String, Any>) -> MSRegistrationResult? {
guard dict.keys.count > 0 else {
return nil
}
guard let uid: String = dict.value("uid"),
let password: String = dict.value("password"),
let accountName: String = dict.value("accountName") else {
return nil
}
return MSRegistrationResult(uid: uid, password: password, accountName: accountName)
}
}
extension MSPermission {
public static func from(dict: Dictionary<String, Any>) -> MSPermission {
return MSPermission(view: dict.value("view") ?? false,
create: dict.value("create") ?? false,
update: dict.value("update") ?? false,
delete: dict.value("delete") ?? false,
approve: dict.value("approve") ?? false,
print: dict.value("print") ?? false,
done: dict.value("done") ?? false)
}
}
extension MSUserPermissions {
public static func from(dict: Dictionary<String, Any>) -> MSUserPermissions {
return MSUserPermissions(uom: MSPermission.from(dict: dict.msValue("uom")),
product: MSPermission.from(dict: dict.msValue("product")),
service: MSPermission.from(dict: dict.msValue("service")),
consignment: MSPermission.from(dict: dict.msValue("consignment")),
variant: MSPermission.from(dict: dict.msValue("variant")),
store: MSPermission.from(dict: dict.msValue("store")),
counterparty: MSPermission.from(dict: dict.msValue("counterparty")),
organization: MSPermission.from(dict: dict.msValue("organization")),
employee: MSPermission.from(dict: dict.msValue("employee")),
companysettings: MSPermission.from(dict: dict.msValue("companysettings")),
contract: MSPermission.from(dict: dict.msValue("contract")),
project: MSPermission.from(dict: dict.msValue("project")),
currency: MSPermission.from(dict: dict.msValue("currency")),
country: MSPermission.from(dict: dict.msValue("country")),
customentity: MSPermission.from(dict: dict.msValue("customentity")),
expenseitem: MSPermission.from(dict: dict.msValue("expenseitem")),
group: MSPermission.from(dict: dict.msValue("group")),
discount: MSPermission.from(dict: dict.msValue("discount")),
specialpricediscount: MSPermission.from(dict: dict.msValue("specialpricediscount")),
personaldiscount: MSPermission.from(dict: dict.msValue("personaldiscount")),
accumulationdiscount: MSPermission.from(dict: dict.msValue("accumulationdiscount")),
demand: MSPermission.from(dict: dict.msValue("demand")),
customerorder: MSPermission.from(dict: dict.msValue("customerorder")),
invoiceout: MSPermission.from(dict: dict.msValue("invoiceout")),
invoicein: MSPermission.from(dict: dict.msValue("invoicein")),
paymentin: MSPermission.from(dict: dict.msValue("paymentin")),
paymentout: MSPermission.from(dict: dict.msValue("paymentout")),
cashin: MSPermission.from(dict: dict.msValue("cashin")),
cashout: MSPermission.from(dict: dict.msValue("cashout")),
supply: MSPermission.from(dict: dict.msValue("supply")),
salesreturn: MSPermission.from(dict: dict.msValue("salesreturn")),
purchasereturn: MSPermission.from(dict: dict.msValue("purchasereturn")),
purchaseorder: MSPermission.from(dict: dict.msValue("purchaseorder")),
move: MSPermission.from(dict: dict.msValue("move")),
enter: MSPermission.from(dict: dict.msValue("enter")),
loss: MSPermission.from(dict: dict.msValue("loss")),
facturein: MSPermission.from(dict: dict.msValue("facturein")),
factureout: MSPermission.from(dict: dict.msValue("factureout")),
assortment: MSPermission.from(dict: dict.msValue("assortment")),
dashboard: MSPermission.from(dict: dict.msValue("dashboard")),
stock: MSPermission.from(dict: dict.msValue("stock")),
pnl: MSPermission.from(dict: dict.msValue("pnl")),
customAttributes: MSPermission.from(dict: dict.msValue("customAttributes")),
companyCrm: MSPermission.from(dict: dict.msValue("company_crm")),
tariffCrm: MSPermission.from(dict: dict.msValue("tariff_crm")),
auditDashboard: MSPermission.from(dict: dict.msValue("audit_dashboard")),
admin: MSPermission.from(dict: dict.msValue("admin")),
task: MSPermission.from(dict: dict.msValue("task")),
viewAllTasks: MSPermission.from(dict: dict.msValue("viewAllTasks")),
updateAllTasks: MSPermission.from(dict: dict.msValue("updateAllTasks")),
commissionreportin: MSPermission.from(dict: dict.msValue("commissionreportin")),
commissionreportout: MSPermission.from(dict: dict.msValue("commissionreportout")),
retailshift: MSPermission.from(dict: dict.msValue("retailshift")),
bundle: MSPermission.from(dict: dict.msValue("bundle")),
dashboardMoney: MSPermission.from(dict: dict.msValue("dashboardMoney")),
inventory: MSPermission.from(dict: dict.msValue("inventory")),
retaildemand: MSPermission.from(dict: dict.msValue("retaildemand")),
retailsalesreturn: MSPermission.from(dict: dict.msValue("retailsalesreturn")),
retaildrawercashin: MSPermission.from(dict: dict.msValue("retaildrawercashin")),
retaildrawercashout: MSPermission.from(dict: dict.msValue("retaildrawercashout")))
}
}
| mit | 5cc33e44cb731a45147eb27bcadcc10e | 48.078067 | 162 | 0.552644 | 4.582437 | false | false | false | false |
ios-ximen/DYZB | 斗鱼直播/斗鱼直播/Classes/Home/Views/AmuseMenuView.swift | 1 | 2962 | //
// AmuseMenuView.swift
// 斗鱼直播
//
// Created by niujinfeng on 2017/7/11.
// Copyright © 2017年 niujinfeng. All rights reserved.
//
import UIKit
fileprivate let collectionAmuseMenuCell = "collectionAmuseMenuCell"
class AmuseMenuView: UIView {
var anchorGroup : [AnchorGroup]? {
didSet{
//刷新数据
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
//系统回调方法
override func awakeFromNib() {
super.awakeFromNib()
//不随着父控件的拉伸而拉伸
autoresizingMask = UIViewAutoresizing()
//注册cell
collectionView.register(UINib(nibName: "CollectionAmuseMenuCell", bundle: nil), forCellWithReuseIdentifier: collectionAmuseMenuCell)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
}
}
//快速创建的类方法
extension AmuseMenuView{
class func amuseMendView() ->AmuseMenuView{
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if anchorGroup == nil{ return 0 }
let pageNum = (anchorGroup!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionAmuseMenuCell, for: indexPath) as! CollectionAmuseMenuCell
//cell.backgroundColor = UIColor.andomColor()
setCellWithData(cell :cell, indexPath : indexPath)
return cell
}
fileprivate func setCellWithData(cell : CollectionAmuseMenuCell, indexPath: IndexPath){
//传入的数据
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
//越界处理
if endIndex > anchorGroup!.count - 1 {
endIndex = anchorGroup!.count - 1
}
cell.anchorGroup = Array(anchorGroup![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = (Int)(collectionView.contentOffset.x / collectionView.bounds.size.width)
}
}
| mit | 80b016cf2247d5067f1fc0d7b6c2baec | 32.752941 | 143 | 0.680725 | 5.312963 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.