repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Alarson93/mmprogressswift
refs/heads/master
Pod/Classes/MMProgressConfiguration.swift
mit
1
// // MMProgressConfiguration.swift // Pods // // Created by Alexander Larson on 3/21/16. // // import Foundation import UIKit public enum MMProgressBackgroundType: NSInteger { case MMProgressBackgroundTypeBlurred = 0, MMProgressBackgroundTypeSolid } public class MMProgressConfiguration: NSObject { //Background public var backgroundColor: UIColor? public var backgroundType: MMProgressBackgroundType? public var backgroundEffect: UIVisualEffect? public var fullScreen: Bool? //Edges public var shadowEnabled: Bool? public var shadowOpacity: CGFloat? public var shadowColor: UIColor? public var borderEnabled: Bool? public var borderWidth: CGFloat? public var borderColor: UIColor? //Custom Animation public var loadingIndicator: UIView? //Presentation public var presentAnimated: Bool? //Status public var statusColor: UIColor? public var statusFont: UIFont? //Interaction public var tapBlock: Bool? override init() { //Background backgroundColor = UIColor.clearColor() backgroundType = MMProgressBackgroundType.MMProgressBackgroundTypeBlurred backgroundEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) fullScreen = false //Edges shadowEnabled = true shadowOpacity = 1 shadowColor = UIColor.blackColor() borderEnabled = false borderWidth = 1 borderColor = UIColor.blackColor() //Default Animation //loading //Presentation presentAnimated = true //Status statusColor = UIColor.darkGrayColor() statusFont = UIFont.systemFontOfSize(17) //Interaction tapBlock = true } }
efcedb9e849887da8d477080c2613cdf
22.922078
81
0.649294
false
false
false
false
JGiola/swift
refs/heads/main
test/Interop/SwiftToCxx/structs/struct-with-refcounted-member.swift
apache-2.0
3
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/structs.h // RUN: %FileCheck %s < %t/structs.h // RUN: %check-interop-cxx-header-in-clang(%t/structs.h -Wno-unused-function) class RefCountedClass { init() { print("create RefCountedClass") } deinit { print("destroy RefCountedClass") } } public struct StructWithRefcountedMember { let x: RefCountedClass } public func returnNewStructWithRefcountedMember() -> StructWithRefcountedMember { return StructWithRefcountedMember(x: RefCountedClass()) } public func printBreak(_ x: Int) { print("breakpoint \(x)") } // CHECK: class StructWithRefcountedMember final { // CHECK-NEXT: public: // CHECK-NEXT: inline ~StructWithRefcountedMember() { // CHECK-NEXT: auto metadata = _impl::$s7Structs26StructWithRefcountedMemberVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: vwTable->destroy(_getOpaquePointer(), metadata._0); // CHECK-NEXT: } // CHECK-NEXT: inline StructWithRefcountedMember(const StructWithRefcountedMember &other) { // CHECK-NEXT: auto metadata = _impl::$s7Structs26StructWithRefcountedMemberVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0); // CHECK-NEXT: } // CHECK-NEXT: inline StructWithRefcountedMember(StructWithRefcountedMember &&) = default; // CHECK-NEXT: private:
71ed7fd06cf3eabdebb0cb82ffc588cf
46.137255
231
0.715474
false
false
false
false
trujillo138/MyExpenses
refs/heads/master
MyExpenses/MyExpenses/Model/ExpensePeriod.swift
apache-2.0
1
// // ExpensePeriod.swift // MyExpenses // // Created by Tomas Trujillo on 5/22/17. // Copyright © 2017 TOMApps. All rights reserved. // import Foundation enum ExpensePeriodSortOption: Int { case amount = 0 case type = 1 case date = 2 case name = 3 static let numberOfOptions = 4 var name: String { switch self { case .amount: return LStrings.ExpensePeriod.SortOptionExpenseAmount case .date: return LStrings.ExpensePeriod.SortOptionExpenseDate case .name: return LStrings.ExpensePeriod.SortOptionExpenseName case .type: return LStrings.ExpensePeriod.SortOptionExpenseType } } } enum ExpensePeriodFilterOption: Int { case type = 0 case date = 1 case amount = 2 static let numberOfOptions = 3 var name: String { switch self { case .amount: return LStrings.ExpensePeriod.FilterOptionExpenseAmount case .date: return LStrings.ExpensePeriod.FilterOptionExpenseDate case .type: return LStrings.ExpensePeriod.FilterOptionExpenseType } } } struct ExpensePeriod { //MARK: Properties var expenses: [Expense] var budget: Double var goal: Double var date: Date var currency: Currency var month: Int var year: Int var amountSaved: Double { return fmax(self.budget - self.amountSpent, 0.0) } var amountSpent: Double { return expenses.reduce(0, { x, y in x + y.amount }) } var formattedAmountSpent: String { return amountSpent.currencyFormat } var formattedAmountSpentWithCurrency: String { return currency.rawValue + " " + amountSpent.currencyFormat } var formattedAmountSaved: String { return amountSaved.currencyFormat } var formattedAmountSavedWithCurrency: String { return currency.rawValue + " " + amountSaved.currencyFormat } var formattedGoal: String { return goal.currencyFormat } var formattedGoalWithCurrency: String { return currency.rawValue + " " + goal.currencyFormat } var formattedIncome: String { return budget.currencyFormat } var formattedIncomeWithCurrency: String { return currency.rawValue + " " + budget.currencyFormat } var name: String { let formatter = DateFormatter() formatter.dateFormat = "MMM yyyy" return formatter.string(from: self.date).capitalized } var maxExpenseDateForPeriod: Date? { if expenses.count == 0 { return nil } else { let descendingExpenseList = expenses.sorted { return $0.date >= $1.date } return descendingExpenseList[0].date } } var minExpenseDateForPeriod: Date? { if expenses.count == 0 { return nil } else { let ascendingExpenseList = expenses.sorted { return $1.date >= $0.date } return ascendingExpenseList[0].date } } var idExpensePeriod: String //MARK: Initializer init(budget: Double, date: Date, currency: Currency, goal: Double) { self.budget = budget self.goal = goal self.date = date self.expenses = [Expense]() self.currency = currency self.month = date.month() self.year = date.year() let currentDate = Date() self.idExpensePeriod = "\(self.date.year())-\(self.date.month())\(currentDate.year())\(currentDate.month())\(currentDate.day())\(currentDate.hour())\(currentDate.minute())\(currentDate.second())" } //MARK: Update func add(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.expenses.insert(expense, at: 0) return copyPeriod } func update(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) for (index, exp) in copyPeriod.expenses.enumerated() { guard exp.idExpense == expense.idExpense else { continue } copyPeriod.expenses[index] = expense } return copyPeriod } func delete(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) for (index, exp) in copyPeriod.expenses.enumerated() { guard exp.idExpense == expense.idExpense else { continue } copyPeriod.expenses.remove(at: index) } return copyPeriod } func updateInfo(monthlyIncome: Double, monthlyGoal: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.budget = monthlyIncome copyPeriod.goal = monthlyGoal return copyPeriod } func updateInfo(monthlyIncome: Double, monthlyGoal: Double, currency: String, currencyTransformRate: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.budget = monthlyIncome copyPeriod.goal = monthlyGoal guard let newCurrency = Currency(rawValue: currency) else { return copyPeriod } return copyPeriod.transformExpenseTo(currency: newCurrency, withRate: currencyTransformRate) } //MARK: Periods func isPeriodIn(date: Date) -> Bool { return date.year() == year && date.month() == month } static func createPeriodsUpUntil(date: Date, fromPeriod: ExpensePeriod, withBudget budget: Double, currency: Currency, goal: Double) -> [ExpensePeriod] { var periods = [ExpensePeriod]() var period = fromPeriod var periodDate = fromPeriod.date var arrivedToCurrentPeriod = period.isPeriodIn(date: date) while !arrivedToCurrentPeriod { periodDate = periodDate.dateByAdding(years: 0, months: 1, days: 0) period = ExpensePeriod(budget: budget, date: periodDate.dateForFirstDayOfMonth(), currency: currency, goal: goal) periods.insert(period, at: 0) arrivedToCurrentPeriod = period.isPeriodIn(date: date) } return periods } //MARK: Sorting func sortExpensesBy(option: ExpensePeriodSortOption, ascending: Bool) -> [Expense] { return sortExpenseListBy(option: option, ascending: ascending, expenseList: expenses) } private func sortExpenseListBy(option: ExpensePeriodSortOption, ascending: Bool, expenseList: [Expense]) -> [Expense] { switch option { case .amount: return ascending ? expenseList.sorted { return $0.amount < $1.amount } : expenseList.sorted { return $0.amount >= $1.amount } case .date: return ascending ? expenseList.sorted { return $0.date < $1.date } : expenseList.sorted { return $0.date >= $1.date } case .name: return ascending ? expenseList.sorted { return $0.name < $1.name } : expenseList.sorted { return $0.name >= $1.name } case .type: return ascending ? expenseList.sorted { return $0.expenseType.displayName < $1.expenseType.displayName } : expenseList.sorted { return $0.expenseType.displayName >= $1.expenseType.displayName } } } //MARK: Filtering func filterExpensesBy(filter: ExpensePeriodFilterOption, fromValue: Any?, toValue: Any?) -> [Expense] { switch filter { case .amount: if let frmValue = fromValue as? Double { return filterExpensesBy(amount: frmValue, greaterThan: true) } else { return filterExpensesBy(amount: toValue as! Double, greaterThan: false) } case .type: return filterExpensesBy(type: ExpenseType(rawValue: fromValue as! String)!) case .date: return filterExpensesFrom(date: fromValue as! Date?, to: toValue as! Date?) } } private func filterExpensesBy(amount: Double, greaterThan: Bool) -> [Expense] { return expenses.filter { return greaterThan ? $0.amount >= amount : $0.amount <= amount } } private func filterExpensesFrom(date: Date?, to: Date?) -> [Expense] { var filteredExpenses = [Expense]() if let fromDate = date, let toDate = to { filteredExpenses = expenses.filter { return $0.date >= fromDate && $0.date <= toDate } } else if let fromDate = date { filteredExpenses = expenses.filter { return $0.date >= fromDate } } else if let toDate = to { filteredExpenses = expenses.filter { return $0.date <= toDate } } return filteredExpenses } private func filterExpensesBy(type: ExpenseType) -> [Expense] { return expenses.filter { return $0.expenseType == type } } //MARK: Sort & Filter func filterAndSortExpensesBy(filter: ExpensePeriodFilterOption, fromValue: Any?, toValue: Any?, option: ExpensePeriodSortOption, ascending: Bool) -> [Expense] { let filteredExpenses = filterExpensesBy(filter: filter, fromValue: fromValue, toValue: toValue) return sortExpenseListBy(option: option, ascending: ascending, expenseList: filteredExpenses) } //MARK: Classify func getCategoriesWithExpenses() -> [ExpenseCategory] { var categories = [ExpenseCategory]() var listOfCats = [ExpenseType: Double]() for expense in expenses { if let amount = listOfCats[expense.expenseType] { listOfCats[expense.expenseType] = amount + expense.amount } else { listOfCats[expense.expenseType] = expense.amount } } for entry in listOfCats { let category = ExpenseCategory(type: entry.key, value: entry.value) categories.append(category) } return categories.sorted { return $0.value > $1.value } } //MARK: Transform func transformExpenseTo(currency: Currency, withRate rate: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.expenses = expenses.map { var newExp = $0 newExp.amount *= rate newExp.currency = currency return newExp } copyPeriod.currency = currency return copyPeriod } } //MARK: Coding Initializers extension ExpensePeriod { private struct CodingKeys { static let ExpensesKey = "expenses" static let BudgetKey = "budget" static let DateKey = "date" static let IdExpensePeriodKey = "id expense period" static let CurrencyKey = "currency" static let GoalKey = "goal" static let MonthKey = "key" static let YearKey = "year" } var plistRepresentation: [String: AnyObject] { return [CodingKeys.BudgetKey: budget as AnyObject, CodingKeys.DateKey: date as AnyObject, CodingKeys.IdExpensePeriodKey: idExpensePeriod as AnyObject, CodingKeys.ExpensesKey: expenses.map { $0.plistRepresentation } as AnyObject, CodingKeys.CurrencyKey: currency.rawValue as AnyObject, CodingKeys.GoalKey: goal as AnyObject, CodingKeys.YearKey: year as AnyObject, CodingKeys.MonthKey: month as AnyObject] } init(plist: [String: AnyObject]) { let periodDate = plist[CodingKeys.DateKey] as! Date budget = plist[CodingKeys.BudgetKey] as! Double date = periodDate idExpensePeriod = plist[CodingKeys.IdExpensePeriodKey] as! String expenses = (plist[CodingKeys.ExpensesKey] as! [[String: AnyObject]]).map(Expense.init(plist:)) currency = Currency(rawValue: plist[CodingKeys.CurrencyKey] as! String)! goal = plist[CodingKeys.GoalKey] as! Double year = plist[CodingKeys.YearKey] as? Int ?? periodDate.year() month = plist[CodingKeys.MonthKey] as? Int ?? periodDate.month() } } //MARK: Statistics extension ExpensePeriod { func calculateExpensePerExpenseType() -> [(ExpenseType, Double)] { var totals = [(ty: ExpenseType, ex: Double)]() let orderedExpenses = expenses.sorted { return $0.expenseType.rawValue.localizedCompare($1.expenseType.rawValue) == .orderedAscending ? true : false } var expenseType: ExpenseType? for expense in orderedExpenses { if expense.expenseType == expenseType { guard let total = totals.last else { continue } totals[totals.count - 1] = (ty: expense.expenseType, ex: total.ex + expense.amount) } else { let newTotal = (ty:expense.expenseType, ex: expense.amount) expenseType = expense.expenseType totals.append(newTotal) } } return totals.sorted(by: { return $0.ex > $1.ex }) } }
294f7aaedc4d08e3fa7a24ed02121d37
34.281501
203
0.622188
false
false
false
false
midoks/Swift-Learning
refs/heads/master
GitHubStar/GitHubStar/GitHubStar/Controllers/me/user/GsLoginViewController.swift
apache-2.0
1
// // LoginViewContoller.swift // GitHubStar // // Created by midoks on 15/12/19. // Copyright © 2015年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsLoginViewController: GsWebViewController { override func viewDidLoad() { super.viewDidLoad() self.title = sysLang(key: "Login") let rightButton = UIBarButtonItem(title: "刷新", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.reloadRequestUrl)) self.navigationItem.rightBarButtonItem = rightButton let leftButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.close)) self.navigationItem.leftBarButtonItem = leftButton self.loadRequestUrl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //关闭 func close(){ self.pop() self.dismiss(animated: true) { () -> Void in self.clearCookie() } } //加载url请求 func loadRequestUrl(){ let urlString = GitHubApi.instance.authUrl() let url = (NSURLComponents(string: urlString)?.url)! self.loadUrl(url: url as NSURL) } //重新加载 func reloadRequestUrl(){ self.reload() } //Mark: - webView delegate - override func webViewDidFinishLoad(_ webView: UIWebView) { super.webViewDidFinishLoad(webView) let code = webView.stringByEvaluatingJavaScript(from: "code") if code != "" { //print(code) GitHubApi.instance.getToken(code: code!, callback: { (data, response, error) -> Void in //print(error) //print(response) if (response != nil) { let data = String(data: data! as Data, encoding: String.Encoding.utf8)! let userInfoData = JSON.parse(data) let token = userInfoData["access_token"].stringValue GitHubApi.instance.setToken(token: token) GitHubApi.instance.user(callback: { (data, response, error) -> Void in let userData = String(data: data! as Data, encoding: String.Encoding.utf8)! let userJsonData = JSON.parse(userData) let name = userJsonData["login"].stringValue let userInfo = UserModelList.instance().selectUser(userName: name) if (userInfo as! NSNumber != false && userInfo.count > 0) { let id = userInfo["id"] as! Int _ = UserModelList.instance().updateMainUserById(id: id) _ = UserModelList.instance().updateInfoById(info: userData, id: id) } else { _ = UserModelList.instance().addUser(userName: name, token: token) _ = UserModelList.instance().updateInfo(info: userData, token: token) } self.close() }) } else { print("error") } }) } } }
e2e39aa0e3b8045b7437c2aa3981688f
34.163265
145
0.511898
false
false
false
false
tsolomko/SWCompression
refs/heads/develop
Sources/Common/Extensions.swift
mit
1
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension UnsignedInteger { @inlinable @inline(__always) func toInt() -> Int { return Int(truncatingIfNeeded: self) } } extension Int { @inlinable @inline(__always) func toUInt8() -> UInt8 { return UInt8(truncatingIfNeeded: UInt(self)) } @inlinable @inline(__always) func roundTo512() -> Int { if self >= Int.max - 510 { return Int.max } else { return (self + 511) & (~511) } } /// Returns an integer with reversed order of bits. func reversed(bits count: Int) -> Int { var a = 1 << 0 var b = 1 << (count - 1) var z = 0 for i in Swift.stride(from: count - 1, to: -1, by: -2) { z |= (self >> i) & a z |= (self << i) & b a <<= 1 b >>= 1 } return z } } extension Date { private static let ntfsReferenceDate = DateComponents(calendar: Calendar(identifier: .iso8601), timeZone: TimeZone(abbreviation: "UTC"), year: 1601, month: 1, day: 1, hour: 0, minute: 0, second: 0).date! init(_ ntfsTime: UInt64) { self.init(timeInterval: TimeInterval(ntfsTime) / 10_000_000, since: .ntfsReferenceDate) } }
119ae7cd82106ff4db3371c5fdbb9f6d
24.55
99
0.493151
false
false
false
false
patrickreynolds/TextFieldEffects
refs/heads/master
TextFieldEffects/TextFieldEffects/HoshiTextField.swift
mit
1
// // HoshiTextField.swift // TextFieldEffects // // Created by Raúl Riera on 24/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit /** An HoshiTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the lower edge of the control. */ @IBDesignable public class HoshiTextField: TextFieldEffects { /** The color of the border when it has no content. This property applies a color to the lower edge of the control. The default value for this property is a clear color. */ @IBInspectable dynamic public var borderInactiveColor: UIColor? { didSet { updateBorder() } } /** The color of the border when it has content. This property applies a color to the lower edge of the control. The default value for this property is a clear color. */ @IBInspectable dynamic public var borderActiveColor: UIColor? { didSet { updateBorder() } } /** The color of the placeholder text. This property applies a color to the complete placeholder string. The default value for this property is a black color. */ @IBInspectable dynamic public var placeholderColor: UIColor = .blackColor() { didSet { updatePlaceholder() } } /** The scale of the placeholder font. This property determines the size of the placeholder label relative to the font size of the text field. */ @IBInspectable dynamic public var placeholderFontScale: CGFloat = 0.65 { didSet { updatePlaceholder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 0.5) private let placeholderInsets = CGPoint(x: 0, y: 6) private let textFieldInsets = CGPoint(x: 0, y: 12) private let inactiveBorderLayer = CALayer() private let activeBorderLayer = CALayer() private var activePlaceholderPoint: CGPoint = CGPointZero // MARK: - TextFieldsEffects override public func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(inactiveBorderLayer) layer.addSublayer(activeBorderLayer) addSubview(placeholderLabel) } override public func animateViewsForTextEntry() { if text!.isEmpty { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .BeginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y) self.placeholderLabel.alpha = 0 }), completion:nil) } layoutPlaceholderInTextRect() placeholderLabel.frame.origin = activePlaceholderPoint UIView.animateWithDuration(0.2, animations: { self.placeholderLabel.alpha = 0.5 }) activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: true) } override public func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ self.layoutPlaceholderInTextRect() self.placeholderLabel.alpha = 1 }), completion: nil) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: false) } } // MARK: - Private private func updateBorder() { inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: true) inactiveBorderLayer.backgroundColor = borderInactiveColor?.CGColor activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: false) activeBorderLayer.backgroundColor = borderActiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale) return smallerFont } private func rectForBorder(thickness: CGFloat, isFilled: Bool) -> CGRect { if isFilled { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: CGRectGetWidth(frame), height: thickness)) } else { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: 0, height: thickness)) } } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch self.textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y) } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } }
0a7471d195b563e7af6ec6b79e827dfb
35.295699
183
0.651556
false
false
false
false
ejeinc/MetalScope
refs/heads/master
Sources/ViewerParameters.swift
mit
1
// // ViewerParameters.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // public protocol ViewerParametersProtocol { var lenses: Lenses { get } var distortion: Distortion { get } var maximumFieldOfView: FieldOfView { get } } public struct ViewerParameters: ViewerParametersProtocol { public var lenses: Lenses public var distortion: Distortion public var maximumFieldOfView: FieldOfView public init(lenses: Lenses, distortion: Distortion, maximumFieldOfView: FieldOfView) { self.lenses = lenses self.distortion = distortion self.maximumFieldOfView = maximumFieldOfView } public init(_ parameters: ViewerParametersProtocol) { self.lenses = parameters.lenses self.distortion = parameters.distortion self.maximumFieldOfView = parameters.maximumFieldOfView } } public struct Lenses { public enum Alignment: Int { case top = -1 case center = 0 case bottom = 1 } public let separation: Float public let offset: Float public let alignment: Alignment public let screenDistance: Float public init(separation: Float, offset: Float, alignment: Alignment, screenDistance: Float) { self.separation = separation self.offset = offset self.alignment = alignment self.screenDistance = screenDistance } } public struct FieldOfView { public let outer: Float // in degrees public let inner: Float // in degrees public let upper: Float // in degrees public let lower: Float // in degrees public init(outer: Float, inner: Float, upper: Float, lower: Float) { self.outer = outer self.inner = inner self.upper = upper self.lower = lower } public init(values: [Float]) { guard values.count == 4 else { fatalError("The values must contain 4 elements") } outer = values[0] inner = values[1] upper = values[2] lower = values[3] } } public struct Distortion { public var k1: Float public var k2: Float public init(k1: Float, k2: Float) { self.k1 = k1 self.k2 = k2 } public init(values: [Float]) { guard values.count == 2 else { fatalError("The values must contain 2 elements") } k1 = values[0] k2 = values[1] } public func distort(_ r: Float) -> Float { let r2 = r * r return ((k2 * r2 + k1) * r2 + 1) * r } public func distortInv(_ r: Float) -> Float { var r0: Float = 0 var r1: Float = 1 var dr0 = r - distort(r0) while abs(r1 - r0) > Float(0.0001) { let dr1 = r - distort(r1) let r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0)) r0 = r1 r1 = r2 dr0 = dr1 } return r1 } }
77ce2acf829c9032cafa66bb8c14aa4d
25.303571
96
0.596062
false
false
false
false
wwq0327/iOS9Example
refs/heads/master
Pinterest/Pinterest/PhotoStreamViewController.swift
apache-2.0
1
// // PhotoStreamViewController.swift // RWDevCon // // Created by Mic Pringle on 26/02/2015. // Copyright (c) 2015 Ray Wenderlich. All rights reserved. // import UIKit import AVFoundation class PhotoStreamViewController: UICollectionViewController { var photos = Photo.allPhotos() override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func viewDidLoad() { super.viewDidLoad() if let patternImage = UIImage(named: "Pattern") { view.backgroundColor = UIColor(patternImage: patternImage) } collectionView!.backgroundColor = UIColor.clearColor() collectionView!.contentInset = UIEdgeInsets(top: 23, left: 5, bottom: 10, right: 5) } } extension PhotoStreamViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("AnnotatedPhotoCell", forIndexPath: indexPath) as! AnnotatedPhotoCell cell.photo = photos[indexPath.item] return cell } }
ff720c83dd0f789cd337d44fec44f3db
26.869565
138
0.74337
false
false
false
false
justindaigle/grogapp-ios
refs/heads/master
GroGApp/GroGApp/GroupMembershipTableViewController.swift
mit
1
// // GroupMembershipTableViewController.swift // GroGApp // // Created by Justin Daigle on 3/27/15. // Copyright (c) 2015 Justin Daigle (.com). All rights reserved. // import UIKit class GroupMembershipTableViewController: UITableViewController { var users:JSON = [] var id = -1 @IBAction func addMember() { var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var prompt = UIAlertController(title: "Add User", message: "Enter the name of the user to add.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addTextFieldWithConfigurationHandler({(textField:UITextField!) in textField.placeholder = "Username" textField.secureTextEntry = false}) prompt.addAction((UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))) prompt.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: {(alertAction: UIAlertAction!) in let text = prompt.textFields![0] as! UITextField var success = DataMethods.AddUserToGroup(username, password, self.id, text.text) if (success) { var newPrompt = UIAlertController(title: "Success", message: "User added.", preferredStyle: UIAlertControllerStyle.Alert) newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))) self.presentViewController(newPrompt, animated: true, completion: {self.reloadGroup(true)}) } else { var newPrompt = UIAlertController(title: "Failure", message: "Failed to add user to group.", preferredStyle: UIAlertControllerStyle.Alert) newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))) self.presentViewController(newPrompt, animated: true, completion: nil) } })) self.presentViewController(prompt, animated: true, completion: nil) } func reloadGroup(reloadTable:Bool) { var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var groups = DataMethods.GetGroups(username, password) var groupSet = groups["groups"] for (index: String, subJson: JSON) in groupSet { if (subJson["id"].intValue == id) { users = subJson["users"] } } if (reloadTable) { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return users.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! GroupsTableViewCell // Configure the cell... cell.groupName.text = users[indexPath.row].stringValue return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var result = DataMethods.DeleteUserFromGroup(username, password, id, users[indexPath.row].stringValue) reloadGroup(false) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) if (result) { var prompt = UIAlertController(title: "Success", message: "Group member removed.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(prompt, animated: true, completion: nil) } else { var prompt = UIAlertController(title: "Failure", message: "Group member not removed.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(prompt, animated: true, completion: nil) } // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
97225297d8295a3f03f5d85b814376d8
42.375
157
0.665418
false
false
false
false
HotWordland/wlblog_server
refs/heads/master
Sources/App/Controllers/LoginController.swift
mit
1
import Vapor import HTTP import VaporJWT import Foundation import VaporPostgreSQL final class LoginController { func login(_ req: Request) throws -> ResponseRepresentable { guard let param_name = req.textplain_json?.node["name"]?.string,let param_pwd = req.textplain_json?.node["pwd"]?.string else{ return try responseWithError(msg: "有未提交的参数") } guard let user = try User.query().filter("name",param_name).all().first else{ return try responseWithError(msg: "用户不存在") } if user.password != param_pwd { return try responseWithError(msg: "密码有误") } let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + (60*60))), signer: HS256(key: "secret")) // let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + 60)), // signer: HS256(key: "secret")) // let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + 60)), signer: ES256(encodedKey: "AL3BRa7llckPgUw3Si2KCy1kRUZJ/pxJ29nlr86xlm0=")) let token = try jwt.createToken() return try responseWithSuccess(data: ["token":Node(token)]) } func saveDefaultUser(_ req: Request) throws -> ResponseRepresentable { if try User.query().filter("name","admin2").all().count != 0 { return try responseWithError(msg: "admin2 aleady exsit") } var user = User(name: "admin2", password: "123456") try user.save() return try JSON(node:User.all().makeNode()) } func uploadFile(_ request: Request) throws -> ResponseRepresentable{ guard let file = request.multipart?["file"]?.file,let fileName = file.name else { throw Abort.custom(status: .notFound, message: "文件未找到") } // let dateFormatter = DateFormatter() // dateFormatter.dateFormat = "yyyyMMddHH:mm:ss" let date = Int(Date().timeIntervalSince1970) // var date_string = dateFormatter.string(from: date) var file_save_name = "\(date)" let separates = fileName.components(separatedBy: ".") if separates.count>1 { if let extension_name = separates.last { file_save_name = "\(file_save_name).\(extension_name)" } } let imagePath = "upload_images/\(file_save_name)" let savePath = drop.workDir + "Public/" + imagePath // try Data(file.data).write(to: URL(fileURLWithPath: "/Users/wulong/Desktop/\(date_string)")) let flag = FileManager.default.createFile(atPath: savePath, contents: Data(bytes: file.data), attributes: nil) if flag { return try responseWithSuccess(data: ["path":Node(imagePath)]) }else{ throw Abort.custom(status: .notFound, message: "保存失败") } } }
e0c202f903983d128f3303b233818c8f
41.924242
151
0.608189
false
false
false
false
lioonline/Swift
refs/heads/master
NSBlockOperation/NSBlockOperation/ViewController.swift
gpl-3.0
1
// // ViewController.swift // NSBlockOperation // // Created by Carlos Butron on 02/12/14. // Copyright (c) 2014 Carlos Butron. // // 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 UIKit class ViewController: UIViewController { override func viewDidLoad() { var queue = NSOperationQueue() let operation1 : NSBlockOperation = NSBlockOperation ( { self.getWebs() let operation2 : NSBlockOperation = NSBlockOperation({ self.loadWebs() }) queue.addOperation(operation2) }) queue.addOperation(operation1) super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadWebs(){ let urls : NSMutableArray = NSMutableArray (objects:NSURL(string:"http://www.google.es")!, NSURL(string: "http://www.apple.com")!,NSURL(string: "http://carlosbutron.es")!, NSURL(string: "http://www.bing.com")!,NSURL(string: "http://www.yahoo.com")!) urls.addObjectsFromArray(googlewebs) for iterator:AnyObject in urls{ NSData(contentsOfURL:iterator as NSURL) println("Downloaded \(iterator)") } } var googlewebs:NSArray = [] func getWebs(){ let languages:NSArray = ["com","ad","ae","com.af","com.ag","com.ai","am","co.ao","com.ar","as","at"] var languageWebs = NSMutableArray() for(var i=0;i < languages.count; i++){ var webString: NSString = "http://www.google.\(languages[i])" languageWebs.addObject(NSURL(fileURLWithPath: webString)!) } googlewebs = languageWebs } }
f9d9935a132a187d4dbd93051bb73704
31.421053
257
0.614042
false
false
false
false
frootloops/swift
refs/heads/master
test/decl/protocol/protocols.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift protocol EmptyProtocol { } protocol DefinitionsInProtocols { init() {} // expected-error {{protocol initializers must not have bodies}} deinit {} // expected-error {{deinitializers may only be declared within a class}} } // Protocol decl. protocol Test { func setTitle(_: String) func erase() -> Bool var creator: String { get } var major : Int { get } var minor : Int { get } var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}} } protocol Test2 { var property: Int { get } var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}} associatedtype mytype associatedtype mybadtype = Int associatedtype V : Test = // expected-error {{expected type in associated type declaration}} {{28-28= <#type#>}} } func test1() { var v1: Test var s: String v1.setTitle(s) v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}} } protocol Bogus : Int {} // expected-error@-1{{inheritance from non-protocol type 'Int'}} // expected-error@-2{{type 'Self' constrained to non-protocol, non-class type 'Int'}} // Explicit conformance checks (successful). protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}} struct TestFormat { } protocol FormattedPrintable : CustomStringConvertible { func print(format: TestFormat) } struct X0 : Any, CustomStringConvertible { func print() {} } class X1 : Any, CustomStringConvertible { func print() {} } enum X2 : Any { } extension X2 : CustomStringConvertible { func print() {} } // Explicit conformance checks (unsuccessful) struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}} class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}} enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}} struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}} func print(format: TestFormat) {} // expected-note{{candidate has non-matching type '(TestFormat) -> ()'}} } // Protocol compositions in inheritance clauses protocol Left { func l() // expected-note {{protocol requires function 'l()' with type '() -> ()'; do you want to add a stub?}} } protocol Right { func r() // expected-note {{protocol requires function 'r()' with type '() -> ()'; do you want to add a stub?}} } typealias Both = Left & Right protocol Up : Both { func u() } struct DoesNotConform : Up { // expected-error@-1 {{type 'DoesNotConform' does not conform to protocol 'Left'}} // expected-error@-2 {{type 'DoesNotConform' does not conform to protocol 'Right'}} func u() {} } // Circular protocols protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error 2 {{circular protocol inheritance CircleMiddle}} // expected-error@-1{{circular protocol inheritance 'CircleMiddle' -> 'CircleStart' -> 'CircleEnd' -> 'CircleMiddle'}} // expected-error @+1 {{circular protocol inheritance CircleStart}} protocol CircleStart : CircleEnd { func circle_start() } // expected-error 2{{circular protocol inheritance CircleStart}} // expected-note@-1{{protocol 'CircleStart' declared here}} protocol CircleEnd : CircleMiddle { func circle_end()} // expected-note{{protocol 'CircleEnd' declared here}} protocol CircleEntry : CircleTrivial { } protocol CircleTrivial : CircleTrivial { } // expected-error 2{{circular protocol inheritance CircleTrivial}} struct Circle { func circle_start() {} func circle_middle() {} func circle_end() {} } func testCircular(_ circle: Circle) { // FIXME: It would be nice if this failure were suppressed because the protocols // have circular definitions. _ = circle as CircleStart // expected-error{{'Circle' is not convertible to 'CircleStart'; did you mean to use 'as!' to force downcast?}} {{14-16=as!}} } // <rdar://problem/14750346> protocol Q : C, H { } protocol C : E { } protocol H : E { } protocol E { } //===----------------------------------------------------------------------===// // Associated types //===----------------------------------------------------------------------===// protocol SimpleAssoc { associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}} } struct IsSimpleAssoc : SimpleAssoc { struct Associated {} } struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}} protocol StreamWithAssoc { associatedtype Element func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}} } struct AnRange<Int> : StreamWithAssoc { typealias Element = Int func get() -> Int {} } // Okay: Word is a typealias for Int struct AWordStreamType : StreamWithAssoc { typealias Element = Int func get() -> Int {} } struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}} typealias Element = Float func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}} } // Okay: Infers Element == Int struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc { func get() -> Int {} } protocol SequenceViaStream { associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}} func makeIterator() -> SequenceStreamTypeType } struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ { typealias Element = Int var min : Int var max : Int var stride : Int mutating func next() -> Int? { if min >= max { return .none } let prev = min min += stride return prev } typealias Generator = IntIterator func makeIterator() -> IntIterator { return self } } extension IntIterator : SequenceViaStream { typealias SequenceStreamTypeType = IntIterator } struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}} typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}} func makeIterator() -> Int {} } protocol GetATuple { associatedtype Tuple func getATuple() -> Tuple } struct IntStringGetter : GetATuple { typealias Tuple = (i: Int, s: String) func getATuple() -> Tuple {} } protocol ClassConstrainedAssocType { associatedtype T : class // expected-error@-1 {{'class' constraint can only appear on protocol declarations}} // expected-note@-2 {{did you mean to write an 'AnyObject' constraint?}}{{22-27=AnyObject}} } //===----------------------------------------------------------------------===// // Default arguments //===----------------------------------------------------------------------===// // FIXME: Actually make use of default arguments, check substitutions, etc. protocol ProtoWithDefaultArg { func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}} } struct HasNoDefaultArg : ProtoWithDefaultArg { func increment(_: Int) {} } //===----------------------------------------------------------------------===// // Variadic function requirements //===----------------------------------------------------------------------===// protocol IntMaxable { func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}} } struct HasIntMax : IntMaxable { func intmax(first: Int, rest: Int...) -> Int {} } struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}} } struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}} func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}} } //===----------------------------------------------------------------------===// // 'Self' type //===----------------------------------------------------------------------===// protocol IsEqualComparable { func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}} } struct HasIsEqual : IsEqualComparable { func isEqual(other: HasIsEqual) -> Bool {} } struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}} func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}} } //===----------------------------------------------------------------------===// // Using values of existential type. //===----------------------------------------------------------------------===// func existentialSequence(_ e: Sequence) { // expected-error{{has Self or associated type requirements}} // FIXME: Weird diagnostic var x = e.makeIterator() // expected-error{{'Sequence' is not convertible to 'Sequence.Iterator'}} x.next() x.nonexistent() } protocol HasSequenceAndStream { associatedtype R : IteratorProtocol, Sequence func getR() -> R } func existentialSequenceAndStreamType(_ h: HasSequenceAndStream) { // expected-error{{has Self or associated type requirements}} // FIXME: Crummy diagnostics. var x = h.getR() // expected-error{{member 'getR' cannot be used on value of protocol type 'HasSequenceAndStream'; use a generic constraint instead}} x.makeIterator() x.next() x.nonexistent() } //===----------------------------------------------------------------------===// // Subscripting //===----------------------------------------------------------------------===// protocol IntIntSubscriptable { subscript (i: Int) -> Int { get } } protocol IntSubscriptable { associatedtype Element subscript (i: Int) -> Element { get } } struct DictionaryIntInt { subscript (i: Int) -> Int { get { return i } } } func testSubscripting(_ iis: IntIntSubscriptable, i_s: IntSubscriptable) { // expected-error{{has Self or associated type requirements}} var i: Int = iis[17] var i2 = i_s[17] // expected-error{{member 'subscript' cannot be used on value of protocol type 'IntSubscriptable'; use a generic constraint instead}} } //===----------------------------------------------------------------------===// // Static methods //===----------------------------------------------------------------------===// protocol StaticP { static func f() } protocol InstanceP { func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}} } struct StaticS1 : StaticP { static func f() {} } struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}} static func f() {} // expected-note{{candidate operates on a type, not an instance as required}} } struct StaticAndInstanceS : InstanceP { static func f() {} func f() {} } func StaticProtocolFunc() { let a: StaticP = StaticS1() a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}} } func StaticProtocolGenericFunc<t : StaticP>(_: t) { t.f() } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// protocol Eq { static func ==(lhs: Self, rhs: Self) -> Bool } extension Int : Eq { } // Matching prefix/postfix. prefix operator <> postfix operator <> protocol IndexValue { static prefix func <> (_ max: Self) -> Int static postfix func <> (min: Self) -> Int } prefix func <> (max: Int) -> Int { return 0 } postfix func <> (min: Int) -> Int { return 0 } extension Int : IndexValue {} //===----------------------------------------------------------------------===// // Class protocols //===----------------------------------------------------------------------===// protocol IntrusiveListNode : class { var next : Self { get } } final class ClassNode : IntrusiveListNode { var next : ClassNode = ClassNode() } struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}} var next : StructNode // expected-error {{value type 'StructNode' cannot have a stored property that recursively contains it}} } final class ClassNodeByExtension { } struct StructNodeByExtension { } extension ClassNodeByExtension : IntrusiveListNode { var next : ClassNodeByExtension { get { return self } set {} } } extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}} var next : StructNodeByExtension { get { return self } set {} } } final class GenericClassNode<T> : IntrusiveListNode { var next : GenericClassNode<T> = GenericClassNode() } struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}} var next : GenericStructNode<T> // expected-error {{value type 'GenericStructNode<T>' cannot have a stored property that recursively contains it}} } // Refined protocols inherit class-ness protocol IntrusiveDListNode : IntrusiveListNode { var prev : Self { get } } final class ClassDNode : IntrusiveDListNode { var prev : ClassDNode = ClassDNode() var next : ClassDNode = ClassDNode() } struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}} // expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}} var prev : StructDNode // expected-error {{value type 'StructDNode' cannot have a stored property that recursively contains it}} var next : StructDNode } @objc protocol ObjCProtocol { func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}} } protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}} func bar() } class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}} } @objc protocol ObjCProtocolRefinement : ObjCProtocol { } @objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}} // <rdar://problem/16079878> protocol P1 { associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}} } protocol P2 { } struct X3<T : P1> where T.Assoc : P2 {} struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}} func getX1() -> X3<X4> { return X3() } } protocol ShouldntCrash { // rdar://16109996 let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}} // <rdar://problem/17200672> Let in protocol causes unclear errors and crashes let fullName2: String // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} // <rdar://problem/16789886> Assert on protocol property requirement without a type var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}} // expected-error@-1 {{computed property must have an explicit type}} {{26-26=: <# Type #>}} } // rdar://problem/18168866 protocol FirstProtocol { weak var delegate : SecondProtocol? { get } // expected-error{{'weak' must not be applied to non-class-bound 'SecondProtocol'; consider adding a protocol conformance that has a class bound}} } protocol SecondProtocol { func aMethod(_ object : FirstProtocol) } // <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing class C1 : P2 {} func f<T : C1>(_ x : T) { _ = x as P2 } class C2 {} func g<T : C2>(_ x : T) { x as P2 // expected-error{{'T' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} {{5-7=as!}} } class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}} func h<T : C3>(_ x : T) { _ = x as P1 // expected-error{{protocol 'P1' can only be used as a generic constraint because it has Self or associated type requirements}} } protocol P4 { associatedtype T // expected-note {{protocol requires nested type 'T'}} } class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}} associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}} } // <rdar://problem/25185722> Crash with invalid 'let' property in protocol protocol LetThereBeCrash { let x: Int // expected-error@-1 {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} // expected-note@-2 {{declared here}} } extension LetThereBeCrash { init() { x = 1 } // expected-error@-1 {{'let' property 'x' may not be initialized directly; use "self.init(...)" or "self = ..." instead}} }
d5b1e1c25b451c74f33372f6ec0888fd
34.800781
232
0.653682
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Room/ReactionHistory/ReactionHistoryCoordinator.swift
apache-2.0
2
// File created from ScreenTemplate // $ createScreen.sh ReactionHistory ReactionHistory /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class ReactionHistoryCoordinator: ReactionHistoryCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private let roomId: String private let eventId: String private let router: NavigationRouter // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: ReactionHistoryCoordinatorDelegate? // MARK: - Setup init(session: MXSession, roomId: String, eventId: String) { self.session = session self.roomId = roomId self.eventId = eventId self.router = NavigationRouter(navigationController: RiotNavigationController()) } // MARK: - Public methods func start() { let reactionHistoryViewModel = ReactionHistoryViewModel(session: session, roomId: roomId, eventId: eventId) let reactionHistoryViewController = ReactionHistoryViewController.instantiate(with: reactionHistoryViewModel) reactionHistoryViewModel.coordinatorDelegate = self self.router.setRootModule(reactionHistoryViewController) } func toPresentable() -> UIViewController { return self.router.toPresentable() } } // MARK: - ReactionHistoryViewModelCoordinatorDelegate extension ReactionHistoryCoordinator: ReactionHistoryViewModelCoordinatorDelegate { func reactionHistoryViewModelDidClose(_ viewModel: ReactionHistoryViewModelType) { self.delegate?.reactionHistoryCoordinatorDidClose(self) } }
ed108fdab56404133d8f198b43da882f
32.029412
117
0.735085
false
false
false
false
hassanabidpk/umapit_ios
refs/heads/master
uMAPit/models/Location.swift
mit
1
// // Location.swift // uMAPit // // Created by Hassan Abid on 16/02/2017. // Copyright © 2017 uMAPit. All rights reserved. // import Foundation import RealmSwift class Location: Object { dynamic var title = "" dynamic var latitude: Double = 0.0 dynamic var longitude: Double = 0.0 dynamic var address = "" dynamic var updated_at: Date? = nil dynamic var created_at: Date? = nil dynamic var id = 0 }
7c63396e9d91da017f2993624bf3269d
18
49
0.652174
false
false
false
false
KlubJagiellonski/pola-ios
refs/heads/master
BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/CompanyContent/CompanyContentView.swift
gpl-2.0
1
import UIKit final class CompanyContentView: UIView { let capitalTitleLabel = UILabel() let capitalProgressView = SecondaryProgressView() let notGlobalCheckRow = CheckRow() let registeredCheckRow = CheckRow() let rndCheckRow = CheckRow() let workersCheckRow = CheckRow() let friendButton = UIButton() let descriptionLabel = UILabel() private let stackView = UIStackView() private let padding = CGFloat(14) override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = padding stackView.distribution = .fillProportionally stackView.alignment = .fill stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) let localizable = R.string.localizable.self capitalTitleLabel.font = Theme.normalFont capitalTitleLabel.textColor = Theme.defaultTextColor capitalTitleLabel.text = localizable.percentOfPolishHolders() capitalTitleLabel.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(capitalTitleLabel) capitalProgressView.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(capitalProgressView) notGlobalCheckRow.text = localizable.notPartOfGlobalCompany() notGlobalCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(notGlobalCheckRow) registeredCheckRow.text = localizable.isRegisteredInPoland() registeredCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(registeredCheckRow) rndCheckRow.text = localizable.createdRichSalaryWorkPlaces() rndCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(rndCheckRow) workersCheckRow.text = localizable.producingInPL() workersCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(workersCheckRow) friendButton.setImage(R.image.heartFilled(), for: .normal) friendButton.tintColor = Theme.actionColor friendButton.setTitle(localizable.thisIsPolaSFriend(), for: .normal) friendButton.setTitleColor(Theme.actionColor, for: .normal) friendButton.titleLabel?.font = Theme.normalFont let buttontitleHorizontalMargin = CGFloat(7) friendButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttontitleHorizontalMargin, bottom: 0, right: 0) friendButton.contentHorizontalAlignment = .left friendButton.adjustsImageWhenHighlighted = false friendButton.isHidden = true friendButton.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(friendButton) descriptionLabel.font = Theme.normalFont descriptionLabel.textColor = Theme.defaultTextColor descriptionLabel.numberOfLines = 0 descriptionLabel.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(descriptionLabel) createConstraints() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createConstraints() { addConstraints([ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor), ]) } }
df0696b82051522a4a55ff7e39ca147b
41.213483
88
0.727974
false
false
false
false
giftbott/HandyExtensions
refs/heads/master
Sources/UIViewExtensions.swift
mit
1
// // UIViewExtensions.swift // HandyExtensions // // Created by giftbot on 2017. 4. 29.. // Copyright © 2017년 giftbot. All rights reserved. // // MARK: - Initializer extension UIView { /// let view = UIView(x: 0, y: 20, w: 200, h: 200) public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) } public convenience init(origin: CGPoint, size: CGSize) { self.init(frame: CGRect(origin: origin, size: size)) } } // MARK: - Computed Property extension UIView { /// Call view's parent UIViewController responder. /// view.viewController public var viewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } /// var view = UIView(x: 0, y: 0, width: 100, height: 100) /// /// view.x = 50 /// view.y = 50 /// view.width = 50 /// view.height = 50 public var x: CGFloat { get { return frame.origin.x } set { self.frame.origin.x = newValue } } public var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } public var width: CGFloat { get { return frame.width } set { frame.size.width = newValue } } public var height: CGFloat { get { return frame.height } set { frame.size.height = newValue } } public var maxX: CGFloat { get { return x + width } set { x = newValue - width } } public var maxY: CGFloat { get { return y + height } set { y = newValue - height } } public var midX: CGFloat { get { return x + (width / 2) } set { x = newValue - (width / 2) } } public var midY: CGFloat { get { return y + (height / 2) } set { y = newValue - (height / 2) } } public var size: CGSize { get { return frame.size } set { frame.size = newValue } } @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } } // MARK: - Method extension UIView { /// view.addSubviews([aLabel, bButton]) public func addSubviews(_ views: [UIView]) { for view in views { self.addSubview(view) } } /// view.removeAllsubviews() public func removeAllSubviews() { for subview in self.subviews { subview.removeFromSuperview() } } /// Rotate view using CoreAnimation. Rotating 360 degree in a second is a default public func rotate( from: CGFloat = 0, to: CGFloat = 2 * .pi, beginTime: CFTimeInterval = 0.0, duration: CFTimeInterval = 1.0, forKey key: String? = nil, _ delegateObject: AnyObject? = nil ) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.beginTime = CACurrentMediaTime() + beginTime rotateAnimation.fromValue = from.degreesToRadians rotateAnimation.toValue = to.degreesToRadians rotateAnimation.duration = duration weak var delegate = delegateObject if delegate != nil { rotateAnimation.delegate = delegate as? CAAnimationDelegate } DispatchQueue.main.async { [weak self] in self?.layer.add(rotateAnimation, forKey: key) } } } // MARK: - LayoutAnchor Helper extension UIView { public func topAnchor(to anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self { topAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func leadingAnchor(to anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self { leadingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func bottomAnchor(to anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self { bottomAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func trailingAnchor(to anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self { trailingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func widthAnchor(constant: CGFloat) -> Self { widthAnchor.constraint(equalToConstant: constant).isActive = true return self } public func heightAnchor(constant: CGFloat) -> Self { heightAnchor.constraint(equalToConstant: constant).isActive = true return self } public func sizeAnchor(width widthConstant: CGFloat, height heightConstant: CGFloat) -> Self { widthAnchor.constraint(equalToConstant: widthConstant).isActive = true heightAnchor.constraint(equalToConstant: heightConstant).isActive = true return self } public func sizeAnchor(size: CGSize) -> Self { widthAnchor.constraint(equalToConstant: size.width).isActive = true heightAnchor.constraint(equalToConstant: size.height).isActive = true return self } public func centerYAnchor(to anchor: NSLayoutYAxisAnchor) -> Self { centerYAnchor.constraint(equalTo: anchor).isActive = true return self } public func centerXAnchor(to anchor: NSLayoutXAxisAnchor) -> Self { centerXAnchor.constraint(equalTo: anchor).isActive = true return self } public func activateAnchors() { translatesAutoresizingMaskIntoConstraints = false } }
59a6ac592fcf3fa12cdee82854dd226b
25.935644
96
0.663481
false
false
false
false
cp3hnu/Bricking
refs/heads/master
Bricking/Source/Center.swift
mit
1
// // Center.swift // Bricking // // Created by CP3 on 2017/7/1. // Copyright © 2017年 CP3. All rights reserved. // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif extension View { @discardableResult public func centerInContainer() -> Self { centerHorizontally() centerVertically() return self } @discardableResult public func centerHorizontally(_ offset: CGFloat = 0) -> Self { self.laCenterX == offset return self } @discardableResult public func centerVertically(_ offset: CGFloat = 0) -> Self { self.laCenterY == offset return self } } @discardableResult public func centerHorizontally(_ views: View...) -> [View] { return centerHorizontally(views) } @discardableResult public func centerHorizontally(_ views: [View]) -> [View] { views.first?.centerHorizontally() alignVertically(views) return views } @discardableResult public func centerVertically(_ views: View...) -> [View] { return centerVertically(views) } @discardableResult public func centerVertically(_ views: [View]) -> [View] { views.first?.centerVertically() alignHorizontally(views) return views } extension Array where Element: View { @discardableResult public func centerHorizontally() -> Array<View> { return Bricking.centerHorizontally(self) } @discardableResult public func centerVertically() -> Array<View> { return Bricking.centerVertically(self) } }
5dd86abdd0166be9b16a84cf32487244
20.943662
67
0.661104
false
false
false
false
SaeidBsn/SwiftyGuideOverlay
refs/heads/master
Sample/SwiftyGuideOverlay/ViewController.swift
mit
1
// // ViewController.swift // SwiftyGuideOverlay // // Created by Saeid Basirnia on 8/19/16. // Copyright © 2016 Saeid Basirnia. All rights reserved. // import UIKit class ViewController: UIViewController, SkipOverlayDelegate{ @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! @IBOutlet weak var tableView: UITableView! var navItem: UIBarButtonItem! var navItem2: UIBarButtonItem! var list: [String] = [ "This is number 1", "This is number 2", "This is number 3", "This is number 4", "This is number 5", ] var o: GDOverlay! override func viewDidAppear(_ animated: Bool){ navItem = navigationItem.leftBarButtonItem navItem2 = navigationItem.rightBarButtonItem navItem2.title = "Share" navItem.title = "cool" //Create an instance of GDOverlay to setup help view o = GDOverlay() /////appereance customizations o.arrowColor = UIColor.red o.showBorder = false o.boxBackColor = UIColor.clear o.highlightView = true //o.arrowWidth = 2.0 //o.backColor = UIColor.blue //o.showBorder = true o.boxBackColor = UIColor.gray.withAlphaComponent(0.2) //o.boxBorderColor = UIColor.black //o.headColor = UIColor.white //o.headRadius = 6 //o.labelFont = UIFont.systemFont(ofSize: 12) //o.labelColor = UIColor.green /// types are .line_arrow | .line_bubble | .dash_bubble o.lineType = LineType.line_arrow //Always set the delegate for SkipOverlayDelegate //for onSkipSignal() function call o.delegate = self self.onSkipSignal() } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } var a = 0 func onSkipSignal(){ a += 1 if a == 1{ o.drawOverlay(to: navItem2, desc: "This is really cool this is really cool this is really cool this is really cool this is really cool this is really cool this is really cool!") }else if a == 2{ o.drawOverlay(to: navItem, desc: "this is really coolt!") }else if a == 3{ o.drawOverlay(to: tableView, section: 0, row: 0, desc: "This is nice!") }else if a == 4{ o.drawOverlay(to: button1, desc: "This button is doing some stuff!") }else if a == 5{ o.drawOverlay(to: button2, desc: "This button is awsome!!") }else if a == 6{ guard let tabbar = tabBarController?.tabBar else { return } o.drawOverlay(to: tabbar, item: 1, desc: "This is second tabbar item!") }else{ // close it! } } } extension ViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let curr = list[indexPath.row] cell.textLabel?.text = curr return cell } }
16fe216bf1b20d9cc96a2007c8bf5945
28.770492
190
0.579295
false
false
false
false
cpuu/OTT
refs/heads/master
OTT/Group1ViewController.swift
mit
1
// // Group1ViewController.swift // BlueCap // // Created by 박재유 on 2016. 6. 1.. // Copyright © 2016년 Troy Stribling. All rights reserved. // import UIKit class Group1ViewController: UIViewController , UITableViewDataSource,UITableViewDelegate { var valueToPass:Int = 0 var valueToTitle: String = String() var marrGroupData : NSMutableArray! var averageValue:Float = 0 @IBOutlet weak var tbGroupData: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //navigation bar style let font = UIFont(name:"Thonburi", size:20.0) var titleAttributes : [String:AnyObject] if let defaultTitleAttributes = UINavigationBar.appearance().titleTextAttributes { titleAttributes = defaultTitleAttributes } else { titleAttributes = [String:AnyObject]() } titleAttributes[NSFontAttributeName] = font self.navigationController?.navigationBar.titleTextAttributes = titleAttributes } override func viewWillAppear(animated: Bool) { self.getGroupData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Other methods func getGroupData() { marrGroupData = NSMutableArray() marrGroupData = ModelManager.getInstance().getAllGroupData() tbGroupData.reloadData() //All member의 평균 계산하기 averageValue = ModelManager.getInstance().getAllMemberAverage() //print("\(averageValue)") } //MARK: UITableView delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return marrGroupData.count + 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Name with value" } func imageResize (cellimage:UIImage, sizeChange:CGSize)-> UIImage{ let hasAlpha = true let scale: CGFloat = 0.0 // Use scale factor of main screen UIGraphicsBeginImageContextWithOptions(sizeChange, !hasAlpha, scale) cellimage.drawInRect(CGRect(origin: CGPointZero, size: sizeChange)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() return scaledImage } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FriendCell = tableView.dequeueReusableCellWithIdentifier("cell") as! FriendCell if(indexPath.row == 0) { cell.lblContent.text = "All Members" cell.valContent.text = "\(averageValue)" } else{ let group:Group = marrGroupData.objectAtIndex((indexPath.row)-1) as! Group cell.lblContent.text = "\(group.GROUP_NM)" cell.valContent.text = "\(group.GROUP_VALUE)" cell.GroupImage.image! = imageResize(UIImage(named: group.GROUP_ICON_FILE_NM)!, sizeChange: CGSizeMake(30,30)) //cell.btnDelete.tag = (indexPath.row)-1 //cell.btnEdit.tag = (indexPath.row)-1 } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //print(group.GROUP_NM) if(indexPath.row == 0) { valueToPass = Int("9999")! valueToTitle = "All Members" } else { let group:Group = marrGroupData.objectAtIndex((indexPath.row)-1) as! Group valueToPass = Int(group.GROUP_SEQ)! valueToTitle = group.GROUP_NM } //print("true answer : ?", valueToPass) self.performSegueWithIdentifier("detailSegue", sender: self) } //MARK: UIButton Action methods @IBAction func btnDeleteClicked(sender: AnyObject) { let btnDelete : UIButton = sender as! UIButton let selectedIndex : Int = btnDelete.tag let friend: Group = marrGroupData.objectAtIndex(selectedIndex) as! Group let isDeleted = ModelManager.getInstance().deleteGroupData(friend) if isDeleted { Util.invokeAlertMethod("", strBody: "Record deleted successfully.", delegate: nil) } else { Util.invokeAlertMethod("", strBody: "Error in deleting record.", delegate: nil) } self.getGroupData() } @IBAction func btnEditClicked(sender: AnyObject) { self.performSegueWithIdentifier("editSegue", sender: sender) } //MARK: Navigation methods override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "editSegue") { let btnEdit : UIButton = sender as! UIButton let selectedIndex : Int = btnEdit.tag let viewController : Group2ViewController = segue.destinationViewController as! Group2ViewController viewController.isEdit = true viewController.groupData = marrGroupData.objectAtIndex(selectedIndex) as! Group } else if(segue.identifier == "detailSegue") { //get a reference to the destination view controller let destinationVC:Group3ViewController = segue.destinationViewController as! Group3ViewController //set properties on the destination view controller destinationVC.groupMemberSeq = valueToPass destinationVC.title = valueToTitle //print("destinationVC.value : ?", destinationVC.groupMemberSeq) //print("valuetopass : ?", valueToPass) //etc... } } }
40aeb21d5ab0763e9021ab037e739341
34.925926
122
0.632818
false
false
false
false
dcunited001/Spectra
refs/heads/master
Pod/Classes/InflightResourceManager.swift
mit
1
// // InflightResourcesManager.swift // Pods // // Created by David Conner on 10/6/15. // let kInflightResourceCountDefault = 3 // three is magic number public class InflightResourceManager { public var inflightResourceCount:Int public var index:Int = 0 public var inflightResourceSemaphore:dispatch_semaphore_t init(inflightResourceCount: Int = kInflightResourceCountDefault) { self.inflightResourceCount = inflightResourceCount self.inflightResourceSemaphore = dispatch_semaphore_create(self.inflightResourceCount) } public func next() { dispatch_semaphore_signal(inflightResourceSemaphore) index = (index + 1) % inflightResourceCount } public func wait() { dispatch_semaphore_wait(inflightResourceSemaphore, DISPATCH_TIME_FOREVER) } deinit { for _ in 0...inflightResourceCount-1 { dispatch_semaphore_signal(inflightResourceSemaphore) } } }
0b741a7ae2464f523e5bf43f7093898d
27.823529
94
0.696939
false
false
false
false
exyte/Macaw
refs/heads/master
Source/animation/types/animation_generators/MorphingGenerator.swift
mit
1
// // MorphingGenerator.swift // Pods // // Created by Victor Sukochev on 24/01/2017. // // import Foundation #if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif func addMorphingAnimation(_ animation: BasicAnimation, _ context: AnimationContext, sceneLayer: CALayer?, completion: @escaping (() -> Void)) { guard let morphingAnimation = animation as? MorphingAnimation else { return } guard let shape = animation.node as? Shape, let renderer = animation.nodeRenderer else { return } let transactionsDisabled = CATransaction.disableActions() CATransaction.setDisableActions(true) let fromLocus = morphingAnimation.getVFunc()(0.0) let toLocus = morphingAnimation.getVFunc()(animation.autoreverses ? 0.5 : 1.0) let duration = animation.autoreverses ? animation.getDuration() / 2.0 : animation.getDuration() let layer = AnimationUtils.layerForNodeRenderer(renderer, animation: animation, shouldRenderContent: false) // Creating proper animation let generatedAnimation = pathAnimation( from: fromLocus, to: toLocus, duration: duration) generatedAnimation.repeatCount = Float(animation.repeatCount) generatedAnimation.timingFunction = caTimingFunction(animation.easing) generatedAnimation.autoreverses = animation.autoreverses generatedAnimation.progress = { progress in let t = Double(progress) animation.progress = t animation.onProgressUpdate?(t) } generatedAnimation.completion = { finished in if animation.manualStop { animation.progress = 0.0 shape.form = morphingAnimation.getVFunc()(0.0) } else if finished { animation.progress = 1.0 shape.form = morphingAnimation.getVFunc()(1.0) } renderer.freeLayer() if !animation.cycled && !animation.manualStop { animation.completion?() } completion() } layer.path = fromLocus.toCGPath() layer.setupStrokeAndFill(shape) let animationId = animation.ID layer.add(generatedAnimation, forKey: animationId) animation.removeFunc = { [weak layer] in shape.animations.removeAll { $0 === animation } layer?.removeAnimation(forKey: animationId) } if !transactionsDisabled { CATransaction.commit() } } fileprivate func pathAnimation(from: Locus, to: Locus, duration: Double) -> CAAnimation { let fromPath = from.toCGPath() let toPath = to.toCGPath() let animation = CABasicAnimation(keyPath: "path") animation.fromValue = fromPath animation.toValue = toPath animation.duration = duration animation.fillMode = MCAMediaTimingFillMode.forwards animation.isRemovedOnCompletion = false return animation }
15310d2e3e7640e667910402ed348db3
27.575758
143
0.681159
false
false
false
false
epv44/TwitchAPIWrapper
refs/heads/master
Example/Tests/Request Tests/GetBannedUsersRequestTests.swift
mit
1
// // GetBannedUsersRequestTests.swift // TwitchAPIWrapper_Tests // // Created by Eric Vennaro on 6/14/21. // Copyright © 2021 CocoaPods. All rights reserved. // import XCTest @testable import TwitchAPIWrapper class GetBannedUsersRequestTests: XCTestCase { override func setUpWithError() throws { TwitchAuthorizationManager.sharedInstance.clientID = "1" TwitchAuthorizationManager.sharedInstance.credentials = Credentials(accessToken: "XXX", scopes: ["user", "read"]) super.setUp() } func testBuildRequest_withRequiredParams_shouldSucceed() { let request = GetBannedUsersRequest(broadcasterID: "1") XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/moderation/banned?broadcaster_id=1") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } func testBuildRequest_withOptionalParams_shouldSucceed() { let request = GetBannedUsersRequest(broadcasterID: "1", userIDs: ["2"], after: "3", first: "4", before: "5") XCTAssertEqual( request.url!.absoluteString, expectedURL: "https://api.twitch.tv/helix/moderation/banned?broadcaster_id=1&user_id=2&after=3&first=4&before=5") XCTAssertEqual(request.data, Data()) XCTAssertEqual(request.headers, ["Client-Id": "1", "Authorization": "Bearer XXX"]) } }
a7ffe52abf604a8cd7975158b79a1bf2
38.702703
125
0.682777
false
true
false
false
segmentio/analytics-swift
refs/heads/main
Sources/Segment/Utilities/QueueTimer.swift
mit
1
// // QueueTimer.swift // Segment // // Created by Brandon Sneed on 6/16/21. // import Foundation internal class QueueTimer { enum State { case suspended case resumed } let interval: TimeInterval let timer: DispatchSourceTimer let queue: DispatchQueue let handler: () -> Void @Atomic var state: State = .suspended static var timers = [QueueTimer]() static func schedule(interval: TimeInterval, queue: DispatchQueue = .main, handler: @escaping () -> Void) { let timer = QueueTimer(interval: interval, queue: queue, handler: handler) Self.timers.append(timer) } init(interval: TimeInterval, queue: DispatchQueue = .main, handler: @escaping () -> Void) { self.interval = interval self.queue = queue self.handler = handler timer = DispatchSource.makeTimerSource(flags: [], queue: queue) timer.schedule(deadline: .now() + self.interval, repeating: self.interval) timer.setEventHandler { [weak self] in self?.handler() } resume() } deinit { timer.setEventHandler { // do nothing ... } // if timer is suspended, we must resume if we're going to cancel. timer.cancel() resume() } func suspend() { if state == .suspended { return } state = .suspended timer.suspend() } func resume() { if state == .resumed { return } state = .resumed timer.resume() } } extension TimeInterval { static func milliseconds(_ value: Int) -> TimeInterval { return TimeInterval(value / 1000) } static func seconds(_ value: Int) -> TimeInterval { return TimeInterval(value) } static func hours(_ value: Int) -> TimeInterval { return TimeInterval(60 * value) } static func days(_ value: Int) -> TimeInterval { return TimeInterval((60 * value) * 24) } }
d2aae5e66ad303df6f4c94f759cd95f2
23.069767
111
0.566184
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/DynamicsCatalog/Controllers/InstantaneousPushVC.swift
mit
1
// // InstantaneousPushVC.swift // Lumia // // Created by 黄伯驹 on 2019/12/31. // Copyright © 2019 黄伯驹. All rights reserved. // import UIKit class InstantaneousPushVC: UIViewController { private lazy var square: UIImageView = { let square = UIImageView(image: UIImage(named: "Box1")) return square }() private lazy var centerPoint: UIImageView = { let centerPoint = UIImageView(image: UIImage(named: "Origin")) centerPoint.translatesAutoresizingMaskIntoConstraints = false return centerPoint }() private lazy var pushBehavior: UIPushBehavior = { let pushBehavior = UIPushBehavior(items: [square], mode: .instantaneous) pushBehavior.angle = 0.0 pushBehavior.magnitude = 0.0 return pushBehavior }() private lazy var animator: UIDynamicAnimator = { let animator = UIDynamicAnimator(referenceView: self.view) return animator }() private lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.text = "Tap anywhere to create a force." textLabel.font = UIFont(name: "Chalkduster", size: 15) textLabel.translatesAutoresizingMaskIntoConstraints = false return textLabel }() override func loadView() { view = DecorationView() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(textLabel) textLabel.bottomAnchor.constraint(equalTo: view.safeBottomAnchor).isActive = true textLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true view.addSubview(centerPoint) centerPoint.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true centerPoint.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true square.frame.origin = CGPoint(x: 200, y: 200) view.addSubview(square) let collisionBehavior = UICollisionBehavior(items: [square]) collisionBehavior.setTranslatesReferenceBoundsIntoBoundary(with: UIEdgeInsets(top: view.safeAreaInsets.top, left: 0, bottom: view.safeAreaInsets.bottom, right: 0)) // Account for any top and bottom bars when setting up the reference bounds. animator.addBehavior(collisionBehavior) animator.addBehavior(pushBehavior) let tap = UITapGestureRecognizer(target: self, action: #selector(handleSnapGesture)) view.addGestureRecognizer(tap) } @objc func handleSnapGesture(_ gesture: UITapGestureRecognizer) { // Tapping will change the angle and magnitude of the impulse. To visually // show the impulse vector on screen, a red arrow representing the angle // and magnitude of this vector is briefly drawn. let p = gesture.location(in: view) let o = CGPoint(x: view.bounds.midX, y: view.bounds.midY) var distance = sqrt(pow(p.x - o.x, 2.0)+pow(p.y-o.y, 2.0)) let angle = atan2(p.y-o.y, p.x-o.x) distance = min(distance, 100.0) // Display an arrow showing the direction and magnitude of the applied // impulse. (view as? DecorationView)?.drawMagnitudeVector(with: distance, angle: angle, color: .red, forLimitedTime: true) // These two lines change the actual force vector. pushBehavior.magnitude = distance / 100 pushBehavior.angle = angle // A push behavior in instantaneous (impulse) mode automatically // deactivate itself after applying the impulse. We thus need to reactivate // it when changing the impulse vector. pushBehavior.active = true } }
acb9af59086c772e3307f8f1fdff4228
37.103093
173
0.665314
false
false
false
false
Decybel07/L10n-swift
refs/heads/master
Example/Example iOS/Scenes/SimpleTranslator/SimpleTranslatorViewController.swift
mit
1
// // SimpleTranslatorViewController.swift // Example // // Created by Adrian Bobrowski on 16.08.2017. // // import UIKit import L10n_swift final class SimpleTranslatorViewController: UIViewController { // MARK: - @IBOutlet @IBOutlet fileprivate weak var pickerView: UIPickerView! @IBOutlet fileprivate weak var tableView: UITableView! // MARK: - variable fileprivate var languages: [String] = L10n.supportedLanguages fileprivate var items: [String] = [ "apple", "bee", "cat", "dolphin", "elephant", "fish", "giraffe", "house", "iceCream", "jelly", "kite", "ladybird", "mouse", "newt", "octopus", "pig", "queen", "rocket", "snake", "teddybear", "umbrella", "vase", "whale", "xylophone", "yoYo", "zebra", ] fileprivate var from = L10n.shared fileprivate var to: L10n = { L10n(language: L10n.supportedLanguages.first(where: { $0 != L10n.shared.language })) }() // MARK: - Life cycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.pickerView.selectRow(self.languages.firstIndex(of: self.from.language) ?? 0, inComponent: 0, animated: false) self.pickerView.selectRow(self.languages.firstIndex(of: self.to.language) ?? 0, inComponent: 1, animated: false) } } // MARK: - UITableViewDataSource extension SimpleTranslatorViewController: UITableViewDataSource { func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { return self.items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "translator", for: indexPath) let key = "simpleTranslator.list.\(self.items[indexPath.row])" cell.textLabel?.text = key.l10n(self.from) cell.detailTextLabel?.text = key.l10n(self.to) return cell } } // MARK: - UIPickerViewDataSource extension SimpleTranslatorViewController: UIPickerViewDataSource { func numberOfComponents(in _: UIPickerView) -> Int { return 2 } func pickerView(_: UIPickerView, numberOfRowsInComponent _: Int) -> Int { return self.languages.count } } // MARK: - UIPickerViewDelegate extension SimpleTranslatorViewController: UIPickerViewDelegate { func pickerView(_: UIPickerView, titleForRow row: Int, forComponent _: Int) -> String? { return L10n.shared.locale?.localizedString(forLanguageCode: self.languages[row]) } func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if component == 0 { self.from = L10n(language: self.languages[row]) } else if component == 1 { self.to = L10n(language: self.languages[row]) } self.tableView.reloadData() } }
7741449cc7f7a502b566709e980bc394
28.752577
122
0.661816
false
false
false
false
zhxnlai/ZLBalancedFlowLayout
refs/heads/master
ZLBalancedFlowLayoutDemo/ZLBalancedFlowLayoutDemo/ViewController.swift
mit
1
// // ViewController.swift // ZLBalancedFlowLayoutDemo // // Created by Zhixuan Lai on 12/23/14. // Copyright (c) 2014 Zhixuan Lai. All rights reserved. // import UIKit class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var numRepetitions: Int = 1 { didSet { collectionView?.reloadData() } } var numSections: Int = 10 { didSet { collectionView?.reloadData() } } var direction: UICollectionViewScrollDirection = .Vertical { didSet { needsResetLayout = true } } var rowHeight: CGFloat = 100 { didSet { needsResetLayout = true } } var enforcesRowHeight: Bool = false { didSet { needsResetLayout = true } } private var images = [UIImage](), needsResetLayout = false private let cellIdentifier = "cell", headerIdentifier = "header", footerIdentifier = "footer" override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) var paths = NSBundle.mainBundle().pathsForResourcesOfType("jpg", inDirectory: "") as! Array<String> for path in paths { if let image = UIImage(contentsOfFile: path) { images.append(image) } } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = "ZLBalancedFlowLayout" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self , action: Selector("refreshButtonAction:")) navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: Selector("settingsButtonAction:")) collectionView?.backgroundColor = UIColor.whiteColor() collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: cellIdentifier) collectionView?.registerClass(LabelCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier) collectionView?.registerClass(LabelCollectionReusableView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) resetLayoutIfNeeded(animated) } private func resetLayoutIfNeeded(animated: Bool) { if needsResetLayout { needsResetLayout = false var layout = ZLBalancedFlowLayout() layout.headerReferenceSize = CGSize(width: 100, height: 100) layout.footerReferenceSize = CGSize(width: 100, height: 100) layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) layout.scrollDirection = direction layout.rowHeight = rowHeight layout.enforcesRowHeight = enforcesRowHeight collectionView?.setCollectionViewLayout(layout, animated: true) } } // MARK: - Action func refreshButtonAction(sender:UIBarButtonItem) { self.collectionView?.reloadData() } func settingsButtonAction(sender:UIBarButtonItem) { SettingsViewController.presentInViewController(self) } // MARK: - UICollectionViewDataSource override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return numSections } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count*numRepetitions } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell var imageView = UIImageView(image: imageForIndexPath(indexPath)) imageView.contentMode = .ScaleAspectFill cell.backgroundView = imageView cell.clipsToBounds = true return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var view = LabelCollectionReusableView(frame: CGRectZero) switch (kind) { case UICollectionElementKindSectionHeader: view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, forIndexPath: indexPath) as! LabelCollectionReusableView view.textLabel.text = "Header" case UICollectionElementKindSectionFooter: view = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: footerIdentifier, forIndexPath: indexPath) as! LabelCollectionReusableView view.textLabel.text = "Footer" default: view.textLabel.text = "N/A" } return view } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var size = imageForIndexPath(indexPath).size var percentWidth = CGFloat(140 - arc4random_uniform(80))/100 return CGSize(width: size.width*percentWidth/4, height: size.height/4) } // MARK: - () func imageForIndexPath(indexPath:NSIndexPath) -> UIImage { return images[indexPath.item%images.count] } }
b6cbbcdd47d90f474f33530360ace3d3
39.026846
206
0.690141
false
false
false
false
zehrer/SOGraphDB
refs/heads/master
Sources/SOGraphDB_old/Model/Values/Node.swift
mit
1
// // Node.swift // SOGraphDB // // Created by Stephan Zehrer on 02.07.15. // Copyright © 2015 Stephan Zehrer. All rights reserved. // import Foundation extension Node : Identiy, PropertyAccess , RelationshipAccess {} // Equatable interface for Node public func ==(lhs: Node, rhs: Node) -> Bool { if (lhs.uid != nil && rhs.uid != nil) { if lhs.uid! == rhs.uid! { return true } } return false } public struct Node : ValueStoreElement , Context , Hashable { public weak var context : GraphContext! = nil public var uid: UID? = nil public var dirty = true public var nextPropertyID: UID = 0 public var nextOutRelationshipID: UID = 0 public var nextInRelationshipID: UID = 0 public static func generateSizeTestInstance() -> Node { var result = Node() result.nextPropertyID = Int.max result.nextOutRelationshipID = Int.max result.nextInRelationshipID = Int.max return result } public init() {} public init (uid aID : UID) { uid = aID } public init(coder decoder: Decode) { nextPropertyID = decoder.decode() nextOutRelationshipID = decoder.decode() nextInRelationshipID = decoder.decode() dirty = false } public func encodeWithCoder(_ encoder : Encode) { encoder.encode(nextPropertyID) encoder.encode(nextOutRelationshipID) encoder.encode(nextInRelationshipID) } // MARK: CRUD public mutating func delete() { context.delete(&self) } public mutating func update() { context.update(&self) } // MARK: Hashable public var hashValue: Int { get { if uid != nil { return uid!.hashValue } return 0 } } }
9dd251c4cbfb6bb44b3286d8fb4234c4
19.62766
64
0.566271
false
false
false
false
inamiy/ReactiveCocoaCatalog
refs/heads/master
ReactiveCocoaCatalog/Samples/MenuSettingsViewController.swift
mit
1
// // MenuSettingsViewController.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2016-04-09. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import UIKit import Result import ReactiveSwift import ReactiveObjC import ReactiveObjCBridge private let _cellIdentifier = "MenuSettingsCell" final class MenuSettingsViewController: UITableViewController, StoryboardSceneProvider { static let storyboardScene = StoryboardScene<MenuSettingsViewController>(name: "MenuBadge") weak var menu: SettingsMenu? override func viewDidLoad() { super.viewDidLoad() guard let menu = self.menu else { fatalError("Required properties are not set.") } let menusChanged = menu.menusProperty.signal.map { _ in () } let badgeChanged = BadgeManager.badges.mergedSignal.map { _ in () } // `reloadData()` when menus or badges changed. menusChanged .merge(with: badgeChanged) .observeValues { [weak self] _ in self?.tableView?.reloadData() } // Modal presentation & dismissal for serial execution. let modalAction = Action<MenuType, (), NoError> { [weak self] menu in return SignalProducer { observer, disposable in let modalVC = menu.viewController self?.present(modalVC, animated: true) { _ = QueueScheduler.main.schedule(after: 1) { self?.dismiss(animated: true) { observer.send(value: ()) observer.sendCompleted() } } } } } // `tableView.didSelectRow()` handling bridgedSignalProducer(from: self.rac_signal(for: Selector._didSelectRow.0, from: Selector._didSelectRow.1)) .on(event: logSink("didSelectRow")) .withLatest(from: self.menu!.menusProperty.producer) .map { racTuple, menus -> MenuType in let racTuple = racTuple as! RACTuple let indexPath = racTuple.second as! NSIndexPath let menu = menus[indexPath.row] return menu } .flatMap(.merge) { menu in return modalAction.apply(menu) .ignoreCastError(NoError.self) } .start() self.tableView.delegate = nil // set nil to clear selector cache self.tableView.delegate = self } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.menu!.menusProperty.value.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: _cellIdentifier, for: indexPath) let menu = self.menu!.menusProperty.value[indexPath.row] cell.textLabel?.text = "\(menu.menuId)" cell.detailTextLabel?.text = menu.badge.value.rawValue cell.imageView?.image = menu.tabImage.value return cell } } // MARK: Selectors extension Selector { // NOTE: needed to upcast to `Protocol` for some reason... fileprivate static let _didSelectRow: (Selector, Protocol) = ( #selector(UITableViewDelegate.tableView(_:didSelectRowAt:)), UITableViewDelegate.self ) }
ffd0b5e2e8b4d70eac4fc3c148c49421
32.307692
115
0.609411
false
false
false
false
amraboelela/SwiftLevelDB
refs/heads/master
Tests/SwiftLevelDBTests/DateTests.swift
mit
1
// // DateTests.swift // SwiftLevelDBAppTests // // Created by Amr Aboelela on 6/29/22. // import XCTest import Foundation import Dispatch @testable import SwiftLevelDB @available(iOS 13.0.0, *) class DateTests: TestsBase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testSecondsSince1970() { let now = Date.secondsSince1970 let now2 = Date.secondsSinceReferenceDate XCTAssertTrue(now - now2 > (1970 - 2001) * 360 * 24 * 60 * 60) } func testSecondsSinceReferenceDate() { let now = Date.secondsSince1970 let now2 = Date.secondsSinceReferenceDate XCTAssertTrue(now - now2 > (1970 - 2001) * 360 * 24 * 60 * 60) } func testDayOfWeek() { var date = Date(timeIntervalSince1970: 1658086329) // Sunday 7/17/22 var dayOfWeek = date.dayOfWeek XCTAssertEqual(dayOfWeek, 0) date = Date(timeIntervalSince1970: 1658345529) // Wednesday 7/20/22 dayOfWeek = date.dayOfWeek XCTAssertEqual(dayOfWeek, 3) } }
ac287c3be5e2c5bc3b4ae1ebfc4ee412
23.543478
76
0.620903
false
true
false
false
salemoh/GoldenQuraniOS
refs/heads/master
GRDB/QueryInterface/VirtualTableModule.swift
mit
2
/// The protocol for SQLite virtual table modules. It lets you define a DSL for /// the `Database.create(virtualTable:using:)` method: /// /// let module = ... /// try db.create(virtualTable: "items", using: module) { t in /// ... /// } /// /// GRDB ships with three concrete classes that implement this protocol: FTS3, /// FTS4 and FTS5. public protocol VirtualTableModule { /// The type of the closure argument in the /// `Database.create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "items", using: module) { t in /// // t is TableDefinition /// } associatedtype TableDefinition /// The name of the module. var moduleName: String { get } /// Returns a table definition that is passed as the closure argument in the /// `Database.create(virtualTable:using:)` method: /// /// try db.create(virtualTable: "items", using: module) { t in /// // t is the result of makeTableDefinition() /// } func makeTableDefinition() -> TableDefinition /// Returns the module arguments for the `CREATE VIRTUAL TABLE` query. func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String] /// Execute any relevant database statement after the virtual table has /// been created. func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws } extension Database { // MARK: - Database Schema: Virtual Table /// Creates a virtual database table. /// /// try db.create(virtualTable: "vocabulary", using: "spellfix1") /// /// See https://www.sqlite.org/lang_createtable.html /// /// - parameters: /// - name: The table name. /// - ifNotExists: If false, no error is thrown if table already exists. /// - module: The name of an SQLite virtual table module. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws { var chunks: [String] = [] chunks.append("CREATE VIRTUAL TABLE") if ifNotExists { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) chunks.append("USING") chunks.append(module) let sql = chunks.joined(separator: " ") try execute(sql) } /// Creates a virtual database table. /// /// let module = ... /// try db.create(virtualTable: "pointOfInterests", using: module) { t in /// ... /// } /// /// The type of the closure argument `t` depends on the type of the module /// argument: refer to this module's documentation. /// /// Use this method to create full-text tables using the FTS3, FTS4, or /// FTS5 modules: /// /// try db.create(virtualTable: "books", using: FTS4()) { t in /// t.column("title") /// t.column("author") /// t.column("body") /// } /// /// See https://www.sqlite.org/lang_createtable.html /// /// - parameters: /// - name: The table name. /// - ifNotExists: If false, no error is thrown if table already exists. /// - module: a VirtualTableModule /// - body: An optional closure that defines the virtual table. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create<Module: VirtualTableModule>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) -> Void)? = nil) throws { // Define virtual table let definition = module.makeTableDefinition() if let body = body { body(definition) } // Create virtual table var chunks: [String] = [] chunks.append("CREATE VIRTUAL TABLE") if ifNotExists { chunks.append("IF NOT EXISTS") } chunks.append(tableName.quotedDatabaseIdentifier) chunks.append("USING") let arguments = try module.moduleArguments(for: definition, in: self) if arguments.isEmpty { chunks.append(module.moduleName) } else { chunks.append(module.moduleName + "(" + arguments.joined(separator: ", ") + ")") } let sql = chunks.joined(separator: " ") try inSavepoint { try execute(sql) try module.database(self, didCreate: tableName, using: definition) return .commit } } }
d2e929e3873b18f30fec9e7b0e963d96
36.580645
191
0.594421
false
false
false
false
trillione/JNaturalKorean
refs/heads/master
Sampler/Sampler/ContentView.swift
mit
2
// // ContentView.swift // Sampler // // Created by won on 2020/11/13. // import SwiftUI import JNaturalKorean struct ContentView: View { var body: some View { ScrollView { Text(sampleText) .padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } let sampleText = """ 주격조사\n\n \("그 사람".이_가) 주인입니다. \("저 여자".이_가) 여친 입니다. \n목적격조사\n \("3개의 문장".을_를) 외워야 합니다. \("12개의 단어".을_를) 외워야 합니다. \n보조사\n \("그 사람".은_는) 프로그래머입니다. \("그 여자".은_는) 개발자. \n호격조사\n \("이 세상".아_야)! \("이 여자".아_야)!\n \("그날".으로_로)부터 \("100일".이_가) 지났습니다. \n==== String+JNaturalKorean ====\n 주격조사\n \("그 사람".이_가) 주인입니다. \("010-0000-7330".이_가) 전 여친 전화번호 입니다.. \("그 여자".이_가) 전 여친 입니다. \n목적격조사\n \("3개의 문장".을_를) 외워야 합니다. \("010-0000-7332".을_를) 해킹. \("12개의 단어".을_를) 외워야 합니다. \n보조사 \("그 사람".은_는) 프로그래머입니 \("그 여자".은_는) 이뻐 \("010-0000-7335".은_는) 내 전화번호 입니다.. \n호격조사\n \("이 세상".아_야)! \("이 세상".아_야)! \("010-0000-7336".아_야)!\n\n \("그 여자".와_과) 함께 \("그 사람".와_과) 함께 \("010-0000-7338".와_과) 내 번호는 비슷함. \("010-0000-7333".으로_로) 인증번호가 발송됩니다. \("오늘".으로_로) 부터 \("100일".이_가) 지났습니다. """
7d46716e90b309c5e4511c4a00fc9711
18.969231
46
0.48228
false
false
false
false
wuyezhiguhun/DDSwift
refs/heads/master
DDSwift/Main/RootViewController.swift
mit
1
// // RootViewController.swift // DDSwift // // Created by 王允顶 on 17/4/23. // Copyright © 2017年 王允顶. All rights reserved. // import UIKit class RootViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let leftImage = UIImage(named: "back")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: leftImage, style: UIBarButtonItemStyle.done, target: self, action:#selector(backTouch)) // Do any additional setup after loading the view. } func backTouch() -> Void { self.navigationController!.popViewController(animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var _titleString:String? var titleString:String { get{ if _titleString == nil { _titleString = String() } return _titleString! } set{ _titleString = newValue self.navigationItem.title = _titleString } } }
9f0fa866d0b483ee8e297a15c652e8d4
26.714286
158
0.633162
false
false
false
false
orta/PonyDebuggerApp
refs/heads/master
PonyDebugger/PonyDServer.swift
mit
1
import Cocoa class PonyDServer: NSObject { let task = NSTask() func startServer() { let outputPipe = NSPipe() task.launchPath = "/usr/local/bin/ponyd" let arguments = ["serve", "--listen-interface=127.0.0.1"] task.arguments = arguments task.launch() let notifications = NSNotificationCenter.defaultCenter() task.standardOutput = outputPipe; notifications.addObserver(self, selector: #selector(outputAvailable), name: NSFileHandleDataAvailableNotification, object: outputPipe.fileHandleForReading) outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotifyForModes([NSDefaultRunLoopMode, NSEventTrackingRunLoopMode]) let errorPipe = NSPipe() task.standardError = errorPipe; notifications.addObserver(self, selector: #selector(outputAvailable), name: NSFileHandleDataAvailableNotification, object: outputPipe.fileHandleForReading) errorPipe.fileHandleForReading.waitForDataInBackgroundAndNotifyForModes([NSDefaultRunLoopMode, NSEventTrackingRunLoopMode]) } func stop() { task.terminate() task.waitUntilExit() let killAll = NSTask() killAll.launchPath = "/usr/bin/killall" killAll.arguments = ["ponyd"] killAll.launch() killAll.waitUntilExit() } func outputAvailable(notification: NSNotification) { guard let fileHandle = notification.object as? NSFileHandle else { return } let data = fileHandle.availableData if data.length > 0 { let output = NSString(data: data, encoding: NSUTF8StringEncoding) print(output) } } }
a8d1b3b6e396cd5166644df6eb03735d
33.244898
163
0.688915
false
false
false
false
DaiYue/HAMLeetcodeSwiftSolutions
refs/heads/master
solutions/26_Remove_Duplicates_from_Sorted_Array.playground/Contents.swift
mit
1
// #26 Remove Duplicates from Sorted Array https://leetcode.com/problems/remove-duplicates-from-sorted-array/ // 很简单的数组处理。一个指针往后读,一个指针指向写入的位置,读到不重复的(跟前一位不一样的)就在写指针的位置写入,不然继续往后读即可。 // 从这道题我们也可以学到如何在 swift 的函数里传进一个可变的参数~ // 时间复杂度:O(n) 空间复杂度:O(1) class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { guard nums.count > 0 else { return 0 } var writeIndex = 1 for readIndex in 1 ..< nums.count { if nums[readIndex] != nums[readIndex - 1] { nums[writeIndex] = nums[readIndex] writeIndex += 1 } } return writeIndex } } var array = [1,2,2,2] Solution().removeDuplicates(&array)
86f693c582236b3bbd41732a6f4d6700
28.2
109
0.588477
false
false
false
false
n8armstrong/CalendarView
refs/heads/master
CalendarView/Carthage/Checkouts/SwiftMoment/SwiftMoment/SwiftMoment/Duration.swift
mit
1
// // Duration.swift // SwiftMoment // // Created by Adrian on 19/01/15. // Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved. // import Foundation public struct Duration: Equatable { let interval: TimeInterval public init(value: TimeInterval) { self.interval = value } public init(value: Int) { self.interval = TimeInterval(value) } public var years: Double { return interval / 31536000 // 365 days } public var quarters: Double { return interval / 7776000 // 3 months } public var months: Double { return interval / 2592000 // 30 days } public var days: Double { return interval / 86400 // 24 hours } public var hours: Double { return interval / 3600 // 60 minutes } public var minutes: Double { return interval / 60 } public var seconds: Double { return interval } public func ago() -> Moment { return moment().subtract(self) } public func add(_ duration: Duration) -> Duration { return Duration(value: self.interval + duration.interval) } public func subtract(_ duration: Duration) -> Duration { return Duration(value: self.interval - duration.interval) } public func isEqualTo(_ duration: Duration) -> Bool { return self.interval == duration.interval } } extension Duration: CustomStringConvertible { public var description: String { let formatter = DateComponentsFormatter() formatter.calendar = Calendar(identifier: Calendar.Identifier.gregorian) formatter.calendar?.timeZone = TimeZone(abbreviation: "UTC")! formatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second] let referenceDate = Date(timeIntervalSinceReferenceDate: 0) let intervalDate = Date(timeInterval: self.interval, since: referenceDate) return formatter.string(from: referenceDate, to: intervalDate)! } }
767fdf69bd577dab9432cc10d4efc600
24.794872
93
0.642644
false
false
false
false
abecker3/SeniorDesignGroup7
refs/heads/master
ProvidenceWayfinding/ProvidenceWayfinding/LocationTableViewController.swift
apache-2.0
1
// // LocationTableViewController.swift // Test2 // // Created by Bilsborough, Michael J on 11/19/15. // Copyright © 2015 Gonzaga University. All rights reserved. // import UIKit class LocationTableViewController: UITableViewController, UISearchResultsUpdating{ //Passed in variables var passInTextFieldTag: Int! var passInCategory: String! var allLocationsClicked: Bool = false //Referencing Outlets @IBOutlet var locationTableView: UITableView! @IBOutlet var controllerTitle: UINavigationItem! //Variables var resultSearchController = UISearchController() var filteredTableData = [String]() var locationOptions:[Directory] = [] var locationStringOptions = [String]() var allLocationsTag: Bool = false override func viewDidLoad() { super.viewDidLoad() //resultSearchController.active = false //Choose options based on passed in building initControllerTitle() initOptions() //definesPresentationContext = true self.resultSearchController = ({ let controller = UISearchController(searchResultsController: nil) controller.searchResultsUpdater = self controller.dimsBackgroundDuringPresentation = false controller.searchBar.sizeToFit() self.tableView.tableHeaderView = controller.searchBar return controller })() //Reload table self.tableView.reloadData() //extendedLayoutIncludesOpaqueBars = true; //keeps the search bar from disappearing on tap } override func viewDidAppear(animated: Bool) { if(resetToRootView == 1){ self.navigationController?.popToRootViewControllerAnimated(true) } } func updateSearchResultsForSearchController(searchController: UISearchController) { filteredTableData.removeAll(keepCapacity: false) let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!) var newArray = [String]() for x in locationOptions { newArray.append(x.name) } //var oldArray = uniqueCategoryArray let array = (newArray as NSArray).filteredArrayUsingPredicate(searchPredicate) filteredTableData = array as! [String] filteredTableData.sortInPlace() self.tableView.reloadData() } /* func uniqueCategoryArray(inputArray: [Location]!) -> [String]! { var newArray = [String]() for x in inputArray { if(newArray.contains(x.category)) { continue } else { newArray.append(x.category) } } return newArray }*/ //Populate Table override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //return locationOptions.count //Takes the filtered data and assigns them to the number of rows needed if(self.resultSearchController.active) { return self.filteredTableData.count } // No searching is going on so the table stays regular using the same number of rows as before else { return self.locationOptions.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("location cell", forIndexPath: indexPath) /*// Configure the cell... let option = locationOptions[indexPath.row] cell.textLabel!.text = option.name return cell*/ if(self.resultSearchController.active) { cell.textLabel?.text = filteredTableData[indexPath.row] //cell.detailTextLabel!.text = "11 AM to 8 PM" return cell } else { let option = locationStringOptions[indexPath.row] cell.textLabel?.text = option //cell.detailTextLabel!.text = "11 AM to 8 PM" return cell } } //This function checks whether the search bar cell that was clicked is part of Locations func checkArrayForMember(tableView: UITableView, indexPath: NSIndexPath) -> Bool { for x in directory { if(filteredTableData.count > indexPath.row) { if(x.name == filteredTableData[indexPath.row]) { return true } } } return false } func getLocationFromName(name: String) -> Directory { for x in directory{ if(x.name == name) { return x } } return Directory(name: "Admitting", category: "Main Tower", floor: "Main", hours: "NA", ext: "", notes: "") } //Pop back 2 once a row is selected override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let navController = self.navigationController! let indexOfLastViewController = navController.viewControllers.count - 1 let indexOfSurvey = indexOfLastViewController - 2 let surveyViewController = navController.viewControllers[indexOfSurvey] as! SurveyViewController if(passInTextFieldTag == surveyViewController.currentTextField.tag && resultSearchController.active && allLocationsTag) { surveyViewController.currentTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.startLocation = location print(location) print("Current: search is active") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag && resultSearchController.active && allLocationsTag) { surveyViewController.destinationTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.destinationTextField.placeholder!) surveyViewController.endLocation = location print(location) print("Destination: search is active") } /*else if(passInTextFieldTag == surveyViewController.currentTextField.tag ) { surveyViewController.currentTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.startLocation = location print("Current: regular cell selection") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag) { surveyViewController.destinationTextField.placeholder = filteredTableData[indexPath.row] let location = getLocationFromName(surveyViewController.currentTextField.placeholder!) surveyViewController.endLocation = location print("Destination: regular cell selection") }*/ else if(passInTextFieldTag == surveyViewController.currentTextField.tag /*&& !allLocationsTag*/) { surveyViewController.currentTextField.placeholder = locationStringOptions[indexPath.row] surveyViewController.startLocation = getLocationFromName(locationStringOptions[indexPath.row]) print(locationOptions[indexPath.row]) print("Current: regular cell selection") } else if(passInTextFieldTag == surveyViewController.destinationTextField.tag /*&& !allLocationsTag*/) { surveyViewController.destinationTextField.placeholder = locationStringOptions[indexPath.row] surveyViewController.endLocation = getLocationFromName(locationStringOptions[indexPath.row]) print(locationOptions[indexPath.row]) print("Destination: regular cell selection") } resultSearchController.active = false navController.popToViewController(surveyViewController, animated: true) } func initOptions() { for location in directory { if(location.category == passInCategory && !allLocationsClicked) { locationOptions.append(location) locationStringOptions.append(location.name) } else if(passInCategory == "All Locations") { allLocationsTag = true if(location.category != "All Locations") { locationOptions.append(location) locationStringOptions.append(location.name) } } } locationStringOptions.sortInPlace() } func initControllerTitle() { controllerTitle.title = passInCategory } }
bea037ab8e393de47135ee1ff0da10aa
35.242188
136
0.628584
false
false
false
false
SheffieldKevin/SwiftGraphics
refs/heads/develop
SwiftGraphics/Geometry/Arc.swift
bsd-2-clause
1
// // Arc.swift // SwiftGraphics // // Created by Jonathan Wight on 12/26/15. // Copyright © 2015 schwa.io. All rights reserved. // private let pi = CGFloat(M_PI) public struct Arc { public let center: CGPoint public let radius: CGFloat public let theta: CGFloat public let phi: CGFloat public init(center: CGPoint, radius: CGFloat, theta: CGFloat, phi: CGFloat) { self.center = center self.radius = radius self.theta = theta self.phi = phi } } // TODO: all geometry should be equatable/fuzzy equatable extension Arc: Equatable { } public func == (lhs: Arc, rhs: Arc) -> Bool { return lhs.center == rhs.center && lhs.radius == rhs.radius && lhs.theta == rhs.theta && lhs.phi == rhs.phi } extension Arc: FuzzyEquatable { } public func ==% (lhs: Arc, rhs: Arc) -> Bool { return lhs.center ==% rhs.center && lhs.radius ==% rhs.radius && lhs.theta ==% rhs.theta && lhs.phi ==% rhs.phi } public extension Arc { static func arcToBezierCurves(center: CGPoint, radius: CGFloat, alpha: CGFloat, beta: CGFloat, maximumArcs: Int = 4) -> [BezierCurve] { assert(maximumArcs >= 3) let limit = pi * 2 / CGFloat(maximumArcs) //If[Abs[\[Beta] - \[Alpha]] > limit, // Return[{ // BezierArcConstruction[{xc, yc}, // r, {\[Alpha], \[Alpha] + limit}], // BezierArcConstruction[{xc, yc}, // r, {\[Alpha] + limit, \[Beta]}] // }] // ]; if abs(beta - alpha) > (limit + CGFloat(FLT_EPSILON)) { return arcToBezierCurves(center, radius: radius, alpha: alpha, beta: alpha + limit, maximumArcs: maximumArcs) + arcToBezierCurves(center, radius: radius, alpha: alpha + limit, beta: beta, maximumArcs: maximumArcs) } //{x1, y1} = {xc, yc} + r*{Cos[\[Alpha]], Sin[\[Alpha]]}; let pt1 = center + radius * CGPoint(x: cos(alpha), y: sin(alpha)) //{x4, y4} = {xc, yc} + r*{Cos[\[Beta]], Sin[\[Beta]]}; let pt4 = center + radius * CGPoint(x: cos(beta), y: sin(beta)) // {ax, ay} = {x1, y1} - {xc, yc}; let (ax, ay) = (pt1 - center).toTuple() // {bx, by} = {x4, y4} - {xc, yc}; let (bx, by) = (pt4 - center).toTuple() // q1 = ax*ax + ay*ay; let q1 = ax * ax + ay * ay // q2 = q1 + ax*bx + ay*by; let q2 = q1 + ax * bx + ay * by // k2 = 4/3 (Sqrt[2*q1*q2] - q2)/(ax*by - ay*bx); var k2 = (sqrt(2 * q1 * q2) - q2) / (ax * by - ay * bx) k2 *= 4 / 3 //x2 = xc + ax - k2*ay; //y2 = yc + ay + k2*ax; let pt2 = center + CGPoint(x: ax - k2 * ay, y: ay + k2 * ax) //x3 = xc + bx + k2*by; //y3 = yc + by - k2*bx; let pt3 = center + CGPoint(x: bx + k2 * by, y: by - k2 * bx) let curve = BezierCurve(points: [pt1, pt2, pt3, pt4]) return [ curve ] } func toBezierCurves(maximumArcs: Int = 4) -> [BezierCurve] { return Arc.arcToBezierCurves(center, radius: radius, alpha: phi, beta: phi + theta, maximumArcs: maximumArcs) } }
94f75ef0598c1295b1b163ae4819c4bf
30.39604
139
0.526963
false
false
false
false
jestspoko/Reveal
refs/heads/master
Reveal/Classes/RevealLabel.swift
mit
1
// // RevealLabel.swift // MaskedLabel // // Created by Lukasz Czechowicz on 26.10.2016. // Copyright © 2016 Lukasz Czechowicz. All rights reserved. // import UIKit /// holds UILabel and creates animations public class RevealLabel:Equatable { /// label's reference private var label:UILabel /// animation speed private var speed:Double /// animation's delay private var delay:Double /// function describing a timing curve private var timingFunction:CAMediaTimingFunction /// animation's direction private var direction:Reveal.RevealDirection /// destination mask frame private var destinationRect:CGRect /// layer with B&W gradient used as mask var gradientLayer:CAGradientLayer /** Initializes new label holder - Parameters: - label: UILabel reference - speed: animation speed - delay: animation delay - timingFunction: function describing timing curve - direction: animation direction */ init(_ label:UILabel, speed:Double, delay:Double, timingFunction:CAMediaTimingFunction, direction:Reveal.RevealDirection) { self.label = label self.speed = speed self.delay = delay self.timingFunction = timingFunction self.direction = direction destinationRect = label.bounds gradientLayer = CAGradientLayer() // creates and tweaks destination frame and mask layer depends of animation direction switch direction { case .fromLeft: destinationRect.origin.x = destinationRect.origin.x - destinationRect.size.width - 20 gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) case .fromRight: destinationRect.origin.x = destinationRect.origin.x + destinationRect.size.width + 20 gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5) gradientLayer.frame = CGRect(x: destinationRect.origin.x-20, y: destinationRect.origin.y, width: destinationRect.size.width + 20, height: destinationRect.size.height) } gradientLayer.colors = [UIColor.black.cgColor,UIColor.clear.cgColor] gradientLayer.locations = [0.9, 1.0] label.layer.mask = gradientLayer } /// holds UILabel content public var text:String? { set { self.label.text = newValue } get { return self.label.text } } public static func ==(l: RevealLabel, r: RevealLabel) -> Bool { return l.label == r.label } /** Creates and perfomrs reveal animation on mask - Parameters: - complete: handler fires when animation in complete */ func reaval(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.fromValue = NSValue(cgRect: label.bounds) animation.toValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"reveal") CATransaction.commit() } /** Creates and perfomrs hide animation on mask - Parameters: - complete: handler fires when animation in complete */ func hide(complete:((_ revealLabel:RevealLabel)->())? = nil) { CATransaction.begin() CATransaction.setCompletionBlock { if let cpl = complete { cpl(self) } } let animation = CABasicAnimation(keyPath: "bounds") animation.duration = speed animation.toValue = NSValue(cgRect: label.bounds) animation.fromValue = NSValue(cgRect: destinationRect) animation.fillMode = "forwards" animation.beginTime = CACurrentMediaTime() + delay animation.isRemovedOnCompletion = false animation.timingFunction = timingFunction label.layer.add(animation, forKey:"hide") CATransaction.commit() } }
d15100d7e94587d18453a0f253ac9c37
31.383562
178
0.624577
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Pods/WCDB.swift/swift/source/core/codable/ColumnTypeDecoder.swift
mit
1
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 final class ColumnTypeDecoder: Decoder { private var results: [String: ColumnType] = [:] static func types(of type: TableDecodableBase.Type) -> [String: ColumnType] { let decoder = ColumnTypeDecoder() _ = try? type.init(from: decoder) return decoder.results } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey { return KeyedDecodingContainer(ColumnTypeDecodingContainer<Key>(with: self)) } private final class ColumnTypeDecodingContainer<CodingKeys: CodingKey>: KeyedDecodingContainerProtocol { typealias Key = CodingKeys private let decoder: ColumnTypeDecoder private struct SizedPointer { private let pointer: UnsafeMutableRawPointer private let size: Int init<T>(of type: T.Type = T.self) { size = MemoryLayout<T>.size pointer = UnsafeMutableRawPointer.allocate(byteCount: size, alignment: 1) memset(pointer, 0, size) } func deallocate() { pointer.deallocate() } func getPointee<T>(of type: T.Type = T.self) -> T { return pointer.assumingMemoryBound(to: type).pointee } } private var sizedPointers: ContiguousArray<SizedPointer> init(with decoder: ColumnTypeDecoder) { self.decoder = decoder self.sizedPointers = ContiguousArray<SizedPointer>() } deinit { for sizedPointer in sizedPointers { sizedPointer.deallocate() } } func contains(_ key: Key) -> Bool { return true } func decodeNil(forKey key: Key) throws -> Bool { decoder.results[key.stringValue] = Bool.columnType return false } func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.results[key.stringValue] = type.columnType return false } func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.results[key.stringValue] = type.columnType return 0 } func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.results[key.stringValue] = type.columnType return "" } func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable { // `type` must conform to ColumnDecodableBase protocol let columnDecodableType = type as! ColumnDecodable.Type decoder.results[key.stringValue] = columnDecodableType.columnType let sizedPointer = SizedPointer(of: T.self) sizedPointers.append(sizedPointer) return sizedPointer.getPointee() } var codingPath: [CodingKey] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } var allKeys: [Key] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func superDecoder() throws -> Decoder { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func superDecoder(forKey key: Key) throws -> Decoder { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } } var codingPath: [CodingKey] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } var userInfo: [CodingUserInfoKey: Any] { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } func singleValueContainer() throws -> SingleValueDecodingContainer { fatalError("It should not be called. If you think it's a bug, please report an issue to us.") } }
a54ac7afdc0d933bccf81ec2940ba51e
35.182266
108
0.606943
false
false
false
false
Reggian/IOS-Pods-DFU-Library
refs/heads/master
iOSDFULibrary/Classes/Implementation/LegacyDFU/Services/LegacyDFUService.swift
mit
1
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth internal typealias Callback = (Void) -> Void internal typealias ErrorCallback = (_ error:DFUError, _ withMessage:String) -> Void @objc internal class LegacyDFUService : NSObject, CBPeripheralDelegate { static internal let UUID = CBUUID.init(string: "00001530-1212-EFDE-1523-785FEABCD123") static func matches(_ service:CBService) -> Bool { return service.uuid.isEqual(UUID) } /// The target DFU Peripheral var targetPeripheral : LegacyDFUPeripheral? /// The logger helper. fileprivate var logger:LoggerHelper /// The service object from CoreBluetooth used to initialize the DFUService instance. fileprivate let service:CBService fileprivate var dfuPacketCharacteristic:DFUPacket? fileprivate var dfuControlPointCharacteristic:DFUControlPoint? fileprivate var dfuVersionCharacteristic:DFUVersion? /// The version read from the DFU Version charactertistic. Nil, if such does not exist. fileprivate(set) var version:(major:Int, minor:Int)? fileprivate var paused = false fileprivate var aborted = false /// A temporary callback used to report end of an operation. fileprivate var success:Callback? /// A temporary callback used to report an operation error. fileprivate var report:ErrorCallback? /// A temporaty callback used to report progress status. fileprivate var progressDelegate:DFUProgressDelegate? // -- Properties stored when upload started in order to resume it -- fileprivate var firmware:DFUFirmware? fileprivate var packetReceiptNotificationNumber:UInt16? // -- End -- // MARK: - Initialization init(_ service:CBService, _ logger:LoggerHelper) { self.service = service self.logger = logger super.init() } // MARK: - Service API methods /** Discovers characteristics in the DFU Service. This method also reads the DFU Version characteristic if such found. */ func discoverCharacteristics(onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { // Save callbacks self.success = success self.report = report // Get the peripheral object let peripheral = service.peripheral // Set the peripheral delegate to self peripheral.delegate = self // Discover DFU characteristics logger.v("Discovering characteristics in DFU Service...") logger.d("peripheral.discoverCharacteristics(nil, forService:DFUService)") peripheral.discoverCharacteristics(nil, for:service) } /** This method tries to estimate whether the DFU target device is in Application mode which supports the buttonless jump to the DFU Bootloader. - returns: true, if it is for sure in the Application more, false, if definitely is not, nil if uknown */ func isInApplicationMode() -> Bool? { // If DFU Version characteritsic returned a correct value... if let version = version { // The app with buttonless update always returns value 0x0100 (major: 0, minor: 1). Otherwise it's in DFU mode. // See the documentation for DFUServiceInitiator.forceDfu(:Bool) for details about supported versions. return version.major == 0 && version.minor == 1 } // The mbed implementation of DFU does not have DFU Packet characteristic in application mode if dfuPacketCharacteristic == nil { return true } // At last, count services. When only one service found - the DFU Service - we must be in the DFU mode already // (otherwise the device would be useless...) // Note: On iOS the Generic Access and Generic Attribute services (nor HID Service) // are not returned during service discovery. let services = service.peripheral.services! if services.count == 1 { return false } // If there are more services than just DFU Service, the state is uncertain return nil } /** Enables notifications for DFU Control Point characteristic. Result it reported using callbacks. - parameter success: method called when notifications were enabled without a problem - parameter report: method called when an error occurred */ func enableControlPoint(onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if !aborted { dfuControlPointCharacteristic!.enableNotifications(onSuccess: success, onError: report) } else { sendReset(onError: report) } } /** Triggers a switch to DFU Bootloader mode on the remote target by sending DFU Start command. - parameter report: method called when an error occurred */ func jumpToBootloaderMode(onError report:@escaping ErrorCallback) { if !aborted { dfuControlPointCharacteristic!.send(Request.jumpToBootloader, onSuccess: nil, onError: report) } else { sendReset(onError: report) } } /** This methods sends the Start DFU command with the firmware type to the DFU Control Point characterristic, followed by the sizes of each firware component <softdevice, bootloader, application> (each as UInt32, Little Endian). - parameter type: the type of the current firmware part - parameter size: the sizes of firmware components in the current part - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendDfuStartWithFirmwareType(_ type:UInt8, andSize size:DFUFirmwareSize, onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if aborted { sendReset(onError: report) return } // 1. Sends the Start DFU command with the firmware type to DFU Control Point characteristic // 2. Sends firmware sizes to DFU Packet characteristic // 3. Receives response notification and calls onSuccess or onError dfuControlPointCharacteristic!.send(Request.startDfu(type: type), onSuccess: success) { (error, aMessage) in if error == DFUError.remoteInvalidState { self.targetPeripheral?.resetInvalidState() self.sendReset(onError: report) return } report(error, aMessage) } dfuPacketCharacteristic!.sendFirmwareSize(size) } /** This methods sends the old Start DFU command (without the firmware type) to the DFU Control Point characterristic, followed by the application size <application> (UInt32, Little Endian). - parameter size: the sizes of firmware components in the current part - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendStartDfuWithFirmwareSize(_ size:DFUFirmwareSize, onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if aborted { sendReset(onError: report) return } // 1. Sends the Start DFU command with the firmware type to the DFU Control Point characteristic // 2. Sends firmware sizes to the DFU Packet characteristic // 3. Receives response notification and calls onSuccess or onError dfuControlPointCharacteristic!.send(Request.startDfu_v1, onSuccess: success, onError: report) dfuPacketCharacteristic!.sendFirmwareSize_v1(size) } /** This method sends the Init Packet with additional firmware metadata to the target DFU device. The Init Packet is required since Bootloader v0.5 (SDK 7.0.0), when it has been extended with firmware verification data, like IDs of supported softdevices, device type and revision, or application version. The extended Init Packet may also contain a hash of the firmware (since DFU from SDK 9.0.0). Before Init Packet became required it could have contained only 2-byte CRC of the firmware. - parameter data: the Init Packet data - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendInitPacket(_ data:Data, onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if aborted { sendReset(onError: report) return } // The procedure of sending the Init Packet has changed the same time the DFU Version characterstic was introduced. // Before it was not required, and could contain only CRC of the firmware (2 bytes). // Since DFU Bootloader version 0.5 (SDK 7.0.0) it is required and has been extended. Must be at least 14 bytes: // Device Type (2), Device Revision (2), Application Version (4), SD array length (2), at least one SD or 0xFEFF (2), CRC or hash (2+) // For more details, see: // http://infocenter.nordicsemi.com/topic/com.nordic.infocenter.sdk5.v11.0.0/bledfu_example_init.html?cp=4_0_0_4_2_1_1_3 // (or another version of this page, matching your DFU version) if version != nil { if data.count < 14 { // Init packet validation would have failed. We can safely abort here. report(DFUError.extendedInitPacketRequired, "Extended init packet required. Old one found instead.") return } // Since DFU v0.5, the Extended Init Packet may contain more than 20 bytes. // Therefore, there are 2 commands to the DFU Control Point required: one before we start sending init packet, // and another one the whole init packet is sent. After sending the second packet a notification will be received dfuControlPointCharacteristic!.send(Request.initDfuParameters(req: InitDfuParametersRequest.receiveInitPacket), onSuccess: nil, onError: report) dfuPacketCharacteristic!.sendInitPacket(data) dfuControlPointCharacteristic!.send(Request.initDfuParameters(req: InitDfuParametersRequest.initPacketComplete), onSuccess: success, onError: { error, message in if error == DFUError.remoteOperationFailed { // Init packet validation failed. The device type, revision, app version or Softdevice version // does not match values specified in the Init packet. report(error, "Operation failed. Ensure the firmware targets that device type and version.") } else { report(error, message) } }) } else { // Before that, the Init Packet could have contained only the 2-bytes CRC and was transfered in a single packet. // There was a single command sent to the DFU Control Point (Op Code = 2), followed by the Init Packet transfer // to the DFU Packet characteristic. After receiving this packet the DFU target was sending a notification with status. if data.count == 2 { dfuControlPointCharacteristic!.send(Request.initDfuParameters_v1, onSuccess: success, onError: report) dfuPacketCharacteristic!.sendInitPacket(data) } else { // After sending the Extended Init Packet, the DFU would fail on CRC validation eventually. // NOTE! // We can do 2 thing: abort, with an error: report(DFUError.initPacketRequired, "Init packet with 2-byte CRC supported. Extended init packet found.") // ..or ignore it and do not send any init packet (not safe!): // success() } } } /** Sends Packet Receipt Notification Request command with given value. The DFU target will send Packet Receipt Notifications every time it receives given number of packets to synchronize the iDevice with the bootloader. The higher number is set, the faster the transmission may be, but too high values may also cause a buffer overflow error (the app may write packets to the outgoing queue then much faster then they are actually delivered). The Packet Receipt Notification procedure has been introduced to empty the outgoing buffer. Setting number to 0 will disable PRNs. - parameter number: number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification. - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendPacketReceiptNotificationRequest(_ number:UInt16, onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if !aborted { dfuControlPointCharacteristic!.send(Request.packetReceiptNotificationRequest(number: number), onSuccess: success, onError: report) } else { sendReset(onError: report) } } /** Sends the firmware data to the DFU target device. - parameter firmware: the firmware to be sent - parameter number: number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification - parameter progressDelegate: a progress delagate that will be informed about transfer progress - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendFirmware(_ firmware:DFUFirmware, withPacketReceiptNotificationNumber number:UInt16, onProgress progressDelegate:DFUProgressDelegate?, onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if aborted { sendReset(onError: report) return } // Store parameters in case the upload was paused and resumed self.firmware = firmware self.packetReceiptNotificationNumber = number self.progressDelegate = progressDelegate self.report = report // 1. Sends the Receive Firmware Image command to the DFU Control Point characteristic // 2. Sends firmware to the DFU Packet characteristic. If number > 0 it will receive Packet Receit Notifications // every number packets. // 3. Receives response notification and calls onSuccess or onError dfuControlPointCharacteristic!.send(Request.receiveFirmwareImage, onSuccess: { // Register callbacks for Packet Receipt Notifications/Responses self.dfuControlPointCharacteristic!.waitUntilUploadComplete( onSuccess: { // Upload is completed, release the temporary parameters self.firmware = nil self.packetReceiptNotificationNumber = nil self.progressDelegate = nil self.report = nil success() }, onPacketReceiptNofitication: { bytesReceived in // Each time a PRN is received, send next bunch of packets if !self.paused && !self.aborted { let bytesSent = self.dfuPacketCharacteristic!.bytesSent if bytesSent == bytesReceived { self.dfuPacketCharacteristic!.sendNext(number, packetsOf: firmware, andReportProgressTo: progressDelegate) } else { // Target device deported invalid number of bytes received report(DFUError.bytesLost, "\(bytesSent) bytes were sent while \(bytesReceived) bytes were reported as received") } } else if self.aborted { // Upload has been aborted. Reset the target device. It will disconnect automatically self.sendReset(onError: report) } }, onError: { error, message in // Upload failed, release the temporary parameters self.firmware = nil self.packetReceiptNotificationNumber = nil self.progressDelegate = nil self.report = nil report(error, message) } ) // ...and start sending firmware if !self.paused && !self.aborted { self.dfuPacketCharacteristic!.sendNext(number, packetsOf: firmware, andReportProgressTo: progressDelegate) } else if self.aborted { // Upload has been aborted. Reset the target device. It will disconnect automatically self.sendReset(onError: report) } }, onError: report) } func pause() -> Bool { if !aborted { paused = true } return paused } func resume() -> Bool { if !aborted && paused && firmware != nil { paused = false // onSuccess and onError callbacks are still kept by dfuControlPointCharacteristic dfuPacketCharacteristic!.sendNext(packetReceiptNotificationNumber!, packetsOf: firmware!, andReportProgressTo: progressDelegate) return paused } paused = false return paused } func abort() -> Bool { aborted = true // When upload has been started and paused, we have to send the Reset command here as the device will // not get a Packet Receipt Notification. If it hasn't been paused, the Reset command will be sent after receiving it, on line 270. if paused && firmware != nil { // Upload has been aborted. Reset the target device. It will disconnect automatically sendReset(onError: report!) } paused = false return aborted } /** Sends the Validate Firmware request to DFU Control Point characteristic. - parameter success: a callback called when a response with status Success is received - parameter report: a callback called when a response with an error status is received */ func sendValidateFirmwareRequest(onSuccess success: @escaping Callback, onError report:@escaping ErrorCallback) { if !aborted { dfuControlPointCharacteristic!.send(Request.validateFirmware, onSuccess: success, onError: report) } else { sendReset(onError: report) } } /** Sends a command that will activate the new firmware and reset the DFU target device. Soon after calling this method the device should disconnect. - parameter report: a callback called when writing characteristic failed */ func sendActivateAndResetRequest(onError report:@escaping ErrorCallback) { if !aborted { dfuControlPointCharacteristic!.send(Request.activateAndReset, onSuccess: nil, onError: report) } else { sendReset(onError: report) } } // MARK: - Private service API methods /** Reads the DFU Version characteristic value. The characteristic must not be nil. - parameter success: the callback called when supported version number has been received - parameter report: the error callback which is called in case of an error, or when obtained data are not supported */ fileprivate func readDfuVersion(onSuccess success:@escaping Callback, onError report:@escaping ErrorCallback) { dfuVersionCharacteristic!.readVersion( onSuccess: { major, minor in self.version = (major, minor) success() }, onError:report ) } /** Sends a Reset command to the target DFU device. The device will disconnect automatically and restore the previous application (if DFU dual bank was used and application wasn't removed to make space for a new softdevice) or bootloader. - parameter report: a callback called when writing characteristic failed */ fileprivate func sendReset(onError report:@escaping ErrorCallback) { dfuControlPointCharacteristic!.send(Request.reset, onSuccess: nil, onError: report) } // MARK: - Peripheral Delegate callbacks func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { // Create local references to callback to release the global ones let _success = self.success let _report = self.report self.success = nil self.report = nil if error != nil { logger.e("Characteristics discovery failed") logger.e(error!) _report?(DFUError.serviceDiscoveryFailed, "Characteristics discovery failed") } else { logger.i("DFU characteristics discovered") // Find DFU characteristics for characteristic in service.characteristics! { if (DFUPacket.matches(characteristic)) { dfuPacketCharacteristic = DFUPacket(characteristic, logger) } else if (DFUControlPoint.matches(characteristic)) { dfuControlPointCharacteristic = DFUControlPoint(characteristic, logger) } else if (DFUVersion.matches(characteristic)) { dfuVersionCharacteristic = DFUVersion(characteristic, logger) } } // Some validation if dfuControlPointCharacteristic == nil { logger.e("DFU Control Point characteristics not found") // DFU Control Point characteristic is required _report?(DFUError.deviceNotSupported, "DFU Control Point characteristic not found") return } if !dfuControlPointCharacteristic!.valid { logger.e("DFU Control Point characteristics must have Write and Notify properties") // DFU Control Point characteristic must have Write and Notify properties _report?(DFUError.deviceNotSupported, "DFU Control Point characteristic does not have the Write and Notify properties") return } // Note: DFU Packet characteristic is not required in the App mode. // The mbed implementation of DFU Service doesn't have such. // Read DFU Version characteristic if such exists if self.dfuVersionCharacteristic != nil { if dfuVersionCharacteristic!.valid { readDfuVersion(onSuccess: _success!, onError: _report!) } else { version = nil _report?(DFUError.readingVersionFailed, "DFU Version found, but does not have the Read property") } } else { // Else... proceed version = nil _success?() } } } }
1fbbdaea81ff0131e07820de775426d0
49.353516
162
0.640627
false
false
false
false
bilogub/Chirrup
refs/heads/master
ChirrupTests/ChirrupSpec.swift
mit
1
// // ChirrupSpec.swift // Chirrup // // Created by Yuriy Bilogub on 2016-01-25. // Copyright © 2016 Yuriy Bilogub. All rights reserved. // import Quick import Nimble import Chirrup class ChirrupSpec: QuickSpec { override func spec() { let chirrup = Chirrup() var fieldName = "" describe("Single validation rule") { describe(".isTrue") { beforeEach { fieldName = "Activate" } context("When `Activate` is switched Off") { it("should return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue)) expect(error!.errorMessageFor(fieldName)) .to(equal("Activate should be true")) } context("When rule evaluation is skipped") { it("should not return an error") { let error = chirrup.validate(fieldName, value: false, with: ValidationRule(.IsTrue, on: { false })) expect(error).to(beNil()) } } } context("When `Activate` is switched On") { it("should not return an error") { let error = chirrup.validate(fieldName, value: true, with: ValidationRule(.IsTrue)) expect(error).to(beNil()) } } } describe(".NonEmpty") { beforeEach { fieldName = "Greeting" } context("When `Greeting` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.NonEmpty)) expect(error!.errorMessageFor(fieldName)) .to(equal("Greeting should not be empty")) } } context("When `Greeting` is set to value") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "hey there!", with: ValidationRule(.NonEmpty)) expect(error).to(beNil()) } } } describe(".Greater") { beforeEach { fieldName = "Min. Price" } context("When `Min. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error because validation is skipped") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: "5499.98"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } } context("When `Min. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "two hundred", with: ValidationRule(.Greater(than: "5499.98"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be a number")) } } context("When `Min. Price` is set to a equal value") { it("should return an error") { let val = "5499.98" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Greater(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Min. Price should be greater than \(val)")) } } context("When `Min. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "5499.99", with: ValidationRule(.Greater(than: "5499.98"))) expect(error).to(beNil()) } } } } describe(".Lower") { beforeEach { fieldName = "Max. Price" } context("When `Max. Price` is empty") { context("When rule evaluation is skipped") { it("should not return an error") { let val = "" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: "10000.00"), on: { !val.isEmpty })) expect(error).to(beNil()) } } context("When rule evaluation is not skipped") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } } context("When `Max. Price` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "ten thousand", with: ValidationRule(.Lower(than: "10000.00"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be a number")) } } context("When `Max. Price` is set to a equal value") { it("should return an error") { let val = "10000.00" let error = chirrup.validate(fieldName, value: val, with: ValidationRule(.Lower(than: val))) expect(error!.errorMessageFor(fieldName)) .to(equal("Max. Price should be lower than \(val)")) } } context("When `Max. Price` is set to a greater value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "9999.99", with: ValidationRule(.Lower(than: "10000.00"))) expect(error).to(beNil()) } } } describe(".Between") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a lower value than possible") { it("should return an error") { let error = chirrup.validate(fieldName, value: "0", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be between 4 and 6")) } it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.Between(from: "4", to: "6"))) expect(error).to(beNil()) } } } describe(".IsNumeric") { beforeEach { fieldName = "Gear Number" } context("When `Gear Number` is set to a NaN value") { it("should return an error") { let error = chirrup.validate(fieldName, value: "five", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName)) .to(equal("Gear Number should be a number")) } } context("When `Gear Number` is empty") { it("should return an error") { let error = chirrup.validate(fieldName, value: "", with: ValidationRule(.IsNumeric)) expect(error!.errorMessageFor(fieldName, should: "be a positive number")) .to(equal("Gear Number should be a positive number")) } } context("When `Gear Number` is a number") { it("should not return an error") { let error = chirrup.validate(fieldName, value: "5", with: ValidationRule(.IsNumeric)) expect(error).to(beNil()) } } } describe("Multiple validation rules") { describe(".Contains .NonBlank") { beforeEach { fieldName = "Greeting" } it("should return .Contains and .NonEmpty errors") { let errors = chirrup.validate(fieldName, value: "", with: [ValidationRule(.NonEmpty, message: "Couple greeting words here?"), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Couple greeting words here?\nGreeting should contain `hey there!`")) } context("When we have a greeting but not the one we expect") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"))]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } context("When rule evaluation is skipped") { it("should return empty error array") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 < 0 })]) expect(errors).to(beEmpty()) } } context("When rule evaluation is not skipped") { it("should return .Contains error only") { let errors = chirrup.validate(fieldName, value: "hey!", with: [ValidationRule(.NonEmpty), ValidationRule(.Contains(value: "hey there!"), on: { 1 > 0 })]) expect(chirrup.formatMessagesFor(fieldName, from: errors)) .to(equal("Greeting should contain `hey there!`")) } } } } } } }
3c16ffcdca38e40f4db4ae04ad4d64bd
31.928339
91
0.510586
false
false
false
false
Smartvoxx/ios
refs/heads/master
Step07/End/SmartvoxxOnWrist Extension/DataController.swift
gpl-2.0
2
// // DataController.swift // Smartvoxx // // Created by Sebastien Arbogast on 26/10/2015. // Copyright © 2015 Epseelon. All rights reserved. // import UIKit class DataController: NSObject { static let flatUiColors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f39c120", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"] static var sharedInstance = DataController() private var session:NSURLSession private var cache:DevoxxCache private var schedulesTask:NSURLSessionDataTask? private var slotsTasks = [String:NSURLSessionDataTask]() private var speakerTasks = [String:NSURLSessionDataTask]() private var avatarTasks = [String:NSURLSessionDataTask]() private override init() { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.requestCachePolicy = .ReloadIgnoringLocalCacheData session = NSURLSession(configuration: configuration) cache = DevoxxCache() } private func cancelTask(task: NSURLSessionDataTask?) { if let task = task { if task.state == NSURLSessionTaskState.Running { task.cancel() } } } func getSchedules(callback:([Schedule] -> Void)) { let schedules = cache.getSchedules() if schedules.count > 0 { dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(schedules) }) } let url = (NSURL(string: "http://cfp.devoxx.be/api/conferences/DV15/schedules/"))! self.schedulesTask = self.session.dataTaskWithURL(url) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in guard let data = data else { print(error) return } self.cache.saveSchedulesFromData(data) dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(self.cache.getSchedules()) }) } self.schedulesTask?.resume() } func cancelSchedules() { cancelTask(self.schedulesTask) } func getSlotsForSchedule(schedule:Schedule, callback:([Slot] -> Void)) { let slots = cache.getSlotsForScheduleWithHref(schedule.href!) if slots.count > 0 { dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(slots) }) } let url = NSURL(string: schedule.href!)! let task = self.session.dataTaskWithURL(url) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in guard let data = data else { print(error) return } self.cache.saveSlotsFromData(data, forScheduleWithHref:schedule.href!) dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(self.cache.getSlotsForScheduleWithHref(schedule.href!)) }) } self.slotsTasks[schedule.href!] = task task.resume() } func cancelSlotsForSchedule(schedule:Schedule) { if let href = schedule.href, task = self.slotsTasks[href] { self.cancelTask(task) } } func swapFavoriteStatusForTalkSlot(talkSlot:TalkSlot, callback:(TalkSlot -> Void)){ cache.swapFavoriteStatusForTalkSlotWithTalkId(talkSlot.talkId!) dispatch_async(dispatch_get_main_queue()) { () -> Void in if let talkSlot = self.cache.getTalkSlotWithTalkId(talkSlot.talkId!) { dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(talkSlot) }) } } } func getSpeaker(speaker:Speaker, callback:(Speaker -> Void)){ if let speaker = cache.getSpeakerWithHref(speaker.href!), _ = speaker.firstName { dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(speaker) }) } let url = NSURL(string: speaker.href!)! let task = self.session.dataTaskWithURL(url, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in guard let data = data else { print(error) return } self.cache.saveSpeakerFromData(data, forSpeakerWithHref:speaker.href!) dispatch_async(dispatch_get_main_queue(), { () -> Void in if let speaker = self.cache.getSpeakerWithHref(speaker.href!) { callback(speaker) } }) }) self.speakerTasks[speaker.href!] = task task.resume() } func cancelSpeaker(speaker:Speaker){ if let task = self.speakerTasks[speaker.href!] { self.cancelTask(task) } } func getAvatarForSpeaker(speaker:Speaker, callback:(NSData -> Void)) { if let speaker = cache.getSpeakerWithHref(speaker.href!), avatar = speaker.avatar where avatar.length > 0 { dispatch_async(dispatch_get_main_queue(), { () -> Void in callback(avatar) }) } let url = NSURL(string: speaker.avatarURL!)! let task = self.session.dataTaskWithURL(url, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in guard let data = data where data.length > 0 else { print(error) return } self.cache.saveAvatarFromData(data, forSpeakerWithHref:speaker.href!) dispatch_async(dispatch_get_main_queue(), { () -> Void in if let avatarData = self.cache.getAvatarForSpeakerWithHref(speaker.href!) { callback(avatarData) } }) }) self.avatarTasks[speaker.avatarURL!] = task task.resume() } func cancelAvatarForSpeaker(speaker:Speaker){ if let task = self.avatarTasks[speaker.href!] { self.cancelTask(task) } } func getFavoriteTalksAfterDate(date: NSDate) -> [TalkSlot] { return cache.getFavoriteTalksAfterDate(date) } func getFavoriteTalksBeforeDate(date: NSDate) -> [TalkSlot] { return cache.getFavoriteTalksBeforeDate(date) } func getFirstTalk() -> TalkSlot? { return cache.getFirstTalk() } func getLastTalk() -> TalkSlot? { return cache.getLastTalk() } }
83de8264a0b9e79f5edf42275fe59a70
35.151351
251
0.576106
false
false
false
false
ObjSer/objser-swift
refs/heads/master
ObjSer/util/IntegralType.swift
mit
1
// // IntegralType.swift // ObjSer // // The MIT License (MIT) // // Copyright (c) 2015 Greg Omelaenko // // 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. // public protocol IntegralType : NumericType, IntegerType { init<T : IntegralType>(_ v: T) init(_ v: Int8) init(_ v: UInt8) init(_ v: Int16) init(_ v: UInt16) init(_ v: Int32) init(_ v: UInt32) init(_ v: Int64) init(_ v: UInt64) init(_ v: Int) init(_ v: UInt) static var min: Self { get } static var max: Self { get } } extension IntegralType { public init<T : IntegralType>(_ v: T) { switch v { case let v as Int8: self = Self(v) case let v as UInt8: self = Self(v) case let v as Int16: self = Self(v) case let v as UInt16: self = Self(v) case let v as Int32: self = Self(v) case let v as UInt32: self = Self(v) case let v as Int64: self = Self(v) case let v as UInt64: self = Self(v) case let v as Int: self = Self(v) case let v as UInt: self = Self(v) default: preconditionFailure("Unrecognised IntegralType type \(T.self).") } } } extension Int8 : IntegralType { } extension UInt8 : IntegralType { } extension Int16 : IntegralType { } extension UInt16 : IntegralType { } extension Int32 : IntegralType { } extension UInt32 : IntegralType { } extension Int64 : IntegralType { } extension UInt64 : IntegralType { } extension Int : IntegralType { } extension UInt : IntegralType { } /// A type-erased integer. public struct AnyInteger { private let negative: Bool private let value: UInt64 public init<T : IntegralType>(_ v: T) { if v < 0 { negative = true value = UInt64(-Int64(v)) } else { negative = false value = UInt64(v) } } } extension IntegralType { /// Initialise from `v`, trapping on overflow. public init(_ v: AnyInteger) { self = v.negative ? Self(-Int64(v.value)) : Self(v.value) } } extension IntegralType { /// Attempt to convert initialise from `v`, performing bounds checking and failing if this is not possible. public init?(convert v: AnyInteger) { if v.negative { if Int64(Self.min) <= -Int64(v.value) { self.init(-Int64(v.value)) } else { return nil } } else { if UInt64(Self.max) >= v.value { self.init(v.value) } else { return nil } } } } extension AnyInteger : IntegerLiteralConvertible { public init(integerLiteral value: Int64) { self.init(value) } } extension AnyInteger : Hashable { public var hashValue: Int { return value.hashValue } } public func ==(a: AnyInteger, b: AnyInteger) -> Bool { return (a.negative == b.negative && a.value == b.value) || (a.value == 0 && b.value == 0) } public func <(a: AnyInteger, b: AnyInteger) -> Bool { return (a.negative == b.negative && (a.value < b.value) != a.negative) || (a.negative && !b.negative) } extension AnyInteger : Equatable, Comparable { }
838e97c1bb8160edfaeee1eedec3b04a
27.541096
111
0.62971
false
false
false
false
Joywii/ImageView
refs/heads/master
Swift/ImageView/ImageViewer/KZImageViewer.swift
mit
2
// // KZImageViewer.swift // ImageViewDemo // // Created by joywii on 15/4/30. // Copyright (c) 2015年 joywii. All rights reserved. // import UIKit let kPadding = 10 class KZImageViewer: UIView , UIScrollViewDelegate ,KZImageScrollViewDelegate{ private var scrollView : UIScrollView? private var selectIndex : NSInteger? private var scrollImageViewArray : NSMutableArray? private var selectImageView : UIImageView? override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { self.backgroundColor = UIColor.blackColor() self.scrollImageViewArray = NSMutableArray() self.scrollView = UIScrollView(frame: self.frameForPagingScrollView()) self.scrollView?.pagingEnabled = true self.scrollView?.showsHorizontalScrollIndicator = false self.scrollView?.showsVerticalScrollIndicator = false self.scrollView?.backgroundColor = UIColor.clearColor() self.scrollView?.delegate = self self.addSubview(self.scrollView!) } func showImages(imageArray:NSArray,index:NSInteger) { self.alpha = 0.0 var window : UIWindow = UIApplication.sharedApplication().keyWindow! window.addSubview(self) let currentPage = index self.selectIndex = index var kzSelectImage : KZImage = imageArray.objectAtIndex(Int(index)) as! KZImage var selectImage : UIImage? = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(kzSelectImage.imageUrl?.absoluteString) if(selectImage == nil) { selectImage = kzSelectImage.thumbnailImage } var selectImageView : UIImageView = kzSelectImage.srcImageView! self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height) self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0) //动画 var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview) var imageView = UIImageView(frame: selectImageViewFrame) imageView.contentMode = selectImageView.contentMode imageView.clipsToBounds = true imageView.image = selectImage imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 1.0 imageView.transform = CGAffineTransformIdentity var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size var ratio = min(fullWidth / size!.width,fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio * size!.width var h = ratio > 1 ? size!.height : ratio * size!.height imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) }) { (finished) -> Void in for(var i = 0 ; i < imageArray.count ; i++) { var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i))) zoomImageView.kzImage = kzImage zoomImageView.imageDelegate = self zoomImageView.userInteractionEnabled = true if(i == Int(currentPage)){ if(kzImage.image == nil) { zoomImageView.startLoadImage() } } self.scrollView?.addSubview(zoomImageView) self.scrollImageViewArray?.addObject(zoomImageView) } self.preLoadImage(currentPage) imageView.removeFromSuperview() } } func showImages(imageArray:NSArray,selectImageView:UIImageView,index:NSInteger) { self.alpha = 0.0 var window : UIWindow = UIApplication.sharedApplication().keyWindow! window.addSubview(self) let currentPage = index self.selectIndex = index self.selectImageView = selectImageView self.scrollView?.contentSize = CGSizeMake(self.scrollView!.bounds.size.width * CGFloat(imageArray.count), self.scrollView!.bounds.size.height) self.scrollView?.contentOffset = CGPointMake(CGFloat(currentPage) * self.scrollView!.bounds.size.width,0) //动画 var selectImageViewFrame = window.convertRect(selectImageView.frame, fromView: selectImageView.superview) var imageView = UIImageView(frame: selectImageViewFrame) imageView.contentMode = selectImageView.contentMode imageView.clipsToBounds = true imageView.image = selectImageView.image imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 1.0 imageView.transform = CGAffineTransformIdentity var size = imageView.image != nil ? imageView.image?.size : imageView.frame.size var ratio = min(fullWidth / size!.width,fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio * size!.width var h = ratio > 1 ? size!.height : ratio * size!.height imageView.frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) }) { (finished) -> Void in for(var i = 0 ; i < imageArray.count ; i++) { var kzImage:KZImage = imageArray.objectAtIndex(i) as! KZImage var zoomImageView = KZImageScrollView(frame: self.frameForPageAtIndex(UInt(i))) zoomImageView.kzImage = kzImage zoomImageView.imageDelegate = self zoomImageView.userInteractionEnabled = true if(i == Int(currentPage)){ if(kzImage.image == nil) { zoomImageView.startLoadImage() } } self.scrollView?.addSubview(zoomImageView) self.scrollImageViewArray?.addObject(zoomImageView) } self.preLoadImage(currentPage) imageView.removeFromSuperview() } } private func tappedScrollView(tap:UITapGestureRecognizer) { self.hide() } private func hide() { for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] { imageView.cancelLoadImage() imageView.removeFromSuperview() } var window : UIWindow = UIApplication.sharedApplication().keyWindow! let fullWidth = window.frame.size.width let fullHeight = window.frame.size.height var index = self.pageIndex() var zoomImageView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView var size = zoomImageView.kzImage?.image != nil ? zoomImageView.kzImage?.image?.size : zoomImageView.frame.size var ratio = min(fullWidth / size!.width, fullHeight / size!.height) var w = ratio > 1 ? size!.width : ratio*size!.width var h = ratio > 1 ? size!.height : ratio*size!.height var frame = CGRectMake((fullWidth - w) / 2, (fullHeight - h) / 2, w, h) var imageView = UIImageView(frame: frame) imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true imageView.image = zoomImageView.kzImage!.image imageView.backgroundColor = UIColor.clearColor() imageView.userInteractionEnabled = true window.addSubview(imageView) var selectImageViewFrame = window.convertRect(zoomImageView.kzImage!.srcImageView!.frame, fromView: zoomImageView.kzImage!.srcImageView!.superview) UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 0.0 imageView.frame = selectImageViewFrame }) { (finished) -> Void in for imageView in self.scrollImageViewArray as NSArray? as! [KZImageScrollView] { SDImageCache.sharedImageCache().removeImageForKey(imageView.kzImage?.imageUrl?.absoluteString, fromDisk: false) } imageView.removeFromSuperview() self.removeFromSuperview() } } private func pageIndex() -> NSInteger{ return NSInteger(self.scrollView!.contentOffset.x / self.scrollView!.frame.size.width) } private func frameForPagingScrollView() -> CGRect { var frame = self.bounds frame.origin.x -= CGFloat(kPadding) frame.size.width += 2 * CGFloat(kPadding) return CGRectIntegral(frame) } private func frameForPageAtIndex(index:UInt) -> CGRect { var bounds = self.scrollView?.bounds var pageFrame = bounds pageFrame?.size.width -= (2*CGFloat(kPadding)) pageFrame?.origin.x = (bounds!.size.width * CGFloat(index)) + CGFloat(kPadding) return CGRectIntegral(pageFrame!) } func imageScrollViewSingleTap(imageScrollView: KZImageScrollView) { self.hide() } func preLoadImage(currentIndex:NSInteger) { var preIndex = currentIndex - 1 if(preIndex > 1) { var preZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(preIndex)) as! KZImageScrollView preZoomImageView.startLoadImage() } var nextIndex = currentIndex + 1 if(nextIndex < self.scrollImageViewArray?.count) { var nextZoomImageView: KZImageScrollView = self.scrollImageViewArray!.objectAtIndex(Int(nextIndex)) as! KZImageScrollView nextZoomImageView.startLoadImage() } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { var index = self.pageIndex() var zoomImageView : KZImageScrollView = self.scrollImageViewArray?.objectAtIndex(Int(index)) as! KZImageScrollView zoomImageView.startLoadImage() self.preLoadImage(index) } }
9eb2944527c9cde28aaa75a7b6952379
43.639004
155
0.630508
false
false
false
false
AgentFeeble/pgoapi
refs/heads/master
pgoapi/Classes/Utility/CellIDUtility.swift
apache-2.0
1
// // CellIDUtility.swift // pgoapi // // Created by Rayman Rosevear on 2016/07/30. // Copyright © 2016 MC. All rights reserved. // import Foundation func getCellIDs(_ location: Location, radius: Int = 1000) -> [UInt64] { // Max values allowed by server according to this comment: // https://github.com/AeonLucid/POGOProtos/issues/83#issuecomment-235612285 let r = min(radius, 1500) let level = Int32(15) let maxCells = Int32(100) //100 is max allowed by the server let cells = MCS2CellID.cellIDsForRegion(atLat: location.latitude, long: location.longitude, radius: Double(r), level: level, maxCellCount: maxCells) return cells.map({ $0.cellID }).sorted() }
aa04d3ade6640e6fdf2f80a4f6654f81
33.538462
79
0.540089
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Views/Cells/ChatRightLocation/ChatRightLocationCell.swift
mit
1
// // ChatRightLocationCell.swift // Yep // // Created by NIX on 15/5/5. // Copyright (c) 2015年 Catch Inc. All rights reserved. // import UIKit import MapKit import YepKit final class ChatRightLocationCell: ChatRightBaseCell { static private let mapSize = CGSize(width: 192, height: 108) lazy var mapImageView: UIImageView = { let imageView = UIImageView() imageView.tintColor = UIColor.rightBubbleTintColor() return imageView }() lazy var locationNameLabel: UILabel = { let label = UILabel() label.textColor = UIColor.whiteColor() label.font = UIFont.systemFontOfSize(12) label.textAlignment = .Center return label }() lazy var borderImageView: UIImageView = { let imageView = UIImageView(image: UIImage.yep_rightTailImageBubbleBorder) return imageView }() typealias MediaTapAction = () -> Void var mediaTapAction: MediaTapAction? func makeUI() { let fullWidth = UIScreen.mainScreen().bounds.width let halfAvatarSize = YepConfig.chatCellAvatarSize() / 2 avatarImageView.center = CGPoint(x: fullWidth - halfAvatarSize - YepConfig.chatCellGapBetweenWallAndAvatar(), y: halfAvatarSize) mapImageView.frame = CGRect(x: CGRectGetMinX(avatarImageView.frame) - YepConfig.ChatCell.gapBetweenAvatarImageViewAndBubble - 192, y: 0, width: 192, height: 108) borderImageView.frame = mapImageView.frame dotImageView.center = CGPoint(x: CGRectGetMinX(mapImageView.frame) - YepConfig.ChatCell.gapBetweenDotImageViewAndBubble, y: CGRectGetMidY(mapImageView.frame)) let locationNameLabelHeight = YepConfig.ChatCell.locationNameLabelHeight locationNameLabel.frame = CGRect(x: CGRectGetMinX(mapImageView.frame) + 20, y: CGRectGetMaxY(mapImageView.frame) - locationNameLabelHeight, width: 192 - 20 * 2 - 7, height: locationNameLabelHeight) } override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(mapImageView) contentView.addSubview(locationNameLabel) contentView.addSubview(borderImageView) UIView.performWithoutAnimation { [weak self] in self?.makeUI() } mapImageView.userInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(ChatRightLocationCell.tapMediaView)) mapImageView.addGestureRecognizer(tap) prepareForMenuAction = { otherGesturesEnabled in tap.enabled = otherGesturesEnabled } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tapMediaView() { mediaTapAction?() } func configureWithMessage(message: Message, mediaTapAction: MediaTapAction?) { self.message = message self.user = message.fromFriend self.mediaTapAction = mediaTapAction UIView.performWithoutAnimation { [weak self] in self?.makeUI() } if let sender = message.fromFriend { let userAvatar = UserAvatar(userID: sender.userID, avatarURLString: sender.avatarURLString, avatarStyle: nanoAvatarStyle) avatarImageView.navi_setAvatar(userAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration) } let locationName = message.textContent locationNameLabel.text = locationName mapImageView.yep_setMapImageOfMessage(message, withSize: ChatRightLocationCell.mapSize, tailDirection: .Right) } }
effb112e3a7f2b6f935f9e15153ecd88
32.027778
205
0.694141
false
true
false
false
egouletlang/ios-BaseUtilityClasses
refs/heads/master
BaseUtilityClasses/DateHelper.swift
mit
1
// // DateHelper.swift // BaseUtilityClasses // // Created by Etienne Goulet-Lang on 8/19/16. // Copyright © 2016 Etienne Goulet-Lang. All rights reserved. // import Foundation private var dateObjs: [String: DateFormatter] = [:] public class DateHelper { // Data formatter Methods public enum DateComparison { case sameDay case dayBefore case sameWeek case sameYear case differentYear case na } public class func isLater(later: Date?, earlier: Date?) -> Bool { if let l = later, let e = earlier { return l.compare(e) == .orderedDescending } else if later == nil { return false } else if earlier == nil { return true } return false } public class func compareDates(day1: Date!, day2: Date!) -> DateComparison { if day1 == nil || day2 == nil { return .na } let calendar = Calendar.current let components: NSCalendar.Unit = [NSCalendar.Unit.year, NSCalendar.Unit.weekOfYear, NSCalendar.Unit.day, NSCalendar.Unit.hour, NSCalendar.Unit.minute] let comp1 = (calendar as NSCalendar).components(components, from: day1) let comp2 = (calendar as NSCalendar).components(components, from: day2) if (comp1.year != comp2.year) { return .differentYear } else if (comp1.weekOfYear != comp2.weekOfYear) { return .sameYear } else if (comp1.day != comp2.day) { if abs(comp1.day! - comp2.day!) == 1 { return .dayBefore } return .sameWeek } else { return .sameDay } } public class func isWithin(curr: Date, prev: Date!, within: Int) -> Bool { if prev == nil { return false } let diff = Int(abs(curr.timeIntervalSince(prev))) return (diff < within) } public class func formatDate(_ format: String, date: Date) -> String { var formatter = dateObjs[format] if formatter == nil { formatter = DateFormatter() formatter!.dateFormat = format dateObjs[format] = formatter } return formatter!.string(from: date) } }
af35e445bf3e30c51aef417f50da9be0
29.223684
159
0.566826
false
false
false
false
MetalheadSanya/GtkSwift
refs/heads/master
src/FlowBox.swift
bsd-3-clause
1
// // FlowBox.swift // GTK-swift // // Created by Alexander Zalutskiy on 16.04.16. // // import CGTK import gobjectswift /// A `FlowBox` positions child widgets in sequence according to its /// orientation. /// /// For instance, with the horizontal orientation, the widgets will be arranged /// from left to right, starting a new row under the previous row when /// necessary. Reducing the width in this case will require more rows, so a /// larger height will be requested. /// /// Likewise, with the vertical orientation, the widgets will be arranged from /// top to bottom, starting a new column to the right when necessary. Reducing /// the height will require more columns, so a larger width will be requested. /// /// The children of a `FlowBox` can be dynamically sorted and filtered. /// /// Although a `FlowBox` must have only `FlowBox.Child` children, you can add /// any kind of widget to it via `addWidget(_:)`, and a `FlowBox.Child` widget /// will automatically be inserted between the box and the widget. /// /// - Seealso: `ListBox`. /// /// - Version: `FlowBox` was added in GTK+ 3.12. public class FlowBox: Container { public class Child: Bin { private var n_FlowBoxChild: UnsafeMutablePointer<GtkFlowBoxChild> internal init(n_FlowBoxChild: UnsafeMutablePointer<GtkFlowBoxChild>) { self.n_FlowBoxChild = n_FlowBoxChild super.init(n_Bin: UnsafeMutablePointer<GtkBin>(n_FlowBoxChild)) } /// Creates a new FlowBoxChild, to be used as a child of a FlowBox. private convenience init() { self.init(n_FlowBoxChild: UnsafeMutablePointer<GtkFlowBoxChild>(gtk_flow_box_child_new())) } /// Gets the current index of the child in its FlowBox container. public var index: Int { return Int(gtk_flow_box_child_get_index(n_FlowBoxChild)) } /// Whether the child is currently selected in its FlowBox container. public var isSelected: Bool { return gtk_flow_box_child_is_selected(n_FlowBoxChild) != 0 } /// Marks child as changed, causing any state that depends on this to be /// updated. This affects sorting and filtering. /// /// Note that calls to this method must be in sync with the data used for /// the sorting and filtering functions. For instance, if the list is /// mirroring some external data set, and *two* children changed in the /// external data set when you call `changed()` on the first child, the sort /// function must only read the new data for the first of the two changed /// children, otherwise the resorting of the children will be wrong. /// /// This generally means that if you don’t fully control the data model, you /// have to duplicate the data that affects the sorting and filtering /// functions into the widgets themselves. Another alternative is to call /// `FlowBox.invalidateSort()` on any model change, but that is more /// expensive. public func changed() { gtk_flow_box_child_changed(n_FlowBoxChild) } // MARK: - Signals /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias ActivateCallback = ( box: Child) -> Void public typealias ActivateNative = ( UnsafeMutablePointer<Child>, UnsafeMutablePointer<gpointer>) -> Void /// The `::activate` signal is emitted when the user activates a child /// widget in a `FlowBox`, either by clicking or double-clicking, or by /// using the Space or Enter key. /// /// While this signal is used as a keybinding signal, it can be used by /// applications for their own purposes. public lazy var activateSignal: Signal<ActivateCallback, Child, ActivateNative> = Signal(obj: self, signal: "activate", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<Child, ActivateCallback>.self) let child = data.obj let action = data.function action(box: child) }) } internal var n_FlowBox: UnsafeMutablePointer<GtkFlowBox> internal init(n_FlowBox: UnsafeMutablePointer<GtkFlowBox>) { self.n_FlowBox = n_FlowBox super.init(n_Container: UnsafeMutablePointer<GtkContainer>(n_FlowBox)) } /// Creates a FlowBox. public convenience init() { self.init(n_FlowBox: UnsafeMutablePointer<GtkFlowBox>(gtk_flow_box_new())) } /// Inserts the `child` into box at `position`. /// /// If a sort function is set, the widget will actually be inserted at the /// calculated position and this function has the same effect as /// `addWidget(_:)`. /// If `position` is -1, or larger than the total number of children in the /// box, then the `child` will be appended to the end. /// /// - Parameter child: the `Widget` to add /// - Parameter position: the position to insert `child` in public func insert(child: Widget, at position: Int) { let row: Child if child is Child { row = child as! Child } else { row = Child() row.show() row.addWidget(child) } gtk_flow_box_insert(n_FlowBox, row.n_Widget, gint(position)) _children.append(row) } private func _childWithPointer( _ pointer: UnsafeMutablePointer<GtkFlowBoxChild>) -> Child { let n_FlowBoxChild = UnsafeMutablePointer<GtkWidget>(pointer) var row = _children.filter{ $0.n_Widget == n_FlowBoxChild}.first if row == nil { row = Container.correctWidgetForWidget(Widget(n_Widget: n_Widget)) _children.append(row!) } return row as! Child } /// Gets the nth child in the box. /// /// - Parameter idx: the position of the child /// /// - Returns: The child widget, which will always be a `FlowBox.Child` or /// `nil` in case no child widget with the given index exists. public func getChild(atIndex idx: Int) -> Child? { let n_FlowBoxChild = gtk_flow_box_get_child_at_index(n_FlowBox, gint(idx)) return _childWithPointer(n_FlowBoxChild) } // TODO: gtk_flow_box_set_hadjustment(), gtk_flow_box_set_vadjustment(), // need GtkAdjustment /// Determines whether all children should be allocated the same size. public var homogeneous: Bool { set { gtk_flow_box_set_homogeneous(n_FlowBox, newValue ? 1 : 0) } get { return gtk_flow_box_get_homogeneous(n_FlowBox) != 0 } } /// The amount of vertical space between two children. public var rowSpacing: UInt { set { gtk_flow_box_set_row_spacing(n_FlowBox, guint(newValue)) } get { return UInt(gtk_flow_box_get_row_spacing(n_FlowBox)) } } /// The amount of horizontal space between two children. public var columnSpacing: UInt { set { gtk_flow_box_set_column_spacing(n_FlowBox, guint(newValue)) } get { return UInt(gtk_flow_box_get_column_spacing(n_FlowBox)) } } /// The minimum number of children to allocate consecutively in the given /// orientation. /// /// Setting the minimum children per line ensures that a reasonably small /// height will be requested for the overall minimum width of the box. public var minChildrenPerLine: UInt { set { gtk_flow_box_set_min_children_per_line(n_FlowBox, guint(newValue)) } get { return UInt(gtk_flow_box_get_min_children_per_line(n_FlowBox)) } } /// The maximum amount of children to request space for consecutively in the /// given orientation. public var maxChildrenPerLine: UInt { set { gtk_flow_box_set_max_children_per_line(n_FlowBox, guint(newValue)) } get { return UInt(gtk_flow_box_get_max_children_per_line(n_FlowBox)) } } /// Determines whether children can be activated with a single click, or /// require a double-click. public var activateOnSingleClick: Bool { set { gtk_flow_box_set_activate_on_single_click(n_FlowBox, newValue ? 1 : 0) } get { return gtk_flow_box_get_activate_on_single_click(n_FlowBox) != 0 } } /// A function used by `selectedForeach()`. It will be called on every /// selected child of the box. /// /// - Parameter child: a `FlowBox.Child` public typealias ForeachFunc = (child: Child) -> Void /// Calls a function for each selected child. /// /// Note that the selection cannot be modified from within this function. /// /// - Parameter f: the function to call for each selected child. public func selectedForeach(_ f: ForeachFunc) { class Data { let f: ForeachFunc let box: FlowBox init(f: ForeachFunc, box: FlowBox) { self.f = f self.box = box } } let data = Data(f: f, box: self) gtk_flow_box_selected_foreach(n_FlowBox, { _, child, user_data in let data = unsafeBitCast(user_data, to: Data.self) data.f(child: data.box._childWithPointer(child)) }, unsafeBitCast(data, to: UnsafeMutablePointer<gpointer>.self)) } /// Creates a array of all selected children. public var selectedChildren: [Child] { let n_Children = Array<UnsafeMutablePointer<GtkFlowBoxChild>>(gList: gtk_flow_box_get_selected_children(n_FlowBox)) var selectedCildren = [Child]() for n_Child in n_Children { selectedCildren.append(_childWithPointer(n_Child)) } return selectedCildren } /// Selects a single child of box, if the selection mode allows it. /// /// - Parameter child: a child of box public func select(child: Child) { gtk_flow_box_select_child(n_FlowBox, child.n_FlowBoxChild) } /// Unselects a single child of box, if the selection mode allows it. /// /// - Parameter child: a child of box public func unselect(child: Child) { gtk_flow_box_unselect_child(n_FlowBox, child.n_FlowBoxChild) } /// Select all children of box, if the selection mode allows it. public func selectAll() { gtk_flow_box_select_all(n_FlowBox) } /// Unselect all children of box, if the selection mode allows it. public func unselectAll() { gtk_flow_box_unselect_all(n_FlowBox) } /// The selection mode used by the flow box. public var selectionMode: SelectionMode { set { gtk_flow_box_set_selection_mode(n_FlowBox, newValue.rawValue) } get { return SelectionMode(rawValue: gtk_flow_box_get_selection_mode(n_FlowBox))! } } /// A function that will be called whenrever a child changes or is added. It /// lets you control if the child should be visible or not. /// /// - Parameter child: a `FlowBox.Child` that may be filtered /// /// - Returns: `true` if the row should be visible, `false` otherwise public typealias FilterFunc = (child: Child) -> Bool /// By setting a filter function on the box one can decide dynamically which /// of the children to show. For instance, to implement a search function that /// only shows the children matching the search terms. /// /// The `filterFunc` will be called for each child after the call, and it will /// continue to be called each time a child changes (via /// `FlowBox.Child.changed()`) or when `invalidateFilter()` is called. /// /// Note that using a filter function is incompatible with using a model (see /// gtk_flow_box_bind_model()). public var filterFunc: FilterFunc? { didSet { if filterFunc == nil { gtk_flow_box_set_filter_func(n_FlowBox, nil, nil, nil) } else { gtk_flow_box_set_filter_func(n_FlowBox, { n_Child, flowBox in let box = unsafeBitCast(flowBox, to: FlowBox.self) let child = box._childWithPointer(n_Child) return box.filterFunc!(child: child) ? 1 : 0 }, unsafeBitCast(self, to: UnsafeMutablePointer<gpointer>.self), nil) } } } /// Updates the filtering for all children. /// /// Call this function when the result of the filter function on the box is /// changed due ot an external factor. For instance, this would be used if the /// filter function just looked for a specific search term, and the entry with /// the string has changed. public func invalidateFilter() { gtk_flow_box_invalidate_filter(n_FlowBox) } /// A function to compare two children to determine which should come first. /// /// - Parameter child1: the first child /// - Parameter child2: the second child /// /// - Returns: < 0 if `child1` should be before `child2`, 0 if the are equal, /// and > 0 otherwise public typealias SortFunc = (child1: Child, child2: Child) -> Int /// By setting a sort function on the box , one can dynamically reorder the /// children of the box, based on the contents of the children. /// /// The sortFunc will be called for each child after the call, and will /// continue to be called each time a child changes (via /// `FlowBox.Child.changed()`) and when `invalidateSort()` is called. /// /// Note that using a sort function is incompatible with using a model (see /// `gtk_flow_box_bind_model()`). public var sortFunc: SortFunc? { didSet { if sortFunc == nil { gtk_flow_box_set_sort_func(n_FlowBox, nil, nil, nil) } else { gtk_flow_box_set_sort_func(n_FlowBox, { n_Child1, n_Child2, listBox in let box = unsafeBitCast(listBox, to: FlowBox.self) let child1 = box._childWithPointer(n_Child1) let child2 = box._childWithPointer(n_Child2) return gint(box.sortFunc!(child1: child1, child2: child2)) }, unsafeBitCast(self, to: UnsafeMutablePointer<gpointer>.self), nil) } } } /// Updates the sorting for all children. /// /// Call this when the result of the sort function on box is changed due to an /// external factor. public func invalidateSort() { gtk_flow_box_invalidate_sort(n_FlowBox) } // TODO: gtk_list_box_bind_model(), need gio-swift // MARK: - Overrides public override func addWidget(_ widget: Widget) { insert(child: widget, at: -1) } public override func removeWidget(_ widget: Widget) { func remove(widget: Widget) { gtk_container_remove(n_Container, widget.n_Widget) if let index = _children.index(of: widget) { _children.remove(at: index) } } if widget is Child { remove(widget: widget) } else { if let widget = widget.parent where widget is Child { remove(widget: widget) } else { print("Tried to remove non-child \(widget)") return } } } // MARK: - Signals /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias ActivateCursorChildCallback = (box: FlowBox) -> Void public typealias ActivateCursorChildNative = (UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<gpointer>) -> Void /// The `::activate-cursor-child` signal is a keybinding signal which gets /// emitted when the user activates the box. public lazy var activateCursorChildSignal: Signal<ActivateCursorChildCallback, FlowBox, ActivateCursorChildNative> = Signal(obj: self, signal: "activate-cursor-child", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, ActivateCursorChildCallback>.self) let flowBox = data.obj let action = data.function action(box: flowBox) }) /// - Parameter box: the `FlowBox` on which the signal is emitted /// - Parameter child: the child that is activated public typealias ChildActivatedCallback = (box: FlowBox, child: Child) -> Void public typealias ChildActivatedNative = (UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<GtkFlowBoxChild>, UnsafeMutablePointer<gpointer>) -> Void /// The `::child-activated` signal is emitted when a child has been activated /// by the user. public lazy var childActivated: Signal<ChildActivatedCallback, FlowBox, ChildActivatedNative> = Signal(obj: self, signal: "child-activated", c_handler: { _, n_Child, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, ChildActivatedCallback>.self) let flowBox = data.obj let action = data.function let child = flowBox._childWithPointer(n_Child) action(box: flowBox, child: child) }) /// - Parameter box: the `FlowBox` on which the signal is emitted /// - Parameter step: the granularity fo the move, as a `MovementStep` /// - Parameter count: the number of `step` units to move /// /// - Returns: `true` to stop other handlers from being invoked for the event. /// `false` to propagate the event further. public typealias MoveCursorCallback = ( box: FlowBox, step: MovementStep, count: Int) -> Bool public typealias MoveCursorNative = (UnsafeMutablePointer<GtkFlowBox>, GtkMovementStep, gint, UnsafeMutablePointer<gpointer>) -> gboolean /// The `::move-cursor` signal is a keybinding signal which gets emitted when /// the user initiates a cursor movement. /// /// Applications should not connect to it, but may emit it with `emit()` if /// they need to control the cursor programmatically. /// /// The default bindings for this signal come in two variants, the variant /// with the Shift modifier extends the selection, the variant without the /// Shift modifer does not. There are too many key combinations to list them /// all here. /// /// * Arrow keys move by individual children /// * Home/End keys move to the ends of the box /// * PageUp/PageDown keys move vertically by pages public lazy var moveCursorSignal: Signal<MoveCursorCallback, FlowBox, MoveCursorNative> = Signal(obj: self, signal: "move-cursor", c_handler: { _, n_Step, count, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, MoveCursorCallback>.self) let flowBox = data.obj let action = data.function let step = MovementStep(rawValue: n_Step)! return action(box: flowBox, step: step, count: Int(count)) ? 1 : 0 }) /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias SelectAllCallback = ( box: FlowBox) -> Void public typealias SelectAllNative = ( UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<gpointer>) -> Void /// The `::select-all` signal is a keybinding signal which gets emitted to /// select all children of the box, if the selection mode permits it. /// /// The default bindings for this signal is Ctrl-a. public lazy var selectAllSignal: Signal<SelectAllCallback, FlowBox, SelectAllNative> = Signal(obj: self, signal: "select-all", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, SelectAllCallback>.self) let flowBox = data.obj let action = data.function action(box: flowBox) }) /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias SelectedChildrenChangedCallback = ( box: FlowBox) -> Void public typealias SelectedChildrenChangedNative = ( UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<gpointer>) -> Void /// The `::selected-children-changed` signal is emitted when the set of /// selected children changes. /// /// Use `selectedForeach(_:)` or `selectedChildren` to obtain the selected /// children. public lazy var selectedChildrenChangedSignal: Signal<SelectedChildrenChangedCallback, FlowBox, SelectedChildrenChangedNative> = Signal(obj: self, signal: "selected-children-changed", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, SelectedChildrenChangedCallback>.self) let flowBox = data.obj let action = data.function action(box: flowBox) }) /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias ToggleCursorChildCallback = ( box: FlowBox) -> Void public typealias ToggleCursorChildNative = ( UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<gpointer>) -> Void /// The `::toggle-cursor-child` signal is a keybinding signal which toggles /// the selection of the child that has the focus. /// /// The default binding for this signal is Ctrl-Space. public lazy var toggleCursorChildSignal: Signal<ToggleCursorChildCallback, FlowBox, ToggleCursorChildNative> = Signal(obj: self, signal: "toggle-cursor-child", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, ToggleCursorChildCallback>.self) let flowBox = data.obj let action = data.function action(box: flowBox) }) /// - Parameter box: the `FlowBox` on which the signal is emitted public typealias UnselectAllCallback = ( box: FlowBox) -> Void public typealias UnselectAllNative = ( UnsafeMutablePointer<GtkFlowBox>, UnsafeMutablePointer<gpointer>) -> Void /// The `::unselect-all signal` is a keybinding signal which gets emitted to /// unselect all children of the box, if the selection mode permits it. /// /// The default bindings for this signal is Ctrl-Shift-a. public lazy var unselectAllSignal: Signal<UnselectAllCallback, FlowBox, UnselectAllNative> = Signal(obj: self, signal: "unselect-all", c_handler: { _, user_data in let data = unsafeBitCast(user_data, to: SignalData<FlowBox, UnselectAllCallback>.self) let flowBox = data.obj let action = data.function action(box: flowBox) }) }
0003d4d01ac394e1363d557120558700
31.690513
79
0.688344
false
false
false
false
edx/edx-app-ios
refs/heads/master
Test/UserPreferenceManagerTests.swift
apache-2.0
2
// // UserPreferenceManagerTests.swift // edX // // Created by Kevin Kim on 8/8/16. // Copyright © 2016 edX. All rights reserved. // import Foundation @testable import edX class UserPreferenceManagerTests : XCTestCase { func testUserPreferencesLoginLogout() { let userPrefernces = UserPreference(json: ["time_zone": "Asia/Tokyo"]) XCTAssertNotNil(userPrefernces) let preferences = userPrefernces! let environment = TestRouterEnvironment() environment.mockNetworkManager.interceptWhenMatching({_ in true }) { return (nil, preferences) } let manager = UserPreferenceManager(networkManager: environment.networkManager) let feed = manager.feed // starts empty XCTAssertNil(feed.output.value ?? nil) // Log in. Preferences should load environment.logInTestUser() feed.refresh() stepRunLoop() waitForStream(feed.output) XCTAssertEqual(feed.output.value??.timeZone, preferences.timeZone) // Log out. Now preferences should be cleared environment.session.closeAndClear() XCTAssertNil(feed.output.value!) } }
418d3a08a17e8d42501c581cd2a5c518
27
87
0.627778
false
true
false
false
niunaruto/DeDaoAppSwift
refs/heads/master
DeDaoSwift/DeDaoSwift/Home/UIKitExtension/UIButton+Extension.swift
mit
1
// // UIButton+Extension.swift // DeDaoSwift // // Created by niuting on 2017/3/13. // Copyright © 2017年 niuNaruto. All rights reserved. // import Foundation public enum UIButtonImagePosition : Int { case left case right case bottom case top } extension UIButton { func setImagePosition(_ position : UIButtonImagePosition ,spacing : CGFloat? = 0) { setImage(currentImage, for: .normal) setTitle(currentTitle, for: .normal) let imageWidth = imageView?.image?.size.width let imageHeight = imageView?.image?.size.height guard imageWidth != nil && imageHeight != nil else { return } var tempSpc : CGFloat = 0 if let temp = spacing{ tempSpc = temp } var attrs = Dictionary<String, Any>() attrs[NSFontAttributeName] = titleLabel?.font; let labelSize = titleLabel?.text?.boundingRect(with: UIScreen.main .bounds.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attrs, context: nil).size if let size = labelSize { let imageOffsetX = imageWidth! + size.width / 2.0 - imageWidth! / 2.0 let imageOffsetY = imageHeight! / 2.0 + tempSpc / 2.0 let labelOffsetX = (imageWidth! + size.width / 2.0) - (imageWidth! + size.width) / 2.0 let labelOffsetY = size.height / 2 + tempSpc / 2 let tempWidth = getMax(size.width,imageWidth!) let changedWidth = size.width + imageWidth! - tempWidth let tempHeight = getMax(size.height, imageHeight!) let changedHeight = size.height + imageHeight! + tempSpc - tempHeight; switch position { case .bottom: self.imageEdgeInsets = UIEdgeInsetsMake(imageOffsetY, imageOffsetX - imageWidth!, -imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(-labelOffsetY, -labelOffsetX, labelOffsetY, labelOffsetX); self.contentEdgeInsets = UIEdgeInsetsMake(changedHeight-imageOffsetY, -changedWidth/2, imageOffsetY, -changedWidth/2); case .top: self.imageEdgeInsets = UIEdgeInsetsMake(-imageOffsetY, imageOffsetX - imageWidth!, imageOffsetY, -imageOffsetX); self.titleEdgeInsets = UIEdgeInsetsMake(labelOffsetY, -labelOffsetX, -labelOffsetY, labelOffsetX); self.contentEdgeInsets = UIEdgeInsetsMake(imageOffsetY, -changedWidth/2, changedHeight-imageOffsetY, -changedWidth/2); case .right: self.imageEdgeInsets = UIEdgeInsetsMake(0, size.width + tempSpc/2, 0, -(size.width + tempSpc/2)); self.titleEdgeInsets = UIEdgeInsetsMake(0, -(imageWidth! + tempSpc/2), 0, imageWidth! + tempSpc/2); self.contentEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, tempSpc/2); case .left: self.imageEdgeInsets = UIEdgeInsetsMake(0, -tempSpc/2, 0, tempSpc/2); self.titleEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, -tempSpc/2); self.contentEdgeInsets = UIEdgeInsetsMake(0, tempSpc/2, 0, tempSpc/2); } } } func getMax(_ num1 : CGFloat ,_ num2 : CGFloat) -> CGFloat { guard num1 >= num2 else { return num1 } return num2 } }
915200e1477c4f888dd37e6ff268193a
33.174312
134
0.562148
false
false
false
false
srn214/Floral
refs/heads/master
Floral/Floral/Classes/Expand/Extensions/RxSwift/Cocoa/UITextField+Rx.swift
mit
1
// // UITextField+Rx.swift // RxSwiftX // // Created by Pircate on 2018/6/1. // Copyright © 2018年 Pircate. All rights reserved. // import RxSwift import RxCocoa public extension Reactive where Base: UITextField { var delegate: RxTextFieldDelegateProxy { return RxTextFieldDelegateProxy.proxy(for: base) } var shouldClear: ControlEvent<UITextField> { let source = delegate.shouldClearPublishSubject return ControlEvent(events: source) } var shouldReturn: ControlEvent<UITextField> { let source = delegate.shouldReturnPublishSubject return ControlEvent(events: source) } var valueChanged: Binder<Void> { return Binder(base) { textField, _ in textField.sendActions(for: .valueChanged) } } } public extension UITextField { var maxLength: Int { get { return 0 } set { RxTextFieldDelegateProxy.proxy(for: self).shouldChangeCharacters = { (textField, range, string) -> Bool in if string.isEmpty { return true } guard let text = textField.text else { return true } let length = text.count + string.count - range.length return length <= newValue } } } }
ce3deda9a748a0f499e65720c8b663d3
26.020833
118
0.619121
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/Buttons/SmallMinimalButton.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI /// Syntactic suguar on MinimalButton to render it in a small size /// /// # Usage /// ``` /// SmallMinimalButton(title: "OK") { print("Tapped") } /// ``` /// /// # Figma /// [Buttons](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=6%3A2955) public struct SmallMinimalButton: View { private let title: String private let isLoading: Bool private let action: () -> Void public init( title: String, isLoading: Bool = false, action: @escaping () -> Void ) { self.title = title self.isLoading = isLoading self.action = action } public var body: some View { MinimalButton(title: title, isLoading: isLoading, action: action) .pillButtonSize(.small) } } struct SmallMinimalButton_Previews: PreviewProvider { static var previews: some View { Group { SmallMinimalButton(title: "OK", isLoading: false) { print("Tapped") } .previewLayout(.sizeThatFits) .previewDisplayName("Enabled") SmallMinimalButton(title: "OK", isLoading: false) { print("Tapped") } .disabled(true) .previewLayout(.sizeThatFits) .previewDisplayName("Disabled") SmallMinimalButton(title: "OK", isLoading: true) { print("Tapped") } .previewLayout(.sizeThatFits) .previewDisplayName("Loading") } } }
4b66aed468b6965459e3b3550bdccf57
26.152542
102
0.576155
false
false
false
false
duycao2506/SASCoffeeIOS
refs/heads/master
Pods/PopupDialog/PopupDialog/Classes/PopupDialogDefaultView.swift
gpl-3.0
1
// // PopupDialogView.swift // // Copyright (c) 2016 Orderella Ltd. (http://orderella.co.uk) // Author - Martin Wildfeuer (http://www.mwfire.de) // // 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 /// The main view of the popup dialog final public class PopupDialogDefaultView: UIView { // MARK: - Appearance /// The font and size of the title label @objc public dynamic var titleFont: UIFont { get { return titleLabel.font } set { titleLabel.font = newValue } } /// The color of the title label @objc public dynamic var titleColor: UIColor? { get { return titleLabel.textColor } set { titleLabel.textColor = newValue } } /// The text alignment of the title label @objc public dynamic var titleTextAlignment: NSTextAlignment { get { return titleLabel.textAlignment } set { titleLabel.textAlignment = newValue } } /// The font and size of the body label @objc public dynamic var messageFont: UIFont { get { return messageLabel.font } set { messageLabel.font = newValue } } /// The color of the message label @objc public dynamic var messageColor: UIColor? { get { return messageLabel.textColor } set { messageLabel.textColor = newValue} } /// The text alignment of the message label @objc public dynamic var messageTextAlignment: NSTextAlignment { get { return messageLabel.textAlignment } set { messageLabel.textAlignment = newValue } } // MARK: - Views /// The view that will contain the image, if set internal lazy var imageView: UIImageView = { let imageView = UIImageView(frame: .zero) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true return imageView }() /// The title label of the dialog internal lazy var titleLabel: UILabel = { let titleLabel = UILabel(frame: .zero) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.textColor = UIColor(white: 0.4, alpha: 1) titleLabel.font = UIFont.boldSystemFont(ofSize: 14) return titleLabel }() /// The message label of the dialog internal lazy var messageLabel: UILabel = { let messageLabel = UILabel(frame: .zero) messageLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.numberOfLines = 0 messageLabel.textAlignment = .center messageLabel.textColor = UIColor(white: 0.6, alpha: 1) messageLabel.font = UIFont.systemFont(ofSize: 14) return messageLabel }() /// The height constraint of the image view, 0 by default internal var imageHeightConstraint: NSLayoutConstraint? // MARK: - Initializers internal override init(frame: CGRect) { super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View setup internal func setupViews() { // Self setup translatesAutoresizingMaskIntoConstraints = false // Add views addSubview(imageView) addSubview(titleLabel) addSubview(messageLabel) // Layout views let views = ["imageView": imageView, "titleLabel": titleLabel, "messageLabel": messageLabel] as [String: Any] var constraints = [NSLayoutConstraint]() constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[imageView]|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[titleLabel]-(==20@900)-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[messageLabel]-(==20@900)-|", options: [], metrics: nil, views: views) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[imageView]-(==30@900)-[titleLabel]-(==8@900)-[messageLabel]-(==30@900)-|", options: [], metrics: nil, views: views) // ImageView height constraint imageHeightConstraint = NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 0, constant: 0) if let imageHeightConstraint = imageHeightConstraint { constraints.append(imageHeightConstraint) } // Activate constraints NSLayoutConstraint.activate(constraints) } }
72b40777fbb561cbbbf29b8b52627989
37.945946
192
0.679216
false
false
false
false
pragmapilot/PPCollectionViewDragNDrop
refs/heads/master
PPCollectionViewDragNDrop/ViewController.swift
unlicense
1
// // ViewController.swift // PPCollectionViewDragNDrop // // Created by PragmaPilot on 13/10/2015. // Copyright © 2015 PragmaPilot. All rights reserved. // import UIKit class ViewController: UIViewController { private var downloadsCounter = 0 var items = NSMutableArray() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() initializeItems(100) let longPress = UILongPressGestureRecognizer(target: self, action: "didLongPress:"); self.collectionView.addGestureRecognizer(longPress) } func didLongPress(gesture: UILongPressGestureRecognizer){ switch(gesture.state) { case UIGestureRecognizerState.Began: guard let indexPath = self.collectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else { break } self.collectionView.beginInteractiveMovementForItemAtIndexPath(indexPath) case UIGestureRecognizerState.Changed: self.collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!)) case UIGestureRecognizerState.Ended: self.collectionView.endInteractiveMovement() default: self.collectionView.cancelInteractiveMovement() } } func initializeItems(size:Int){ self.downloadsCounter = size let photoManager = PhotoManager() UIApplication.sharedApplication().networkActivityIndicatorVisible = true for i in 0 ..< size { let photo = photoManager.buildPhoto(i) photoManager.loadImage(photo, completion: { (model) -> () in self.downloadsCounter-- if self.downloadsCounter == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } dispatch_after(DISPATCH_TIME_NOW, dispatch_get_main_queue(), { () -> Void in self.collectionView.reloadItemsAtIndexPaths([NSIndexPath(forRow: model.id, inSection: 0)]) }) }) items.addObject(photo) } } }
37be725fe0e3d16fd9c7a73258eede4f
31.260274
122
0.609342
false
false
false
false
loudnate/xDripG5
refs/heads/master
CGMBLEKit/PeripheralManager+G5.swift
mit
1
// // PeripheralManager+G5.swift // xDripG5 // // Copyright © 2017 LoopKit Authors. All rights reserved. // import CoreBluetooth import os.log private let log = OSLog(category: "PeripheralManager+G5") extension PeripheralManager { private func getCharacteristicWithUUID(_ uuid: CGMServiceCharacteristicUUID) -> CBCharacteristic? { return peripheral.getCharacteristicWithUUID(uuid) } func setNotifyValue(_ enabled: Bool, for characteristicUUID: CGMServiceCharacteristicUUID, timeout: TimeInterval = 2) throws { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } try setNotifyValue(enabled, for: characteristic, timeout: timeout) } func readMessage<R: TransmitterRxMessage>( for characteristicUUID: CGMServiceCharacteristicUUID, timeout: TimeInterval = 2 ) throws -> R { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } var capturedResponse: R? try runCommand(timeout: timeout) { addCondition(.valueUpdate(characteristic: characteristic, matching: { (data) -> Bool in guard let value = data else { return false } guard let response = R(data: value) else { // We don't recognize the contents. Keep listening. return false } capturedResponse = response return true })) peripheral.readValue(for: characteristic) } guard let response = capturedResponse else { // TODO: This is an "unknown value" issue, not a timeout if let value = characteristic.value { log.error("Unknown response data: %{public}@", value.hexadecimalString) } throw PeripheralManagerError.timeout } return response } /// - Throws: PeripheralManagerError func writeMessage<T: RespondableMessage>(_ message: T, for characteristicUUID: CGMServiceCharacteristicUUID, type: CBCharacteristicWriteType = .withResponse, timeout: TimeInterval = 2 ) throws -> T.Response { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } var capturedResponse: T.Response? try runCommand(timeout: timeout) { if case .withResponse = type { addCondition(.write(characteristic: characteristic)) } if characteristic.isNotifying { addCondition(.valueUpdate(characteristic: characteristic, matching: { (data) -> Bool in guard let value = data else { return false } guard let response = T.Response(data: value) else { // We don't recognize the contents. Keep listening. return false } capturedResponse = response return true })) } peripheral.writeValue(message.data, for: characteristic, type: type) } guard let response = capturedResponse else { // TODO: This is an "unknown value" issue, not a timeout if let value = characteristic.value { log.error("Unknown response data: %{public}@", value.hexadecimalString) } throw PeripheralManagerError.timeout } return response } /// - Throws: PeripheralManagerError func writeMessage(_ message: TransmitterTxMessage, for characteristicUUID: CGMServiceCharacteristicUUID, type: CBCharacteristicWriteType = .withResponse, timeout: TimeInterval = 2) throws { guard let characteristic = getCharacteristicWithUUID(characteristicUUID) else { throw PeripheralManagerError.unknownCharacteristic } try writeValue(message.data, for: characteristic, type: type, timeout: timeout) } } fileprivate extension CBPeripheral { func getServiceWithUUID(_ uuid: TransmitterServiceUUID) -> CBService? { return services?.itemWithUUIDString(uuid.rawValue) } func getCharacteristicForServiceUUID(_ serviceUUID: TransmitterServiceUUID, withUUIDString UUIDString: String) -> CBCharacteristic? { guard let characteristics = getServiceWithUUID(serviceUUID)?.characteristics else { return nil } return characteristics.itemWithUUIDString(UUIDString) } func getCharacteristicWithUUID(_ uuid: CGMServiceCharacteristicUUID) -> CBCharacteristic? { return getCharacteristicForServiceUUID(.cgmService, withUUIDString: uuid.rawValue) } }
ace80c2849ec4e313d7e141495877123
32.586667
137
0.626836
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/NSCFDictionary.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation internal final class _NSCFDictionary : NSMutableDictionary { deinit { _CFDeinit(self) _CFZeroUnsafeIvars(&_storage) } required init() { fatalError() } required init?(coder aDecoder: NSCoder) { fatalError() } required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) { fatalError() } required public convenience init(dictionaryLiteral elements: (Any, Any)...) { fatalError("init(dictionaryLiteral:) has not been implemented") } override var count: Int { return CFDictionaryGetCount(unsafeBitCast(self, to: CFDictionary.self)) } override func object(forKey aKey: Any) -> Any? { let value = CFDictionaryGetValue(_cfObject, unsafeBitCast(__SwiftValue.store(aKey), to: UnsafeRawPointer.self)) if value != nil { return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self)) } else { return nil } } // This doesn't feel like a particularly efficient generator of CFDictionary keys, but it works for now. We should probably put a function into CF that allows us to simply iterate the keys directly from the underlying CF storage. private struct _NSCFKeyGenerator : IteratorProtocol { var keyArray : [NSObject] = [] var index : Int = 0 let count : Int mutating func next() -> AnyObject? { if index == count { return nil } else { let item = keyArray[index] index += 1 return item } } init(_ dict : _NSCFDictionary) { let cf = dict._cfObject count = CFDictionaryGetCount(cf) let keys = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: count) CFDictionaryGetKeysAndValues(cf, keys, nil) for idx in 0..<count { let key = unsafeBitCast(keys.advanced(by: idx).pointee!, to: NSObject.self) keyArray.append(key) } keys.deinitialize(count: 1) keys.deallocate() } } override func keyEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(_NSCFKeyGenerator(self)) } override func removeObject(forKey aKey: Any) { CFDictionaryRemoveValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(aKey), to: UnsafeRawPointer.self)) } override func setObject(_ anObject: Any, forKey aKey: AnyHashable) { CFDictionarySetValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(aKey), to: UnsafeRawPointer.self), unsafeBitCast(__SwiftValue.store(anObject), to: UnsafeRawPointer.self)) } override var classForCoder: AnyClass { return NSMutableDictionary.self } } internal func _CFSwiftDictionaryGetCount(_ dictionary: AnyObject) -> CFIndex { return (dictionary as! NSDictionary).count } internal func _CFSwiftDictionaryGetCountOfKey(_ dictionary: AnyObject, key: AnyObject) -> CFIndex { if _CFSwiftDictionaryContainsKey(dictionary, key: key) { return 1 } else { return 0 } } internal func _CFSwiftDictionaryContainsKey(_ dictionary: AnyObject, key: AnyObject) -> Bool { return (dictionary as! NSDictionary).object(forKey: key) != nil } //(AnyObject, AnyObject) -> Unmanaged<AnyObject> internal func _CFSwiftDictionaryGetValue(_ dictionary: AnyObject, key: AnyObject) -> Unmanaged<AnyObject>? { let dict = dictionary as! NSDictionary if type(of: dictionary) === NSDictionary.self || type(of: dictionary) === NSMutableDictionary.self { if let obj = dict._storage[key as! NSObject] { return Unmanaged<AnyObject>.passUnretained(obj) } } else { let k = __SwiftValue.fetch(nonOptional: key) let value = dict.object(forKey: k) let v = __SwiftValue.store(value) dict._storage[key as! NSObject] = v if let obj = v { return Unmanaged<AnyObject>.passUnretained(obj) } } return nil } internal func _CFSwiftDictionaryGetValueIfPresent(_ dictionary: AnyObject, key: AnyObject, value: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) -> Bool { if let val = _CFSwiftDictionaryGetValue(dictionary, key: key) { value?.pointee = val return true } else { value?.pointee = nil return false } } internal func _CFSwiftDictionaryGetCountOfValue(_ dictionary: AnyObject, value: AnyObject) -> CFIndex { if _CFSwiftDictionaryContainsValue(dictionary, value: value) { return 1 } else { return 0 } } internal func _CFSwiftDictionaryContainsValue(_ dictionary: AnyObject, value: AnyObject) -> Bool { NSUnimplemented() } // HAZARD! WARNING! // The contract of these CF APIs is that the elements in the buffers have a lifespan of the container dictionary. // Since the public facing elements of the dictionary may be a structure (which could not be retained) or the boxing // would potentially make a reference that is not the direct access of the element, this function must do a bit of // hoop jumping to deal with storage. // In the case of NSDictionary and NSMutableDictionary (NOT subclasses) we can directly reach into the storage and // grab the un-fetched items. This allows the same behavior to be maintained. // In the case of subclasses of either NSDictionary or NSMutableDictionary we cannot reconstruct boxes here since // they will fall out of scope and be consumed by automatic reference counting at the end of this function. But since // swift has a fragile layout we can reach into the super-class ivars (NSDictionary) and store boxed references to ensure lifespan // is similar to how it works on Darwin. Effectively this binds the acceess point of all values and keys for those objects // to have the same lifespan of the parent container object. internal func _CFSwiftDictionaryGetValuesAndKeys(_ dictionary: AnyObject, valuebuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>?, keybuf: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) { var idx = 0 if valuebuf == nil && keybuf == nil { return } let dict = dictionary as! NSDictionary if type(of: dictionary) === NSDictionary.self || type(of: dictionary) === NSMutableDictionary.self { for (key, value) in dict._storage { valuebuf?[idx] = Unmanaged<AnyObject>.passUnretained(value) keybuf?[idx] = Unmanaged<AnyObject>.passUnretained(key) idx += 1 } } else { dict.enumerateKeysAndObjects(options: []) { k, v, _ in let key = __SwiftValue.store(k) let value = __SwiftValue.store(v) valuebuf?[idx] = Unmanaged<AnyObject>.passUnretained(value) keybuf?[idx] = Unmanaged<AnyObject>.passUnretained(key) dict._storage[key] = value idx += 1 } } } internal func _CFSwiftDictionaryApplyFunction(_ dictionary: AnyObject, applier: @convention(c) (AnyObject, AnyObject, UnsafeMutableRawPointer) -> Void, context: UnsafeMutableRawPointer) { (dictionary as! NSDictionary).enumerateKeysAndObjects(options: []) { key, value, _ in applier(__SwiftValue.store(key), __SwiftValue.store(value), context) } } internal func _CFSwiftDictionaryAddValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionaryReplaceValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionarySetValue(_ dictionary: AnyObject, key: AnyObject, value: AnyObject) { (dictionary as! NSMutableDictionary).setObject(value, forKey: key as! NSObject) } internal func _CFSwiftDictionaryRemoveValue(_ dictionary: AnyObject, key: AnyObject) { (dictionary as! NSMutableDictionary).removeObject(forKey: key) } internal func _CFSwiftDictionaryRemoveAllValues(_ dictionary: AnyObject) { (dictionary as! NSMutableDictionary).removeAllObjects() } internal func _CFSwiftDictionaryCreateCopy(_ dictionary: AnyObject) -> Unmanaged<AnyObject> { return Unmanaged<AnyObject>.passRetained((dictionary as! NSDictionary).copy() as! NSObject) }
a2c3ea65bed581945c4a5dde8cf815d9
39.378995
233
0.67692
false
false
false
false
Stitch7/Instapod
refs/heads/master
Instapod/ColorCube.swift
mit
1
// // ColorCube.swift // Instapod // // Created by Christopher Reitz on 23.03.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit extension UIImage { var colorCube: UIColor { var color = UIColor.black let cube = ColorCube() let imageColors = cube.extractColorsFromImage(self, flags: [.AvoidWhite, .AvoidBlack]) if let mainColor = imageColors.first { color = mainColor } return color } } extension Data { var colorCube: UIColor { guard let image = UIImage(data: self) else { return UIColor.black } return image.colorCube } } struct ColorCubeFlags: OptionSet { let rawValue: Int static let None = ColorCubeFlags(rawValue: 0) static let OnlyBrightColors = ColorCubeFlags(rawValue: 1 << 0) static let OnlyDarkColors = ColorCubeFlags(rawValue: 1 << 1) static let OnlyDistinctColors = ColorCubeFlags(rawValue: 1 << 2) static let OrderByBrightness = ColorCubeFlags(rawValue: 1 << 3) static let OrderByDarkness = ColorCubeFlags(rawValue: 1 << 4) static let AvoidWhite = ColorCubeFlags(rawValue: 1 << 5) static let AvoidBlack = ColorCubeFlags(rawValue: 1 << 6) } final class ColorCubeLocalMaximum { let hitCount: Int // Linear index of the cell let cellIndex: Int // Average color of cell let red: Double let green: Double let blue: Double // Maximum color component value of average color let brightness: Double init( hitCount: Int, cellIndex: Int, red: Double, green: Double, blue: Double, brightness: Double ) { self.hitCount = hitCount self.cellIndex = cellIndex self.red = red self.green = green self.blue = blue self.brightness = brightness } } struct ColorCubeCell { // Count of hits (dividing the accumulators by this value gives the average) var hitCount: Int = 0 // Accumulators for color components var redAcc: Double = 0.0 var greenAcc: Double = 0.0 var blueAcc: Double = 0.0 } final class ColorCube { // The cell resolution in each color dimension let resolution = 30 // Threshold used to filter bright colors let brightColorThreshold = 0.6 // Threshold used to filter dark colors let darkColorThreshold = 0.4 // Threshold (distance in color space) for distinct colors let distinctColorThreshold: CGFloat = 0.2 // Helper macro to compute linear index for cells // let CELL_INDEX(r,g,b) (r+g*COLOR_CUBE_RESOLUTION+b*COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION) // Helper macro to get total count of cells // let CELL_COUNT COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION*COLOR_CUBE_RESOLUTION // Indices for neighbour cells in three dimensional grid let neighbourIndices: [[Int]] = [ [0, 0, 0], [0, 0, 1], [0, 0,-1], [0, 1, 0], [0, 1, 1], [0, 1,-1], [0,-1, 0], [0,-1, 1], [0,-1,-1], [1, 0, 0], [1, 0, 1], [1, 0,-1], [1, 1, 0], [1, 1, 1], [1, 1,-1], [1,-1, 0], [1,-1, 1], [1,-1,-1], [-1, 0, 0], [-1, 0, 1], [-1, 0,-1], [-1, 1, 0], [-1, 1, 1], [-1, 1,-1], [-1,-1, 0], [-1,-1, 1], [-1,-1,-1] ] var cells = [ColorCubeCell](repeating: ColorCubeCell(), count: 27000) func cellIndexCreate(_ r: Int, _ g: Int, _ b: Int) -> Int { return r + g * resolution + b * resolution * resolution } func findLocalMaximaInImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // We collect local maxima in here var localMaxima = [ColorCubeLocalMaximum]() // Reset all cells clearCells() // guard let context = rawPixelDataFromImage(image, pixelCount: &pixelCount) else { return localMaxima } // let rawData = UnsafeMutablePointer<UInt8>(context.data) // let rawData: UnsafeMutablePointer<CGImage> = context.data! let cgImage = image.cgImage! let width = cgImage.width let height = cgImage.height // Allocate storage for the pixel data let rawDataSize = height * width * 4 let rawData: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.allocate(capacity: rawDataSize) // Create the color space let colorSpace = CGColorSpaceCreateDeviceRGB(); // Set some metrics let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue).rawValue // Create context using the storage _ = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // rawData.deallocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) // rawData.deallocate(capacity: rawDataSize) let pixelCount = width * height // Helper vars var red, green, blue: Double var redIndex, greenIndex, blueIndex, cellIndex, localHitCount: Int var isLocalMaximum: Bool // Project each pixel into one of the cells in the three dimensional grid for k in 0 ..< pixelCount { // Get color components as floating point value in [0,1] red = Double(rawData[k * 4 + 0]) / 255.0 green = Double(rawData[k * 4 + 1]) / 255.0 blue = Double(rawData[k * 4 + 2]) / 255.0 // If we only want bright colors and this pixel is dark, ignore it if flags.contains(.OnlyBrightColors) { if red < brightColorThreshold && green < brightColorThreshold && blue < brightColorThreshold { continue } } else if flags.contains(.OnlyDarkColors) { if red >= darkColorThreshold || green >= darkColorThreshold || blue >= darkColorThreshold { continue } } // Map color components to cell indices in each color dimension let redIndex = Int(red * (Double(resolution) - 1.0)) let greenIndex = Int(green * (Double(resolution) - 1.0)) let blueIndex = Int(blue * (Double(resolution) - 1.0)) // Compute linear cell index cellIndex = cellIndexCreate(redIndex, greenIndex, blueIndex) // Increase hit count of cell cells[cellIndex].hitCount += 1 // Add pixel colors to cell color accumulators cells[cellIndex].redAcc += red cells[cellIndex].greenAcc += green cells[cellIndex].blueAcc += blue } // Deallocate raw pixel data memory rawData.deinitialize() rawData.deallocate(capacity: rawDataSize) // Find local maxima in the grid for r in 0 ..< resolution { for g in 0 ..< resolution { for b in 0 ..< resolution { // Get hit count of this cell localHitCount = cells[cellIndexCreate(r, g, b)].hitCount // If this cell has no hits, ignore it (we are not interested in zero hits) if localHitCount == 0 { continue } // It is local maximum until we find a neighbour with a higher hit count isLocalMaximum = true // Check if any neighbour has a higher hit count, if so, no local maxima for n in 0..<27 { redIndex = r + neighbourIndices[n][0]; greenIndex = g + neighbourIndices[n][1]; blueIndex = b + neighbourIndices[n][2]; // Only check valid cell indices (skip out of bounds indices) if redIndex >= 0 && greenIndex >= 0 && blueIndex >= 0 { if redIndex < resolution && greenIndex < resolution && blueIndex < resolution { if cells[cellIndexCreate(redIndex, greenIndex, blueIndex)].hitCount > localHitCount { // Neighbour hit count is higher, so this is NOT a local maximum. isLocalMaximum = false // Break inner loop break } } } } // If this is not a local maximum, continue with loop. if !isLocalMaximum { continue } // Otherwise add this cell as local maximum let cellIndex = cellIndexCreate(r, g, b) let hitCount = cells[cellIndex].hitCount let red = cells[cellIndex].redAcc / Double(cells[cellIndex].hitCount) let green = cells[cellIndex].greenAcc / Double(cells[cellIndex].hitCount) let blue = cells[cellIndex].blueAcc / Double(cells[cellIndex].hitCount) let brightness = fmax(fmax(red, green), blue) let maximum = ColorCubeLocalMaximum( hitCount: hitCount, cellIndex: cellIndex, red: red, green: green, blue: blue, brightness: brightness ) localMaxima.append(maximum) } } } let sorttedMaxima = localMaxima.sorted { $0.hitCount > $1.hitCount } return sorttedMaxima } func findAndSortMaximaInImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // First get local maxima of image var sortedMaxima = findLocalMaximaInImage(image, flags: flags) // Filter the maxima if we want only distinct colors if flags.contains(.OnlyDistinctColors) { sortedMaxima = filterDistinctMaxima(sortedMaxima, threshold: distinctColorThreshold) } // If we should order the result array by brightness, do it if flags.contains(.OrderByBrightness) { sortedMaxima = orderByBrightness(sortedMaxima) } else if flags.contains(.OrderByDarkness) { sortedMaxima = orderByDarkness(sortedMaxima) } return sortedMaxima } // MARK: - Filtering and sorting func filterDistinctMaxima(_ maxima: [ColorCubeLocalMaximum], threshold: CGFloat) -> [ColorCubeLocalMaximum] { var filteredMaxima = [ColorCubeLocalMaximum]() // Check for each maximum for k in 0 ..< maxima.count { // Get the maximum we are checking out let max1 = maxima[k] // This color is distinct until a color from before is too close var isDistinct = true // Go through previous colors and look if any of them is too close for n in 0 ..< k { // Get the maximum we compare to let max2 = maxima[n] // Compute delta components let redDelta = max1.red - max2.red let greenDelta = max1.green - max2.green let blueDelta = max1.blue - max2.blue // Compute delta in color space distance let delta = CGFloat(sqrt(redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta)) // If too close mark as non-distinct and break inner loop if delta < threshold { isDistinct = false break } } // Add to filtered array if is distinct if isDistinct { filteredMaxima.append(max1) } } return filteredMaxima } func filterMaxima(_ maxima: [ColorCubeLocalMaximum], tooCloseToColor color: UIColor) -> [ColorCubeLocalMaximum] { // Get color components let components = color.cgColor.components var filteredMaxima = [ColorCubeLocalMaximum]() // Check for each maximum for k in 0..<maxima.count { // Get the maximum we are checking out let max1 = maxima[k] // Compute delta components let redDelta = max1.red - Double((components?[0])!) let greenDelta = max1.green - Double((components?[1])!) let blueDelta = max1.blue - Double((components?[2])!) // Compute delta in color space distance let delta = sqrt(redDelta * redDelta + greenDelta * greenDelta + blueDelta * blueDelta) // If not too close add it if delta >= 0.5 { filteredMaxima.append(max1) } } return filteredMaxima } func orderByBrightness(_ maxima: [ColorCubeLocalMaximum]) -> [ColorCubeLocalMaximum] { return maxima.sorted { $0.brightness > $1.brightness } } func orderByDarkness(_ maxima: [ColorCubeLocalMaximum]) -> [ColorCubeLocalMaximum] { return maxima.sorted { $0.brightness < $1.brightness } } func performAdaptiveDistinctFilteringForMaxima(_ maxima: [ColorCubeLocalMaximum], count: Int) -> [ColorCubeLocalMaximum] { var tempMaxima = maxima // If the count of maxima is higher than the requested count, perform distinct thresholding if (maxima.count > count) { var tempDistinctMaxima = maxima var distinctThreshold: CGFloat = 0.1 // Decrease the threshold ten times. If this does not result in the wanted count for _ in 0 ..< 10 { // Get array with current distinct threshold tempDistinctMaxima = filterDistinctMaxima(maxima, threshold: distinctThreshold) // If this array has less than count, break and take the current sortedMaxima if tempDistinctMaxima.count <= count { break } // Keep this result (length is > count) tempMaxima = tempDistinctMaxima // Increase threshold by 0.05 distinctThreshold += 0.05 } // Only take first count maxima tempMaxima = Array(maxima[0..<count]) } return tempMaxima } // MARK: - Maximum to color conversion func colorsFromMaxima(_ maxima: [ColorCubeLocalMaximum]) -> [UIColor] { // Build the resulting color array var colorArray = [UIColor]() // For each local maximum generate UIColor and add it to the result array for maximum in maxima { let color = UIColor( red: CGFloat(maximum.red), green: CGFloat(maximum.green), blue: CGFloat(maximum.blue), alpha: 1.0 ) colorArray.append(color) } return colorArray } // MARK: - Default maxima extraction and filtering func extractAndFilterMaximaFromImage(_ image: UIImage, flags: ColorCubeFlags) -> [ColorCubeLocalMaximum] { // Get maxima var sortedMaxima = findAndSortMaximaInImage(image, flags: flags) // Filter out colors too close to black if flags.contains(.AvoidBlack) { let black = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1) sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: black) } // Filter out colors too close to white if flags.contains(.AvoidWhite) { let white = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1) sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: white) } // Return maxima array return sortedMaxima } // MARK: - Public methods func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags) -> [UIColor] { // Get maxima let sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Return color array return colorsFromMaxima(sortedMaxima) } func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags, avoidColor: UIColor) -> [UIColor] { // Get maxima var sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Return color array return colorsFromMaxima(sortedMaxima) } func extractBrightColorsFromImage(_ image: UIImage, avoidColor: UIColor, count: Int) -> [UIColor] { // Get maxima (bright only) var sortedMaxima = findAndSortMaximaInImage(image, flags: .OnlyBrightColors) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } func extractDarkColorsFromImage(_ image: UIImage, avoidColor: UIColor, count: Int) -> [UIColor] { // Get maxima (bright only) var sortedMaxima = findAndSortMaximaInImage(image, flags: .OnlyDarkColors) // Filter out colors that are too close to the specified color sortedMaxima = filterMaxima(sortedMaxima, tooCloseToColor: avoidColor) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } func extractColorsFromImage(_ image: UIImage, flags: ColorCubeFlags, count: Int) -> [UIColor] { // Get maxima var sortedMaxima = extractAndFilterMaximaFromImage(image, flags: flags) // Do clever distinct color filtering sortedMaxima = performAdaptiveDistinctFilteringForMaxima(sortedMaxima, count: count) // Return color array return colorsFromMaxima(sortedMaxima) } // MARK: - Resetting cells func clearCells() { let cellCount = resolution * resolution * resolution for k in 0 ..< cellCount { cells[k].hitCount = 0 cells[k].redAcc = 0.0 cells[k].greenAcc = 0.0 cells[k].blueAcc = 0.0 } } // MARK: - Pixel data extraction func rawPixelDataFromImage(_ image: UIImage, pixelCount: inout Int) -> CGContext? { // Get cg image and its size guard let cgImage = image.cgImage else { return nil } let width = cgImage.width let height = cgImage.height // Allocate storage for the pixel data let rawDataSize = height * width * 4 // let rawData = UnsafeMutableRawPointer.allocate(capacity: rawDataSize) // let rawData = UnsafeMutableRawPointer.allocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) let rawData: UnsafeMutablePointer<CGImage> = UnsafeMutablePointer.allocate(capacity: rawDataSize) // Create the color space let colorSpace = CGColorSpaceCreateDeviceRGB(); // Set some metrics let bytesPerPixel = 4 let bytesPerRow = bytesPerPixel * width let bitsPerComponent = 8 let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue).rawValue // Create context using the storage let context = CGContext(data: rawData, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // rawData.deallocate(bytes: rawDataSize, alignedTo: MemoryLayout<UIImage>.alignment) rawData.deallocate(capacity: rawDataSize) // Draw the image into the storage context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) // Write pixel count to passed pointer pixelCount = width * height // Return pixel data (needs to be freed) return context } }
76532858b699970a8d0578bbc8508acf
35.139085
181
0.593511
false
false
false
false
ceecer1/open-muvr
refs/heads/master
ios/Lift/Device/This/ThisDeviceSession+HealthKit.swift
apache-2.0
5
import Foundation import HealthKit /// /// Provides HK connector /// extension ThisDeviceSession { class HealthKit { let store: HKHealthStore! var heartRateQuery: HKObserverQuery? init() { let readTypes: NSSet = NSSet(object: HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)) let shareTypes: NSSet = NSSet() store = HKHealthStore() let hr = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) store.requestAuthorizationToShareTypes(shareTypes, readTypes: readTypes) { (x, err) in self.store.enableBackgroundDeliveryForType(hr, frequency: HKUpdateFrequency.Immediate, withCompletion: { (x, err) in self.heartRateQuery = HKObserverQuery(sampleType: hr, predicate: nil, updateHandler: self.heartRateUpdateHandler) self.store.executeQuery(self.heartRateQuery!) }) } } func stop() { store.stopQuery(heartRateQuery?) } func heartRateUpdateHandler(query: HKObserverQuery!, completion: HKObserverQueryCompletionHandler!, error: NSError!) { NSLog("Got HR") } } }
8bea3e3cf86961f47c9bd6c07c16621c
34.833333
133
0.629946
false
false
false
false
Centroida/SwiftImageCarousel
refs/heads/master
SwiftImageCarousel/SwiftImageCarouselVC.swift
mit
1
import UIKit // // SwiftImageCarouselVC.swift // SwiftImageCarousel // // Created by Deyan Aleksandrov on 1/3/17. // /// The delegate of a SwiftImageCarouselVC object must adopt this protocol. Optional methods of the protocol allow the delegate to configure the appearance of the view controllers, the timer and get notified when a new image is shown @objc public protocol SwiftImageCarouselVCDelegate: class { /// Fires when the timer starts helps to track of all the properties the timer has when it was started. /// /// - Parameter timer: The timer that manages the automatic swiping of images @objc optional func didStartTimer(_ timer: Timer) /// Fires when the timer is on and a new SwiftImageCarouselItemVC gets instantiated every few seconds. /// /// - Parameter SwiftImageCarouselItemController: The next pageItemController that has been initialized due to the timer ticking @objc optional func didGetNextITemController(next SwiftImageCarouselItemController: SwiftImageCarouselItemVC) /// Fires when an unwinding action coming from GalleryItemVC is performed and a new SwiftImageCarouselItemVC gets instantiated. /// /// - Parameter SwiftImageCarouselItemController: The page controller received when unwinding the GalleryVC @objc optional func didunwindToSwiftImageCarouselVC(unwindedTo SwiftImageCarouselItemController: SwiftImageCarouselItemVC) /// Fires when SwiftImageCarouselVC is initialized. Use it to setup the appearance of the paging controls (dots) of both the SwiftImageCarouselVC and the GalleryVC. /// /// - Parameters: /// - firstPageControl: The page control in SwiftImageCarouselVC /// - secondPageControl: The page control in GalleryVC @objc optional func setupAppearance(forFirst firstPageControl: UIPageControl, forSecond secondPageControl: UIPageControl) /// Fires when a pageItemController is tapped. /// /// - Parameter SwiftImageCarouselItemController: The SwiftImageCarouselItemVC taht is tapped @objc optional func didTapSwiftImageCarouselItemVC(swiftImageCarouselItemController: SwiftImageCarouselItemVC) } /// SwiftImageCarouselVC is the controller base class and initilizes the first view the user sees when a developer implements this carousel. It implements methods used for instantiating the proper page view, setting up the page controller appearance and setting up the timer used for automatic swiping of the page views. public class SwiftImageCarouselVC: UIPageViewController { /// The model array of image urls used in the carousel. public var contentImageURLs: [String] = [] { didSet { getNextItemController() } } // MARK: - Delegate weak public var swiftImageCarouselVCDelegate: SwiftImageCarouselVCDelegate? /// When set to TRUE, sets the image container frame to extend over the UIPageControl frame but not cover it (it goes underneath). To see it the proper effect of this variable in most cases, the contentMode should be .scaleToFill. Note also that background of the page control defaults to .clear when this variable is set to TRUE Default value is FALSE. public var escapeFirstPageControlDefaultFrame = false /// Keeps track of the page control frame height and provides it when needed var pageControlFrameHeight: CGFloat = 0 /// Enables/disables the showing of the modal gallery. public var showModalGalleryOnTap = true /// The image shown when an image to be downloaded does not do that successfully public var noImage: UIImage? = nil /// Enables resetting the UIViewContentMode of SwiftImageCarouselItemVC UIViewContentMode. The default is .scaleAspectFit. public var contentMode: UIViewContentMode = .scaleAspectFit // MARK: - Timer properties /// The timer that is used to move the next page item. var timer = Timer() /// Enables/disables the automatic swiping of the timer. Default value is true. public var isTimerOn = true /// The interval on which the view changes when the timer is on. Default value is 3 seconds. public var swipeTimeIntervalSeconds = 3.0 /// Shows/hides the close button in the modal gallery. Default value is false. public var showCloseButtonInModalGallery = false /// This variable keeps track of the index used in the page control in terms of the array of URLs. fileprivate var pageIndicatorIndex = 0 /// This variable keeps track of the index of the SwiftImageCarouselVC in terms of the array of URLs. fileprivate var currentPageViewControllerItemIndex = 0 // MARK: - Unwind segue /// In this unwind method, it is made sure that the view that will be instantiated has the proper image (meaning that same that we unwinded from). /// It is also made sure that that pageIndicatorIndex is setup to the proper dot shows up on the page control. @IBAction func unwindToSwiftImageCarouselVC(withSegue segue: UIStoryboardSegue) { // Making sure that the proper page control appearance comes on here when unwinding. setupPageControl() if let galleryItemVC = segue.source as? GalleryItemVC { loadPageViewControllerWhenUnwinding(atIndex: galleryItemVC.itemIndex) } } /// Loads a view controller with the index from the unwind segue. /// /// - Parameter itemIndex: The index for the VC from the model that will be loaded func loadPageViewControllerWhenUnwinding(atIndex itemIndex: Int) { if let currentController = getItemController(itemIndex) { swiftImageCarouselVCDelegate?.didunwindToSwiftImageCarouselVC?(unwindedTo: currentController) pageIndicatorIndex = currentController.itemIndex let startingViewControllers = [currentController] setViewControllers(startingViewControllers, direction: .forward, animated: false, completion: nil) } } // MARK: - Functions /// Loads a starting view controller from the model array with an index. /// /// - Parameter index: The index for the VC from the model that will be loaded func loadPageViewController(atIndex index: Int = 0) { if let firstController = getItemController(index) { let startingViewControllers = [firstController] setViewControllers(startingViewControllers, direction: .forward, animated: true, completion: nil) } } /// A method for getting the next SwiftImageCarouselItemVC. Called only by the timer selector. @objc func getNextItemController() { guard let currentViewController = viewControllers?.first else { return } // Use delegate method to retrieve the next view controller. guard let nextViewController = pageViewController(self, viewControllerAfter: currentViewController) as? SwiftImageCarouselItemVC else { return } swiftImageCarouselVCDelegate?.didGetNextITemController?(next: nextViewController) // Need to keep track of page indicator index in order to update it properly. pageIndicatorIndex = nextViewController.itemIndex setViewControllers([nextViewController], direction: .forward, animated: true, completion: nil) } /// A method for getting SwiftImageCarouselItemVC with a given index. func getItemController(_ itemIndex: Int) -> SwiftImageCarouselItemVC? { if !contentImageURLs.isEmpty && itemIndex <= contentImageURLs.count { let pageItemController = storyboard!.instantiateViewController(withIdentifier: "SwiftImageCarouselItemVC") as! SwiftImageCarouselItemVC pageItemController.itemIndex = itemIndex < contentImageURLs.count ? itemIndex : 0 pageItemController.contentImageURLs = contentImageURLs pageItemController.swiftImageCarouselVCDelegate = swiftImageCarouselVCDelegate pageItemController.showModalGalleryOnTap = showModalGalleryOnTap pageItemController.contentMode = contentMode pageItemController.noImage = noImage pageItemController.showCloseButtonInModalGallery = showCloseButtonInModalGallery return pageItemController } return nil } // MARK: - Timer Function func startTimer() { if timer.isValid { timer.invalidate() } timer = Timer.scheduledTimer(timeInterval: swipeTimeIntervalSeconds, target: self, selector: #selector(getNextItemController), userInfo: nil, repeats: true) swiftImageCarouselVCDelegate?.didStartTimer?(timer) } // MARK: - Page Indicator public func presentationCount(for pageViewController: UIPageViewController) -> Int { return contentImageURLs.count } public func presentationIndex(for pageViewController: UIPageViewController) -> Int { return pageIndicatorIndex } // MARK: - Setup page control func setupPageControl() { view.backgroundColor = .white // Default appearance let appearance = UIPageControl.appearance() appearance.pageIndicatorTintColor = .orange appearance.currentPageIndicatorTintColor = .gray appearance.backgroundColor = .clear // Custom appearance setup with delegation from outside this framework. let firstAppearance = UIPageControl.appearance(whenContainedInInstancesOf: [SwiftImageCarouselVC.self]) let secondAppearance = UIPageControl.appearance(whenContainedInInstancesOf: [GalleryVC.self]) swiftImageCarouselVCDelegate?.setupAppearance?(forFirst: firstAppearance, forSecond: secondAppearance) } // MARK: - View Lifecycle override public func viewDidLoad() { super.viewDidLoad() dataSource = self loadPageViewController() setupPageControl() } /// A method fixing the bounds of the image so that page control with the dots does not cover that particular image. override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if escapeFirstPageControlDefaultFrame { for view in self.view.subviews { if view is UIScrollView { // Sets the image container frame to extend over the UIPageControl frame but not cover it (it goes underneath). // To see it properly working contentMode should be .scaleToFill // 37 is generally the default height of a UIPageControl if pageControlFrameHeight != 0 { view.frame = CGRect(x: view.frame.minX , y: view.frame.minY, width: view.frame.width, height: view.frame.height + pageControlFrameHeight) } } else if view is UIPageControl { pageControlFrameHeight = view.frame.height view.backgroundColor = .clear } } } } public override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if isTimerOn { startTimer() } } public override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) timer.invalidate() } override public var prefersStatusBarHidden : Bool { return true } } // MARK: - UIPageViewControllerDataSource extension SwiftImageCarouselVC: UIPageViewControllerDataSource { public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard contentImageURLs.count > 1 else { return nil } let itemController = viewController as! SwiftImageCarouselItemVC let nextIndex = itemController.itemIndex > 0 ? (itemController.itemIndex - 1) : (contentImageURLs.count - 1) return getItemController(nextIndex) } public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard contentImageURLs.count > 1 else { return nil } let itemController = viewController as! SwiftImageCarouselItemVC let previousIndex = itemController.itemIndex + 1 < contentImageURLs.count ? (itemController.itemIndex + 1) : (0) return getItemController(previousIndex) } }
ae0565a866ab4e1266d36a09657338b4
48.01992
357
0.72131
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Networking/Auth/Jwt/RSASSA_PKCS1.swift
gpl-3.0
1
import Foundation import Security private func paddingForHashFunction(_ f: SignatureAlgorithm.HashFunction) -> SecPadding { switch f { case .sha256: return SecPadding.PKCS1SHA256 case .sha384: return SecPadding.PKCS1SHA384 case .sha512: return SecPadding.PKCS1SHA512 } } public struct RSAKey { enum Error: Swift.Error { case securityError(OSStatus) case publicKeyNotFoundInCertificate case cannotCreateCertificateFromData case invalidP12ImportResult case invalidP12NoIdentityFound } let value: SecKey public init(secKey: SecKey) { self.value = secKey } public init(secCertificate cert: SecCertificate) throws { var trust: SecTrust? = nil let result = SecTrustCreateWithCertificates(cert, nil, &trust) if result == errSecSuccess && trust != nil { if let publicKey = SecTrustCopyPublicKey(trust!) { self.init(secKey: publicKey) } else { throw Error.publicKeyNotFoundInCertificate } } else { throw Error.securityError(result) } } //Creates a certificate object from a DER representation of a certificate. public init(certificateData data: Data) throws { if let cert = SecCertificateCreateWithData(nil, data as CFData) { try self.init(secCertificate: cert) } else { throw Error.cannotCreateCertificateFromData } } public static func keysFromPkcs12Identity(_ p12Data: Data, passphrase: String) throws -> (publicKey: RSAKey, privateKey: RSAKey) { var importResult: CFArray? = nil let importParam = [kSecImportExportPassphrase as String: passphrase] let status = SecPKCS12Import(p12Data as CFData, importParam as CFDictionary, &importResult) guard status == errSecSuccess else { throw Error.securityError(status) } if let array = importResult.map({ unsafeBitCast($0, to: NSArray.self) }), let content = array.firstObject as? NSDictionary, let identity = (content[kSecImportItemIdentity as String] as! SecIdentity?) { var privateKey: SecKey? = nil var certificate: SecCertificate? = nil let status = ( SecIdentityCopyPrivateKey(identity, &privateKey), SecIdentityCopyCertificate(identity, &certificate) ) guard status.0 == errSecSuccess else { throw Error.securityError(status.0) } guard status.1 == errSecSuccess else { throw Error.securityError(status.1) } if privateKey != nil && certificate != nil { return try (RSAKey(secCertificate: certificate!), RSAKey(secKey: privateKey!)) } else { throw Error.invalidP12ImportResult } } else { throw Error.invalidP12NoIdentityFound } } } public struct RSAPKCS1Verifier: SignatureValidator { let hashFunction: SignatureAlgorithm.HashFunction let key: RSAKey public init(key: RSAKey, hashFunction: SignatureAlgorithm.HashFunction) { self.hashFunction = hashFunction self.key = key } public func canVerifyWithSignatureAlgorithm(_ alg: SignatureAlgorithm) -> Bool { if case SignatureAlgorithm.rsassa_PKCS1(self.hashFunction) = alg { return true } return false } public func verify(_ input: Data, signature: Data) -> Bool { let signedDataHash = (input as NSData).jwt_shaDigest(withSize: self.hashFunction.rawValue) let padding = paddingForHashFunction(self.hashFunction) let result = signature.withUnsafeBytes { signatureRawPointer in signedDataHash.withUnsafeBytes { signedHashRawPointer in SecKeyRawVerify( key.value, padding, signedHashRawPointer, signedDataHash.count, signatureRawPointer, signature.count ) } } switch result { case errSecSuccess: return true default: return false } } } public struct RSAPKCS1Signer: TokenSigner { enum Error: Swift.Error { case securityError(OSStatus) } let hashFunction: SignatureAlgorithm.HashFunction let key: RSAKey public init(hashFunction: SignatureAlgorithm.HashFunction, key: RSAKey) { self.hashFunction = hashFunction self.key = key } public var signatureAlgorithm: SignatureAlgorithm { return .rsassa_PKCS1(self.hashFunction) } public func sign(_ input: Data) throws -> Data { let signedDataHash = (input as NSData).jwt_shaDigest(withSize: self.hashFunction.rawValue) let padding = paddingForHashFunction(self.hashFunction) var result = Data(count: SecKeyGetBlockSize(self.key.value)) var resultSize = result.count let status = result.withUnsafeMutableBytes { resultBytes in SecKeyRawSign(key.value, padding, (signedDataHash as NSData).bytes.bindMemory(to: UInt8.self, capacity: signedDataHash.count), signedDataHash.count, UnsafeMutablePointer<UInt8>(resultBytes), &resultSize) } switch status { case errSecSuccess: return result.subdata(in: 0..<resultSize) default: throw Error.securityError(status) } } }
215f6ffeccc1f615234b679968198b16
32.694611
215
0.62289
false
false
false
false
montionugera/swift-101
refs/heads/master
4-swiftTour-Class.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" /*Objects and Classes Use class followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it is in the context of a class. Likewise, method and function declarations are written the same way. */ class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } /*EXPERIMENT Add a constant property with let, and add another method that takes an argument. */ class RectShape { let numberOfSides = 4 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } /* Create an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance. */ var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription() //This version of the Shape class is missing something important: an initializer to set up the class when an instance is created. Use init to create one. class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } } //Notice how self is used to distinguish the name property from the name argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as with numberOfSides) or in the initializer (as with name). // //Use deinit to create a deinitializer if you need to perform some cleanup before the object is deallocated. // //Subclasses include their superclass name after their class name, separated by a colon. There is no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed. // //Methods on a subclass that override the superclass’s implementation are marked with override—overriding a method by accident, without override, is detected by the compiler as an error. The compiler also detects methods with override that don’t actually override any method in the superclass. // class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription() //EXPERIMENT // //Make another subclass of NamedShape called Circle that takes a radius and a name as arguments to its initializer. Implement an area() and a simpleDescription() method on the Circle class. //In addition to simple properties that are stored, properties can have a getter and a setter. class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") println(triangle.perimeter) triangle.perimeter = 9.9 println(triangle.sideLength) //In the setter for perimeter, the new value has the implicit name newValue. You can provide an explicit name in parentheses after set. //Notice that the initializer for the EquilateralTriangle class has three different steps: // //Setting the value of properties that the subclass declares. //Calling the superclass’s initializer. //Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point. //If you don’t need to compute the property but still need to provide code that is run before and after setting a new value, use willSet and didSet. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square. class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") println(triangleAndSquare.square.sideLength) println(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "larger square") println(triangleAndSquare.triangle.sideLength) //Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method. class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) { count += amount * times } } var counter = Counter() counter.incrementBy(2, numberOfTimes: 7) //When working with optional values, you can write ? before operations like methods, properties, and subscripting. If the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, the optional value is unwrapped, and everything after the ? acts on the unwrapped value. In both cases, the value of the whole expression is an optional value. let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
a94558311ab7d69219aa542ca595d28f
39.209877
404
0.724593
false
false
false
false
EugeneVegner/sws-copyleaks-sdk-test
refs/heads/master
PlagiarismChecker/Classes/CopyleaksRequest.swift
mit
1
/* * The MIT License(MIT) * * Copyright(c) 2016 Copyleaks LTD (https://copyleaks.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ import Foundation public class CopyleaksRequest { /* The delegate for the underlying task. */ public let delegate: TaskDelegate /* The underlying task. */ public var task: NSURLSessionTask { return delegate.task } /* The session belonging to the underlying task. */ public let session: NSURLSession /* The request sent or to be sent to the server. */ public var request: NSURLRequest? { return task.originalRequest } /* The response received from the server, if any. */ public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse } /* The progress of the request lifecycle. */ public var progress: NSProgress { return delegate.progress } // MARK: - Lifecycle init(session: NSURLSession, task: NSURLSessionTask) { self.session = session switch task { case is NSURLSessionUploadTask: delegate = UploadTaskDelegate(task: task) case is NSURLSessionDataTask: delegate = DataTaskDelegate(task: task) default: delegate = TaskDelegate(task: task) } } // MARK: - State /** Resumes the request. */ public func resume() { task.resume() } /** Suspends the request. */ public func suspend() { task.suspend() } /** Cancels the request. */ public func cancel() { task.cancel() } // MARK: - TaskDelegate /** The task delegate is responsible for handling all delegate callbacks for the underlying task as well as executing all operations attached to the serial operation queue upon task completion. */ public class TaskDelegate: NSObject { public let queue: NSOperationQueue let task: NSURLSessionTask let progress: NSProgress var data: NSData? { return nil } var error: NSError? init(task: NSURLSessionTask) { self.task = task self.progress = NSProgress(totalUnitCount: 0) self.queue = { let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 1 operationQueue.suspended = true return operationQueue }() } deinit { queue.cancelAllOperations() queue.suspended = false } // MARK: - NSURLSessionTaskDelegate var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidCompleteWithError = taskDidCompleteWithError { taskDidCompleteWithError(session, task, error) } else { if let error = error { self.error = error } queue.suspended = false } } } // MARK: - DataTaskDelegate class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate { var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask } private var totalBytesReceived: Int64 = 0 private var mutableData: NSMutableData override var data: NSData? { return mutableData } private var expectedContentLength: Int64? private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)? override init(task: NSURLSessionTask) { mutableData = NSMutableData() super.init(task: task) } // MARK: - NSURLSessionDataDelegate var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow expectedContentLength = response.expectedContentLength if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else { mutableData.appendData(data) totalBytesReceived += data.length let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown progress.totalUnitCount = totalBytesExpected progress.completedUnitCount = totalBytesReceived dataProgress?( bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpected ) } } } class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
6f9d4f4c5e68630e1583112e71e53ced
34.376106
162
0.61626
false
false
false
false
bradvandyk/OpenSim
refs/heads/master
OpenSim/DirectoryWatcher.swift
mit
1
// // DirectoryWatcher.swift // Markdown // // Created by Luo Sheng on 15/10/31. // Copyright © 2015年 Pop Tap. All rights reserved. // import Foundation public class DirectoryWatcher { enum Error: ErrorType { case CannotOpenPath case CannotCreateSource } enum Mask { case Attribute case Delete case Extend case Link case Rename case Revoke case Write var flag: dispatch_source_vnode_flags_t { get { switch self { case .Attribute: return DISPATCH_VNODE_ATTRIB case .Delete: return DISPATCH_VNODE_DELETE case .Extend: return DISPATCH_VNODE_EXTEND case .Link: return DISPATCH_VNODE_LINK case .Rename: return DISPATCH_VNODE_RENAME case .Revoke: return DISPATCH_VNODE_REVOKE case .Write: return DISPATCH_VNODE_WRITE } } } } public typealias CompletionCallback = () -> () var watchedURL: NSURL let mask: Mask public var completionCallback: CompletionCallback? private let queue = dispatch_queue_create("com.pop-tap.directory-watcher", DISPATCH_QUEUE_SERIAL) private var source: dispatch_source_t? private var directoryChanging = false private var oldDirectoryInfo = [FileInfo?]() init(URL: NSURL, mask: Mask = .Write) { watchedURL = URL self.mask = mask } deinit { self.stop() } public func start() throws { guard source == nil else { return } guard let path = watchedURL.path else { return } let fd = open((path as NSString).fileSystemRepresentation, O_EVTONLY) guard fd >= 0 else { throw Error.CannotOpenPath } let cleanUp: () -> () = { close(fd) } guard let src = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, UInt(fd), mask.flag, queue) else { cleanUp() throw Error.CannotCreateSource } source = src dispatch_source_set_event_handler(src) { self.waitForDirectoryToFinishChanging() } dispatch_source_set_cancel_handler(src, cleanUp) dispatch_resume(src) } public func stop() { guard let src = source else { return } dispatch_source_cancel(src) } private func waitForDirectoryToFinishChanging() { if (!directoryChanging) { directoryChanging = true oldDirectoryInfo = self.directoryInfo() // print(oldDirectoryInfo) let timer = NSTimer(timeInterval: 0.5, target: self, selector: #selector(checkDirectoryInfo(_:)), userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes) } } private func directoryInfo() -> [FileInfo?] { do { let contents = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(watchedURL, includingPropertiesForKeys: FileInfo.prefetchedProperties, options: .SkipsSubdirectoryDescendants) return contents.map { FileInfo(URL: $0) } } catch { return [] } } @objc private func checkDirectoryInfo(timer: NSTimer) { let directoryInfo = self.directoryInfo() directoryChanging = directoryInfo != oldDirectoryInfo if directoryChanging { oldDirectoryInfo = directoryInfo } else { timer.invalidate() if let completion = completionCallback { completion() } } } }
f59e29bc6923ac87ae8896f98c073c66
27.126761
197
0.542449
false
false
false
false
tempestrock/CarPlayer
refs/heads/master
CarPlayer/TransitionManager.swift
gpl-3.0
1
// // TransitionManager.swift // Transitions between views // import UIKit class TransitionManager_Rotating: TransitionManager_Base { // // Animates a rotation from one view controller to another. // override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // DEBUG print("TransitionManager_Rotating.animateTransition()") // Get reference to our fromView, toView and the container view that we should perform the transition in: let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // set up from 2D transforms that we'll use in the animation: let π : CGFloat = 3.14159265359 let offScreenDown = CGAffineTransformMakeRotation(π/2) let offScreenUp = CGAffineTransformMakeRotation(-π/2) // Prepare the toView for the animation, depending on whether we are presenting or dismissing: toView.transform = self.presenting ? offScreenDown : offScreenUp // set the anchor point so that rotations happen from the top-left corner toView.layer.anchorPoint = CGPoint(x: 0, y: 0) fromView.layer.anchorPoint = CGPoint(x: 0, y: 0) // updating the anchor point also moves the position to we have to move the center position to the top-left to compensate toView.layer.position = CGPoint(x :0, y: 0) fromView.layer.position = CGPoint(x: 0, y: 0) // add the both views to our view controller container!.addSubview(toView) container!.addSubview(fromView) // Get the duration of the animation: let duration = self.transitionDuration(transitionContext) // Perform the animation: UIView.animateWithDuration( duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [], animations: { // slide fromView off either the left or right edge of the screen // depending if we're presenting or dismissing this view fromView.transform = self.presenting ? offScreenUp : offScreenDown toView.transform = CGAffineTransformIdentity }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) } ) } } // // A manager for vertical sliding transitions. Use the "DirectionToStartWith" to define whether the initial animation goes up or down. // class TransitionManager_Sliding: TransitionManager_Base { // An enum to define the initial animation direction enum DirectionToStartWith { case Up case Down } // The direction to us when animating the presentation. The dismissal is in the respective opposite direction private var _directionToStartWith: DirectionToStartWith = .Down override func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView() let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! // set up from 2D transforms that we'll use in the animation let offScreenDown = CGAffineTransformMakeTranslation(0, container!.frame.height) let offScreenUp = CGAffineTransformMakeTranslation(0, -container!.frame.height) // start the toView to the right of the screen if _directionToStartWith == DirectionToStartWith.Up { toView.transform = self.presenting ? offScreenDown : offScreenUp } else { toView.transform = self.presenting ? offScreenUp : offScreenDown } // add the both views to our view controller container!.addSubview(toView) container!.addSubview(fromView) // Get the duration of the animation: let duration = self.transitionDuration(transitionContext) // Perform the animation: UIView.animateWithDuration( duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: [], animations: { // Depending on the two aspects "direction to start with" and "presentation or dismissal" we set the fromview's transformation: if self._directionToStartWith == DirectionToStartWith.Up { fromView.transform = self.presenting ? offScreenUp : offScreenDown } else { fromView.transform = self.presenting ? offScreenDown : offScreenUp } toView.transform = CGAffineTransformIdentity }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) } ) } // // Sets the direction of swiping for the presentation. The direction back (dismissal) is always the respective opposite direction. // func setDirectionToStartWith(direction: DirectionToStartWith) { _directionToStartWith = direction } } // // The base class of all transition managers // class TransitionManager_Base: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { // --------- attributes --------- // A flag to define whether we are in the presenting or in the dismissing part of the animation: private var presenting = true // --------- methods --------- // // Empty animation. Needs to be implemented by derived class. // func animateTransition(transitionContext: UIViewControllerContextTransitioning) { assert(false, "TransitionManager_Base.animateTransition(): Missing implementation in derived class") } // // Returns how many seconds the transiton animation will take. // func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.75 } // // Returns the animator when presenting a viewcontroller. // Remmeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol // func animationControllerForPresentedController( presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { // DEBUG print("TransitionManager_Base.animationControllerForPresentedController()") // These methods are the perfect place to set our `presenting` flag to either true or false - voila! self.presenting = true return self } // // Returns the animator used when dismissing from a view controller. // func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // DEBUG print("TransitionManager_Base.animationControllerForDismissedController()") self.presenting = false return self } }
84663eda4a863b50605c10fc5d75f4dc
35.665072
143
0.666319
false
false
false
false
Tinkertanker/intro-coding-swift
refs/heads/master
0-2 Number Variables.playground/Contents.swift
mit
1
/*: # Intro to Programming in Swift Worksheet 2 In this set of exercises, you'll use Swift to learn about variables. Remember to turn on the *Assistant Editor* before you start. */ /*: ## Part 1B: Numbers This is a demonstration of number variables */ println("Part 1B: Numbers") println("--------------------------------") println("") //: Read through this code. var a : Int = 5 var b : Int = 6 var c : Int = a * b // * is times println("a is \(a), b is \(b), and a times b is \(c)") println("") var d : Double = 5.0 var e : Double = 2.4 var f : Double = d / e // / is divide println("d is \(d), e is \(e), and d divided by e is \(f)") println("") //: Your turn! Can you edit the variables **result1** and **result2** so that the sentence is correct? //: **Hint for result1**: squaring is the same as multiplying something by itself. var var1 : Int = 5 var result1 : Int = var1 + var1 // THIS IS WRONG! Please fix it. println("I know that the square of \(var1) is \(result1)!") println("") //: **Hint for result2**: * is multiply, / is divide. var var2 : Double = 4.0 var var3 : Double = 5.0 var result2 = var2 * var3 // THIS IS WRONG! Please fix it. println("My maths skills say that \(var2) divided by \(var3) is equal to \(result2)!")
10cdd7dfd0127150dcc011fe71666908
27.409091
103
0.6296
false
false
false
false
googlemaps/last-mile-fleet-solution-samples
refs/heads/main
ios_driverapp_samples/LMFSDriverSampleApp/Services/NetworkServiceManager.swift
apache-2.0
1
/* * Copyright 2022 Google LLC. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import Combine import Foundation /// This protocol defines an interface for obtaining publishers for network data operations. protocol NetworkManagerSession { /// The type of the objects that the publisher(for:) method returns. This is aligned with /// URLSession.DataTaskPublisher since that's a common production implementation. typealias Publisher = AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure> /// Returns an publisher for the given URLRequest. func publisher(for: URLRequest) -> Publisher } /// The production implementation of NetworkManagerSession is created by extending URLSession to /// implement the protocol. extension URLSession: NetworkManagerSession { func publisher(for request: URLRequest) -> NetworkManagerSession.Publisher { return self.dataTaskPublisher(for: request).eraseToAnyPublisher() } } /// The class that manages communication with the backend. class NetworkServiceManager: ObservableObject { /// Pending manifest get requests. private var pendingManifestFetches = InMemoryRequestTracker<String>() /// The identifier for a task update request is the final state of the task after the update. private struct TaskUpdateIdentifier: Hashable { let taskId: String let outcome: ModelData.Task.Outcome } /// Pending task update requests. private var pendingTaskUpdates = InMemoryRequestTracker<TaskUpdateIdentifier>() /// The identifier for a stop update request is the final state of the stop after the update. private struct StopUpdateIdentifier: Hashable { let newState: ModelData.StopState? let stopIds: [String] } /// Pending stop update requests. /// /// We limit the number of outstanding stop requests to one, because subsequent stop requests /// should always incorporate the result of preceding requests: Stop states can only go in a /// certain order, and the remaining stop IDs list should only ever get shorter. By only keeping /// a single outstanding stop update, we don't have to worry about stop updates being applied /// out-of-order on the backend. private var pendingStopUpdates = InMemoryRequestTracker<StopUpdateIdentifier>(requestLimit: 1) /// The properties below are published for the sake of diagnostic/debugging views. /// The error, if any, from the most recent attempt to update tasks. @Published var taskUpdateLatestError: Error? @Published var taskUpdatesCompleted = 0 @Published var taskUpdatesFailed = 0 /// A status string for the most recent attempt to fetch a manifest. @Published var manifestFetchStatus = "Uninitialized" /// A status string for the most recent attempt to update tasks. @Published var taskUpdateStatus = "Uninitialized" /// A status string for the most recent attempt to update stops. @Published var stopUpdateStatus = "None" /// Sends a request to update the outcome of the given task. /// - Parameter task: The task whose outcome should be updated. /// - Parameter updateCompletion: A block which will be invoked when the update completes or fails. public func updateTask(task: ModelData.Task, updateCompletion: os_block_t? = nil) { let taskId = task.taskInfo.taskId let outcomeValue: String switch task.outcome { case .pending: return case .completed: outcomeValue = "SUCCEEDED" case .couldNotComplete: outcomeValue = "FAILED" } do { var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/task/\(taskId)" var request = URLRequest(url: components.url!) request.httpMethod = "POST" let requestBody = ["task_outcome": outcomeValue] request.httpBody = try JSONEncoder().encode(requestBody) let taskUpdateIdentifier = TaskUpdateIdentifier(taskId: taskId, outcome: task.outcome) let taskUpdateCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .finished: self.taskUpdateLatestError = nil case .failure(let error): self.taskUpdateLatestError = error self.taskUpdatesFailed += 1 } self.taskUpdatesCompleted += 1 self.pendingTaskUpdates.completed(identifier: taskUpdateIdentifier) updateCompletion?(); }, receiveValue: { _ in }) self.pendingTaskUpdates.started( identifier: taskUpdateIdentifier, cancellable: taskUpdateCancellable) } catch { taskUpdateLatestError = error let errorDesc = "Error encoding json: \(error)" self.taskUpdateStatus = errorDesc updateCompletion?(); } } /// Attempts to fetch a new manifest from the backend. /// /// - Parameters: /// - clientId: This client's persistent ID string. /// - vehicleId: Specifies the ID of the vehicle to fetch. If nil, the next available vehicle /// will be fetched. /// - completion: This will be called exactly once with the new manifest or nil. public func fetchManifest( clientId: String, vehicleId: String?, fetchCompletion: @escaping (Manifest?) -> Void ) { manifestFetchStatus = "waiting for response" var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/manifest/\(vehicleId ?? "")" var request = URLRequest(url: components.url!) request.httpMethod = "POST" let requestBody = ["client_id": clientId] do { request.httpBody = try JSONEncoder().encode(requestBody) } catch { self.manifestFetchStatus = "Error encoding json: \(error)" fetchCompletion(nil) } let manifestFetchCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .failure(let error): self.manifestFetchStatus = "Error: \(String(describing: error))" fetchCompletion(nil) case .finished: self.manifestFetchStatus = "Success" } self.pendingManifestFetches.completed(identifier: clientId) }, receiveValue: { urlResponse in do { if let httpResponse = urlResponse.response as? HTTPURLResponse { if httpResponse.statusCode != 200 { let responseCodeString = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode) let dataString = String(decoding: urlResponse.data, as: UTF8.self) self.manifestFetchStatus = "Status \(responseCodeString) Response: \(dataString)" fetchCompletion(nil) return } } let newManifest = try Manifest.loadFrom(data: urlResponse.data) self.manifestFetchStatus = "Success" fetchCompletion(newManifest) } catch { let dataString = String(decoding: urlResponse.data, as: UTF8.self) let errorDesc = "Error parsing output: \(error) data: \(dataString)" self.manifestFetchStatus = errorDesc fetchCompletion(nil) } } ) self.pendingManifestFetches.started( identifier: clientId, cancellable: manifestFetchCancellable) } /// Sends a request to update the current stop's state and/or the list of remaining stops. /// - Parameters: /// - vehicleId: The vehicle ID for the currently loaded manifest. /// - newStopState: The new state of the current stop. /// - stops: The new list of remaining stops in this manifest. public func updateStops( vehicleId: String, newStopState: ModelData.StopState? = nil, stops: [ModelData.Stop], updateCompletion: os_block_t? = nil ) { let newStopIds = stops.filter { $0.taskStatus == .pending }.map { $0.stopInfo.id } let stopUpdateIdentifier = StopUpdateIdentifier(newState: newStopState, stopIds: newStopIds) var components = URLComponents(url: NetworkServiceManager.backendBaseURL(), resolvingAgainstBaseURL: false)! components.path = "/manifest/\(vehicleId)" var request = URLRequest(url: components.url!) request.httpMethod = "POST" var requestBody: [String: Any] = [:] if let newStopStateValue = newStopState { requestBody["current_stop_state"] = newStopStateValue.rawValue } requestBody["remaining_stop_id_list"] = newStopIds do { request.httpBody = try JSONSerialization.data( withJSONObject: requestBody, options: JSONSerialization.WritingOptions() ) as Data } catch { self.stopUpdateStatus = "Error encoding json: \(error)" } self.stopUpdateStatus = "Pending" let stopUpdateCancellable = session .publisher(for: request) .receive(on: RunLoop.main) .sink( receiveCompletion: { completion in switch completion { case .failure(let error): self.stopUpdateStatus = "Error: \(String(describing: error))" case .finished: self.stopUpdateStatus = "Success" } self.pendingStopUpdates.completed(identifier: stopUpdateIdentifier) updateCompletion?() }, receiveValue: { _ in }) self.pendingStopUpdates.started( identifier: stopUpdateIdentifier, cancellable: stopUpdateCancellable) } private var session: NetworkManagerSession /// Creates a new NetworkServiceManager. /// - Parameter session: The NetworkManagerSession to use for HTTP requests. init(session: NetworkManagerSession = URLSession.shared) { self.session = session // This can't be done in the property initialization because self must be available. pendingManifestFetches.errorHandler = self.manifestTrackingError pendingTaskUpdates.errorHandler = self.taskUpdateTrackingError pendingStopUpdates.errorHandler = self.stopUpdateTrackingError } /// The base URL for the backend from defaults. static func backendBaseURL() -> URL { // The backend URL may be updated while the app is running, so always re-read from defaults. return URL(string: ApplicationDefaults.backendBaseURLString.value)! } private func manifestTrackingError(error: RequestTrackingError) { // The tracker calls back on an arbitrary queue, so dispatch to main queue before updating UI. DispatchQueue.main.async { self.manifestFetchStatus = String(describing: error) } } private func taskUpdateTrackingError(error: RequestTrackingError) { DispatchQueue.main.async { self.taskUpdateStatus = String(describing: error) } } private func stopUpdateTrackingError(error: RequestTrackingError) { DispatchQueue.main.async { self.stopUpdateStatus = String(describing: error) } } }
b602966ddf000fc3519aa8f77b373bcf
38.898305
101
0.682753
false
false
false
false
IngmarStein/swift
refs/heads/master
test/type/self.swift
apache-2.0
10
// RUN: %target-parse-verify-swift struct S0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'S0'?}}{{21-25=S0}} } class C0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'C0'?}}{{21-25=C0}} } enum E0<T> { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'E0'?}}{{21-25=E0}} } // rdar://problem/21745221 struct X { typealias T = Int } extension X { struct Inner { } } extension X.Inner { func foo(_ other: Self) { } // expected-error{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'Inner'?}}{{21-25=Inner}} }
1cfe31f273bfff26e5bd011f35556906
30.925926
167
0.647332
false
false
false
false
ZB0106/MCSXY
refs/heads/master
MCSXY/MCSXY/Root/MCAPPRoot.swift
mit
1
// // MCAPPRoot.swift // MCSXY // // Created by 瞄财网 on 2017/6/16. // Copyright © 2017年 瞄财网. All rights reserved. // import UIKit import Foundation class MCAPPRoot: NSObject { public class func setRootViewController(window:UIWindow) -> Void{ UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true) let locaVersion :String? = RHUserDefaults.objectForKey(key: LocalVersion) as? String let appVersion :String = RHUserDefaults .currentAppVersion()! UITableView .appearance() let isInstall:Bool = appVersion == locaVersion sleep(UInt32(1.5)) let tab : MCTabBarController = MCTabBarController() let nav : MCNavigationController = MCNavigationController.init(rootViewController:tab) if !isInstall { window.rootViewController = MCGuideController.init(images: ["guidePage1", "guidePage2", "guidePage3"], enter: { RHUserDefaults .setObject(value: appVersion, key: LocalVersion) window.rootViewController = nav }) UIApplication.shared.isStatusBarHidden = true } else { window.rootViewController = nav } window.makeKeyAndVisible() } }
87d900099f9c002ea93dcfc0964a25c2
30.682927
124
0.639723
false
false
false
false
robertzhang/Enterprise-Phone
refs/heads/master
EP/LoginViewController.swift
mit
1
// // LoginViewController.swift // EP // // Created by robertzhang on 27/9/15. // Copyright (c) 2015年 [email protected]. All rights reserved. // import UIKit import SwiftyJSON class LoginViewController: UIViewController , UITextFieldDelegate{ @IBOutlet weak var userTextField: ElasticTextField! @IBOutlet weak var passwordTextField: ElasticTextField! @IBOutlet weak var goto: UIButton! override func viewDidLoad() { super.viewDidLoad() // 给viewcontroller的view添加一个点击事件,用于关闭键盘 self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("backgroundTap"))) // 确定按钮的颜色 goto.backgroundColor = UIColor(red: 30.0/255.0, green: 144.0/255.0, blue: 205.0/255.0, alpha: 0.7) // userTextField.keyboardType = UIKeyboardType.Default userTextField.returnKeyType = UIReturnKeyType.Next userTextField.borderStyle = UITextBorderStyle.RoundedRect userTextField.delegate = self // passwordTextField.keyboardType = UIKeyboardType.Default passwordTextField.returnKeyType = UIReturnKeyType.Done passwordTextField.borderStyle = UITextBorderStyle.RoundedRect passwordTextField.delegate = self goto.addTarget(self, action: "pressed", forControlEvents: UIControlEvents.TouchUpInside) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // #mark textField delegate begin ----- func textFieldShouldReturn(textField: UITextField) -> Bool{ UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) let rect = CGRectMake(0.0,20.0,self.view.frame.size.width,self.view.frame.size.height) self.view.frame = rect UIView.commitAnimations() textField.resignFirstResponder() return true } func textFieldDidBeginEditing(textField: UITextField) { var frame = textField.frame let offset = CGFloat(-35.0) UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) let width = self.view.frame.size.width let height = self.view.frame.size.height let rect = CGRectMake(0.0, offset, width, height) self.view.frame = rect NSLog("---\(self.view.frame.origin.y)---\(self.view.frame.size.height)--\(offset)") UIView.commitAnimations() } func textFieldDidEndEditing(textField: UITextField) { self.view.frame = CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height) } // #mark textField delegate end ----- func backgroundTap() { if self.view.frame.origin.y < 0 { UIView.beginAnimations("ResizeForKeyboard", context: nil) UIView.setAnimationDuration(0.30) var rect = CGRectMake(0.0,20.0,self.view.frame.size.width,self.view.frame.size.height) self.view.frame = rect UIView.commitAnimations() } userTextField.resignFirstResponder() passwordTextField.resignFirstResponder() } var alert:UIAlertView? func pressed() { alert = UIAlertView(title: "正在登陆", message: "正在登陆请稍候...", delegate: nil, cancelButtonTitle: nil) let activity = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activity.center = CGPointMake(alert!.bounds.size.width / 2.0, alert!.bounds.size.height-40.0) activity.startAnimating() alert!.addSubview(activity) alert!.show() self.view.addSubview(activity) guard let jsonData = NSData.dataFromJSONFile("enterprise") else { return } let jsonObject = JSON(data: jsonData) if ContactsCompany.sharedInstance.parseJSON(jsonObject.object as! Dictionary) {//解析json数据 FMDBHelper.shareInstance().deleteAllDBData() FMDBHelper.shareInstance().insert(ContactsCompany.sharedInstance._organization!, groups: ContactsCompany.sharedInstance._groups, users: ContactsCompany.sharedInstance._users) } else { FMDBHelper.shareInstance().query() } //计时器模仿登陆效果 NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "closeAlert", userInfo: nil, repeats: false) } func closeAlert() { alert!.dismissWithClickedButtonIndex(0, animated: false) //关闭alert view self.performSegueWithIdentifier("second", sender: self) } }
d75941d615c0f452c18685554bc750f7
36.48
186
0.661686
false
false
false
false
zisko/swift
refs/heads/master
stdlib/public/core/ValidUTF8Buffer.swift
apache-2.0
1
//===--- ValidUTF8Buffer.swift - Bounded Collection of Valid UTF-8 --------===// // // 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 // //===----------------------------------------------------------------------===// // // Stores valid UTF8 inside an unsigned integer. // // Actually this basic type could be used to store any UInt8s that cannot be // 0xFF // //===----------------------------------------------------------------------===// @_fixed_layout public struct _ValidUTF8Buffer<Storage: UnsignedInteger & FixedWidthInteger> { public typealias Element = Unicode.UTF8.CodeUnit internal typealias _Storage = Storage @_versioned internal var _biasedBits: Storage @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits } @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_containing e: Element) { _sanityCheck( e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte") _biasedBits = Storage(truncatingIfNeeded: e &+ 1) } } extension _ValidUTF8Buffer : Sequence { public typealias SubSequence = Slice<_ValidUTF8Buffer> @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator : IteratorProtocol, Sequence { @_inlineable // FIXME(sil-serialize-all) public init(_ x: _ValidUTF8Buffer) { _biasedBits = x._biasedBits } @_inlineable // FIXME(sil-serialize-all) public mutating func next() -> Element? { if _biasedBits == 0 { return nil } defer { _biasedBits >>= 8 } return Element(truncatingIfNeeded: _biasedBits) &- 1 } @_versioned // FIXME(sil-serialize-all) internal var _biasedBits: Storage } @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(self) } } extension _ValidUTF8Buffer : Collection { @_fixed_layout // FIXME(sil-serialize-all) public struct Index : Comparable { @_versioned internal var _biasedBits: Storage @_inlineable // FIXME(sil-serialize-all) @_versioned internal init(_biasedBits: Storage) { self._biasedBits = _biasedBits } @_inlineable // FIXME(sil-serialize-all) public static func == (lhs: Index, rhs: Index) -> Bool { return lhs._biasedBits == rhs._biasedBits } @_inlineable // FIXME(sil-serialize-all) public static func < (lhs: Index, rhs: Index) -> Bool { return lhs._biasedBits > rhs._biasedBits } } @_inlineable // FIXME(sil-serialize-all) public var startIndex : Index { return Index(_biasedBits: _biasedBits) } @_inlineable // FIXME(sil-serialize-all) public var endIndex : Index { return Index(_biasedBits: 0) } @_inlineable // FIXME(sil-serialize-all) public var count : Int { return Storage.bitWidth &>> 3 &- _biasedBits.leadingZeroBitCount &>> 3 } @_inlineable // FIXME(sil-serialize-all) public var isEmpty : Bool { return _biasedBits == 0 } @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { _debugPrecondition(i._biasedBits != 0) return Index(_biasedBits: i._biasedBits >> 8) } @_inlineable // FIXME(sil-serialize-all) public subscript(i: Index) -> Element { return Element(truncatingIfNeeded: i._biasedBits) &- 1 } } extension _ValidUTF8Buffer : BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { let offset = _ValidUTF8Buffer(_biasedBits: i._biasedBits).count _debugPrecondition(offset != 0) return Index(_biasedBits: _biasedBits &>> (offset &<< 3 - 8)) } } extension _ValidUTF8Buffer : RandomAccessCollection { public typealias Indices = DefaultIndices<_ValidUTF8Buffer> @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func distance(from i: Index, to j: Index) -> Int { _debugPrecondition(_isValid(i)) _debugPrecondition(_isValid(j)) return ( i._biasedBits.leadingZeroBitCount - j._biasedBits.leadingZeroBitCount ) &>> 3 } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { let startOffset = distance(from: startIndex, to: i) let newOffset = startOffset + n _debugPrecondition(newOffset >= 0) _debugPrecondition(newOffset <= count) return Index(_biasedBits: _biasedBits._fullShiftRight(newOffset &<< 3)) } } extension _ValidUTF8Buffer : RangeReplaceableCollection { @_inlineable // FIXME(sil-serialize-all) public init() { _biasedBits = 0 } @_inlineable // FIXME(sil-serialize-all) public var capacity: Int { return _ValidUTF8Buffer.capacity } @_inlineable // FIXME(sil-serialize-all) public static var capacity: Int { return Storage.bitWidth / Element.bitWidth } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func append(_ e: Element) { _debugPrecondition(count + 1 <= capacity) _sanityCheck( e != 192 && e != 193 && !(245...255).contains(e), "invalid UTF8 byte") _biasedBits |= Storage(e &+ 1) &<< (count &<< 3) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) @discardableResult public mutating func removeFirst() -> Element { _debugPrecondition(!isEmpty) let result = Element(truncatingIfNeeded: _biasedBits) &- 1 _biasedBits = _biasedBits._fullShiftRight(8) return result } @_inlineable // FIXME(sil-serialize-all) @_versioned internal func _isValid(_ i: Index) -> Bool { return i == endIndex || indices.contains(i) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func replaceSubrange<C: Collection>( _ target: Range<Index>, with replacement: C ) where C.Element == Element { _debugPrecondition(_isValid(target.lowerBound)) _debugPrecondition(_isValid(target.upperBound)) var r = _ValidUTF8Buffer() for x in self[..<target.lowerBound] { r.append(x) } for x in replacement { r.append(x) } for x in self[target.upperBound...] { r.append(x) } self = r } } extension _ValidUTF8Buffer { @_inlineable // FIXME(sil-serialize-all) @inline(__always) public mutating func append<T>(contentsOf other: _ValidUTF8Buffer<T>) { _debugPrecondition(count + other.count <= capacity) _biasedBits |= Storage( truncatingIfNeeded: other._biasedBits) &<< (count &<< 3) } } extension _ValidUTF8Buffer { @_inlineable // FIXME(sil-serialize-all) public static var encodedReplacementCharacter : _ValidUTF8Buffer { return _ValidUTF8Buffer(_biasedBits: 0xBD_BF_EF &+ 0x01_01_01) } }
b3f2fa7f34432598400bce9b6b97b9dd
30.09375
80
0.655276
false
false
false
false
chaserCN/Action
refs/heads/master
Action.swift
mit
1
import Foundation import RxSwift import RxCocoa /// Typealias for compatibility with UIButton's rx_action property. public typealias CocoaAction = Action<Void, Void> /// Possible errors from invoking execute() public enum ActionError: ErrorType { case NotEnabled case UnderlyingError(ErrorType) } /// TODO: Add some documentation. public final class Action<Input, Element> { public typealias WorkFactory = Input -> Observable<Element> public let _enabledIf: Observable<Bool> public let workFactory: WorkFactory /// Errors aggrevated from invocations of execute(). /// Delivered on whatever scheduler they were sent from. public var errors: Observable<ActionError> { return self._errors.asObservable() } private let _errors = PublishSubject<ActionError>() /// Whether or not we're currently executing. /// Delivered on whatever scheduler they were sent from. public var elements: Observable<Element> { return self._elements.asObservable() } private let _elements = PublishSubject<Element>() /// Whether or not we're currently executing. /// Always observed on MainScheduler. public var executing: Observable<Bool> { return self._executing.asObservable().observeOn(MainScheduler.instance) } private let _executing = Variable(false) /// Whether or not we're enabled. Note that this is a *computed* sequence /// property based on enabledIf initializer and if we're currently executing. /// Always observed on MainScheduler. public var enabled: Observable<Bool> { return _enabled.asObservable().observeOn(MainScheduler.instance) } public private(set) var _enabled = BehaviorSubject(value: true) private let executingQueue = dispatch_queue_create("com.ashfurrow.Action.executingQueue", DISPATCH_QUEUE_SERIAL) private let disposeBag = DisposeBag() public init<B: BooleanType>(enabledIf: Observable<B>, workFactory: WorkFactory) { self._enabledIf = enabledIf.map { booleanType in return booleanType.boolValue } self.workFactory = workFactory Observable.combineLatest(self._enabledIf, self.executing) { (enabled, executing) -> Bool in return enabled && !executing }.bindTo(_enabled).addDisposableTo(disposeBag) } } // MARK: Convenience initializers. public extension Action { /// Always enabled. public convenience init(workFactory: WorkFactory) { self.init(enabledIf: .just(true), workFactory: workFactory) } } // MARK: Execution! public extension Action { public func execute(input: Input) -> Observable<Element> { // Buffer from the work to a replay subject. let buffer = ReplaySubject<Element>.createUnbounded() // See if we're already executing. var startedExecuting = false self.doLocked { if self._enabled.valueOrFalse { self._executing.value = true startedExecuting = true } } // Make sure we started executing and we're accidentally disabled. guard startedExecuting else { let error = ActionError.NotEnabled self._errors.onNext(error) buffer.onError(error) return buffer } let work = self.workFactory(input) defer { // Subscribe to the work. work.multicast(buffer).connect().addDisposableTo(disposeBag) } buffer.subscribe(onNext: {[weak self] element in self?._elements.onNext(element) }, onError: {[weak self] error in self?._errors.onNext(ActionError.UnderlyingError(error)) }, onCompleted: nil, onDisposed: {[weak self] in self?.doLocked { self?._executing.value = false } }) .addDisposableTo(disposeBag) return buffer.asObservable() } } private extension Action { private func doLocked(closure: () -> Void) { dispatch_sync(executingQueue, closure) } } internal extension BehaviorSubject where Element: BooleanLiteralConvertible { var valueOrFalse: Element { guard let value = try? value() else { return false } return value } }
48d71364764c09ea1e4773d251c713e4
31.244444
116
0.648518
false
false
false
false
nearfri/Strix
refs/heads/main
Sources/StrixParsers/CSVParser.swift
mit
1
import Foundation import Strix public typealias CSV = [[String]] public struct CSVParser { private let parser: Parser<CSV> public init() { let ws = Parser.many(.whitespace) parser = ws *> Parser.csv <* ws <* .endOfStream } public func parse(_ csvString: String) throws -> CSV { return try parser.run(csvString) } public func callAsFunction(_ csvString: String) throws -> CSV { return try parse(csvString) } } extension Parser where T == CSV { public static var csv: Parser<CSV> { CSVParserGenerator().csv } } private struct CSVParserGenerator { var csv: Parser<CSV> { Parser.many(record, separatedBy: .newline).map({ fixCSV($0) }) } private var record: Parser<[String]> { .many(field, separatedBy: .character(",")) } private var field: Parser<String> { escapedField <|> nonEscapedField } private var escapedField: Parser<String> { doubleQuote *> escapedText <* doubleQuote } private var escapedText: Parser<String> { return Parser.many((.none(of: "\"") <|> twoDoubleQuote)).map({ String($0) }) } private let doubleQuote: Parser<Character> = .character("\"") private let twoDoubleQuote: Parser<Character> = Parser.string("\"\"") *> .just("\"") private var nonEscapedField: Parser<String> { .skipped(by: .many(nonSeparator)) } private let nonSeparator: Parser<Character> = .satisfy({ $0 != "," && !$0.isNewline }, label: "non-separator") } private func fixCSV(_ csv: CSV) -> CSV { var csv = csv if let lastValidRecordIndex = csv.lastIndex(where: { $0 != [""] }) { let invalidRecordIndex = lastValidRecordIndex + 1 csv.removeSubrange(invalidRecordIndex...) } else { csv.removeAll() } return csv }
c78d71fc1935fb841c104ea8b26f0b79
31.614035
91
0.60893
false
false
false
false
cornerstonecollege/401
refs/heads/master
olderFiles/boyoung_chae/Swift/Introduction of Swift.playground/Contents.swift
gpl-3.0
1
//: Playground - noun: a place where people can play import Foundation var str = "Hello, playground" str = "Hi 2" // It is ok to change the value! str = str.appending("a") print(str) let j:Int j = 1 // J = 2 // It si not going to work because j is a constant. print(j); var studentName:String? studentName = nil studentName = "Chris" studentName = "Bo Young" print(studentName) // Wrapped value print(studentName!) // Unwrapped value. I know that the value is not nil. print(studentName?.appending("a")) // Unwrapped value if studentName is not nil. print(studentName!.appending("a")) // Unwrapped value (we know that it is not nil.) // Functions work just like Objective-C. //[Object print:@"aaa" second:@"bbb" third:@ccc"]; print("Hey", "Hi", "Hello", separator: " ", terminator: ".\n") /* Wrong - It's not Bollean. It's Ingeger. if 1 { } */ // Right - The if needs a boolean value unlike C and Objective-C. if 1 == 1 { } if str == "Luiz" { print("str equals to Luiz.") } else { print("str is not equals to Luiz.") } let alwaysTrue = true while alwaysTrue { // Infinite loop print("hi") break // It will excute the loop only once. } let checkCondition = 1 > 2 // boolean value repeat { // run at least once even though the condition is false. print("It will run only once") } while (checkCondition) // for (int i = 1 ; i <=10 ; i++) for i in 1...10 { // 1,2,3,4,5,6,7,8,9,10 print(i) } // for (int i = 1 ; i < 10 ; i++) for i in 1..<10 { // 1,2,3,4,5,6,7,8,9 print(i) } var string = String() // new regular string var arr = [String]() // new array of strings //var arr:[String] = [String]() arr.append("a") // addObject arr.append("b") print(arr[1]) // print letter "b" for string in arr { print("The string is \(string) \(1 + 2)") } let arrStrings = ["a", "b", "123", "567"] print(arrStrings) for (index, value) in arrStrings.enumerated() { print("The index: \(index) contains the value: \(value)"); } var x = 1 true.description // true is object. 1.description // 1 is object. // ==> Everything is an object. 1.description == "2" // REPL - Rean, Evaluate, Print and Loop var dictionary = [ "object1" : "table", "object2" : "fridge" ] print(dictionary["object1"]) print(dictionary["object1"]!) var dictionaryElements = [String:Int]() dictionaryElements.updateValue(1, forKey: "DS") var dictionaryElements2:[String:Int] = ["DS1":1, "DS2":2, "DS3":3] //dictionaryElements2.removeValue(forKey: "DS3") for (key, value) in dictionaryElements2 { print("The key is \(key) and the value is \(value)") } dictionaryElements2["DS4"] = 4 dictionaryElements2 print("\n") print("=== Exercise1: Array ===") let array1 = ["String1", "String2", "String3"] var array2 = array1 //array2.append("String1") //array2.append("String2") //array2.append("String3") array2.append("String4") array2.append("String5") print("The first value is \(array2[0])."); print("The fifth value is \(array2[4])."); print("\n") print("=== Exercise2: Dictionary ===") var storeDictionary = [String:String]() storeDictionary.updateValue("table", forKey: "object1") storeDictionary.updateValue("fridge", forKey: "object2") storeDictionary.updateValue("WallMart", forKey: "storeName") storeDictionary.updateValue("123 Fake St", forKey: "address") print("The store \(storeDictionary["storeName"]!) in \(storeDictionary["address"]!) is selling \(storeDictionary["object1"]!) and \(storeDictionary["object2"]!).") print("\n") var str1 = "1234" let intFromStr = Int(str1) print(intFromStr) print(intFromStr!)
10130486ca741064dcc760b7932db7cf
22.134615
163
0.650596
false
false
false
false
MrAlek/Swiftalytics
refs/heads/master
Source/Swiftalytics.swift
mit
1
// // Swiftalytics.swift // // Created by Alek Åström on 2015-02-14. // Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public enum TrackingNameType { case navigationTitle } private let storage = SWAClassBlockStorage() public func setTrackingName<T: UIViewController>(for viewController: T.Type, name: @autoclosure () -> String) { let n = name() setTrackingName(for: viewController) {_ in n} } public func setTrackingName<T: UIViewController>(for viewController: T.Type, trackingType: TrackingNameType) { switch trackingType { case .navigationTitle: setTrackingName(for: viewController) { vc in if let title = vc.navigationItem.title { return title } let className = String(describing: type(of: vc)) print("Swiftalytics: View Controller \(className) missing navigation item title") return className } } } public func setTrackingName<T: UIViewController>(for viewController: T.Type, nameFunction: @escaping ((T) -> String)) { let block: MapBlock = { vc in nameFunction(vc as! T) } storage.setBlock(block, forClass: T.value(forKey: "self")!) } public func setTrackingName<T: UIViewController>(for curriedNameFunction: @escaping (T) -> () -> String) { let block: MapBlock = { vc in curriedNameFunction(vc as! T)() } storage.setBlock(block, forClass:T.value(forKey: "self")!) } public func trackingName<T: UIViewController>(for viewController: T) -> String? { return storage.block(forClass: viewController.value(forKey: "class")!)?(viewController) as! String? } public func clearTrackingNames() { storage.removeAllBlocks() } public func removeTrackingForViewController<T: UIViewController>(_: T.Type) { storage.removeBlock(forClass: T.value(forKey: "self")!) }
d401be0ecb99f0e4919af14895b1b75c
39.054795
119
0.716826
false
false
false
false
lanjing99/iOSByTutorials
refs/heads/master
iOS Animations by Tutorials 2.0_iOS_9_Swift_2/Chapter 04 - View Animations in Practice/FlightInfo-Starter/Flight Info/SnowView.swift
mit
1
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import QuartzCore class SnowView: UIView { override init(frame: CGRect) { super.init(frame: frame) let emitter = layer as! CAEmitterLayer emitter.emitterPosition = CGPoint(x: bounds.size.width / 2, y: 0) emitter.emitterSize = bounds.size emitter.emitterShape = kCAEmitterLayerRectangle let emitterCell = CAEmitterCell() emitterCell.contents = UIImage(named: "flake.png")!.CGImage emitterCell.birthRate = 200 emitterCell.lifetime = 3.5 emitterCell.color = UIColor.whiteColor().CGColor emitterCell.redRange = 0.0 emitterCell.blueRange = 0.1 emitterCell.greenRange = 0.0 emitterCell.velocity = 10 emitterCell.velocityRange = 350 emitterCell.emissionRange = CGFloat(M_PI_2) emitterCell.emissionLongitude = CGFloat(-M_PI) emitterCell.yAcceleration = 70 emitterCell.xAcceleration = 0 emitterCell.scale = 0.33 emitterCell.scaleRange = 1.25 emitterCell.scaleSpeed = -0.25 emitterCell.alphaRange = 0.5 emitterCell.alphaSpeed = -0.15 emitter.emitterCells = [emitterCell] } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override class func layerClass() -> AnyClass { return CAEmitterLayer.self } }
d27a7d988f783f49a91921128f9d7a2e
34.746269
79
0.734447
false
false
false
false
akane/Gaikan
refs/heads/master
Gaikan/Style/StyleRule.swift
mit
1
// // This file is part of Gaikan // // Created by JC on 30/08/15. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation /** * Defines design properties with their values. */ public struct StyleRule : ExpressibleByDictionaryLiteral { public typealias Key = Property public typealias Value = Any? var attributes : Dictionary<Key, Value> public init(attributes: [Key:Value]) { self.attributes = attributes } public init(dictionaryLiteral elements: (Key, Value)...) { var attributes = Dictionary<Key, Value>() for (attributeName, attributeValue) in elements { attributes[attributeName] = attributeValue } self.attributes = attributes } public init(_ styleBlock: (_ style: inout StyleRule) -> ()) { self.init(attributes: [:]) styleBlock(&self) } public func extends(_ styles: StyleRule?...) -> StyleRule { var composedAttributes: [Key:Value] = [:] for style in styles { if let styleAttributes = style?.attributes { composedAttributes.gaikan_merge(styleAttributes) } } return StyleRule(attributes: composedAttributes.gaikan_merge(self.attributes)) } subscript(keyname: Property) -> Value { get { return self.attributes[keyname] != nil ? self.attributes[keyname]! : nil } } } extension StyleRule { public var textAttributes: [String:AnyObject] { let attributes: [String:AnyObject?] = [ NSForegroundColorAttributeName: self.color, NSFontAttributeName: self.font, NSShadowAttributeName: self.textShadow ] return attributes.trimmed() } }
8305852f5fa3bac359c7c439a5cde9b4
26
88
0.636263
false
false
false
false
ppamorim/CrazyAutomaticDimension
refs/heads/master
UITableView-AutomaticDimension/ViewController.swift
apache-2.0
1
/* * Copyright (C) 2016 Pedro Paulo de Amorim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import PureLayout class ViewController: UIViewController { var didUpdateViews = false var secondState = false var alternativeType = false var comments : NSMutableArray? = NSMutableArray() var videoPinEdgeLeftConstraint : NSLayoutConstraint? var videoPinEdgeRightConstraint : NSLayoutConstraint? var videoPinEdgeTopConstraint : NSLayoutConstraint? var videoPinEdgeBottomConstraint : NSLayoutConstraint? var videoPaddingConstraint : NSLayoutConstraint? let container : UIView = { let container = UIView.newAutoLayoutView() return container }() let commentsTableView : UITableView = { let commentsTableView = UITableView.newAutoLayoutView() commentsTableView.registerClass(ChatViewCell.self, forCellReuseIdentifier: "ChatViewCell") commentsTableView.separatorStyle = .None commentsTableView.backgroundColor = UIColor.grayColor() return commentsTableView }() deinit { self.commentsTableView.dataSource = nil self.commentsTableView.delegate = nil } override func loadView() { super.loadView() configTableview() container.addSubview(commentsTableView) self.view.addSubview(container) view.setNeedsUpdateConstraints() } override func updateViewConstraints() { if !didUpdateViews { commentsTableView.autoPinEdgesToSuperviewEdges() didUpdateViews = true } videoPinEdgeLeftConstraint?.autoRemove() videoPinEdgeRightConstraint?.autoRemove() videoPinEdgeTopConstraint?.autoRemove() videoPinEdgeBottomConstraint?.autoRemove() if(!secondState) { videoPinEdgeLeftConstraint = container.autoPinEdgeToSuperviewEdge(.Left) videoPinEdgeRightConstraint = container.autoPinEdgeToSuperviewEdge(.Right) videoPinEdgeTopConstraint = container.autoMatchDimension( .Height, toDimension: .Width, ofView: self.view, withMultiplier: 0.57) videoPinEdgeBottomConstraint = container.autoPinEdgeToSuperviewEdge(.Top, withInset: 0.0) } else { videoPinEdgeLeftConstraint = container.autoMatchDimension( .Width, toDimension: .Width, ofView: self.view, withMultiplier: 0.45) videoPinEdgeRightConstraint = container.autoPinEdgeToSuperviewEdge(.Right, withInset: 4.0) videoPinEdgeTopConstraint = container.autoMatchDimension( .Height, toDimension: .Width, ofView: container, withMultiplier: 0.57) videoPinEdgeBottomConstraint = container.autoPinEdge(.Bottom, toEdge: .Bottom, ofView: self.view, withOffset: -4.0) } super.updateViewConstraints() } override func viewDidLoad() { super.viewDidLoad() infiniteChat() toggleContainer() } func configTableview() { commentsTableView.dataSource = self commentsTableView.delegate = self } func infiniteChat() { let seconds = 4.0 let delay = seconds * Double(NSEC_PER_SEC) let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue(), { self.addItem(self.alternativeType ? Comment(userName: "Paulo", comment: "Teste legal") : Comment(userName: "Paulo nervoso", comment: "Texto longo pq eu quero testar essa bagaça que não funciona com AutomaticDimension direito")) self.alternativeType = !self.alternativeType self.infiniteChat() }) } func addItem(comment: Comment) { self.commentsTableView.beginUpdates() if self.comments!.count == 5 { self.commentsTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow : 4, inSection: 0)], withRowAnimation: .Right) comments?.removeObjectAtIndex(4) } self.comments?.insertObject(comment, atIndex: 0) self.commentsTableView.insertRowsAtIndexPaths([NSIndexPath(forRow : 0, inSection: 0)], withRowAnimation: .Right) self.commentsTableView.endUpdates() } func toggleContainer() { if secondState { collapse() } else { expand() } } func expand() { self.secondState = true view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(2, delay: 5.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (completion) in self.toggleContainer() }) } func collapse() { self.secondState = false view.setNeedsUpdateConstraints() view.updateConstraintsIfNeeded() UIView.animateWithDuration(2, delay: 5.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2, options: UIViewAnimationOptions(), animations: { self.view.layoutIfNeeded() }, completion: { (completion) in self.toggleContainer() }) } } extension ViewController : UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if self.comments != nil { (cell as! ChatViewCell).load((self.comments?.objectAtIndex(indexPath.row))! as? Comment) } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } } extension ViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.comments?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return tableView.dequeueReusableCellWithIdentifier("ChatViewCell", forIndexPath: indexPath) as! ChatViewCell } }
7c7efa8819bece980eb6a4d6e950501a
31.581281
233
0.721911
false
false
false
false
mmick66/GradientViewiOS
refs/heads/master
KDGradientView/GradientView.swift
mit
1
// // GradientView.swift // GradientView // // Created by Michael Michailidis on 23/07/2015. // Copyright © 2015 karmadust. All rights reserved. // import UIKit class GradientView: UIView { var lastElementIndex: Int = 0 var colors: Array<UIColor> = [] { didSet { lastElementIndex = colors.count - 1 } } var index: Int = 0 lazy var displayLink : CADisplayLink = { let displayLink : CADisplayLink = CADisplayLink(target: self, selector: "screenUpdated:") displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.paused = true return displayLink }() func animateToNextGradient() { index = (index + 1) % colors.count factor = 0.0 self.displayLink.paused = false } var factor: CGFloat = 1.0 func screenUpdated(displayLink : CADisplayLink) { self.factor += CGFloat(displayLink.duration) if(self.factor > 1.0) { self.displayLink.paused = true } self.setNeedsDisplay() } override func drawRect(rect: CGRect) { if colors.count < 2 { return; } let context = UIGraphicsGetCurrentContext(); CGContextSaveGState(context); let c1 = colors[index == 0 ? lastElementIndex : index - 1] // => previous color from index let c2 = colors[index] // => current color let c3 = colors[index == lastElementIndex ? 0 : index + 1] // => next color var c1Comp = CGColorGetComponents(c1.CGColor) var c2Comp = CGColorGetComponents(c2.CGColor) var c3Comp = CGColorGetComponents(c3.CGColor) var colorComponents = [ c1Comp[0] * (1 - factor) + c2Comp[0] * factor, c1Comp[1] * (1 - factor) + c2Comp[1] * factor, c1Comp[2] * (1 - factor) + c2Comp[2] * factor, c1Comp[3] * (1 - factor) + c2Comp[3] * factor, c2Comp[0] * (1 - factor) + c3Comp[0] * factor, c2Comp[1] * (1 - factor) + c3Comp[1] * factor, c2Comp[2] * (1 - factor) + c3Comp[2] * factor, c2Comp[3] * (1 - factor) + c3Comp[3] * factor ] let gradient = CGGradientCreateWithColorComponents( CGColorSpaceCreateDeviceRGB(), &colorComponents, [0.0, 1.0], 2 ) CGContextDrawLinearGradient( context, gradient, CGPoint(x: 0.0, y: 0.0), CGPoint(x: rect.size.width, y: rect.size.height), 0 ) CGContextRestoreGState(context); } }
580ca38aa92fc6064053baaf80d04584
24.405172
101
0.503902
false
false
false
false
doncl/shortness-of-pants
refs/heads/master
ModalPopup/BaseModalPopup.swift
mit
1
// // BaseModalPopup.swift // BaseModalPopup // // Created by Don Clore on 5/21/18. // Copyright © 2018 Beer Barrel Poker Studios. All rights reserved. // import UIKit enum PointerDirection { case up case down } enum AvatarMode { case leftTopLargeProtruding case leftTopMediumInterior } fileprivate struct AvatarLayoutInfo { var width : CGFloat var offset : CGFloat var constraintsMaker : (UIImageView, UIView, CGFloat, CGFloat) -> () func layout(avatar : UIImageView, popup : UIView) { constraintsMaker(avatar, popup, width, offset) } } class BaseModalPopup: UIViewController { var loaded : Bool = false var presenting : Bool = true static let pointerHeight : CGFloat = 16.0 static let pointerBaseWidth : CGFloat = 24.0 static let horzFudge : CGFloat = 15.0 var origin : CGPoint weak var referenceView : UIView? private var width : CGFloat private var height : CGFloat let popupView : UIView = UIView() let avatar : UIImageView = UIImageView() let pointer : CAShapeLayer = CAShapeLayer() var avatarMode : AvatarMode? var avatarUserId : String? var avatarImage : UIImage? var avatarOffset : CGFloat { var offset : CGFloat = 0 if let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { offset = layoutInfo.offset } return offset } private let avatarModeSizeMap : [AvatarMode : AvatarLayoutInfo] = [ .leftTopLargeProtruding : AvatarLayoutInfo(width: 48.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(-offset) } }), .leftTopMediumInterior : AvatarLayoutInfo(width: 32.0, offset: 16.0, constraintsMaker: { (avatar, popup, width, offset) in avatar.snp.remakeConstraints { make in make.width.equalTo(width) make.height.equalTo(width) make.left.equalTo(popup.snp.left).offset(offset) make.top.equalTo(popup.snp.top).offset(offset) } }) ] required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(origin : CGPoint, referenceView : UIView, size: CGSize, avatarUserId: String? = nil, avatarImage : UIImage?, avatarMode : AvatarMode?) { self.origin = origin self.width = size.width self.height = size.height self.referenceView = referenceView super.init(nibName: nil, bundle: nil) self.avatarMode = avatarMode self.avatarUserId = avatarUserId if let image = avatarImage { self.avatarImage = image.deepCopy() } } override func viewDidLoad() { if loaded { return } loaded = true super.viewDidLoad() if let ref = referenceView { origin = view.convert(origin, from: ref) } view.addSubview(popupView) view.backgroundColor = .clear popupView.backgroundColor = .white popupView.layer.shadowOffset = CGSize(width: 2.0, height: 3.0) popupView.layer.shadowRadius = 5.0 popupView.layer.shadowOpacity = 0.5 popupView.addSubview(avatar) popupView.clipsToBounds = false popupView.layer.masksToBounds = false if let userId = avatarUserId, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { if let image = avatarImage { avatar.image = image.deepCopy() avatar.createRoundedImageView(diameter: layoutInfo.width, borderColor: UIColor.clear) } else { avatar.setAvatarImage(fromId: userId, avatarVersion: nil, diameter: layoutInfo.width, bustCache: false, placeHolderImageURL: nil, useImageProxy: true, completion: nil) } popupView.bringSubview(toFront: avatar) } view.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(BaseModalPopup.tap)) view.addGestureRecognizer(tap) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let tuple = getPopupFrameAndPointerDirection(size: view.frame.size) let popupFrame = tuple.0 let direction = tuple.1 let pointerPath = makePointerPath(direction: direction, popupFrame: popupFrame) pointer.path = pointerPath.cgPath pointer.fillColor = UIColor.white.cgColor pointer.lineWidth = 0.5 pointer.masksToBounds = false popupView.layer.addSublayer(pointer) remakeConstraints(popupFrame) let bounds = UIScreen.main.bounds let width = view.frame.width + avatarOffset if bounds.width < width && width > 0 { let ratio = (bounds.width / width) * 0.9 let xform = CGAffineTransform(scaleX: ratio, y: ratio) popupView.transform = xform } else { popupView.transform = .identity } } private func getPopupFrameAndPointerDirection(size: CGSize) -> (CGRect, PointerDirection) { let y : CGFloat let direction : PointerDirection if origin.y > size.height / 2 { y = origin.y - (height + BaseModalPopup.pointerHeight) direction = .down } else { y = origin.y + BaseModalPopup.pointerHeight direction = .up } var rc : CGRect = CGRect(x: 30.0, y: y, width: width, height: height) let rightmost = rc.origin.x + rc.width let center = rc.center if origin.x > rightmost { let offset = origin.x - center.x rc = rc.offsetBy(dx: offset, dy: 0) } else if origin.x < rc.origin.x { let offset = center.x - origin.x rc = rc.offsetBy(dx: -offset, dy: 0) } let bounds = UIScreen.main.bounds let popupWidth = rc.width + avatarOffset if bounds.width <= popupWidth { rc = CGRect(x: 0, y: rc.origin.y, width: rc.width, height: rc.height) } return (rc, direction) } fileprivate func remakeConstraints(_ popupFrame: CGRect) { popupView.snp.remakeConstraints { make in make.leading.equalTo(view).offset(popupFrame.origin.x) make.top.equalTo(view).offset(popupFrame.origin.y) make.width.equalTo(popupFrame.width) make.height.equalTo(popupFrame.height) } if let _ = avatar.image, let avatarMode = avatarMode, let layoutInfo = avatarModeSizeMap[avatarMode] { layoutInfo.layout(avatar: avatar, popup: popupView) } } private func makePointerPath(direction: PointerDirection, popupFrame : CGRect) -> UIBezierPath { let path = UIBezierPath() path.lineJoinStyle = CGLineJoin.bevel // previous code is supposed to assure that the popupFrame is not outside the origin. assert(popupFrame.origin.x < origin.x && popupFrame.origin.x + popupFrame.width > origin.x) let adjustedX = origin.x - popupFrame.origin.x if direction == .down { let adjustedApex = CGPoint(x: adjustedX, y: popupFrame.height + BaseModalPopup.pointerHeight - 1) path.move(to: adjustedApex) // down is up. let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y - BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } else { let adjustedApex = CGPoint(x: adjustedX, y: -BaseModalPopup.pointerHeight + 1) path.move(to: adjustedApex) let leftBase = CGPoint(x: adjustedApex.x - (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: leftBase) let rightBase = CGPoint(x: adjustedApex.x + (BaseModalPopup.pointerBaseWidth / 2), y: adjustedApex.y + BaseModalPopup.pointerHeight) path.addLine(to: rightBase) path.close() } return path } @objc func tap() { dismiss(animated: true, completion: nil) } } //MARK: - rotation extension BaseModalPopup { override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { dismiss(animated: true, completion: nil) } }
479b890143d8cf5651458d1f0f90e007
31.198556
103
0.641664
false
false
false
false
zirinisp/SlackKit
refs/heads/master
SlackKit/Sources/Client+EventHandling.swift
mit
1
// // Client+EventHandling.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation internal extension Client { //MARK: - Pong func pong(_ event: Event) { pong = event.replyTo } //MARK: - Messages func messageSent(_ event: Event) { guard let reply = event.replyTo, let message = sentMessages[NSNumber(value: reply).stringValue], let channel = message.channel, let ts = message.ts else { return } message.ts = event.ts message.text = event.text channels[channel]?.messages[ts] = message messageEventsDelegate?.sent(message, client: self) } func messageReceived(_ event: Event) { guard let channel = event.channel, let message = event.message, let id = channel.id, let ts = message.ts else { return } channels[id]?.messages[ts] = message messageEventsDelegate?.received(message, client:self) } func messageChanged(_ event: Event) { guard let id = event.channel?.id, let nested = event.nestedMessage, let ts = nested.ts else { return } channels[id]?.messages[ts] = nested messageEventsDelegate?.changed(nested, client:self) } func messageDeleted(_ event: Event) { guard let id = event.channel?.id, let key = event.message?.deletedTs, let message = channels[id]?.messages[key] else { return } _ = channels[id]?.messages.removeValue(forKey: key) messageEventsDelegate?.deleted(message, client:self) } //MARK: - Channels func userTyping(_ event: Event) { guard let channel = event.channel, let channelID = channel.id, let user = event.user, let userID = user.id , channels.index(forKey: channelID) != nil && !channels[channelID]!.usersTyping.contains(userID) else { return } channels[channelID]?.usersTyping.append(userID) channelEventsDelegate?.userTypingIn(channel, user: user, client: self) let timeout = DispatchTime.now() + Double(Int64(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: timeout, execute: { if let index = self.channels[channelID]?.usersTyping.index(of: userID) { self.channels[channelID]?.usersTyping.remove(at: index) } }) } func channelMarked(_ event: Event) { guard let channel = event.channel, let id = channel.id, let timestamp = event.ts else { return } channels[id]?.lastRead = event.ts channelEventsDelegate?.marked(channel, timestamp: timestamp, client: self) } func channelCreated(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id] = channel channelEventsDelegate?.created(channel, client: self) } func channelDeleted(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels.removeValue(forKey: id) channelEventsDelegate?.deleted(channel, client: self) } func channelJoined(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id] = event.channel channelEventsDelegate?.joined(channel, client: self) } func channelLeft(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } if let userID = authenticatedUser?.id, let index = channels[id]?.members?.index(of: userID) { channels[id]?.members?.remove(at: index) } channelEventsDelegate?.left(channel, client: self) } func channelRenamed(_ event: Event) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.name = channel.name channelEventsDelegate?.renamed(channel, client: self) } func channelArchived(_ event: Event, archived: Bool) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.isArchived = archived channelEventsDelegate?.archived(channel, client: self) } func channelHistoryChanged(_ event: Event) { guard let channel = event.channel else { return } channelEventsDelegate?.historyChanged(channel, client: self) } //MARK: - Do Not Disturb func doNotDisturbUpdated(_ event: Event) { guard let dndStatus = event.dndStatus else { return } authenticatedUser?.doNotDisturbStatus = dndStatus doNotDisturbEventsDelegate?.updated(dndStatus, client: self) } func doNotDisturbUserUpdated(_ event: Event) { guard let dndStatus = event.dndStatus, let user = event.user, let id = user.id else { return } users[id]?.doNotDisturbStatus = dndStatus doNotDisturbEventsDelegate?.userUpdated(dndStatus, user: user, client: self) } //MARK: - IM & Group Open/Close func open(_ event: Event, open: Bool) { guard let channel = event.channel, let id = channel.id else { return } channels[id]?.isOpen = open groupEventsDelegate?.opened(channel, client: self) } //MARK: - Files func processFile(_ event: Event) { guard let file = event.file, let id = file.id else { return } if let comment = file.initialComment, let commentID = comment.id { if files[id]?.comments[commentID] == nil { files[id]?.comments[commentID] = comment } } files[id] = file fileEventsDelegate?.processed(file, client: self) } func filePrivate(_ event: Event) { guard let file = event.file, let id = file.id else { return } files[id]?.isPublic = false fileEventsDelegate?.madePrivate(file, client: self) } func deleteFile(_ event: Event) { guard let file = event.file, let id = file.id else { return } if files[id] != nil { files.removeValue(forKey: id) } fileEventsDelegate?.deleted(file, client: self) } func fileCommentAdded(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } files[id]?.comments[commentID] = comment fileEventsDelegate?.commentAdded(file, comment: comment, client: self) } func fileCommentEdited(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } files[id]?.comments[commentID]?.comment = comment.comment fileEventsDelegate?.commentAdded(file, comment: comment, client: self) } func fileCommentDeleted(_ event: Event) { guard let file = event.file, let id = file.id, let comment = event.comment, let commentID = comment.id else { return } _ = files[id]?.comments.removeValue(forKey: commentID) fileEventsDelegate?.commentDeleted(file, comment: comment, client: self) } //MARK: - Pins func pinAdded(_ event: Event) { guard let id = event.channelID, let item = event.item else { return } channels[id]?.pinnedItems.append(item) pinEventsDelegate?.pinned(item, channel: channels[id], client: self) } func pinRemoved(_ event: Event) { guard let id = event.channelID, let item = event.item else { return } if let pins = channels[id]?.pinnedItems.filter({$0 != item}) { channels[id]?.pinnedItems = pins } pinEventsDelegate?.unpinned(item, channel: channels[id], client: self) } //MARK: - Stars func itemStarred(_ event: Event, star: Bool) { guard let item = event.item, let type = item.type else { return } switch type { case "message": starMessage(item, star: star) case "file": starFile(item, star: star) case "file_comment": starComment(item) default: break } starEventsDelegate?.starred(item, starred: star, self) } func starMessage(_ item: Item, star: Bool) { guard let message = item.message, let ts = message.ts, let channel = item.channel , channels[channel]?.messages[ts] != nil else { return } channels[channel]?.messages[ts]?.isStarred = star } func starFile(_ item: Item, star: Bool) { guard let file = item.file, let id = file.id else { return } files[id]?.isStarred = star if let stars = files[id]?.stars { if star == true { files[id]?.stars = stars + 1 } else { if stars > 0 { files[id]?.stars = stars - 1 } } } } func starComment(_ item: Item) { guard let file = item.file, let id = file.id, let comment = item.comment, let commentID = comment.id else { return } files[id]?.comments[commentID] = comment } //MARK: - Reactions func addedReaction(_ event: Event) { guard let item = event.item, let type = item.type, let reaction = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else { return } switch type { case "message": guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else { return } message.reactions.append(Reaction(name: reaction, user: userID)) case "file": guard let id = item.file?.id else { return } files[id]?.reactions.append(Reaction(name: reaction, user: userID)) case "file_comment": guard let id = item.file?.id, let commentID = item.fileCommentID else { return } files[id]?.comments[commentID]?.reactions.append(Reaction(name: reaction, user: userID)) default: break } reactionEventsDelegate?.added(reaction, item: item, itemUser: itemUser, client: self) } func removedReaction(_ event: Event) { guard let item = event.item, let type = item.type, let key = event.reaction, let userID = event.user?.id, let itemUser = event.itemUser else { return } switch type { case "message": guard let channel = item.channel, let ts = item.ts, let message = channels[channel]?.messages[ts] else { return } message.reactions = message.reactions.filter({$0.name != key && $0.user != userID}) case "file": guard let itemFile = item.file, let id = itemFile.id else { return } files[id]?.reactions = files[id]!.reactions.filter({$0.name != key && $0.user != userID}) case "file_comment": guard let id = item.file?.id, let commentID = item.fileCommentID else { return } files[id]?.comments[commentID]?.reactions = files[id]!.comments[commentID]!.reactions.filter({$0.name != key && $0.user != userID}) default: break } reactionEventsDelegate?.removed(key, item: item, itemUser: itemUser, client: self) } //MARK: - Preferences func changePreference(_ event: Event) { guard let name = event.name else { return } authenticatedUser?.preferences?[name] = event.value slackEventsDelegate?.preferenceChanged(name, value: event.value, client: self) } //Mark: - User Change func userChange(_ event: Event) { guard let user = event.user, let id = user.id else { return } let preferences = users[id]?.preferences users[id] = user users[id]?.preferences = preferences slackEventsDelegate?.userChanged(user, client: self) } //MARK: - User Presence func presenceChange(_ event: Event) { guard let user = event.user, let id = user.id, let presence = event.presence else { return } users[id]?.presence = event.presence slackEventsDelegate?.presenceChanged(user, presence: presence, client: self) } //MARK: - Team func teamJoin(_ event: Event) { guard let user = event.user, let id = user.id else { return } users[id] = user teamEventsDelegate?.userJoined(user, client: self) } func teamPlanChange(_ event: Event) { guard let plan = event.plan else { return } team?.plan = plan teamEventsDelegate?.planChanged(plan, client: self) } func teamPreferenceChange(_ event: Event) { guard let name = event.name else { return } team?.prefs?[name] = event.value teamEventsDelegate?.preferencesChanged(name, value: event.value, client: self) } func teamNameChange(_ event: Event) { guard let name = event.name else { return } team?.name = name teamEventsDelegate?.nameChanged(name, client: self) } func teamDomainChange(_ event: Event) { guard let domain = event.domain else { return } team?.domain = domain teamEventsDelegate?.domainChanged(domain, client: self) } func emailDomainChange(_ event: Event) { guard let domain = event.emailDomain else { return } team?.emailDomain = domain teamEventsDelegate?.emailDomainChanged(domain, client: self) } func emojiChanged(_ event: Event) { teamEventsDelegate?.emojiChanged(self) } //MARK: - Bots func bot(_ event: Event) { guard let bot = event.bot, let id = bot.id else { return } bots[id] = bot slackEventsDelegate?.botEvent(bot, client: self) } //MARK: - Subteams func subteam(_ event: Event) { guard let subteam = event.subteam, let id = subteam.id else { return } userGroups[id] = subteam subteamEventsDelegate?.event(subteam, client: self) } func subteamAddedSelf(_ event: Event) { guard let subteamID = event.subteamID, let _ = authenticatedUser?.userGroups else { return } authenticatedUser?.userGroups![subteamID] = subteamID subteamEventsDelegate?.selfAdded(subteamID, client: self) } func subteamRemovedSelf(_ event: Event) { guard let subteamID = event.subteamID else { return } _ = authenticatedUser?.userGroups?.removeValue(forKey: subteamID) subteamEventsDelegate?.selfRemoved(subteamID, client: self) } //MARK: - Team Profiles func teamProfileChange(_ event: Event) { guard let profile = event.profile else { return } for user in users { for key in profile.fields.keys { users[user.0]?.profile?.customProfile?.fields[key]?.updateProfileField(profile.fields[key]) } } teamProfileEventsDelegate?.changed(profile, client: self) } func teamProfileDeleted(_ event: Event) { guard let profile = event.profile else { return } for user in users { if let id = profile.fields.first?.0 { users[user.0]?.profile?.customProfile?.fields[id] = nil } } teamProfileEventsDelegate?.deleted(profile, client: self) } func teamProfileReordered(_ event: Event) { guard let profile = event.profile else { return } for user in users { for key in profile.fields.keys { users[user.0]?.profile?.customProfile?.fields[key]?.ordering = profile.fields[key]?.ordering } } teamProfileEventsDelegate?.reordered(profile, client: self) } //MARK: - Authenticated User func manualPresenceChange(_ event: Event) { guard let presence = event.presence, let user = authenticatedUser else { return } authenticatedUser?.presence = presence slackEventsDelegate?.manualPresenceChanged(user, presence: presence, client: self) } }
3d6fc603d2a6cc54d3485dc3497d7d39
31.768683
162
0.575749
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Observability/Sources/ObservabilityKit/Performance/Trace.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import ToolKit struct Trace { private class DebugTrace { private enum State { struct Started { let traceId: TraceID let startTime: Date } struct Ended { let traceId: TraceID let startTime: Date let endTime: Date let timeInterval: TimeInterval } case started(Started) case ended(Ended) } private var state: State func stop() { guard case .started(let started) = state else { return } let traceId = started.traceId let startTime = started.startTime let endTime = Date() let timeInterval = endTime.timeIntervalSince(startTime) let endState = State.Ended( traceId: traceId, startTime: startTime, endTime: endTime, timeInterval: timeInterval ) state = .ended(endState) Self.printTrace(ended: endState) } convenience init(traceId: TraceID) { self.init( state: .started(.init(traceId: traceId, startTime: Date())) ) } private init(state: State) { self.state = state } private static func printTrace(ended: State.Ended) { let traceId = ended.traceId let timeInterval = ended.timeInterval let seconds = timeInterval.string(with: 2) Logger.shared.debug( "Trace \(traceId), finished in \(seconds) seconds" ) } } private enum TraceType { case debugTrace(DebugTrace) case remoteTrace(RemoteTrace) func stop() { switch self { case .debugTrace(let debugTrace): debugTrace.stop() case .remoteTrace(let remoteTrace): remoteTrace.stop() } } static func debugTrace(with traceId: TraceID) -> Self { .debugTrace(DebugTrace(traceId: traceId)) } static func remoteTrace( with traceId: TraceID, properties: [String: String], create: PerformanceTracing.CreateRemoteTrace ) -> Self { let remoteTrace = create(traceId, properties) return .remoteTrace(remoteTrace) } } private let trace: TraceType private init(trace: TraceType) { self.trace = trace } func stop() { trace.stop() } static func createTrace( with traceId: TraceID, properties: [String: String], create: PerformanceTracing.CreateRemoteTrace ) -> Self { let traceType: TraceType = isDebug() ? .debugTrace(with: traceId) : .remoteTrace(with: traceId, properties: properties, create: create) return Self(trace: traceType) } private static func isDebug() -> Bool { var isDebug = false #if DEBUG isDebug = true #endif return isDebug } }
56c91565153cd8df47adcf2e3770010b
25.188525
77
0.537402
false
false
false
false
GhostSK/SpriteKitPractice
refs/heads/master
TileMap/TileMap/File.swift
apache-2.0
1
// // File.swift // TileMap // // Created by 胡杨林 on 17/3/22. // Copyright © 2017年 胡杨林. All rights reserved. // import Foundation import CoreGraphics //加载来自图片的瓦片地图 func tileMapLayerFromFileNamed(fileName:String) ->TileMapLayer? { let path = Bundle.main.path(forResource: fileName, ofType: nil) if path == nil { return nil } let fileContents = try? String(contentsOfFile: path!) let lines = Array<String>(fileContents!.components(separatedBy: "\n")) let atlasName = lines[0] let tileSizeComps = lines[1].components(separatedBy: "x") let width = Int(tileSizeComps[0]) let height = Int(tileSizeComps[1]) if width != nil && height != nil { let tileSize = CGSize(width: width!, height: height!) let tileCodes = lines[2..<lines.endIndex] return TileMapLayer(atlasName: atlasName, tileSize: tileSize, tileCodes: Array(tileCodes)) } return nil }
f398195c1187b2401cf62078a94d7c9e
30.793103
98
0.669197
false
false
false
false
iOSDevLog/InkChat
refs/heads/master
InkChat/Pods/IBAnimatable/IBAnimatable/PresentationModalSize.swift
apache-2.0
1
// // Created by Tom Baranes on 17/07/16. // Copyright © 2016 Jake Lin. All rights reserved. // import UIKit public enum PresentationModalSize: IBEnum { case half case full case custom(size: Float) func width(parentSize: CGSize) -> Float { switch self { case .half: return floorf(Float(parentSize.width) / 2.0) case .full: return Float(parentSize.width) case .custom(let size): return size } } func height(parentSize: CGSize) -> Float { switch self { case .half: return floorf(Float(parentSize.height) / 2.0) case .full: return Float(parentSize.height) case .custom(let size): return size } } } public extension PresentationModalSize { init?(string: String?) { guard let string = string else { return nil } let (name, params) = PresentationModalSize.extractNameAndParams(from: string) switch name { case "half": self = .half case "full": self = .full case "custom" where params.count == 1: self = .custom(size: params[0].toFloat() ?? 0) default: return nil } } }
300e37b17b7efe56bc84695a184b2730
19
81
0.613158
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOPerformanceTester/DeadlineNowBenchmark.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore final class DeadlineNowBenchmark: Benchmark { private let iterations: Int init(iterations: Int) { self.iterations = iterations } func setUp() throws { } func tearDown() { } func run() -> Int { var counter: UInt64 = 0 for _ in 0..<self.iterations { let now = NIODeadline.now().uptimeNanoseconds counter &+= now } return Int(truncatingIfNeeded: counter) } }
2af76cf60a36940fe9394daae33cd6fb
24.5
80
0.531476
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/0020-rdar21598514.swift
apache-2.0
66
// RUN: not %target-swift-frontend %s -typecheck protocol Resettable : AnyObject { func reset() } internal var _allResettables: [Resettable] = [] public class TypeIndexed<Value> : Resettable { public init(_ value: Value) { self.defaultValue = value _allResettables.append(self) } public subscript(t: Any.Type) -> Value { get { return byType[ObjectIdentifier(t)] ?? defaultValue } set { byType[ObjectIdentifier(t)] = newValue } } public func reset() { byType = [:] } internal var byType: [ObjectIdentifier:Value] = [:] internal var defaultValue: Value } public protocol Wrapper { typealias Base init(_: Base) var base: Base {get set} } public protocol LoggingType : Wrapper { typealias Log : AnyObject } extension LoggingType { public var log: Log.Type { return Log.self } public var selfType: Any.Type { return self.dynamicType } } public class IteratorLog { public static func dispatchTester<G : IteratorProtocol>( g: G ) -> LoggingIterator<LoggingIterator<G>> { return LoggingIterator(LoggingIterator(g)) } public static var next = TypeIndexed(0) } public struct LoggingIterator<Base : IteratorProtocol> : IteratorProtocol, LoggingType { typealias Log = IteratorLog public init(_ base: Base) { self.base = base } public mutating func next() -> Base.Element? { ++Log.next[selfType] return base.next() } public var base: Base } public class SequenceLog { public class func dispatchTester<S: Sequence>( s: S ) -> LoggingSequence<LoggingSequence<S>> { return LoggingSequence(LoggingSequence(s)) } public static var iterator = TypeIndexed(0) public static var underestimatedCount = TypeIndexed(0) public static var map = TypeIndexed(0) public static var filter = TypeIndexed(0) public static var _customContainsEquatableElement = TypeIndexed(0) public static var _preprocessingPass = TypeIndexed(0) public static var _copyToNativeArrayBuffer = TypeIndexed(0) public static var _copyContents = TypeIndexed(0) } public protocol LoggingSequenceType : Sequence, LoggingType { typealias Base : Sequence } extension LoggingSequenceType { public init(_ base: Base) { self.base = base } public func makeIterator() -> LoggingIterator<Base.Iterator> { ++SequenceLog.iterator[selfType] return LoggingIterator(base.makeIterator()) } public func underestimatedCount() -> Int { ++SequenceLog.underestimatedCount[selfType] return base.underestimatedCount() } public func map<T>( transform: (Base.Iterator.Element) -> T ) -> [T] { ++SequenceLog.map[selfType] return base.map(transform) } public func filter( isIncluded: (Base.Iterator.Element) -> Bool ) -> [Base.Iterator.Element] { ++SequenceLog.filter[selfType] return base.filter(isIncluded) } public func _customContainsEquatableElement( element: Base.Iterator.Element ) -> Bool? { ++SequenceLog._customContainsEquatableElement[selfType] return base._customContainsEquatableElement(element) } /// If `self` is multi-pass (i.e., a `Collection`), invoke /// `preprocess` on `self` and return its result. Otherwise, return /// `nil`. public func _preprocessingPass<R>( _ preprocess: (Self) -> R ) -> R? { ++SequenceLog._preprocessingPass[selfType] return base._preprocessingPass { _ in preprocess(self) } } /// Create a native array buffer containing the elements of `self`, /// in the same order. public func _copyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Base.Iterator.Element> { ++SequenceLog._copyToNativeArrayBuffer[selfType] return base._copyToNativeArrayBuffer() } /// Copy a Sequence into an array. public func _copyContents( initializing ptr: UnsafeMutablePointer<Base.Iterator.Element> ) { ++SequenceLog._copyContents[selfType] return base._copyContents(initializing: ptr) } } public struct LoggingSequence<Base_: Sequence> : LoggingSequenceType { typealias Log = SequenceLog typealias Base = Base_ public init(_ base: Base_) { self.base = base } public var base: Base_ } public class CollectionLog : SequenceLog { public class func dispatchTester<C: Collection>( c: C ) -> LoggingCollection<LoggingCollection<C>> { return LoggingCollection(LoggingCollection(c)) } static var subscriptIndex = TypeIndexed(0) static var subscriptRange = TypeIndexed(0) static var isEmpty = TypeIndexed(0) static var count = TypeIndexed(0) static var _customIndexOfEquatableElement = TypeIndexed(0) static var first = TypeIndexed(0) } public protocol LoggingCollectionType : Collection, LoggingSequenceType { typealias Base : Collection } extension LoggingCollectionType { subscript(position: Base.Index) -> Base.Iterator.Element { ++CollectionLog.subscriptIndex[selfType] return base[position] } subscript(_prext_bounds: Range<Base.Index>) -> Base._prext_SubSequence { ++CollectionLog.subscriptRange[selfType] return base[_prext_bounds] } var isEmpty: Bool { ++CollectionLog.isEmpty[selfType] return base.isEmpty } var count: Base.Index.Distance { ++CollectionLog.count[selfType] return base.count } func _customIndexOfEquatableElement(element: Iterator.Element) -> Base.Index?? { ++CollectionLog._customIndexOfEquatableElement[selfType] return base._customIndexOfEquatableElement(element) } var first: Iterator.Element? { ++CollectionLog.first[selfType] return base.first } } struct LoggingCollection<Base_: Collection> : LoggingCollectionType {}
583750932fe171bfdcad740724b2d7f4
24.731818
82
0.704469
false
false
false
false
koekeishiya/kwm
refs/heads/master
overlaylib/overlaylib.swift
mit
1
import Foundation import AppKit import Cocoa class OverlayView: NSView { var borderColor: NSColor var borderWidth: CGFloat var cornerRadius: CGFloat init(frame: NSRect, borderColor: NSColor, borderWidth: CGFloat, cornerRadius: CGFloat) { self.borderColor = borderColor self.borderWidth = borderWidth self.cornerRadius = cornerRadius super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: NSRect) { let bpath:NSBezierPath = NSBezierPath(roundedRect: borderRect, xRadius:cornerRadius, yRadius:cornerRadius) borderColor.set() bpath.lineWidth = borderWidth bpath.stroke() } var borderRect: NSRect { return bounds.insetBy(dx: borderWidth/2, dy: borderWidth/2) } } class OverlayWindow { private let window: NSWindow private let overlayView: OverlayView private var _borderColor: NSColor private var _borderWidth: CGFloat private var _cornerRadius: CGFloat private var _nodeFrame = NSRect(x:0,y:0,width:0,height:0) init(frame: NSRect, borderColor: NSColor, borderWidth: CGFloat, cornerRadius: CGFloat) { _nodeFrame = frame _borderColor = borderColor _borderWidth = borderWidth _cornerRadius = cornerRadius window = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: true) window.isOpaque = false window.backgroundColor = NSColor.clear window.ignoresMouseEvents = true window.level = Int(CGWindowLevelForKey(.floatingWindow)) window.hasShadow = false window.collectionBehavior = .canJoinAllSpaces window.isReleasedWhenClosed = false overlayView = OverlayView(frame: window.contentView!.bounds, borderColor: borderColor, borderWidth: borderWidth, cornerRadius: cornerRadius) overlayView.autoresizingMask = [.viewWidthSizable, .viewHeightSizable] window.contentView!.addSubview(overlayView) updateFrame() window.makeKeyAndOrderFront(nil) } func hide() { window.close() } var grownFrame: NSRect { return nodeFrame.insetBy(dx: -self.borderWidth, dy: -self.borderWidth) } func updateFrame() { window.setFrame(grownFrame, display: true) overlayView.needsDisplay = true } var nodeFrame: NSRect { get { return _nodeFrame } set(newFrame) { self._nodeFrame = newFrame } } var borderColor: NSColor { get { return _borderColor } set(newBorderColor) { _borderColor = newBorderColor self.overlayView.borderColor = newBorderColor } } var borderWidth: CGFloat { get { return _borderWidth } set(newBorderWidth) { _borderWidth = newBorderWidth self.overlayView.borderWidth = newBorderWidth } } var cornerRadius: CGFloat { get { return _cornerRadius } set(newRadius) { _cornerRadius = newRadius self.overlayView.cornerRadius = newRadius } } } class OverlayController: NSObject, NSApplicationDelegate { private var borders: [UInt32: OverlayWindow] = [:] private var lastIndex: UInt32 = 0 func createBorder(frame: NSRect, borderColor: NSColor, borderWidth: CGFloat, cornerRadius: CGFloat) -> UInt32 { let windowIndex = lastIndex DispatchQueue.main.async { let newWindow = OverlayWindow( frame: frame, borderColor: borderColor, borderWidth: borderWidth, cornerRadius: cornerRadius ) self.borders[windowIndex] = newWindow } lastIndex += 1 return windowIndex } func updateBorderFrame(id borderId: UInt32, frame: NSRect, borderColor: NSColor, borderWidth: CGFloat, cornerRadius: CGFloat) { DispatchQueue.main.async { guard let border = self.borders[borderId] else { return } border.nodeFrame = frame border.borderColor = borderColor border.borderWidth = borderWidth border.cornerRadius = cornerRadius border.updateFrame() } } func removeBorder(id borderId: UInt32) { DispatchQueue.main.async { let overlayWindow = self.borders.removeValue(forKey: borderId) overlayWindow?.hide() } } } @objc public class CBridge : NSObject { static var overlayController: OverlayController! = nil class func invertY(y: Double, height: Double) -> Double { let scrns: Array<NSScreen> = NSScreen.screens()! let scrn: NSScreen = scrns[0] let scrnHeight: Double = Double(scrn.frame.size.height) let invertedY = scrnHeight - (y + height) return invertedY } class func initializeOverlay() { overlayController = OverlayController() } class func createBorder( x: Double, y: Double, width: Double, height: Double, r: Double, g: Double, b: Double, a: Double, borderWidth: Double, cornerRadius: Double) -> UInt32 { return overlayController.createBorder( frame: NSRect(x:x, y:invertY(y:y, height:height), width:width, height:height), borderColor: NSColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: CGFloat(a)), borderWidth: CGFloat(borderWidth), cornerRadius: CGFloat(cornerRadius) ) } class func updateBorder( id borderId: UInt32, x: Double, y: Double, width: Double, height: Double, r: Double, g: Double, b: Double, a: Double, borderWidth: Double, cornerRadius: Double) { return overlayController.updateBorderFrame( id: borderId, frame: NSRect(x:x, y:invertY(y:y, height:height), width:width, height:height), borderColor: NSColor(red: CGFloat(r), green: CGFloat(g), blue: CGFloat(b), alpha: CGFloat(a)), borderWidth: CGFloat(borderWidth), cornerRadius: CGFloat(cornerRadius) ) } class func removeBorder(id borderId: UInt32) { return overlayController.removeBorder(id: borderId) } }
79e957870439c0a542778021875edd40
24.396396
142
0.714792
false
false
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveMapKitTests/MKMapViewSpec.swift
gpl-3.0
4
import ReactiveSwift import ReactiveCocoa import ReactiveMapKit import Quick import Nimble import enum Result.NoError import MapKit @available(tvOS 9.2, *) class MKMapViewSpec: QuickSpec { override func spec() { var mapView: MKMapView! weak var _mapView: MKMapView? beforeEach { mapView = MKMapView(frame: .zero) _mapView = mapView } afterEach { autoreleasepool { mapView = nil } // FIXME: SDK_ISSUE // // Temporarily disabled since the expectation keeps failing with // Xcode 8.3 and macOS Sierra 10.12.4. #if !os(macOS) // using toEventually(beNil()) here // since it takes time to release MKMapView expect(_mapView).toEventually(beNil()) #endif } it("should accept changes from bindings to its map type") { expect(mapView.mapType) == MKMapType.standard let (pipeSignal, observer) = Signal<MKMapType, NoError>.pipe() mapView.reactive.mapType <~ pipeSignal observer.send(value: MKMapType.satellite) expect(mapView.mapType) == MKMapType.satellite observer.send(value: MKMapType.hybrid) expect(mapView.mapType) == MKMapType.hybrid } it("should accept changes from bindings to its zoom enabled state") { expect(mapView.isZoomEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isZoomEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isZoomEnabled) == false } it("should accept changes from bindings to its scroll enabled state") { expect(mapView.isScrollEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isScrollEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isScrollEnabled) == false } #if !os(tvOS) it("should accept changes from bindings to its pitch enabled state") { expect(mapView.isPitchEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isPitchEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isPitchEnabled) == false } it("should accept changes from bindings to its rotate enabled state") { expect(mapView.isRotateEnabled) == true let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() mapView.reactive.isRotateEnabled <~ pipeSignal observer.send(value: false) expect(mapView.isRotateEnabled) == false } #endif } }
4ce7e8b0073b4957e96f739acd00a4e5
24.147368
73
0.710758
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Blockchain/DIKit/DIKit.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import BitcoinCashKit import BitcoinChainKit import BitcoinKit import BlockchainNamespace import Combine import DIKit import ERC20Kit import EthereumKit import FeatureAppDomain import FeatureAppUI import FeatureAttributionData import FeatureAttributionDomain import FeatureAuthenticationData import FeatureAuthenticationDomain import FeatureCardIssuingUI import FeatureCoinData import FeatureCoinDomain import FeatureCryptoDomainData import FeatureCryptoDomainDomain import FeatureDashboardUI import FeatureDebugUI import FeatureKYCDomain import FeatureKYCUI import FeatureNFTData import FeatureNFTDomain import FeatureNotificationPreferencesData import FeatureNotificationPreferencesDomain import FeatureOnboardingUI import FeatureOpenBankingData import FeatureOpenBankingDomain import FeatureOpenBankingUI import FeatureProductsData import FeatureProductsDomain import FeatureReferralData import FeatureReferralDomain import FeatureSettingsDomain import FeatureSettingsUI import FeatureTransactionDomain import FeatureTransactionUI import FeatureUserDeletionData import FeatureUserDeletionDomain import FeatureWalletConnectData import FirebaseDynamicLinks import FirebaseMessaging import FirebaseRemoteConfig import MoneyKit import NetworkKit import ObservabilityKit import PlatformDataKit import PlatformKit import PlatformUIKit import RemoteNotificationsKit import RxToolKit import StellarKit import ToolKit import UIKit import WalletPayloadKit // MARK: - Settings Dependencies extension UIApplication: PlatformKit.AppStoreOpening {} extension Wallet: WalletRecoveryVerifing {} // MARK: - Dashboard Dependencies extension AnalyticsUserPropertyInteractor: FeatureDashboardUI.AnalyticsUserPropertyInteracting {} extension AnnouncementPresenter: FeatureDashboardUI.AnnouncementPresenting {} extension FeatureSettingsUI.BackupFundsRouter: FeatureDashboardUI.BackupRouterAPI {} // MARK: - AnalyticsKit Dependencies extension BlockchainSettings.App: AnalyticsKit.GuidRepositoryAPI {} // MARK: - Blockchain Module extension DependencyContainer { // swiftlint:disable closure_body_length static var blockchain = module { factory { NavigationRouter() as NavigationRouterAPI } factory { DeepLinkHandler() as DeepLinkHandling } factory { DeepLinkRouter() as DeepLinkRouting } factory { UIDevice.current as DeviceInfo } factory { PerformanceTracing.live as PerformanceTracingServiceAPI } single { () -> LogMessageServiceAPI in let loggers = LogMessageTracing.provideLoggers() return LogMessageTracing.live( loggers: loggers ) } factory { CrashlyticsRecorder() as MessageRecording } factory { CrashlyticsRecorder() as ErrorRecording } factory(tag: "CrashlyticsRecorder") { CrashlyticsRecorder() as Recording } factory { ExchangeClient() as ExchangeClientAPI } factory { RecoveryPhraseStatusProvider() as RecoveryPhraseStatusProviding } single { TradeLimitsMetadataService() as TradeLimitsMetadataServiceAPI } factory { SiftService() } factory { () -> FeatureAuthenticationDomain.SiftServiceAPI in let service: SiftService = DIKit.resolve() return service as FeatureAuthenticationDomain.SiftServiceAPI } factory { () -> PlatformKit.SiftServiceAPI in let service: SiftService = DIKit.resolve() return service as PlatformKit.SiftServiceAPI } single { SecondPasswordHelper() } factory { () -> SecondPasswordHelperAPI in let helper: SecondPasswordHelper = DIKit.resolve() return helper as SecondPasswordHelperAPI } factory { () -> SecondPasswordPresenterHelper in let helper: SecondPasswordHelper = DIKit.resolve() return helper as SecondPasswordPresenterHelper } single { () -> SecondPasswordPromptable in SecondPasswordPrompter( secondPasswordStore: DIKit.resolve(), secondPasswordPrompterHelper: DIKit.resolve(), secondPasswordService: DIKit.resolve(), nativeWalletEnabled: { nativeWalletFlagEnabled() } ) } single { SecondPasswordStore() as SecondPasswordStorable } single { () -> AppDeeplinkHandlerAPI in let appSettings: BlockchainSettings.App = DIKit.resolve() let isPinSet: () -> Bool = { appSettings.isPinSet } let deeplinkHandler = CoreDeeplinkHandler( markBitpayUrl: { BitpayService.shared.content = $0 }, isBitPayURL: BitPayLinkRouter.isBitPayURL, isPinSet: isPinSet ) let blockchainHandler = BlockchainLinksHandler( validHosts: BlockchainLinks.validLinks, validRoutes: BlockchainLinks.validRoutes ) return AppDeeplinkHandler( deeplinkHandler: deeplinkHandler, blockchainHandler: blockchainHandler, firebaseHandler: FirebaseDeeplinkHandler(dynamicLinks: DynamicLinks.dynamicLinks()) ) } // MARK: ExchangeCoordinator // MARK: - AuthenticationCoordinator factory { () -> AuthenticationCoordinating in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveAuthenticationCoordinating() as AuthenticationCoordinating } // MARK: - Dashboard factory { () -> AccountsRouting in let routing: TabSwapping = DIKit.resolve() return AccountsRouter( routing: routing ) } factory { UIApplication.shared as AppStoreOpening } factory { BackupFundsRouter( entry: .custody, navigationRouter: NavigationRouter() ) as FeatureDashboardUI.BackupRouterAPI } factory { AnalyticsUserPropertyInteractor() as FeatureDashboardUI.AnalyticsUserPropertyInteracting } factory { AnnouncementPresenter() as FeatureDashboardUI.AnnouncementPresenting } factory { SimpleBuyAnalyticsService() as PlatformKit.SimpleBuyAnalayticsServicing } // MARK: - AppCoordinator single { LoggedInDependencyBridge() as LoggedInDependencyBridgeAPI } factory { () -> TabSwapping in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveTabSwapping() as TabSwapping } factory { () -> AppCoordinating in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveAppCoordinating() as AppCoordinating } factory { () -> FeatureDashboardUI.WalletOperationsRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveWalletOperationsRouting() as FeatureDashboardUI.WalletOperationsRouting } factory { () -> BackupFlowStarterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveBackupFlowStarter() as BackupFlowStarterAPI } factory { () -> CashIdentityVerificationAnnouncementRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveCashIdentityVerificationAnnouncementRouting() as CashIdentityVerificationAnnouncementRouting } factory { () -> SettingsStarterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveSettingsStarter() as SettingsStarterAPI } factory { () -> DrawerRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveDrawerRouting() as DrawerRouting } factory { () -> LoggedInReloadAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveLoggedInReload() as LoggedInReloadAPI } factory { () -> ClearOnLogoutAPI in EmptyClearOnLogout() } factory { () -> QRCodeScannerRouting in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveQRCodeScannerRouting() as QRCodeScannerRouting } factory { () -> ExternalActionsProviderAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveExternalActionsProvider() as ExternalActionsProviderAPI } factory { () -> SupportRouterAPI in let bridge: LoggedInDependencyBridgeAPI = DIKit.resolve() return bridge.resolveSupportRouterAPI() } // MARK: - WalletManager single { WalletManager() } factory { () -> WalletManagerAPI in let manager: WalletManager = DIKit.resolve() return manager as WalletManagerAPI } factory { () -> LegacyMnemonicAccessAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet as LegacyMnemonicAccessAPI } factory { () -> WalletRepositoryProvider in let walletManager: WalletManager = DIKit.resolve() return walletManager as WalletRepositoryProvider } factory { () -> JSContextProviderAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager as JSContextProviderAPI } factory { () -> WalletRecoveryVerifing in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet as WalletRecoveryVerifing } factory { () -> WalletConnectMetadataAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.walletConnect as WalletConnectMetadataAPI } // MARK: - BlockchainSettings.App single { KeychainItemSwiftWrapper() as KeychainItemWrapping } factory { LegacyPasswordProvider() as LegacyPasswordProviding } single { BlockchainSettings.App() } factory { () -> AppSettingsAPI in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsAPI } factory { () -> AppSettingsAuthenticating in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsAuthenticating } factory { () -> PermissionSettingsAPI in let app: BlockchainSettings.App = DIKit.resolve() return app } factory { () -> AppSettingsSecureChannel in let app: BlockchainSettings.App = DIKit.resolve() return app as AppSettingsSecureChannel } // MARK: - Settings factory { () -> RecoveryPhraseVerifyingServiceAPI in let manager: WalletManager = DIKit.resolve() let backupService: VerifyMnemonicBackupServiceAPI = DIKit.resolve() return RecoveryPhraseVerifyingService( wallet: manager.wallet, verifyMnemonicBackupService: backupService, nativeWalletEnabledFlag: { nativeWalletFlagEnabled() } ) } // MARK: - AppFeatureConfigurator single { AppFeatureConfigurator( app: DIKit.resolve() ) } factory { () -> FeatureFetching in let featureFetching: AppFeatureConfigurator = DIKit.resolve() return featureFetching } factory { PolygonSupport(app: DIKit.resolve()) as MoneyKit.PolygonSupport } // MARK: - UserInformationServiceProvider // user state can be observed by multiple objects and the state is made up of multiple components // so, better have a single instance of this object. single { () -> UserAdapterAPI in UserAdapter( kycTiersService: DIKit.resolve(), paymentMethodsService: DIKit.resolve(), productsService: DIKit.resolve(), ordersService: DIKit.resolve() ) } factory { () -> SettingsServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> SettingsServiceCombineAPI in let settings: SettingsServiceAPI = DIKit.resolve() return settings as SettingsServiceCombineAPI } factory { () -> FiatCurrencyServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> SupportedFiatCurrenciesServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } factory { () -> MobileSettingsServiceAPI in let completeSettingsService: CompleteSettingsServiceAPI = DIKit.resolve() return completeSettingsService } // MARK: - BlockchainDataRepository factory { BlockchainDataRepository() as DataRepositoryAPI } // MARK: - Ethereum Wallet factory { () -> EthereumWalletBridgeAPI in let manager: WalletManager = DIKit.resolve() return manager.wallet.ethereum } factory { () -> EthereumWalletAccountBridgeAPI in let manager: WalletManager = DIKit.resolve() return manager.wallet.ethereum } // MARK: - Stellar Wallet factory { StellarWallet() as StellarWalletBridgeAPI } factory { () -> BitcoinWalletBridgeAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.bitcoin } factory { () -> WalletMnemonicProvider in let mnemonicAccess: MnemonicAccessAPI = DIKit.resolve() return { mnemonicAccess.mnemonic .eraseError() .map(BitcoinChainKit.Mnemonic.init) .eraseToAnyPublisher() } } factory { () -> BitcoinChainSendBridgeAPI in let walletManager: WalletManager = DIKit.resolve() return walletManager.wallet.bitcoin } single { BitcoinCashWallet() as BitcoinCashWalletBridgeAPI } // MARK: Wallet Upgrade factory { WalletUpgrading() as WalletUpgradingAPI } // MARK: Remote Notifications factory { ExternalNotificationServiceProvider() as ExternalNotificationProviding } factory { () -> RemoteNotificationEmitting in let relay: RemoteNotificationRelay = DIKit.resolve() return relay as RemoteNotificationEmitting } factory { () -> RemoteNotificationBackgroundReceiving in let relay: RemoteNotificationRelay = DIKit.resolve() return relay as RemoteNotificationBackgroundReceiving } single { RemoteNotificationRelay( app: DIKit.resolve(), cacheSuite: DIKit.resolve(), userNotificationCenter: UNUserNotificationCenter.current(), messagingService: Messaging.messaging(), secureChannelNotificationRelay: DIKit.resolve() ) } // MARK: Helpers factory { UIApplication.shared as ExternalAppOpener } factory { UIApplication.shared as URLOpener } factory { UIApplication.shared as OpenURLProtocol } // MARK: KYC Module factory { () -> FeatureSettingsUI.KYCRouterAPI in KYCAdapter() } factory { () -> FeatureKYCDomain.EmailVerificationAPI in EmailVerificationAdapter(settingsService: DIKit.resolve()) } // MARK: Onboarding Module // this must be kept in memory because of how PlatformUIKit.Router works, otherwise the flow crashes. single { () -> FeatureOnboardingUI.OnboardingRouterAPI in FeatureOnboardingUI.OnboardingRouter() } factory { () -> FeatureOnboardingUI.TransactionsRouterAPI in TransactionsAdapter( router: DIKit.resolve(), coincore: DIKit.resolve(), app: DIKit.resolve() ) } factory { () -> FeatureOnboardingUI.KYCRouterAPI in KYCAdapter() } // MARK: Transactions Module factory { () -> PaymentMethodsLinkingAdapterAPI in PaymentMethodsLinkingAdapter() } factory { () -> TransactionsAdapterAPI in TransactionsAdapter( router: DIKit.resolve(), coincore: DIKit.resolve(), app: DIKit.resolve() ) } factory { () -> PlatformUIKit.KYCRouting in KYCAdapter() } factory { () -> FeatureSettingsUI.PaymentMethodsLinkerAPI in PaymentMethodsLinkingAdapter() } factory { () -> FeatureTransactionUI.UserActionServiceAPI in TransactionUserActionService(userService: DIKit.resolve()) } factory { () -> FeatureTransactionDomain.TransactionRestrictionsProviderAPI in TransactionUserActionService(userService: DIKit.resolve()) } // MARK: FeatureAuthentication Module factory { () -> AutoWalletPairingServiceAPI in let manager: WalletManager = DIKit.resolve() return AutoWalletPairingService( walletPayloadService: DIKit.resolve(), walletPairingRepository: DIKit.resolve(), walletCryptoService: DIKit.resolve(), parsingService: DIKit.resolve() ) as AutoWalletPairingServiceAPI } factory { () -> CheckReferralClientAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) return CheckReferralClient(networkAdapter: adapter, requestBuilder: builder) } factory { () -> GuidServiceAPI in GuidService( sessionTokenRepository: DIKit.resolve(), guidRepository: DIKit.resolve() ) } factory { () -> SessionTokenServiceAPI in sessionTokenServiceFactory( sessionRepository: DIKit.resolve() ) } factory { () -> SMSServiceAPI in SMSService( smsRepository: DIKit.resolve(), credentialsRepository: DIKit.resolve(), sessionTokenRepository: DIKit.resolve() ) } factory { () -> TwoFAWalletServiceAPI in let manager: WalletManager = DIKit.resolve() return TwoFAWalletService( repository: DIKit.resolve(), walletRepository: manager.repository, walletRepo: DIKit.resolve(), nativeWalletFlagEnabled: { nativeWalletFlagEnabled() } ) } factory { () -> WalletPayloadServiceAPI in let manager: WalletManager = DIKit.resolve() return WalletPayloadService( repository: DIKit.resolve(), walletRepository: manager.repository, walletRepo: DIKit.resolve(), credentialsRepository: DIKit.resolve(), nativeWalletEnabledUse: nativeWalletEnabledUseImpl ) } factory { () -> LoginServiceAPI in LoginService( payloadService: DIKit.resolve(), twoFAPayloadService: DIKit.resolve(), repository: DIKit.resolve() ) } factory { () -> EmailAuthorizationServiceAPI in EmailAuthorizationService(guidService: DIKit.resolve()) as EmailAuthorizationServiceAPI } factory { () -> DeviceVerificationServiceAPI in let sessionTokenRepository: SessionTokenRepositoryAPI = DIKit.resolve() return DeviceVerificationService( sessionTokenRepository: sessionTokenRepository ) as DeviceVerificationServiceAPI } factory { RecaptchaClient(siteKey: AuthenticationKeys.googleRecaptchaSiteKey) } factory { GoogleRecaptchaService() as GoogleRecaptchaServiceAPI } // MARK: Analytics single { () -> AnalyticsKit.GuidRepositoryAPI in let guidRepository: BlockchainSettings.App = DIKit.resolve() return guidRepository as AnalyticsKit.GuidRepositoryAPI } single { () -> AnalyticsEventRecorderAPI in let firebaseAnalyticsServiceProvider = FirebaseAnalyticsServiceProvider() let userAgent = UserAgentProvider().userAgent ?? "" let nabuAnalyticsServiceProvider = NabuAnalyticsProvider( platform: .wallet, basePath: BlockchainAPI.shared.apiUrl, userAgent: userAgent, tokenProvider: DIKit.resolve(), guidProvider: DIKit.resolve(), traitRepository: DIKit.resolve() ) return AnalyticsEventRecorder(analyticsServiceProviders: [ firebaseAnalyticsServiceProvider, nabuAnalyticsServiceProvider ]) } single { AppAnalyticsTraitRepository(app: DIKit.resolve()) } single { () -> TraitRepositoryAPI in let analytics: AppAnalyticsTraitRepository = DIKit.resolve() return analytics as TraitRepositoryAPI } // MARK: Account Picker factory { () -> AccountPickerViewControllable in let controller = FeatureAccountPickerControllableAdapter() return controller as AccountPickerViewControllable } // MARK: Open Banking single { () -> OpenBanking in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = OpenBankingClient( app: DIKit.resolve(), requestBuilder: builder, network: adapter.network ) return OpenBanking(app: DIKit.resolve(), banking: client) } // MARK: Coin View single { () -> HistoricalPriceClientAPI in let requestBuilder: NetworkKit.RequestBuilder = DIKit.resolve() let networkAdapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve() return HistoricalPriceClient( request: requestBuilder, network: networkAdapter ) } single { () -> HistoricalPriceRepositoryAPI in HistoricalPriceRepository(DIKit.resolve()) } single { () -> RatesClientAPI in let requestBuilder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let networkAdapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) return RatesClient( networkAdapter: networkAdapter, requestBuilder: requestBuilder ) } single { () -> RatesRepositoryAPI in RatesRepository(DIKit.resolve()) } single { () -> WatchlistRepositoryAPI in WatchlistRepository( WatchlistClient( networkAdapter: DIKit.resolve(tag: DIKitContext.retail), requestBuilder: DIKit.resolve(tag: DIKitContext.retail) ) ) } // MARK: Feature Product factory { () -> FeatureProductsDomain.ProductsServiceAPI in ProductsService( repository: ProductsRepository( client: ProductsAPIClient( networkAdapter: DIKit.resolve(tag: DIKitContext.retail), requestBuilder: DIKit.resolve(tag: DIKitContext.retail) ) ), featureFlagsService: DIKit.resolve() ) } // MARK: Feature NFT factory { () -> FeatureNFTDomain.AssetProviderServiceAPI in let repository: EthereumWalletAccountRepositoryAPI = DIKit.resolve() let publisher = repository .defaultAccount .map(\.publicKey) .eraseError() return AssetProviderService( repository: AssetProviderRepository( client: FeatureNFTData.APIClient( retailNetworkAdapter: DIKit.resolve(tag: DIKitContext.retail), defaultNetworkAdapter: DIKit.resolve(), retailRequestBuilder: DIKit.resolve(tag: DIKitContext.retail), defaultRequestBuilder: DIKit.resolve() ) ), ethereumWalletAddressPublisher: publisher ) } factory { () -> FeatureNFTDomain.ViewWaitlistRegistrationRepositoryAPI in let emailService: EmailSettingsServiceAPI = DIKit.resolve() let publisher = emailService .emailPublisher .eraseError() return ViewWaitlistRegistrationRepository( client: FeatureNFTData.APIClient( retailNetworkAdapter: DIKit.resolve(tag: DIKitContext.retail), defaultNetworkAdapter: DIKit.resolve(), retailRequestBuilder: DIKit.resolve(tag: DIKitContext.retail), defaultRequestBuilder: DIKit.resolve() ), emailAddressPublisher: publisher ) } // MARK: Feature Crypto Domain factory { () -> SearchDomainRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve() let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve() let client = SearchDomainClient(networkAdapter: adapter, requestBuilder: builder) return SearchDomainRepository(apiClient: client) } factory { () -> OrderDomainRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = OrderDomainClient(networkAdapter: adapter, requestBuilder: builder) return OrderDomainRepository(apiClient: client) } factory { () -> ClaimEligibilityRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = ClaimEligibilityClient(networkAdapter: adapter, requestBuilder: builder) return ClaimEligibilityRepository(apiClient: client) } // MARK: Feature Notification Preferences factory { () -> NotificationPreferencesRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = NotificationPreferencesClient(networkAdapter: adapter, requestBuilder: builder) return NotificationPreferencesRepository(client: client) } // MARK: Feature Referrals factory { () -> ReferralRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = ReferralClientClient(networkAdapter: adapter, requestBuilder: builder) return ReferralRepository(client: client) } factory { () -> ReferralServiceAPI in ReferralService( app: DIKit.resolve(), repository: DIKit.resolve() ) } // MARK: - Websocket single(tag: DIKitContext.websocket) { RequestBuilder(config: Network.Config.websocketConfig) } // MARK: Feature Attribution single { () -> AttributionServiceAPI in let errorRecorder = CrashlyticsRecorder() let skAdNetworkService = SkAdNetworkService(errorRecorder: errorRecorder) let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.websocket) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let featureFlagService: FeatureFlagsServiceAPI = DIKit.resolve() let attributionClient = AttributionClient( networkAdapter: adapter, requestBuilder: builder ) let attributionRepository = AttributionRepository(with: attributionClient) return AttributionService( skAdNetworkService: skAdNetworkService, attributionRepository: attributionRepository, featureFlagService: featureFlagService ) as AttributionServiceAPI } // MARK: User Deletion factory { () -> UserDeletionRepositoryAPI in let builder: NetworkKit.RequestBuilder = DIKit.resolve(tag: DIKitContext.retail) let adapter: NetworkKit.NetworkAdapterAPI = DIKit.resolve(tag: DIKitContext.retail) let client = UserDeletionClient(networkAdapter: adapter, requestBuilder: builder) return UserDeletionRepository(client: client) } // MARK: Native Wallet Debugging single { NativeWalletLogger() as NativeWalletLoggerAPI } // MARK: Pulse Network Debugging single { PulseNetworkDebugLogger() as NetworkDebugLogger } single { PulseNetworkDebugScreenProvider() as NetworkDebugScreenProvider } single { app } factory { () -> NativeWalletFlagEnabled in let app: AppProtocol = DIKit.resolve() let flag: Tag.Event = BlockchainNamespace.blockchain.app.configuration.native.wallet.payload.is.enabled return NativeWalletFlagEnabled( app.publisher(for: flag, as: Bool.self) .prefix(1) .replaceError(with: false) ) } single { () -> RequestBuilderQueryParameters in let app: AppProtocol = DIKit.resolve() return RequestBuilderQueryParameters( app.publisher( for: BlockchainNamespace.blockchain.app.configuration.localized.error.override, as: String.self ) .map { result -> [URLQueryItem]? in try? [URLQueryItem(name: "localisedError", value: result.get().nilIfEmpty)] } .replaceError(with: []) ) } } } extension UIApplication: OpenURLProtocol {}
f4be591e5d55ff4a77e2dc8b9b3fc369
34.832009
115
0.628928
false
false
false
false
livioso/cpib
refs/heads/master
Compiler/Compiler/extensions/characterExtension.swift
mit
1
import Foundation extension Character { enum Kind { case Skippable case Literal case Letter case Symbol case Other } func kind() -> Kind { if isSkipable() { return Kind.Skippable } if isLiteral() { return Kind.Literal } if isSymbol() { return Kind.Symbol } if isLetter() { return Kind.Letter } return Kind.Other } private func isSkipable() -> Bool { return ( (" " == self) || ("\t" == self) || ("\n" == self) ) } private func isLiteral() -> Bool { return ("0" <= self && self <= "9") } private func isLetter() -> Bool { return ( ("A" <= self && self <= "Z") || ("a" <= self && self <= "z") ) } private func isSymbol() -> Bool { var isMatch = false switch self { case "(": fallthrough case ")": fallthrough case "{": fallthrough case "}": fallthrough case ",": fallthrough case ":": fallthrough case ";": fallthrough case "=": fallthrough case "*": fallthrough case "+": fallthrough case "-": fallthrough case "/": fallthrough case "<": fallthrough case ">": fallthrough case "&": fallthrough case "|": fallthrough case ".": isMatch = true case _: isMatch = false } return isMatch } }
674e78b94b6c86303a1ff93df2ccb273
17.765625
43
0.582015
false
false
false
false
sambhav7890/RecurrenceRuleUI-iOS
refs/heads/master
RecurrenceRuleUI-iOS/Classes/RecurrencePicker.swift
mit
1
// // RecurrenceRuleUI.swift // RecurrenceRuleUI // // Created by Sambhav on 16/8/7. // Copyright © 2016 Practo. All rights reserved. // import UIKit import EventKit import RecurrenceRule_iOS open class RecurrencePicker: UITableViewController { open var language: RecurrencePickerLanguage = .english { didSet { InternationalControl.sharedControl.language = language } } open weak var delegate: RecurrencePickerDelegate? open var tintColor = UIColor.blue open var calendar = Calendar.current open var occurrenceDate = Date() open var backgroundColor: UIColor? open var separatorColor: UIColor? fileprivate var recurrenceRule: RecurrenceRule? fileprivate var selectedIndexPath = IndexPath(row: 0, section: 0) // MARK: - Initialization public convenience init(recurrenceRule: RecurrenceRule?) { self.init(style: .grouped) self.recurrenceRule = recurrenceRule } // MARK: - Life cycle open override func viewDidLoad() { super.viewDidLoad() commonInit() } open override func didMove(toParentViewController parent: UIViewController?) { if parent == nil { // navigation is popped if let rule = recurrenceRule { switch rule.frequency { case .daily: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth.removeAll() case .weekly: recurrenceRule?.byweekday = rule.byweekday.sorted(by: <) recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth.removeAll() case .monthly: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday = rule.bymonthday.sorted(by: <) recurrenceRule?.bymonth.removeAll() case .yearly: recurrenceRule?.byweekday.removeAll() recurrenceRule?.bymonthday.removeAll() recurrenceRule?.bymonth = rule.bymonth.sorted(by: <) default: break } } recurrenceRule?.startDate = Date() delegate?.recurrencePicker(self, didPickRecurrence: recurrenceRule) } } } extension RecurrencePicker { // MARK: - Table view data source and delegate open override func numberOfSections(in tableView: UITableView) -> Int { return 2 } open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return Constant.basicRecurrenceStrings().count } else { return 1 } } open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return Constant.DefaultRowHeight } open override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return section == 1 ? recurrenceRuleText() : nil } open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: CellID.BasicRecurrenceCell) if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: CellID.BasicRecurrenceCell) } if (indexPath as NSIndexPath).section == 0 { cell?.accessoryType = .none cell?.textLabel?.text = Constant.basicRecurrenceStrings()[(indexPath as NSIndexPath).row] } else { cell?.accessoryType = .disclosureIndicator cell?.textLabel?.text = LocalizedString("RecurrencePicker.TextLabel.Custom") } let checkmark = UIImage(named: "checkmark", in: Bundle(for: type(of: self)), compatibleWith: nil) cell?.imageView?.image = checkmark?.withRenderingMode(.alwaysTemplate) if indexPath == selectedIndexPath { cell?.imageView?.isHidden = false } else { cell?.imageView?.isHidden = true } return cell! } open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let lastSelectedCell = tableView.cellForRow(at: selectedIndexPath) let currentSelectedCell = tableView.cellForRow(at: indexPath) lastSelectedCell?.imageView?.isHidden = true currentSelectedCell?.imageView?.isHidden = false selectedIndexPath = indexPath if (indexPath as NSIndexPath).section == 0 { updateRecurrenceRule(withSelectedIndexPath: indexPath) updateRecurrenceRuleText() navigationController?.popViewController(animated: true) } else { let customRecurrenceViewController = CustomRecurrenceViewController(style: .grouped) customRecurrenceViewController.occurrenceDate = occurrenceDate customRecurrenceViewController.tintColor = tintColor customRecurrenceViewController.backgroundColor = backgroundColor customRecurrenceViewController.separatorColor = separatorColor customRecurrenceViewController.delegate = self var rule = recurrenceRule ?? RecurrenceRule.dailyRecurrence() let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday, .day, .month], from: occurrenceDate) if rule.byweekday.count == 0 { let weekday = EKWeekday(rawValue: occurrenceDateComponents.weekday!)! rule.byweekday = [weekday] } if rule.bymonthday.count == 0 { if let monthday = occurrenceDateComponents.day { rule.bymonthday = [monthday] } } if rule.bymonth.count == 0 { if let month = occurrenceDateComponents.month { rule.bymonth = [month] } } customRecurrenceViewController.recurrenceRule = rule navigationController?.pushViewController(customRecurrenceViewController, animated: true) } tableView.deselectRow(at: indexPath, animated: true) } } extension RecurrencePicker { // MARK: - Helper fileprivate func commonInit() { navigationItem.title = LocalizedString("RecurrencePicker.Navigation.Title") navigationController?.navigationBar.tintColor = tintColor tableView.tintColor = tintColor if let backgroundColor = backgroundColor { tableView.backgroundColor = backgroundColor } if let separatorColor = separatorColor { tableView.separatorColor = separatorColor } updateSelectedIndexPath(withRule: recurrenceRule) } fileprivate func updateSelectedIndexPath(withRule recurrenceRule: RecurrenceRule?) { guard let recurrenceRule = recurrenceRule else { selectedIndexPath = IndexPath(row: 0, section: 0) return } if recurrenceRule.isDailyRecurrence() { selectedIndexPath = IndexPath(row: 1, section: 0) } else if recurrenceRule.isWeeklyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 2, section: 0) } else if recurrenceRule.isBiWeeklyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 3, section: 0) } else if recurrenceRule.isMonthlyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 4, section: 0) } else if recurrenceRule.isYearlyRecurrence(occurrenceDate: occurrenceDate) { selectedIndexPath = IndexPath(row: 5, section: 0) } else if recurrenceRule.isWeekdayRecurrence() { selectedIndexPath = IndexPath(row: 6, section: 0) } else { selectedIndexPath = IndexPath(row: 0, section: 1) } } fileprivate func updateRecurrenceRule(withSelectedIndexPath indexPath: IndexPath) { guard indexPath.section == 0 else { return } switch indexPath.row { case 0: recurrenceRule = nil case 1: recurrenceRule = RecurrenceRule.dailyRecurrence() case 2: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday], from: occurrenceDate) if let weekDayRaw = occurrenceDateComponents.weekday, let weekday = EKWeekday(rawValue: weekDayRaw) { recurrenceRule = RecurrenceRule.weeklyRecurrence(weekday: weekday) } case 3: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.weekday], from: occurrenceDate) if let weekDayRaw = occurrenceDateComponents.weekday, let weekday = EKWeekday(rawValue: weekDayRaw) { recurrenceRule = RecurrenceRule.biWeeklyRecurrence(weekday: weekday) } case 4: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.day], from: occurrenceDate) if let monthday = occurrenceDateComponents.day { recurrenceRule = RecurrenceRule.monthlyRecurrence(monthday: monthday) } case 5: let occurrenceDateComponents = (calendar as Calendar).dateComponents([.month], from: occurrenceDate) if let month = occurrenceDateComponents.month { recurrenceRule = RecurrenceRule.yearlyRecurrence(month: month) } case 6: recurrenceRule = RecurrenceRule.weekdayRecurrence() default: break } } fileprivate func recurrenceRuleText() -> String? { return (selectedIndexPath as IndexPath).section == 1 ? recurrenceRule?.toText(on: occurrenceDate) : nil } fileprivate func updateRecurrenceRuleText() { let footerView = tableView.footerView(forSection: 1) tableView.beginUpdates() footerView?.textLabel?.text = recurrenceRuleText() tableView.endUpdates() footerView?.setNeedsLayout() } } extension RecurrencePicker: CustomRecurrenceViewControllerDelegate { func customRecurrenceViewController(_ controller: CustomRecurrenceViewController, didPickRecurrence recurrenceRule: RecurrenceRule) { self.recurrenceRule = recurrenceRule updateRecurrenceRuleText() } }
5b66412f998ca7dfc679cb29405e5afe
39.011673
137
0.659438
false
false
false
false
groovelab/SwiftBBS
refs/heads/master
SwiftBBS/SwiftBBS/BbsDetailViewController.swift
mit
1
// // BbsDetailViewController.swift // SwiftBBS // // Created by Takeo Namba on 2016/01/16. // Copyright GrooveLab // import UIKit import PerfectLib class BbsDetailViewController: UIViewController { let END_POINT: String = "http://\(Config.END_POINT_HOST):\(Config.END_POINT_PORT)/bbs/detail/" let END_POINT_COMMENT: String = "http://\(Config.END_POINT_HOST):\(Config.END_POINT_PORT)/bbs/addcomment/" var bbsId: Int? var bbs: JSONDictionaryType? var commentArray: JSONArrayType? var doScrollBottom = false private var cellForHeight: BbsDetailTableViewCell! @IBOutlet weak private var titleLabel: UILabel! @IBOutlet weak private var commentLabel: UILabel! @IBOutlet weak private var userNameLabel: UILabel! @IBOutlet weak private var createdAtLabel: UILabel! @IBOutlet weak private var tableView: UITableView! @IBOutlet weak private var commentTextView: UITextView! @IBOutlet weak private var bottomMarginConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 44.0)) toolBar.items = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil), UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(BbsDetailViewController.closeKeyboard(_:))) ] commentTextView.inputAccessoryView = toolBar commentTextView.text = nil cellForHeight = tableView.dequeueReusableCellWithIdentifier(BbsDetailTableViewCell.identifierForReuse) as! BbsDetailTableViewCell fetchData() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BbsDetailViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BbsDetailViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { guard let userInfo = notification.userInfo, let keyBoardRectValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else { return } let keyboardRect = keyBoardRectValue.CGRectValue() bottomMarginConstraint.constant = keyboardRect.height - (navigationController?.tabBarController?.tabBar.frame.height)! UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() } } func keyboardWillHide(notification: NSNotification) { guard let userInfo = notification.userInfo, let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else { return } bottomMarginConstraint.constant = 0.0 UIView.animateWithDuration(duration) { self.view.layoutIfNeeded() } } func closeKeyboard(sender: UIBarButtonItem) { commentTextView.resignFirstResponder() } private func fetchData() { guard let bbsId = bbsId else { return } let req = NSMutableURLRequest(URL: NSURL(string: END_POINT + "\(bbsId)")!) req.HTTPMethod = "GET" req.addValue("application/json", forHTTPHeaderField: "Accept") req.addTokenToCookie() let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(req, completionHandler: { (data:NSData?, res:NSURLResponse?, error:NSError?) -> Void in if let error = error { print("Request failed with error \(error)") return; } guard let data = data, let stringData = String(data: data, encoding: NSUTF8StringEncoding) else { print("response is empty") return; } do { let jsonDecoded = try JSONDecoder().decode(stringData) if let jsonMap = jsonDecoded as? JSONDictionaryType { if let bbsDictionary = jsonMap.dictionary["bbs"] as? JSONDictionaryType { self.bbs = bbsDictionary } if let comments = jsonMap.dictionary["comments"] as? JSONArrayType { self.commentArray = comments dispatch_async(dispatch_get_main_queue(), { self.didFetchData() }) } } } catch let exception { print("JSON decoding failed with exception \(exception)") } }) task.resume() } private func didFetchData() { if let bbs = bbs { if let title = bbs.dictionary["title"] as? String { titleLabel.text = title } if let comment = bbs.dictionary["comment"] as? String { commentLabel.text = comment } if let userName = bbs.dictionary["userName"] as? String { userNameLabel.text = userName } if let createdAt = bbs.dictionary["createdAt"] as? String { createdAtLabel.text = createdAt } } tableView.reloadData() if doScrollBottom { doScrollBottom = false if let commentArray = commentArray where commentArray.array.count > 0 { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: commentArray.array.count - 1, inSection: 0), atScrollPosition: .Bottom, animated: true) } } } @IBAction private func commentAction(sender: UIButton) { doComment() } private func doComment() { guard let bbsId = bbsId, let comment = commentTextView.text else { return } if comment.isEmpty { return } let req = NSMutableURLRequest(URL: NSURL(string: END_POINT_COMMENT)!) req.HTTPMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Accept") req.addTokenToCookie() let postBody = "bbs_id=\(bbsId)&comment=\(comment)" req.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(req, completionHandler: { (data:NSData?, res:NSURLResponse?, error:NSError?) -> Void in if let error = error { print("Request failed with error \(error)") return; } guard let data = data, let stringData = String(data: data, encoding: NSUTF8StringEncoding) else { print("response is empty") return; } do { let jsonDecoded = try JSONDecoder().decode(stringData) if let jsonMap = jsonDecoded as? JSONDictionaryType { if let _ = jsonMap["commentId"] as? Int { dispatch_async(dispatch_get_main_queue(), { self.didComment() }) } } } catch let exception { print("JSON decoding failed with exception \(exception)") } }) task.resume() } private func didComment() { commentTextView.text = nil commentTextView.resignFirstResponder() doScrollBottom = true fetchData() } } extension BbsDetailViewController : UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let commentArray = commentArray else { return 0 } return commentArray.array.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { cellForHeight.prepareForReuse() configureCell(cellForHeight, indexPath: indexPath) return cellForHeight.fittingSizeForWith(view.frame.width).height } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(BbsDetailTableViewCell.identifierForReuse, forIndexPath: indexPath) as! BbsDetailTableViewCell configureCell(cell, indexPath: indexPath) return cell } func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } private func configureCell(cell: BbsDetailTableViewCell, indexPath: NSIndexPath) { if let commentArray = commentArray, let comment = commentArray.array[indexPath.row] as? JSONDictionaryType { cell.item = comment.dictionary } } }
951b521251695541b03c0af62615c0e7
37.569106
180
0.611404
false
false
false
false
CanyFrog/HCComponent
refs/heads/master
HCSource/HCProgressView.swift
mit
1
// // HCProgressView.swift // HCComponents // // Created by Magee Huang on 5/9/17. // Copyright © 2017 Person Inc. All rights reserved. // // tips progressview import UIKit /// Progress view open class HCProgressView: UIView { public enum progressStyle{ case pie case ring } open var progress: CGFloat = 0.0 { willSet { if progress != newValue { setNeedsDisplay() } } } open var progressTintColor = UIColor.white { willSet { if progressTintColor != newValue && !progressTintColor.isEqual(newValue) { setNeedsDisplay() } } } open var backgroundTintColor = UIColor.white { willSet { if backgroundTintColor != newValue && !backgroundTintColor.isEqual(newValue) { setNeedsDisplay() } } } public var style: progressStyle = .ring public var lineWidth: CGFloat = 2.0 open override var intrinsicContentSize: CGSize { return CGSize(width: 37, height: 37) } public override init(frame: CGRect) { super.init(frame: frame) backgroundTintColor = UIColor.clear isOpaque = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func draw(_ rect: CGRect) { // back let processBackPath = UIBezierPath() processBackPath.lineWidth = lineWidth processBackPath.lineCapStyle = .round let centerPoint = CGPoint(x: centerX, y: centerY) let radius = (width - lineWidth) / 2 let startAngle = -CGFloat.pi/2 var endAngle = startAngle + CGFloat.pi * 2 processBackPath.addArc(withCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) backgroundTintColor.set() processBackPath.stroke() // process let processPath = UIBezierPath() processPath.lineCapStyle = .square processPath.lineWidth = lineWidth endAngle = progress * 2 * CGFloat.pi + startAngle processPath.addArc(withCenter: centerPoint, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) progressTintColor.set() if style == .ring { processPath.stroke() } else { processPath.addLine(to: centerPoint) processPath.close() processPath.fill() } } } /// Tips progress view open class HCTipsProgessView: HCTipsView { public private(set) var progressView: HCProgressView = { let progress = HCProgressView(frame: CGRect.zero) progress.backgroundTintColor = UIColor.darkGray progress.progressTintColor = UIColor.red progress.style = .ring return progress }() public var progress: CGFloat = 0.0 { didSet { progressView.progress = progress } } public override init(frame: CGRect) { super.init(frame: frame) addArrangedSubview(progressView) stackInsert = UIEdgeInsetsMake(12, 12, 12, 12) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @discardableResult public class func show(progress: CGFloat = 0.0, in view: UIView, animation: HCTipsAnimationType = .none) -> HCTipsProgessView { let tips = HCTipsProgessView(in: view) tips.progress = progress tips.showTipsView(animation) return tips } }
f7696b71bb0f248c9d411ecbf4eac6db
27.88189
132
0.60687
false
false
false
false
carolight/RWThreeRingControl
refs/heads/master
Example/RWThreeRingControl-Example/Pods/RWThreeRingControl/RWThreeRingControl/ThreeRingView/CircularGradient.swift
mit
2
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import CoreImage import UIKit private class CircularGradientFilter : CIFilter { private lazy var kernel: CIColorKernel = { return self.createKernel() }() var outputSize: CGSize! var colors: (CIColor, CIColor)! override var outputImage : CIImage { let dod = CGRect(origin: .zero, size: outputSize) let args = [ colors.0 as AnyObject, colors.1 as AnyObject, outputSize.width, outputSize.height] return kernel.apply(withExtent: dod, arguments: args)! } private func createKernel() -> CIColorKernel { let kernelString = "kernel vec4 chromaKey( __color c1, __color c2, float width, float height ) { \n" + " vec2 pos = destCoord();\n" + " float x = 1.0 - 2.0 * pos.x / width;\n" + " float y = 1.0 - 2.0 * pos.y / height;\n" + " float prop = atan(y, x) / (3.1415926535897932 * 2.0) + 0.5;\n" + " return c1 * prop + c2 * (1.0 - prop);\n" + "}" return CIColorKernel(string: kernelString)! } } class CircularGradientLayer : CALayer { private let gradientFilter = CircularGradientFilter() private let ciContext = CIContext(options: [ kCIContextUseSoftwareRenderer : false ]) override init() { super.init() needsDisplayOnBoundsChange = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) needsDisplayOnBoundsChange = true } override init(layer: AnyObject) { super.init(layer: layer) needsDisplayOnBoundsChange = true if let layer = layer as? CircularGradientLayer { colors = layer.colors } } var colors: (CGColor, CGColor) = (UIColor.white().cgColor, UIColor.black().cgColor) { didSet { setNeedsDisplay() } } override func draw(in ctx: CGContext) { super.draw(in: ctx) gradientFilter.outputSize = bounds.size gradientFilter.colors = (CIColor(cgColor: colors.0), CIColor(cgColor: colors.1)) let image = ciContext.createCGImage(gradientFilter.outputImage, from: bounds) ctx.draw(in: bounds, image: image!) } }
8eb9366e80eb11ae9d7557684b10e558
33.054348
99
0.696457
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Fitting/Cargo/FittingCargoActions.swift
lgpl-2.1
2
// // FittingCargoActions.swift // Neocom // // Created by Artem Shimanski on 4/17/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Dgmpp struct FittingCargoActions: View { @ObservedObject var ship: DGMShip @ObservedObject var cargo: DGMCargo var completion: () -> Void @Environment(\.managedObjectContext) private var managedObjectContext @State private var selectedType: SDEInvType? @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState @State private var isEditing = false var body: some View { let type = cargo.type(from: managedObjectContext) let perItem = Double(cargo.volume) / Double(cargo.quantity) let bind = Binding<String>(get: { "\(self.cargo.quantity)" }) { (newValue) in self.cargo.quantity = NumberFormatter().number(from: newValue)?.intValue ?? 0 } return List { Button(action: {self.selectedType = type}) { HStack { type.map{Icon($0.image).cornerRadius(4)} type?.typeName.map{Text($0)} ?? Text("Unknown") } }.buttonStyle(PlainButtonStyle()) HStack { Text("Volume") Spacer() CargoVolume(ship: ship, cargo: cargo).foregroundColor(.secondary) } HStack { Text("Per Item") Spacer() Text(UnitFormatter.localizedString(from: perItem, unit: .cubicMeter, style: .long)).foregroundColor(.secondary) } HStack { Text("Quantity") Spacer() // TextField(<#T##title: StringProtocol##StringProtocol#>, text: <#T##Binding<String>#>, onEditingChanged: <#T##(Bool) -> Void#>, onCommit: <#T##() -> Void#>) TextField(NSLocalizedString("Quantity", comment:""), text: bind, onEditingChanged: { isEditing in withAnimation { self.isEditing = isEditing } }) .textFieldStyle(RoundedBorderTextFieldStyle()) .keyboardType(.numberPad) .frame(width: 100) .multilineTextAlignment(.center) Stepper("Quantity", value: $cargo.quantity).labelsHidden() if isEditing { Button(NSLocalizedString("Done", comment: "")) { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) }.buttonStyle(BorderlessButtonStyle()).fixedSize() } else { Button(NSLocalizedString("Max", comment: "")) { let free = self.ship.cargoCapacity - self.ship.usedCargoCapacity + self.cargo.volume let qty = (free / perItem).rounded(.down) self.cargo.quantity = Int(max(qty, 1)) }.buttonStyle(BorderlessButtonStyle()).fixedSize() } } } .listStyle(GroupedListStyle()) .navigationBarTitle(Text("Actions")) .navigationBarItems(leading: BarButtonItems.close(completion), trailing: BarButtonItems.trash { self.completion() DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) { self.ship.remove(self.cargo) } }) .sheet(item: $selectedType) { type in NavigationView { TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil}) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } #if DEBUG struct FittingCargoActions_Previews: PreviewProvider { static var previews: some View { let ship = DGMShip.testDominix() let cargo = ship.cargo[0] cargo.quantity = 10 return FittingCargoActions(ship: ship, cargo: cargo) {} .modifier(ServicesViewModifier.testModifier()) } } #endif
f49c1c025da31c816be4aff8df3f3ae3
37.936937
173
0.558769
false
false
false
false
alvinvarghese/Natalie
refs/heads/master
NatalieExample/NatalieExample/MainViewController.swift
mit
4
// // ViewController.swift // NatalieExample // // Created by Marcin Krzyzanowski on 15/04/15. // Copyright (c) 2015 Marcin Krzyżanowski. All rights reserved. // import UIKit class MainViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } //MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue == MainViewController.Segue.ScreenOneSegue, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.yellowColor() } else if segue == MainViewController.Segue.ScreenOneSegueButton, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.brownColor() } else if segue == MainViewController.Segue.ScreenTwoSegue, let twoViewController = segue.destinationViewController as? ScreenTwoViewController { twoViewController.view.backgroundColor = UIColor.magentaColor() } else if segue == MainViewController.Segue.SceneOneGestureRecognizerSegue, let oneViewController = segue.destinationViewController as? ScreenOneViewController { oneViewController.view.backgroundColor = UIColor.greenColor() } } //MARK: Actions @IBAction func screen1ButtonPressed(button:UIButton) { self.performSegue(MainViewController.Segue.ScreenOneSegue) } @IBAction func screen22ButtonPressed(button:UIButton) { self.performSegue(MainViewController.Segue.ScreenTwoSegue, sender: nil) } }
1bf295334da431600eefe630a090d404
38.642857
169
0.737538
false
false
false
false
pourhadi/SuperSerial
refs/heads/master
Example/SuperSerialPlayground.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit import SuperSerial struct Person { let name:String let age:Int } extension Person: AutoSerializable { init?(withValuesForKeys:[String:Serializable]) { guard let name = withValuesForKeys["name"] as? String else { return nil } guard let age = withValuesForKeys["age"] as? Int else { return nil } self.name = name self.age = age } } let person = Person(name:"Bob", age:20) let serialized = person.ss_serialize() print(serialized)
3dd1e7325412f5195d9c01a424b58b6c
21.24
81
0.660072
false
false
false
false
scarviz/SampleBLEforiOS
refs/heads/master
SampleBLE/PeripheralManagerDelegate.swift
mit
1
// // PeripheralManagerDelegate.swift // SampleBLE // // Created by scarviz on 2014/09/08. // Copyright (c) 2014年 scarviz. All rights reserved. // import CoreBluetooth class PeripheralManagerDelegate : NSObject, CBPeripheralManagerDelegate{ /* BLEの状態変更時処理 */ func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!){ if (peripheral.state == CBPeripheralManagerState.PoweredOn) { NSLog("state PoweredOn") } } /* PeripheralManager登録完了時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didAddService service: CBService!, error: NSError!) { if error != nil { NSLog(error.localizedFailureReason!) return } var name = "SampleBLE" // アドバタイズを開始する peripheral.startAdvertising( [CBAdvertisementDataLocalNameKey:name , CBAdvertisementDataServiceUUIDsKey:[service.UUID] ]) NSLog("start Advertising") } /* アドバタイズ開始後処理 */ func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager!, error: NSError!) { if error != nil { NSLog(error.localizedFailureReason!) } else { NSLog("DidStartAdvertising no error") } } /* CentralからのRead要求時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didReceiveReadRequest request: CBATTRequest!) { // ReadでCentralに返す値(テスト用) var val:Byte = 0x10 request.value = NSData(bytes: &val, length: 1) // Centralに返す peripheral.respondToRequest(request, withResult: CBATTError.Success) } /* CentralからのWrite要求時処理 */ func peripheralManager(peripheral: CBPeripheralManager!, didReceiveWriteRequests requests: [AnyObject]!) { for item in requests { // Centralからのデータ取得 var res = NSString(data: item.value, encoding: NSUTF8StringEncoding) // TODO:取得したデータを処理する } } }
6a2b64283225d25d69603ad6f6d4d96c
27.136986
114
0.622017
false
false
false
false
ello/ello-ios
refs/heads/master
Specs/Controllers/Onboarding/OnboardingProfileScreenSpec.swift
mit
1
//// /// OnboardingProfileScreenSpec.swift // @testable import Ello import Quick import Nimble class OnboardingProfileScreenSpec: QuickSpec { class MockDelegate: OnboardingProfileDelegate { var didAssignName = false var didAssignBio = false var didAssignLinks = false var didAssignCoverImage = false var didAssignAvatar = false func present(controller: UIViewController) {} func dismissController() {} func assign(name: String?) -> ValidationState { didAssignName = true return (name?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(bio: String?) -> ValidationState { didAssignBio = true return (bio?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(links: String?) -> ValidationState { didAssignLinks = true return (links?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(coverImage: ImageRegionData) { didAssignCoverImage = true } func assign(avatarImage: ImageRegionData) { didAssignAvatar = true } } override func spec() { describe("OnboardingProfileScreen") { var subject: OnboardingProfileScreen! var delegate: MockDelegate! beforeEach { subject = OnboardingProfileScreen() delegate = MockDelegate() subject.delegate = delegate showView(subject) } context("snapshots") { validateAllSnapshots(named: "OnboardingProfileScreen") { return subject } } context("snapshots setting existing data") { validateAllSnapshots(named: "OnboardingProfileScreen with data") { subject.name = "name" subject.bio = "bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio" subject.links = "links links links links links links links links links links links links" subject.linksValid = true subject.coverImage = ImageRegionData( image: UIImage.imageWithColor( .blue, size: CGSize(width: 1000, height: 1000) )! ) subject.avatarImage = ImageRegionData(image: specImage(named: "specs-avatar")!) return subject } } context("setting text") { it("should notify delegate of name change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Name") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignName) == true } it("should notify delegate of bio change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Bio") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignBio) == true } it("should notify delegate of link change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Links") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignLinks) == true } it("should notify delegate of avatar change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .avatar, updateDelegate: true) expect(delegate.didAssignAvatar) == true } it("should notify delegate of coverImage change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .coverImage, updateDelegate: true) expect(delegate.didAssignCoverImage) == true } } } } }
75c4e779df757704b13e4e251ba72f66
40.470588
99
0.505167
false
false
false
false
LinDing/Positano
refs/heads/master
Positano/Extensions/UISegmentedControl+Yep.swift
mit
1
// // UISegmentedControl+Yep.swift // Yep // // Created by NIX on 16/8/3. // Copyright © 2016年 Catch Inc. All rights reserved. // import UIKit extension UISegmentedControl { func yep_setTitleFont(_ font: UIFont, withPadding padding: CGFloat) { let attributes = [NSFontAttributeName: font] setTitleTextAttributes(attributes, for: .normal) var maxWidth: CGFloat = 0 for i in 0..<numberOfSegments { if let title = titleForSegment(at: i) { let width = (title as NSString).size(attributes: attributes).width + (padding * 2) maxWidth = max(maxWidth, width) } } for i in 0..<numberOfSegments { setWidth(maxWidth, forSegmentAt: i) } } }
5c7ce51fa3784a822fed57842b9a187c
23.15625
98
0.596378
false
false
false
false
inquisitiveSoft/SwiftCoreExtensions
refs/heads/dev
Extensions/String.swift
mit
1
// // String.swift // Syml // // Created by Harry Jordan on 26/08/2015. // Copyright © 2015 Inquisitive Software. All rights reserved. // import Foundation func NSRangeOfString(string: NSString!) -> NSRange { let range = NSRange(location: 0, length:string.length) return range } extension String { func isMatchedBy(_ pattern: String) -> Bool { do { let regex = try NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators) let matches = regex.numberOfMatches(in: self, options: [], range: NSRangeOfString(string: self as NSString)) return matches > 0 } catch {} return false } var numberOfWords: UInt { var numberOfWords: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: .byWords) { (_, _, _, _) in numberOfWords += 1 } return numberOfWords } var numberOfSentences: UInt { var numberOfSentences: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: [.bySentences, .substringNotRequired]) { (_, _, _, _) -> () in numberOfSentences += 1 } return numberOfSentences } var numberOfParagraphs: UInt { var numberOfParagraphs: UInt = 0 let searchRange = self.startIndex..<self.endIndex self.enumerateSubstrings(in: searchRange, options: [.byParagraphs, .substringNotRequired]) { (_, _, _, _) -> () in numberOfParagraphs += 1 } return numberOfParagraphs } var numberOfCharacters: UInt { return UInt(count) } var numberOfDecimalCharacters: Int { return numberOfCharacters(in: .decimalDigits) } func numberOfCharacters(in characterSet: CharacterSet, minimumRun: Int = 0) -> Int { var numberOfMatchingCharacters = 0 let scanner = Scanner(string: self) repeat { scanner.scanUpToCharacters(from: characterSet, into: nil) var matchingString: NSString? = nil if !scanner.isAtEnd && scanner.scanCharacters(from: characterSet, into: &matchingString), let matchingString = matchingString { numberOfMatchingCharacters += matchingString.length } } while (!scanner.isAtEnd) return numberOfMatchingCharacters } var looksLikeAnIdentifier: Bool { let knownPrefixes = ["text-"] var numberOfIdentifierCharacters = knownPrefixes.filter { self.hasPrefix($0) }.reduce(0) { $0 + $1.count } let identifierCharacterSets: [CharacterSet] = [ CharacterSet.decimalDigits, CharacterSet(charactersIn: "–-_"), CharacterSet.uppercaseLetters ] var combinedIdentifierCharacterSet = CharacterSet() for characterSet in identifierCharacterSets { combinedIdentifierCharacterSet.formUnion(characterSet) } numberOfIdentifierCharacters += self.numberOfCharacters(in: combinedIdentifierCharacterSet, minimumRun: 5) let stringLength = self.count if (stringLength > 0) && (numberOfIdentifierCharacters > 0) && (Double(numberOfIdentifierCharacters) / Double(stringLength) > 0.55) { return true } return false } func firstLine(upToCharacter desiredNumberOfCharacters: Int) -> String { var numberOfCharacters = 0 var desiredRange: Range = startIndex..<endIndex enumerateLines { (line, stop) -> () in if !line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { line.enumerateSubstrings(in: line.startIndex..<line.endIndex, options: [.byWords]) { (substring, _, enclosingRange, stopInternal) -> () in desiredRange = line.startIndex..<enclosingRange.upperBound numberOfCharacters += substring?.count ?? 0 if numberOfCharacters >= desiredNumberOfCharacters { stopInternal = true } } stop = true } } let resultingString = self[desiredRange].trimmingCharacters(in: .whitespacesAndNewlines) return resultingString } func substringForUntestedRange(range: NSRange) -> String? { let text = self as NSString let textRange = NSRangeOfString(string: text) let validRange = NSIntersectionRange(textRange, range) if validRange.length > 0 { return text.substring(with: validRange) } return nil } // MARK: String localization var localized: String { get { return localized() } } func localized(comment: String = "") -> String { return NSLocalizedString(self, comment: comment) } }
fae680b0787200a361ca552886cd61d2
29.881657
154
0.583062
false
false
false
false