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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27629678/RxDemo | refs/heads/master | RxDemo/SearchViewController.swift | mit | 1 | //
// SearchViewController.swift
// RxDemo
//
// Created by hzyuxiaohua on 2016/10/25.
// Copyright © 2016年 hzyuxiaohua. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SearchViewController: UIViewController {
let disposeBag = DisposeBag()
var myDisposable: Disposable? = nil
@IBOutlet weak var input: UITextField!
@IBOutlet weak var `switch`: UISwitch!
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "Search"
// bind switch action
`switch`.rx.value
.subscribe(onNext: { [weak self] in self?.switchBtnAction(isOn: $0)} )
.addDisposableTo(disposeBag)
}
func switchBtnAction(isOn: Bool) {
input.text = ""
textView.text = ""
myDisposable?.dispose()
if isOn {
textView.text.append("Throttle")
myDisposable = input.rx.text
.throttle(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.handle($0) })
}
else {
textView.text.append("Debounce")
myDisposable = input.rx.text
.debounce(1, scheduler: MainScheduler.instance)
.subscribe(onNext: { [weak self] in self?.handle($0) })
}
myDisposable?.addDisposableTo(disposeBag)
}
func handle(_ keyword: String?) {
guard let text = keyword, text.characters.count > 0 else {
return
}
textView.text.append("\n" + String(Int(Date().timeIntervalSince1970)) + "\t:" + text)
}
}
| f79fe6bd2e866fcda9fa7770c6e6a2e8 | 26.390625 | 93 | 0.575585 | false | false | false | false |
koutalou/iOS-CleanArchitecture | refs/heads/master | iOSCleanArchitectureTwitterSample/Presentation/UI/ViewController/LoginAccountViewController.swift | mit | 1 | //
// LoginAccountViewController.swift
// iOSCleanArchitectureTwitterSample
//
// Created by koutalou on 2015/12/20.
// Copyright © 2015年 koutalou. All rights reserved.
//
import UIKit
protocol LoginAccountViewInput: class {
func setAccountsModel(_: RegisteredAccountsModel)
func changedStatus(_: LoginAccountStatus)
}
class LoginAccountViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var footerLabel: UILabel!
var presenter: LoginAccountPresenter?
var twitterAccountsModel: RegisteredAccountsModel?
var accountStatus: LoginAccountStatus = .none
public func inject(presenter: LoginAccountPresenter) {
self.presenter = presenter
}
override func viewDidLoad() {
super.viewDidLoad()
presenter?.loadAccounts()
}
}
// MARK: LoginUserView
extension LoginAccountViewController: LoginAccountViewInput {
func setAccountsModel(_ accountsModel: RegisteredAccountsModel) {
twitterAccountsModel = accountsModel
self.tableView.reloadData()
}
func changedStatus(_ status: LoginAccountStatus) {
switch status {
case .normal:
footerLabel.text = "Select use account"
case .error:
footerLabel.text = "An error occured"
case .notAuthorized:
footerLabel.text = "Not authorized"
case .none:
footerLabel.text = "No twitter user"
}
}
}
// MARK: UIButton
extension LoginAccountViewController {
@IBAction func tapCancel(_ sender: UIBarButtonItem) {
presenter?.tapCancel()
}
@IBAction func tapReload(_ sender: UIBarButtonItem) {
// Reload accounts
presenter?.tapReload()
}
}
// MARK: Table view data source
extension LoginAccountViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (twitterAccountsModel?.accounts.count) ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoginAccountCell", for: indexPath) as! LoginAccountViewCell
let account: RegisteredAccountModel = twitterAccountsModel!.accounts[indexPath.row]
cell.updateCell(account)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
presenter?.selectAccount(indexPath.row)
}
}
| dcfa2d3e91f77f12bec2d1e0386ca1a2 | 28.362637 | 125 | 0.684132 | false | false | false | false |
ludoded/ReceiptBot | refs/heads/master | Pods/Material/Sources/iOS/SearchBar.swift | lgpl-3.0 | 2 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(SearchBarDelegate)
public protocol SearchBarDelegate {
/**
A delegation method that is executed when the textField changed.
- Parameter searchBar: A SearchBar.
- Parameter didChange textField: A UITextField.
- Parameter with text: An optional String.
*/
@objc
optional func searchBar(searchBar: SearchBar, didChange textField: UITextField, with text: String?)
/**
A delegation method that is executed when the textField will clear.
- Parameter searchBar: A SearchBar.
- Parameter willClear textField: A UITextField.
- Parameter with text: An optional String.
*/
@objc
optional func searchBar(searchBar: SearchBar, willClear textField: UITextField, with text: String?)
/**
A delegation method that is executed when the textField is cleared.
- Parameter searchBar: A SearchBar.
- Parameter didClear textField: A UITextField.
- Parameter with text: An optional String.
*/
@objc
optional func searchBar(searchBar: SearchBar, didClear textField: UITextField, with text: String?)
}
open class SearchBar: Bar {
/// The UITextField for the searchBar.
@IBInspectable
open let textField = UITextField()
/// Reference to the clearButton.
open fileprivate(set) var clearButton: IconButton!
/// A reference to the delegate.
open weak var delegate: SearchBarDelegate?
/// Handle the clearButton manually.
@IBInspectable
open var isClearButtonAutoHandleEnabled = true {
didSet {
clearButton.removeTarget(self, action: #selector(handleClearButton), for: .touchUpInside)
if isClearButtonAutoHandleEnabled {
clearButton.addTarget(self, action: #selector(handleClearButton), for: .touchUpInside)
}
}
}
/// TintColor for searchBar.
@IBInspectable
open override var tintColor: UIColor? {
get {
return textField.tintColor
}
set(value) {
textField.tintColor = value
}
}
/// TextColor for searchBar.
@IBInspectable
open var textColor: UIColor? {
get {
return textField.textColor
}
set(value) {
textField.textColor = value
}
}
/// Sets the textField placeholder value.
@IBInspectable
open var placeholder: String? {
didSet {
if let v = placeholder {
textField.attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderColor])
}
}
}
/// Placeholder text
@IBInspectable
open var placeholderColor = Color.darkText.others {
didSet {
if let v = placeholder {
textField.attributedPlaceholder = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: placeholderColor])
}
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
super.init(frame: frame)
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout else {
return
}
textField.frame = contentView.bounds
layoutLeftView()
layoutClearButton()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
prepareTextField()
prepareClearButton()
}
}
extension SearchBar {
/// Layout the clearButton.
open func layoutClearButton() {
let h = textField.frame.height
clearButton.frame = CGRect(x: textField.frame.width - h - 4, y: 4, width: h, height: h - 8)
}
/// Layout the leftView.
open func layoutLeftView() {
guard let v = textField.leftView else {
return
}
let h = textField.frame.height
v.frame = CGRect(x: 4, y: 4, width: h, height: h - 8)
(v as? UIImageView)?.contentMode = .scaleAspectFit
}
}
extension SearchBar {
/// Clears the textField text.
@objc
fileprivate func handleClearButton() {
guard nil == textField.delegate?.textFieldShouldClear || true == textField.delegate?.textFieldShouldClear?(textField) else {
return
}
let t = textField.text
delegate?.searchBar?(searchBar: self, willClear: textField, with: t)
textField.text = nil
delegate?.searchBar?(searchBar: self, didClear: textField, with: t)
}
// Live updates the search results.
@objc
fileprivate func handleEditingChanged(textField: UITextField) {
delegate?.searchBar?(searchBar: self, didChange: textField, with: textField.text)
}
}
extension SearchBar {
/// Prepares the textField.
fileprivate func prepareTextField() {
textField.contentScaleFactor = Screen.scale
textField.font = RobotoFont.regular(with: 17)
textField.backgroundColor = Color.clear
textField.clearButtonMode = .whileEditing
tintColor = placeholderColor
textColor = Color.darkText.primary
placeholder = "Search"
contentView.addSubview(textField)
textField.addTarget(self, action: #selector(handleEditingChanged(textField:)), for: .editingChanged)
}
/// Prepares the clearButton.
fileprivate func prepareClearButton() {
clearButton = IconButton(image: Icon.cm.close, tintColor: placeholderColor)
clearButton.contentEdgeInsets = .zero
isClearButtonAutoHandleEnabled = true
textField.clearButtonMode = .never
textField.rightViewMode = .whileEditing
textField.rightView = clearButton
}
}
| dcb78b805c9018679934762c3a058d22 | 31.729958 | 132 | 0.692407 | false | false | false | false |
PedroTrujilloV/TIY-Assignments | refs/heads/master | 19--Keep-On-The-Sunny-Side/Forecaster/GitHub Friends/ForecasterListViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import UIKit
protocol APIControllerProtocol
{
func didReceiveAPIResults(results:NSArray)
}
protocol SearchTableViewProtocol
{
func cityWasFound(city:String)
}
class ForecasterListViewController: UITableViewController, APIControllerProtocol,SearchTableViewProtocol
{
var rigthAddButtonItem:UIBarButtonItem!
var cities = Array<CityData>()
var citiesRegistered = Array<String>()
var api: APIController!
var friendForSearch = ""
override func viewDidLoad()
{
super.viewDidLoad()
title = "Forecaster ⛅️"
// Do any additional setup after loading the view, typically from a nib.
api = APIController(delegate: self)
//api.searchGitHubFor("jcgohlke")
//api.searchGitHubFor("Ben Gohlke")
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
rigthAddButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addButtonActionTapped:")
self.navigationItem.setRightBarButtonItems([rigthAddButtonItem], animated: true)
self.tableView.registerClass(CityCell.self, forCellReuseIdentifier: "CityCell")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return cities.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return 50.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("CityCell", forIndexPath: indexPath) as! CityCell
let friend = cities[indexPath.row]
print("friend: "+friend.name)
cell.textLabel!.text = friend.name
cell.loadImage(friend.thumbnailImageURL)
//cell.editing = true
//cell.detailTextLabel?.text = "Penpenuche"
return cell
}
//
// // Override to support conditional editing of the table view.
// override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// // Return false 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
// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// } else if editingStyle == .Insert {
// // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
// }
// }
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let datailsVC:DetailViewController = DetailViewController()
datailsVC.cityData = cities[indexPath.row]
//presentViewController(datailsVC, animated: true, completion: nil)// it shows like a modal view
navigationController?.pushViewController(datailsVC, animated: true)
}
//MARK: - Handle Actions
func addButtonActionTapped(sender: UIButton)
{
print("Hay que rico!")
//MARK: this piece of code is fucking awesome !!!!
let searchTableVC = SearchTableViewController()
let navigationController = UINavigationController(rootViewController: searchTableVC)// THIS is fucking awesome!!!! this create a new navigation controller that allows the modal view animation !!!!!!!!!!!!!
searchTableVC.delegator = self // 3 nescessary to get the value from the popover
// navigationController?.pushViewController(searchTableVC, animated: true)
//presentViewController(searchTableVC, animated: true, completion: nil)// it shows like a modal view
presentViewController(navigationController, animated: true, completion: nil)
}
//MARK: - API Controller Protocl
func didReceiveAPIResults(results:NSArray)
{
print("didReceiveAPIResults got: \(results)")
dispatch_async(dispatch_get_main_queue(), {
//self.gitHubFriends = GitHubFriend.CitiesDataWithJSON(results)
self.cities.append( CityData.aCityDataWithJSON(results))
self.tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
})
}
//MARK: - Search View Controller Protocl
func cityWasFound(cicty:String)
{
if !citiesRegistered.contains(cicty)
{
citiesRegistered.append(cicty)
api.searchApiForData(cicty, byCriteria: "user")
tableView.reloadData()
print("Friend was found!!!!!!!: "+cicty)
dismissViewControllerAnimated(true, completion: nil) // this destroy the modal view like the popover
}
}
}
| fb9f8854a75e7042bb83d327080680bb | 34.724359 | 214 | 0.67522 | false | false | false | false |
SamirTalwar/advent-of-code | refs/heads/main | 2018/AOC_07_2.swift | mit | 1 | let minimumTime = CommandLine.arguments.count == 3 ? Int(CommandLine.arguments[1])! : 60
let workerCount = CommandLine.arguments.count == 3 ? Int(CommandLine.arguments[2])! : 5
let orderingParser = try! RegExp(pattern: "^Step (\\w) must be finished before step (\\w) can begin\\.$")
typealias Step = String
typealias Time = Int
let allSteps: [Step] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".map { Step($0) }
extension Step {
func timeTaken() -> Time {
return minimumTime + allSteps.firstIndex(where: { $0 == self })! + 1
}
}
struct Ordering {
let before: Step
let after: Step
}
struct Worker {
var done: [(Step, Time)] = []
var busyUntil: Time {
return done.last?.1 ?? 0
}
mutating func handle(step: Step, at start: Time) {
done.append((step, start + step.timeTaken()))
}
}
func main() {
let orderings = StdIn().map(parseOrdering)
let orderingLookup: [Step: Set<Step>] =
Dictionary(grouping: orderings, by: { $0.after })
.mapValues { steps in Set(steps.map { $0.before }) }
let befores: Set<Step> = Set(orderings.map { $0.before })
let afters: Set<Step> = Set(orderings.map { $0.after })
let steps = befores.union(afters)
var workers = Array(repeating: Worker(), count: workerCount)
var seen: Set<Step> = Set()
var unseen = steps
while !unseen.isEmpty {
for currentTime in Set(workers.map { $0.busyUntil }).sorted() {
let done = Set(workers.flatMap { worker in worker.done.filter { _, time in time <= currentTime }.map { step, _ in step } })
let next = unseen.subtracting(done).filter { step in (orderingLookup[step] ?? Set()).isSubset(of: done) }
if !next.isEmpty {
for selected in next.sorted() {
for i in 0 ..< workers.count {
if workers[i].busyUntil <= currentTime {
workers[i].handle(step: selected, at: currentTime)
seen.insert(selected)
unseen.remove(selected)
break
}
}
}
break
}
}
}
let timeTaken = workers.map { $0.busyUntil }.max()!
print(timeTaken)
}
func parseOrdering(string: String) -> Ordering {
guard let match = orderingParser.firstMatch(in: string) else {
fatalError("This ordering was unparseable: \(string)")
}
return Ordering(
before: String(match[1]),
after: String(match[2])
)
}
| 072bc64122115b51c22727779e47a91c | 31.325 | 135 | 0.566125 | false | false | false | false |
hyperconnect/Bond | refs/heads/master | Bond/Bond+UILabel.swift | mit | 1 | //
// Bond+UILabel.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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
private var textDynamicHandleUILabel: UInt8 = 0;
private var attributedTextDynamicHandleUILabel: UInt8 = 0;
extension UILabel: Bondable {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUILabel) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.text ?? "")
let bond = Bond<String>() { [weak self] v in if let s = self { s.text = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynAttributedText: Dynamic<NSAttributedString> {
if let d: AnyObject = objc_getAssociatedObject(self, &attributedTextDynamicHandleUILabel) {
return (d as? Dynamic<NSAttributedString>)!
} else {
let d = InternalDynamic<NSAttributedString>(self.attributedText ?? NSAttributedString(string: ""))
let bond = Bond<NSAttributedString>() { [weak self] v in if let s = self { s.attributedText = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &attributedTextDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
| 4f84410090d9d077fa32c6ddbc202f77 | 41.174603 | 135 | 0.71735 | false | false | false | false |
SPECURE/rmbt-ios-client | refs/heads/main | Sources/QOSNonTransparentProxyTest.swift | apache-2.0 | 1 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************************************/
import Foundation
///
class QOSNonTransparentProxyTest: QOSTest {
private let PARAM_REQUEST = "request"
private let PARAM_PORT = "port"
//
/// The request string to use by the non-transparent proxy test (provided by control server)
var request: String?
/// The port to test by the non-transparent proxy test (provided by control server)
var port: UInt16?
//
///
override var description: String {
return super.description + ", [request: \(String(describing: request)), port: \(String(describing: port))]"
}
//
///
override init(testParameters: QOSTestParameters) {
// request
if let request = testParameters[PARAM_REQUEST] as? String {
// TODO: length check on request?
self.request = request
// append newline character if not already added
if !self.request!.hasSuffix("\n") {
self.request! += "\n"
}
}
// port
if let portString = testParameters[PARAM_PORT] as? String {
if let port = UInt16(portString) {
self.port = port
}
}
super.init(testParameters: testParameters)
}
///
override func getType() -> QosMeasurementType! {
return .NonTransparentProxy
}
}
| 211ede95711efb283d64a344f25bbf05 | 29.457143 | 115 | 0.570826 | false | true | false | false |
allbto/WayThere | refs/heads/master | ios/WayThere/WayThere/Classes/Controllers/Cities/CitiesDataStore.swift | mit | 2 | //
// CitiesDataStore.swift
// WayThere
//
// Created by Allan BARBATO on 5/17/15.
// Copyright (c) 2015 Allan BARBATO. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
protocol CitiesDataStoreDelegate
{
func foundWeatherConfiguration(cities : [City])
func unableToFindWeatherConfiguration(error: NSError)
func foundCitiesForQuery(cities : [SimpleCity])
func unableToFindCitiesForQuery(error: NSError?)
func didSaveNewCity(city: City)
func didRemoveCity(city: City)
func foundWeatherForecastForCity(weathers: [Weather])
func unableToFindForecastForCity(error: NSError?)
}
class CitiesDataStore
{
/// Vars
let CountOfQueryResult = 5
let NumberOfDaysToFetch = 7
var delegate: CitiesDataStoreDelegate?
var isQuerying = false
var lastQuery : String?
// Url
let FindCitiesUrl = MainDataStore.BaseUrl + "/find"
let FetchCityUrl = MainDataStore.BaseUrl + "/forecast/daily"
/// Funcs
func retrieveWeatherConfiguration()
{
delegate?.foundWeatherConfiguration(MainDataStore.retrieveCities())
}
/**
Fetch api to find list of cities for given query string
Has a block system allowing to delay the requests if one is already running
For example, an user will write the name of the city, with a mistake, go back fix it then write the rest of name.
To prevent a request to be sent everytime a letter is written, the func doesn't a request to be launched if there is already one in process
In addition, the lastest query is saved and a request is sent when the first one is complete
:param: query E.g. "Prag" if you want to look for Prague or similar (there is nothing similar to Prague ;) )
*/
func retrieveCitiesForQuery(query : String)
{
if isQuerying {
lastQuery = query
return
}
isQuerying = true
Alamofire.request(.GET, FindCitiesUrl, parameters: [
"q" : query,
"type" : "like",
"sort" : "population",
"cnt" : String(CountOfQueryResult)
])
.responseJSON { [unowned self] (req, response, json, error) in
// Call another query if there is a 'waiting list'
if let query = self.lastQuery {
self.lastQuery = nil
self.isQuerying = false
self.retrieveCitiesForQuery(query)
}
else if (error == nil && json != nil) {
var json = JSON(json!)
var cities = [SimpleCity]()
for (index, (sIndex : String, cityJSON : JSON)) in enumerate(json["list"]) {
if let id = cityJSON["id"].int, name = cityJSON["name"].string, country = cityJSON["sys"]["country"].string {
cities.append(SimpleCity(String(id), name, country))
}
}
self.delegate?.foundCitiesForQuery(cities)
} else {
self.delegate?.unableToFindCitiesForQuery(error)
}
self.isQuerying = false
}
}
/**
Save city to CoreData
Fetch the latest weather report for the city before saving it to CoreData
If request fails the city is still saved, the forecast can be retrieved later on
:param: city to save
*/
func saveCity(city : SimpleCity)
{
// Preventing user from including 2 times the same city
if let cityEntity = City.MR_findFirstByAttribute("remoteId", withValue: city.id) as? City {
return
}
Alamofire.request(.GET, MainDataStore.WeatherUrl, parameters: [
"id" : city.id,
"units" : "metric"
])
.responseJSON { [unowned self] (req, response, json, error) in
if let cityEntity = City.MR_createEntity() as? City {
cityEntity.remoteId = city.id
if (error == nil && json != nil) {
var json = JSON(json!)
cityEntity.fromJson(json)
} else {
cityEntity.name = city.name
cityEntity.country = city.country
}
CoreDataHelper.saveAndWait()
self.delegate?.didSaveNewCity(cityEntity)
}
}
}
/**
Remove city from CoreData
Also remove related photo (CityPhoto, see TodayDataStore)
Also remove related weathers (see under)
:param: city to remove
*/
func removeCity(city : City)
{
var cityId = city.remoteId
CityPhoto.MR_findByAttribute("cityId", withValue: cityId).map { $0.MR_deleteEntity() }
Weather.MR_findByAttribute("cityId", withValue: cityId).map { $0.MR_deleteEntity() }
city.MR_deleteEntity()
CoreDataHelper.saveAndWait()
self.delegate?.didRemoveCity(city)
}
/**
Get local stored weather for city only if weathers were saved on the same day (after 1 day needs to be reloaded)
Otherwise they are deleted from Core Data
:param: city to get weathers from
:returns: A weathers array corresponding to the latest weathers for the city or nil
*/
private func _getWeatherForCity(city: City) -> [Weather]?
{
if let localWeathers = Weather.MR_findByAttribute("cityId", withValue: city.remoteId, andOrderBy: "creationDate", ascending: true) as? [Weather] where localWeathers.count > 0 {
if localWeathers[0].creationDate.dateComposents(unit: .CalendarUnitDay, toDate: NSDate()).day == 0 {
return localWeathers
} else {
localWeathers.map { $0.MR_deleteEntity() }
CoreDataHelper.saveAndWait()
}
}
return nil
}
private func _saveWeathersJSON(weathers: JSON, forCity city: City)
{
for (index, (sIndex : String, cityJSON : JSON)) in enumerate(weathers) {
if let title = cityJSON["weather"][0]["main"].string, timeStamp = cityJSON["dt"].int, temp = cityJSON["temp"]["day"].double {
var date = NSDate(timeIntervalSince1970: Double(timeStamp))
var formater = NSDateFormatter()
formater.dateFormat = "EEEE"
if let weather = Weather.MR_createEntity() as? Weather {
weather.title = title
weather.day = formater.stringFromDate(date)
weather.temp = Float(temp)
weather.cityId = city.remoteId
}
}
}
CoreDataHelper.saveAndWait()
}
/**
Retrieve weather forecast for NumberOfDaysToFetch days
:param: city to fetch weather from
*/
func retrieveWeatherForecastForCity(city: City)
{
// Try to get local weathers for this city
if let weathers = _getWeatherForCity(city) {
delegate?.foundWeatherForecastForCity(weathers)
return
}
// Not found requesting API
Alamofire.request(.GET, FetchCityUrl, parameters: [
"id" : city.remoteId,
"cnt" : NumberOfDaysToFetch,
"units": "metric"
])
.responseJSON { [unowned self] (req, response, json, error) in
if (error == nil && json != nil) {
var json = JSON(json!)
self._saveWeathersJSON(json["list"], forCity: city)
self.delegate?.foundWeatherForecastForCity(self._getWeatherForCity(city) ?? [])
} else {
self.delegate?.unableToFindForecastForCity(error)
}
}
}
}
| ca110948bd83d6c4e366b9382896e084 | 33.917749 | 184 | 0.56298 | false | false | false | false |
AttilaTheFun/SwaggerParser | refs/heads/master | Sources/SecuritySchema.swift | mit | 1 |
public typealias SecurityRequirement = [String: [String]]
public enum SecuritySchema {
case basic(description: String?)
case apiKey(description: String?, schema: APIKeySchema)
case oauth2(description: String?, schema: OAuth2Schema)
}
enum SecuritySchemaBuilder: Codable {
case basic(description: String?)
case apiKey(description: String?, schema: APIKeySchemaBuilder)
case oauth2(description: String?, schema: OAuth2SchemaBuilder)
enum CodingKeys: String, CodingKey {
case type
case description
}
init(from decoder: Decoder) throws {
enum SecurityType: String, Codable {
case basic = "basic"
case apiKey = "apiKey"
case oauth2 = "oauth2"
}
let values = try decoder.container(keyedBy: CodingKeys.self)
let type = try values.decode(SecurityType.self, forKey: .type)
let description = try values.decodeIfPresent(String.self, forKey: .description)
switch type {
case .basic:
self = .basic(description: description)
case .apiKey:
self = .apiKey(description: description, schema: try APIKeySchemaBuilder(from: decoder))
case .oauth2:
self = .oauth2(description: description, schema: try OAuth2SchemaBuilder(from: decoder))
}
}
func encode(to encoder: Encoder) throws {
var values = encoder.container(keyedBy: CodingKeys.self)
let description: String?
switch self {
case .basic(let basicDescription):
description = basicDescription
case .apiKey(let apiKeyDescription, let schema):
description = apiKeyDescription
try schema.encode(to: encoder)
case .oauth2(let oauth2Description, let schema):
description = oauth2Description
try schema.encode(to: encoder)
}
if let description = description {
try values.encode(description, forKey: .description)
}
}
}
extension SecuritySchemaBuilder: Builder {
typealias Building = SecuritySchema
func build(_ swagger: SwaggerBuilder) throws -> SecuritySchema {
switch self {
case .basic(let description):
return .basic(description: description)
case .apiKey(let description, let builder):
return .apiKey(description: description, schema: try builder.build(swagger))
case .oauth2(let description, let builder):
return .oauth2(description: description, schema: try builder.build(swagger))
}
}
}
| d7369a8208fad436bcbb947dfc72b9b7 | 34.328767 | 100 | 0.646762 | false | false | false | false |
ivanbruel/SwipeIt | refs/heads/master | Pods/Localizable/Pod/AppLanguage.swift | mit | 1 | //
// AppLanguage.swift
// Pods
//
// Created by Ivan Bruel on 10/04/16.
//
//
import Foundation
final class AppLanguage: Language {
private struct JSONKeys {
static let code = "code"
static let strings = "keywords"
}
private static let directory = "AppLanguage"
private static let baseLanguageCode = "Base"
let code: String
let strings: [String: String]
init(code: String, strings: [String: String]) {
self.code = code
self.strings = strings
}
convenience init(code: String) {
self.init(code: code, strings: AppHelper.stringsForLanguageCode(code))
}
func save() {
StorageHelper.saveObject(json, directory: AppLanguage.directory, filename: code)
}
}
// MARK: Accessors
extension AppLanguage {
static var availableLanguageCodes: [String] {
return NSBundle.mainBundle().localizations
}
static var allLanguages: [AppLanguage] {
return availableLanguageCodes.flatMap { AppLanguage(code: $0) }
}
}
// MARK: Helpers
extension AppLanguage {
static func printMissingStrings() {
let allLanguages = AppLanguage.allLanguages
let allKeys = Set(allLanguages.map { $0.strings.keys }.flatten())
let missing = allLanguages.flatMap { language -> (AppLanguage, [String])? in
let missingKeys = allKeys.filter { !language.strings.keys.contains($0) }
guard missingKeys.count > 0 else {
return nil
}
return (language, missingKeys)
}
guard missing.count > 0 else {
return
}
Logger.logInfo("Missing strings:")
missing.forEach { (language, keys) -> () in
Logger.logInfo("Language: \(language.code)")
let strings = keys.map { " \"\($0)\""}.joinWithSeparator("\n")
Logger.logInfo(strings)
}
}
}
// MARK: JSONRepresentable
extension AppLanguage: JSONRepresentable {
convenience init?(json: [String: AnyObject]) {
guard let code = json[JSONKeys.code] as? String,
strings = json[JSONKeys.strings] as? [String: String] else {
return nil
}
self.init(code: code, strings: strings)
}
var json: [String: AnyObject] {
return [
JSONKeys.code: code,
JSONKeys.strings: strings
]
}
}
// MARK: Delta
extension AppLanguage {
private var oldLanguage: AppLanguage? {
guard let json: [String: AnyObject]
= StorageHelper.loadObject(AppLanguage.directory, filename: code) else {
return nil
}
return AppLanguage(json: json)
}
var delta: AppLanguageDelta? {
return AppLanguageDelta(newLanguage: self, oldLanguage: oldLanguage)
}
static var languageDeltas: [AppLanguageDelta]? {
let languageDifferences = AppLanguage.allLanguages.flatMap { $0.delta }
guard languageDifferences.count > 0 else {
return nil
}
return languageDifferences
}
static func saveAppLanguages() {
AppLanguage.allLanguages.forEach { $0.save() }
}
}
// MARK: Networking
extension AppLanguage {
static func upload(token: String) {
guard let languageDeltas = languageDeltas else { return }
Logger.logWarning("Detected string changes:")
languageDeltas.forEach { Logger.logWarning($0.description) }
Network.sharedInstance
.performRequest(.UploadLanguages(languageDeltas: languageDeltas), token: token) {
(_, error) -> Void in
guard error == nil else {
return
}
saveAppLanguages()
}
}
}
| 7d949aaeefe50b6e99bc87aed8e97505 | 21.66 | 87 | 0.664313 | false | false | false | false |
svyatoslav-zubrin/zControls | refs/heads/master | SZTableView/SZTableViewDemo/SZTableViewDemo/TableView/SZTableView.swift | mit | 1 | //
// SZTableView.swift
// SZTableViewDemo
//
// Created by Slava Zubrin on 1/14/15.
// Copyright (c) 2015 Slava Zubrin. All rights reserved.
//
import UIKit
enum SZScrollDirection
{
case Unknown
case FromMinToMax
case FromMaxToMin
}
typealias SZTableViewScrollDirection = (vertical: SZScrollDirection, horizontal: SZScrollDirection)
class SZTableView
: UIScrollView
, UIScrollViewDelegate
{
@IBOutlet weak var tableDataSource: SZTableViewDataSource!
@IBOutlet weak var tableDelegate: SZTableViewDelegate!
var gridLayout: SZTableViewGridLayout!
// MARK: Public properties
var rowHeadersAlwaysVisible = false
var columnHeadersAlwaysVisible = false
// MARK: Private properties
private var reusePool = [String: SZTableViewReusableView]()
private var cellsOnView = [SZIndexPath: SZTableViewCell]()
private var headersOnView = [SZIndexPath: SZTableViewReusableView]()
private var previousScrollPosition: CGPoint = CGPoint.zeroPoint
private var scrollDirection: SZTableViewScrollDirection = (SZScrollDirection.Unknown, SZScrollDirection.Unknown)
private var registeredViewNibs = [String: UINib]()
private var registeredViewClasses = [String: AnyClass]()
private var cellsBorderIndexes: SZBorderIndexes! = nil
private var rowHeadersBorderIndexes: SZBorderIndexes? = nil
private var columnHeadersBorderIndexes: SZBorderIndexes? = nil
// MARK: - Lifecycle
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
private func setup()
{
self.delegate = self
self.clipsToBounds = true
}
// MARK: - Public
func dequeReusableViewOfKind(kind: SZReusableViewKind,
withReuseIdentifier reuseIdentifier: String) -> SZTableViewReusableView?
{
if let view = reusePool[reuseIdentifier] {
reusePool[reuseIdentifier] = nil
return view
}
else {
// TODO: instantiate new cell and return it
// return type after that must be changed to non-optional ))
if let nib = registeredViewNibs[reuseIdentifier] {
if let view = loadReusableViewFromNib(nib) {
view.reuseIdentifier = reuseIdentifier
view.kind = kind
return view
}
else {
return nil
}
}
else if let cellClass: AnyClass = registeredViewClasses[reuseIdentifier] {
if let view = loadCellFromClass(cellClass) {
view.reuseIdentifier = reuseIdentifier
view.kind = kind
return view
}
else {
return nil
}
}
return nil
}
}
private func registerClass(cellClass: AnyClass,
forCellWithReuseIdentifier cellReuseIdentifier: String)
{
registeredViewClasses[cellReuseIdentifier] = cellClass
registeredViewNibs[cellReuseIdentifier] = nil
}
func registerNib(nib: UINib, forViewWithReuseIdentifier reuseIdentifier: String)
{
registeredViewNibs[reuseIdentifier] = nib
registeredViewClasses[reuseIdentifier] = nil
}
func reloadData() {
// renew data
// remove all subviews (place to reuse pool if needed)
for (_, cell) in cellsOnView {
cell.removeFromSuperview()
}
cellsOnView.removeAll(keepCapacity: true)
for (_, header) in headersOnView {
header.removeFromSuperview()
}
headersOnView.removeAll(keepCapacity: true)
//
gridLayout.prepareLayout()
cellsBorderIndexes = gridLayout.cellsVisibleBorderIndexes()
rowHeadersBorderIndexes = gridLayout.headersVisibleBorderIndexesForHeaderKind(SZReusableViewKind.RowHeader)
columnHeadersBorderIndexes = gridLayout.headersVisibleBorderIndexesForHeaderKind(SZReusableViewKind.ColumnHeader)
// add all needed headers
if rowHeadersBorderIndexes != nil {
for rowIndex in rowHeadersBorderIndexes!.row.minIndex ... rowHeadersBorderIndexes!.row.maxIndex {
let indexPath = SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex)
placeHeaderOfKind(SZReusableViewKind.RowHeader, atIndexPath: indexPath)
}
for columnIndex in columnHeadersBorderIndexes!.column.minIndex ... columnHeadersBorderIndexes!.column.maxIndex {
let indexPath = SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex)
placeHeaderOfKind(SZReusableViewKind.ColumnHeader, atIndexPath: indexPath)
}
}
// add all needed cells again
for rowIndex in cellsBorderIndexes.row.minIndex ... cellsBorderIndexes.row.maxIndex {
for columnIndex in cellsBorderIndexes.column.minIndex ... cellsBorderIndexes.column.maxIndex {
let indexPath = SZIndexPath(rowSectionIndex: 0,
columnSectionIndex: 0,
rowIndex: rowIndex,
columnIndex: columnIndex)
placeCellWithIndexPath(indexPath)
}
}
setNeedsDisplay()
}
// MARK: - Private
private func loadReusableViewFromNib(nib: UINib) -> SZTableViewReusableView?
{
let array = nib.instantiateWithOwner(nil, options: nil)
return array.first as? SZTableViewReusableView
}
private func loadCellFromClass(cellClass: AnyClass) -> SZTableViewCell?
{
// if cellClass.self is SZTableViewCell.Type {
// if let cell = cellClass() {
// return cell
// }
// }
return nil
}
private func getScrollDirection()
{
var d: SZTableViewScrollDirection = (SZScrollDirection.Unknown, SZScrollDirection.Unknown)
if contentOffset.y < previousScrollPosition.y {
d.vertical = SZScrollDirection.FromMaxToMin
}
else if contentOffset.y > previousScrollPosition.y {
d.vertical = SZScrollDirection.FromMinToMax
}
if contentOffset.x < previousScrollPosition.x {
d.horizontal = SZScrollDirection.FromMaxToMin
}
else if contentOffset.x > previousScrollPosition.x {
d.horizontal = SZScrollDirection.FromMinToMax
}
previousScrollPosition = contentOffset
scrollDirection = d
}
private func placeCellWithIndexPath(indexPath: SZIndexPath)
{
// prevent cells duplication
// ...perhaps it may me replaced with correct border indexes calculation in 'borderVisibleIndexes()'
if let cellOnView = cellsOnView[indexPath] {
return
}
let cell = tableDataSource.tableView(self, cellForItemAtIndexPath: indexPath)
cell.frame = gridLayout.frameForReusableViewOfKind(SZReusableViewKind.Cell, atIndexPath: indexPath)
self.addSubview(cell)
cellsOnView[indexPath] = cell
}
private func removeCellWithIndexPath(indexPath: SZIndexPath)
{
if let cell = cellsOnView[indexPath] {
cell.removeFromSuperview()
cellsOnView[indexPath] = nil
reusePool[cell.reuseIdentifier!] = cell
}
}
private func placeHeaderOfKind(kind: SZReusableViewKind, atIndexPath indexPath: SZIndexPath)
{
// prevent cells duplication
// ...perhaps it may me replaced with correct border indexes calculation in 'borderVisibleIndexes()'
if let cellOnView = headersOnView[indexPath] {
return
}
let header = kind == SZReusableViewKind.ColumnHeader
? tableDataSource.tableView!(self, headerForColumnAtIndex: indexPath.columnIndex)
: tableDataSource.tableView!(self, headerForRowAtIndex: indexPath.rowIndex)
header.frame = gridLayout.frameForReusableViewOfKind(kind, atIndexPath: indexPath)
self.addSubview(header)
headersOnView[indexPath] = header
}
private func removeHeaderAtIndexPath(indexPath: SZIndexPath)
{
if let header = headersOnView[indexPath] {
header.removeFromSuperview()
headersOnView[indexPath] = nil
reusePool[header.reuseIdentifier!] = header
}
}
private func repositionHeaderOfKind(kind: SZReusableViewKind, atIndexPath indexPath: SZIndexPath)
{
if let header = headersOnView[indexPath] as SZTableViewReusableView? {
header.frame = gridLayout.frameForReusableViewOfKind(kind, atIndexPath: indexPath)
header.setNeedsLayout()
}
}
}
// MARK: - UIScrollViewDelegate
extension SZTableView: UIScrollViewDelegate
{
enum SZTableViewInternalCellOperation
{
case Place
case Remove
case Reposition
}
func scrollViewDidScroll(scrollView: UIScrollView)
{
getScrollDirection()
// column headers
if let newColumnHeadersBorderIndexes = gridLayout.headersVisibleBorderIndexesForHeaderKind(SZReusableViewKind.ColumnHeader) as SZBorderIndexes? {
// remove
let columnHedearsToRemove = findHeadersOfKind(SZReusableViewKind.ColumnHeader,
forOperation: .Remove,
andNewBorderIndexes: newColumnHeadersBorderIndexes)
for indexPath in columnHedearsToRemove {
removeHeaderAtIndexPath(indexPath)
}
// place
let columnHeadersToPlace = findHeadersOfKind(SZReusableViewKind.ColumnHeader,
forOperation: .Place,
andNewBorderIndexes: newColumnHeadersBorderIndexes)
for indexPath in columnHeadersToPlace {
placeHeaderOfKind(SZReusableViewKind.ColumnHeader, atIndexPath: indexPath)
}
// reposition
let columnHeadersToReposition = findHeadersOfKind(SZReusableViewKind.ColumnHeader,
forOperation: .Reposition,
andNewBorderIndexes: newColumnHeadersBorderIndexes)
for indexPath in columnHeadersToReposition {
repositionHeaderOfKind(SZReusableViewKind.ColumnHeader, atIndexPath: indexPath)
}
columnHeadersBorderIndexes = newColumnHeadersBorderIndexes
}
else {
columnHeadersBorderIndexes = nil
}
// row headers
if let newRowHeadersBorderIndexes = gridLayout.headersVisibleBorderIndexesForHeaderKind(SZReusableViewKind.RowHeader) as SZBorderIndexes? {
// remove
let rowHeadersToRemove = findHeadersOfKind(SZReusableViewKind.RowHeader,
forOperation: .Remove,
andNewBorderIndexes: newRowHeadersBorderIndexes)
for indexPath in rowHeadersToRemove {
removeHeaderAtIndexPath(indexPath)
}
// place
let rowHeadersToPlace = findHeadersOfKind(SZReusableViewKind.RowHeader,
forOperation: .Place,
andNewBorderIndexes: newRowHeadersBorderIndexes)
for indexPath in rowHeadersToPlace {
placeHeaderOfKind(SZReusableViewKind.RowHeader, atIndexPath: indexPath)
}
// reposition
let rowHeadersToReposition = findHeadersOfKind(SZReusableViewKind.RowHeader,
forOperation: .Reposition,
andNewBorderIndexes: newRowHeadersBorderIndexes)
for indexPath in rowHeadersToReposition {
repositionHeaderOfKind(SZReusableViewKind.RowHeader, atIndexPath: indexPath)
}
rowHeadersBorderIndexes = newRowHeadersBorderIndexes
}
else {
rowHeadersBorderIndexes = nil
}
// cells
let newCellsBorderIndexes = gridLayout.cellsVisibleBorderIndexes()
let cellIndexesToRemove = findCellsForOperation(.Remove, andNewBorderIndexes: newCellsBorderIndexes!)
for indexPath in cellIndexesToRemove {
removeCellWithIndexPath(indexPath)
}
let cellIndexesToPlace = findCellsForOperation(.Place, andNewBorderIndexes: newCellsBorderIndexes!)
for indexPath in cellIndexesToPlace {
placeCellWithIndexPath(indexPath)
}
cellsBorderIndexes = newCellsBorderIndexes
// global
setNeedsDisplay()
}
func findCellsForOperation(operation: SZTableViewInternalCellOperation,
andNewBorderIndexes newBorderIndexes: SZBorderIndexes) -> [SZIndexPath]
{
var indexes = [SZIndexPath]()
for z in 0...1 { // 0 - for columns, 1 - for rows
let mainItem = z==0 ? cellsBorderIndexes.column : cellsBorderIndexes.row
let oppositeItem = z==0 ? cellsBorderIndexes.row : cellsBorderIndexes.column
let newMainItem = z==0 ? newBorderIndexes.column : newBorderIndexes.row
let newOppositeItem = z==0 ? newBorderIndexes.row : newBorderIndexes.column
let scrollDirectionToHandle = z==0 ? scrollDirection.horizontal : scrollDirection.vertical
if scrollDirectionToHandle == SZScrollDirection.FromMinToMax {
let maxIndexValue = operation == .Place ? newMainItem.maxIndex + 1 : newMainItem.maxIndex
if mainItem.maxIndex < maxIndexValue {
for mainIndex in mainItem.maxIndex ... newMainItem.maxIndex {
for oppositeIndex in newOppositeItem.minIndex ... newOppositeItem.maxIndex {
let columnIndex = z==0 ? mainIndex : oppositeIndex
let rowIndex = z==0 ? oppositeIndex : mainIndex
indexes.append(SZIndexPath(rowSectionIndex: 0,
columnSectionIndex: 0,
rowIndex: rowIndex,
columnIndex: columnIndex))
}
}
}
}
else if scrollDirectionToHandle == SZScrollDirection.FromMaxToMin {
let maxIndexValue = operation == .Place ? newMainItem.minIndex + 1 : newMainItem.minIndex
if mainItem.minIndex < maxIndexValue {
for mainIndex in mainItem.minIndex ... maxIndexValue {
for oppositeIndex in newOppositeItem.minIndex ... newOppositeItem.maxIndex {
let columnIndex = z==0 ? mainIndex : oppositeIndex
let rowIndex = z==0 ? oppositeIndex : mainIndex
indexes.append(SZIndexPath(rowSectionIndex: 0,
columnSectionIndex: 0,
rowIndex: rowIndex,
columnIndex: columnIndex))
}
}
}
}
}
return indexes
}
func findHeadersOfKind(kind: SZReusableViewKind,
forOperation operation: SZTableViewInternalCellOperation,
andNewBorderIndexes newBorderIndexes: SZBorderIndexes) -> [SZIndexPath]
{
var indexes = [SZIndexPath]()
// columns
if let newHeadersBorderIndexes = gridLayout.headersVisibleBorderIndexesForHeaderKind(kind) as SZBorderIndexes? {
let isColumns = kind == SZReusableViewKind.ColumnHeader
let oldBorderIndexes = isColumns ? columnHeadersBorderIndexes : rowHeadersBorderIndexes
if isColumns { // column headers
if scrollDirection.horizontal == .FromMinToMax {
if operation == .Remove && oldBorderIndexes != nil {
let minIndex = oldBorderIndexes!.column.minIndex
let maxIndex = newHeadersBorderIndexes.column.minIndex - 1
if minIndex < maxIndex {
for columnIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex))
}
if indexes.count > 0 {
println("indexes: \(indexes)")
}
}
}
else if operation == .Place {
let minIndex = oldBorderIndexes != nil ? oldBorderIndexes!.column.maxIndex : newHeadersBorderIndexes.column.minIndex
let maxIndex = newHeadersBorderIndexes.column.maxIndex + 1
if minIndex < maxIndex {
for columnIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex))
}
}
}
else if operation == .Reposition {
// there is no need in repositioning for column headers in case of horizontal scrolling
}
}
else if scrollDirection.horizontal == .FromMaxToMin {
if operation == .Remove && oldBorderIndexes != nil {
let minIndex = oldBorderIndexes!.column.maxIndex
let maxIndex = newHeadersBorderIndexes.column.maxIndex
if minIndex < maxIndex {
for columnIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex))
}
}
}
else if operation == .Place {
let minIndex = newHeadersBorderIndexes.column.minIndex + 1
let maxIndex = oldBorderIndexes != nil ? oldBorderIndexes!.column.minIndex : newHeadersBorderIndexes.column.maxIndex
if minIndex < maxIndex {
for columnIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex))
}
}
}
else if operation == .Reposition {
// there is no need in repositioning for column headers in case of horizontal scrolling
}
}
else if scrollDirection.vertical != .Unknown
&& operation == .Reposition
&& columnHeadersAlwaysVisible == true
&& oldBorderIndexes != nil {
for columnIndex in oldBorderIndexes!.column.minIndex ... oldBorderIndexes!.column.maxIndex {
indexes.append(SZIndexPath.indexPathOfColumnHeaderAtIndex(columnIndex))
}
}
}
else { // isColumn != true
// row headers
if scrollDirection.vertical == .FromMinToMax {
if operation == .Remove && oldBorderIndexes != nil {
let minIndex = oldBorderIndexes!.row.minIndex
let maxIndex = newHeadersBorderIndexes.row.minIndex - 1
if minIndex < maxIndex {
for rowIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex))
}
}
} else if operation == .Place {
let minIndex = oldBorderIndexes != nil ? oldBorderIndexes!.row.maxIndex : newHeadersBorderIndexes.row.minIndex
let maxIndex = newHeadersBorderIndexes.row.maxIndex + 1
if minIndex < maxIndex {
for rowIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex))
}
}
} else if operation == .Reposition {
// there is no need in repositioning for row headers in case of vertical scrolling
}
} else if scrollDirection.vertical == .FromMaxToMin {
if operation == .Remove && oldBorderIndexes != nil {
let maxIndex = oldBorderIndexes!.row.maxIndex
let minIndex = newHeadersBorderIndexes.row.maxIndex + 1
if minIndex < maxIndex {
for rowIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex))
}
}
} else if operation == .Place {
let maxIndex = newHeadersBorderIndexes.row.minIndex + 1
let minIndex = oldBorderIndexes != nil ? oldBorderIndexes!.row.minIndex : newHeadersBorderIndexes.row.maxIndex
if minIndex < maxIndex {
for rowIndex in minIndex ... maxIndex {
indexes.append(SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex))
}
}
} else if operation == .Reposition {
// there is no need in repositioning for row headers in case of vertical scrolling
}
} else if scrollDirection.horizontal != .Unknown
&& operation == .Reposition
&& rowHeadersAlwaysVisible == true
&& oldBorderIndexes != nil {
for rowIndex in oldBorderIndexes!.row.minIndex ... oldBorderIndexes!.row.maxIndex {
indexes.append(SZIndexPath.indexPathOfRowHeaderAtIndex(rowIndex))
}
}
}
}
else {
println("no new headers of kind: " + ((kind == SZReusableViewKind.ColumnHeader) ? ".ColumnHeader" : ".RowHeader"))
}
return indexes
}
}
| 9e305fc66f477bf0e1613afd76cc4c1f | 42.5 | 153 | 0.576775 | false | false | false | false |
albert438/JSPatch | refs/heads/master | Demo/SwiftDemo/SwiftDemo/AppDelegate.swift | mit | 3 | //
// AppDelegate.swift
// SwiftDemo
//
// Created by KouArlen on 16/2/3.
// Copyright © 2016年 Arlen. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let aClass: AnyClass? = NSClassFromString("SwiftDemo.ViewController")
if (aClass != nil) {
let clsName = NSStringFromClass(aClass!)
print(clsName)
} else {
print("error ViewController not found")
}
let bClass: AnyClass? = NSClassFromString("SwiftDemo.TestObject")
if (bClass != nil) {
let clsName = NSStringFromClass(bClass!)
print(clsName)
} else {
print("error TestObject not found")
}
let path = NSBundle.mainBundle().pathForResource("demo", ofType: "js")
do {
let patch = try String(contentsOfFile: path!)
JPEngine.startEngine()
JPEngine.evaluateScript(patch)
} catch {}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 84a58d466dc28bca90eb73531d82cbcd | 39.767123 | 285 | 0.684812 | false | false | false | false |
dnevera/ImageMetalling | refs/heads/master | ImageMetalling-15/ImageMetalling-15/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// ImageMetalling-15
//
// Created by denis svinarchuk on 24.05.2018.
// Copyright © 2018 Dehancer. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var controller:ViewController! {
return (NSApplication.shared.keyWindow?.contentViewController as? ViewController)
}
func applicationDidFinishLaunching(_ notification: Notification) {
if let view = controller?.view {
view.window?.title = "LUT: Identity"
view.addCursorRect(view.bounds, cursor: NSCursor.pointingHand )
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.darkGray.cgColor
}
}
@IBAction func toggleRendering(_ sender: NSMenuItem) {
controller.lutView.renderCube = !controller.lutView.renderCube
}
@IBAction func showStatistics(_ sender: NSMenuItem) {
controller.lutView.sceneView.showsStatistics = !controller.lutView.sceneView.showsStatistics
}
@IBAction func resetView(_ sender: NSMenuItem) {
controller?.resetView()
}
@IBAction func openLut(_ sender: NSMenuItem) {
if openPanel.runModal() == NSApplication.ModalResponse.OK {
if let url = openPanel.urls.first{
controller?.lutUrl = url
}
}
}
lazy var openPanel:NSOpenPanel = {
let p = NSOpenPanel()
p.canChooseFiles = true
p.canChooseDirectories = false
p.resolvesAliases = true
p.isExtensionHidden = false
p.allowedFileTypes = [
"cube", "png"
]
return p
}()
}
| 99b42c8709bb5e42410ac7fc63ff430c | 27.316667 | 100 | 0.625662 | false | false | false | false |
Anish-kumar-dev/Spring | refs/heads/master | SpringApp/SpringViewController.swift | mit | 19 | //
// SpringViewController.swift
// DesignerNewsApp
//
// Created by Meng To on 2015-01-02.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
import Spring
class SpringViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, OptionsViewControllerDelegate {
@IBOutlet weak var delayLabel: UILabel!
@IBOutlet weak var durationLabel: UILabel!
@IBOutlet weak var forceLabel: UILabel!
@IBOutlet weak var delaySlider: UISlider!
@IBOutlet weak var durationSlider: UISlider!
@IBOutlet weak var forceSlider: UISlider!
@IBOutlet weak var ballView: SpringView!
@IBOutlet weak var animationPicker: UIPickerView!
var selectedRow: Int = 0
var selectedEasing: Int = 0
var selectedForce: CGFloat = 1
var selectedDuration: CGFloat = 1
var selectedDelay: CGFloat = 0
var selectedDamping: CGFloat = 0.7
var selectedVelocity: CGFloat = 0.7
var selectedScale: CGFloat = 1
var selectedX: CGFloat = 0
var selectedY: CGFloat = 0
var selectedRotate: CGFloat = 0
@IBAction func forceSliderChanged(sender: AnyObject) {
selectedForce = sender.valueForKey("value") as! CGFloat
animateView()
forceLabel.text = String(format: "Force: %.1f", Double(selectedForce))
}
@IBAction func durationSliderChanged(sender: AnyObject) {
selectedDuration = sender.valueForKey("value") as! CGFloat
animateView()
durationLabel.text = String(format: "Duration: %.1f", Double(selectedDuration))
}
@IBAction func delaySliderChanged(sender: AnyObject) {
selectedDelay = sender.valueForKey("value") as! CGFloat
animateView()
delayLabel.text = String(format: "Delay: %.1f", Double(selectedDelay))
}
func dampingSliderChanged(sender: AnyObject) {
selectedDamping = sender.valueForKey("value") as! CGFloat
animateView()
}
func velocitySliderChanged(sender: AnyObject) {
selectedVelocity = sender.valueForKey("value") as! CGFloat
animateView()
}
func scaleSliderChanged(sender: AnyObject) {
selectedScale = sender.valueForKey("value") as! CGFloat
animateView()
}
func xSliderChanged(sender: AnyObject) {
selectedX = sender.valueForKey("value") as! CGFloat
animateView()
}
func ySliderChanged(sender: AnyObject) {
selectedY = sender.valueForKey("value") as! CGFloat
animateView()
}
func rotateSliderChanged(sender: AnyObject) {
selectedRotate = sender.valueForKey("value") as! CGFloat
animateView()
}
func animateView() {
setOptions()
ballView.animate()
}
func setOptions() {
ballView.force = selectedForce
ballView.duration = selectedDuration
ballView.delay = selectedDelay
ballView.damping = selectedDamping
ballView.velocity = selectedVelocity
ballView.scaleX = selectedScale
ballView.scaleY = selectedScale
ballView.x = selectedX
ballView.y = selectedY
ballView.rotate = selectedRotate
ballView.animation = animations[selectedRow].rawValue
ballView.curve = animationCurves[selectedEasing].rawValue
}
func minimizeView(sender: AnyObject) {
SpringAnimation.spring(0.7, animations: {
self.view.transform = CGAffineTransformMakeScale(0.935, 0.935)
})
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true)
}
func maximizeView(sender: AnyObject) {
SpringAnimation.spring(0.7, animations: {
self.view.transform = CGAffineTransformMakeScale(1, 1)
})
UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true)
}
let animations: [Spring.AnimationPreset] = [
.Shake,
.Pop,
.Morph,
.Squeeze,
.Wobble,
.Swing,
.FlipX,
.FlipY,
.Fall,
.SqueezeLeft,
.SqueezeRight,
.SqueezeDown,
.SqueezeUp,
.SlideLeft,
.SlideRight,
.SlideDown,
.SlideUp,
.FadeIn,
.FadeOut,
.FadeInLeft,
.FadeInRight,
.FadeInDown,
.FadeInUp,
.ZoomIn,
.ZoomOut,
.Flash
]
var animationCurves: [Spring.AnimationCurve] = [
.EaseIn,
.EaseOut,
.EaseInOut,
.Linear,
.Spring,
.EaseInSine,
.EaseOutSine,
.EaseInOutSine,
.EaseInQuad,
.EaseOutQuad,
.EaseInOutQuad,
.EaseInCubic,
.EaseOutCubic,
.EaseInOutCubic,
.EaseInQuart,
.EaseOutQuart,
.EaseInOutQuart,
.EaseInQuint,
.EaseOutQuint,
.EaseInOutQuint,
.EaseInExpo,
.EaseOutExpo,
.EaseInOutExpo,
.EaseInCirc,
.EaseOutCirc,
.EaseInOutCirc,
.EaseInBack,
.EaseOutBack,
.EaseInOutBack
]
override func viewDidLoad() {
super.viewDidLoad()
animationPicker.delegate = self
animationPicker.dataSource = self
animationPicker.showsSelectionIndicator = true
}
@IBAction func ballButtonPressed(sender: AnyObject) {
UIView.animateWithDuration(0.1, animations: {
self.ballView.backgroundColor = UIColor(hex: "69DBFF")
}, completion: { finished in
UIView.animateWithDuration(0.5, animations: {
self.ballView.backgroundColor = UIColor(hex: "#279CEB")
})
})
animateView()
}
var isBall = false
func changeBall() {
isBall = !isBall
let animation = CABasicAnimation()
let halfWidth = ballView.frame.width / 2
let cornerRadius: CGFloat = isBall ? halfWidth : 10
animation.keyPath = "cornerRadius"
animation.fromValue = isBall ? 10 : halfWidth
animation.toValue = cornerRadius
animation.duration = 0.2
ballView.layer.cornerRadius = cornerRadius
ballView.layer.addAnimation(animation, forKey: "radius")
}
@IBAction func shapeButtonPressed(sender: AnyObject) {
changeBall()
}
func resetButtonPressed(sender: AnyObject) {
selectedForce = 1
selectedDuration = 1
selectedDelay = 0
selectedDamping = 0.7
selectedVelocity = 0.7
selectedScale = 1
selectedX = 0
selectedY = 0
selectedRotate = 0
forceSlider.setValue(Float(selectedForce), animated: true)
durationSlider.setValue(Float(selectedDuration), animated: true)
delaySlider.setValue(Float(selectedDelay), animated: true)
forceLabel.text = String(format: "Force: %.1f", Double(selectedForce))
durationLabel.text = String(format: "Duration: %.1f", Double(selectedDuration))
delayLabel.text = String(format: "Delay: %.1f", Double(selectedDelay))
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return component == 0 ? animations.count : animationCurves.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return component == 0 ? animations[row].rawValue : animationCurves[row].rawValue
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
switch component {
case 0:
selectedRow = row
animateView()
default:
selectedEasing = row
animateView()
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let optionsViewController = segue.destinationViewController as? OptionsViewController {
optionsViewController.delegate = self
setOptions()
optionsViewController.data = ballView
}
else if let codeViewController = segue.destinationViewController as? CodeViewController {
setOptions()
codeViewController.data = ballView
}
}
} | 2df8b680f184ee2545ef850d92515069 | 29.843066 | 123 | 0.621538 | false | false | false | false |
eofster/Telephone | refs/heads/master | UseCases/DefaultCallHistories.swift | gpl-3.0 | 1 | //
// DefaultCallHistories.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone 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.
//
// Telephone 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.
//
public final class DefaultCallHistories {
private var histories: [String: CallHistory] = [:]
private let factory: CallHistoryFactory
var count: Int { return histories.count }
public init(factory: CallHistoryFactory) {
self.factory = factory
}
}
extension DefaultCallHistories: CallHistories {
public func history(withUUID uuid: String) -> CallHistory {
if let history = histories[uuid] {
return history
} else {
return makeHistory(uuid: uuid)
}
}
public func remove(withUUID uuid: String) {
histories.removeValue(forKey: uuid)
}
private func makeHistory(uuid: String) -> CallHistory {
let result = factory.make(uuid: uuid)
histories[uuid] = result
return result
}
}
| 233149e71cb0b812a2a91c58f06f81d9 | 29.145833 | 72 | 0.68141 | false | false | false | false |
jmgc/swift | refs/heads/master | test/IRGen/objc_super.swift | apache-2.0 | 1 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) %s -emit-ir | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// REQUIRES: swift_stdlib_no_asserts,optimized_stdlib
import gizmo
// CHECK: [[CLASS:%objc_class]] = type
// CHECK: [[HOOZIT:%T10objc_super6HoozitC]] = type
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[PARTIAL_APPLY_CLASS:%T10objc_super12PartialApplyC]] = type
// CHECK: [[SUPER:%objc_super]] = type
// CHECK: [[OBJC:%objc_object]] = type
// CHECK: [[GIZMO:%TSo5GizmoC]] = type
// CHECK: [[NSRECT:%TSo6NSRectV]] = type
class Hoozit : Gizmo {
// CHECK: define hidden swiftcc void @"$s10objc_super6HoozitC4frobyyF"([[HOOZIT]]* swiftself %0) {{.*}} {
override func frob() {
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s10objc_super6HoozitCMa"([[INT]] 0)
// CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frob)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.frob()
}
// CHECK: }
// CHECK: define hidden swiftcc void @"$s10objc_super6HoozitC5runceyyFZ"(%swift.type* swiftself %0) {{.*}} {
override class func runce() {
// CHECK: store [[CLASS]]* @"OBJC_METACLASS_$__TtC10objc_super6Hoozit", [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(runce)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2 to void ([[SUPER]]*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
super.runce()
}
// CHECK: }
// CHECK: define hidden swiftcc { double, double, double, double } @"$s10objc_super6HoozitC5frameSo6NSRectVyF"(%T10objc_super6HoozitC* swiftself %0) {{.*}} {
override func frame() -> NSRect {
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s10objc_super6HoozitCMa"([[INT]] 0)
// CHECK: [[T0:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK: [[T1:%.*]] = bitcast %swift.type* [[T0]] to [[CLASS]]*
// CHECK: store [[CLASS]]* [[T1]], [[CLASS]]** {{.*}}, align 8
// CHECK: load i8*, i8** @"\01L_selector(frame)"
// CHECK: call void bitcast (void ()* @objc_msgSendSuper2_stret to void ([[NSRECT]]*, [[SUPER]]*, i8*)*)([[NSRECT]]* noalias nocapture sret {{.*}}, [[SUPER]]* {{.*}}, i8* {{.*}})
return NSInsetRect(super.frame(), 2.0, 2.0)
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @"$s10objc_super6HoozitC1xACSi_tcfc"(i64 %0, %T10objc_super6HoozitC* swiftself %1) {{.*}} {
init(x:Int) {
// CHECK: load i8*, i8** @"\01L_selector(init)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*)*)([[SUPER]]* {{.*}}, i8* {{.*}})
// CHECK-NOT: @swift_dynamicCastClassUnconditional
// CHECK: ret
super.init()
}
// CHECK: }
// CHECK: define hidden swiftcc [[HOOZIT]]* @"$s10objc_super6HoozitC1yACSi_tcfc"(i64 %0, %T10objc_super6HoozitC* swiftself %1) {{.*}} {
init(y:Int) {
// CHECK: load i8*, i8** @"\01L_selector(initWithBellsOn:)"
// CHECK: call [[OPAQUE:.*]]* bitcast (void ()* @objc_msgSendSuper2 to [[OPAQUE:.*]]* (%objc_super*, i8*, i64)*)([[SUPER]]* {{.*}}, i8* {{.*}}, i64 {{.*}})
// CHECK-NOT: swift_dynamicCastClassUnconditional
// CHECK: ret
super.init(bellsOn:y)
}
// CHECK: }
}
func acceptFn(_ fn: () -> Void) { }
class PartialApply : Gizmo {
// CHECK: define hidden swiftcc void @"$s10objc_super12PartialApplyC4frobyyF"([[PARTIAL_APPLY_CLASS]]* swiftself %0) {{.*}} {
override func frob() {
// CHECK: call swiftcc void @"$s10objc_super8acceptFnyyyyXEF"(i8* bitcast (void (%swift.refcounted*)* [[PARTIAL_FORWARDING_THUNK:@"\$[A-Za-z0-9_]+"]] to i8*), %swift.opaque* %{{[0-9]+}})
acceptFn(super.frob)
}
// CHECK: }
}
// CHECK: define internal swiftcc void @"$s10objc_super12PartialApplyC4frobyyFyycfu_"(%T10objc_super12PartialApplyC* %0)
// CHECK: call swiftcc %swift.metadata_response @"$s10objc_super12PartialApplyCMa"([[INT]] 0)
// CHECK: @"\01L_selector(frob)"
// CHECK: @objc_msgSendSuper2
// CHECK: }
class GenericRuncer<T> : Gizmo {
var x: Gizmo? = nil
var y: T?
// Use a constant indirect field access instead of a non-constant direct
// access because the layout dependents on the alignment of y.
// CHECK: define hidden swiftcc i64 @"$s10objc_super13GenericRuncerC1xSo5GizmoCSgvg"(%T10objc_super13GenericRuncerC* swiftself %0)
// CHECK: inttoptr
// CHECK: [[CAST:%.*]] = bitcast %T10objc_super13GenericRuncerC* %0 to i64*
// CHECK: [[ISA:%.*]] = load i64, i64* [[CAST]]
// CHECK: [[ISAMASK:%.*]] = load i64, i64* @swift_isaMask
// CHECK: [[CLASS:%.*]] = and i64 [[ISA]], [[ISAMASK]]
// CHECK: [[TY:%.*]] = inttoptr i64 [[CLASS]] to %swift.type*
// CHECK: [[CAST:%.*]] = bitcast %swift.type* [[TY]] to i64*
// CHECK: [[OFFSETADDR:%.*]] = getelementptr inbounds i64, i64* [[CAST]], i64 11
// CHECK: [[FIELDOFFSET:%.*]] = load i64, i64* [[OFFSETADDR]]
// CHECK: [[BYTEADDR:%.*]] = bitcast %T10objc_super13GenericRuncerC* %0 to i8*
// CHECK: [[FIELDADDR:%.*]] = getelementptr inbounds i8, i8* [[BYTEADDR]], i64 [[FIELDOFFSET]]
// CHECK: [[XADDR:%.*]] = bitcast i8* [[FIELDADDR]] to %TSo5GizmoCSg*
// CHECK: [[OPTIONALADDR:%.*]] = bitcast %TSo5GizmoCSg* [[XADDR]] to i64*
// CHECK: [[OPTIONAL:%.*]] = load i64, i64* [[OPTIONALADDR]]
// CHECK: [[OBJ:%.*]] = inttoptr i64 [[OPTIONAL]] to %objc_object*
// CHECK: [[OBJ_CAST:%.*]] = bitcast %objc_object* [[OBJ]] to i8*
// CHECK: call i8* @llvm.objc.retain(i8* [[OBJ_CAST]])
// CHECK: ret i64 [[OPTIONAL]]
// CHECK: define hidden swiftcc void @"$s10objc_super13GenericRuncerC5runceyyFZ"(%swift.type* swiftself %0) {{.*}} {
override class func runce() {
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s10objc_super13GenericRuncerCMa"([[INT]] 0, %swift.type* %T)
// CHECK-NEXT: [[CLASS:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK-NEXT: [[CLASS1:%.*]] = bitcast %swift.type* [[CLASS]] to %objc_class*
// CHECK-NEXT: [[CLASS2:%.*]] = bitcast %objc_class* [[CLASS1]] to i64*
// CHECK-NEXT: [[ISA:%.*]] = load i64, i64* [[CLASS2]], align 8
// CHECK-NEXT: [[ISA_MASK:%.*]] = load i64, i64* @swift_isaMask, align 8
// CHECK-NEXT: [[ISA_MASKED:%.*]] = and i64 [[ISA]], [[ISA_MASK]]
// CHECK-NEXT: [[ISA_PTR:%.*]] = inttoptr i64 [[ISA_MASKED]] to %swift.type*
// CHECK-NEXT: [[METACLASS:%.*]] = bitcast %swift.type* [[ISA_PTR]] to %objc_class*
// CHECK: [[METACLASS_ADDR:%.*]] = getelementptr inbounds %objc_super, %objc_super* %objc_super, i32 0, i32 1
// CHECK-NEXT: store %objc_class* [[METACLASS]], %objc_class** [[METACLASS_ADDR]], align 8
// CHECK-NEXT: [[SELECTOR:%.*]] = load i8*, i8** @"\01L_selector(runce)", align 8
// CHECK-NEXT: call void bitcast (void ()* @objc_msgSendSuper2 to void (%objc_super*, i8*)*)(%objc_super* %objc_super, i8* [[SELECTOR]])
// CHECK-NEXT: ret void
super.runce()
}
}
// CHECK: define internal swiftcc void [[PARTIAL_FORWARDING_THUNK]](%swift.refcounted* swiftself %0) {{.*}} {
// CHECK: @"$ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFxAFXEfU_yt_Tgq5"
// CHECK: }
| c2d1cf81679107498b857b1e67dea9c0 | 51.617021 | 190 | 0.608303 | false | false | false | false |
mansoor92/MaksabComponents | refs/heads/master | MaksabComponents/Classes/Registeration/RegisterationTemplateViewController.swift | mit | 1 | //
// RegisterationTemplateViewController.swift
// Pods
//
// Created by Incubasys on 19/07/2017.
//
//
import UIKit
import StylingBoilerPlate
public enum RegisterationViewType: Int {
case PhoneNumber = 0
case VerificationCode = 1
case NameAndEmail = 2
case Password = 3
case PasswordAndConfirmPassword = 4
case InviteCode = 5
case ForgotPassword = 6
case BasicInfo = 7
case AddVehicleDetails = 8
case ResetPassUsingPhone = 9
public func next() -> RegisterationViewType? {
return RegisterationViewType(rawValue: self.rawValue+1)
}
}
public struct RegisterationAssets {
var _logo:UIImage
var _tooltip: UIImage?
var _btnNext: UIImage
var _facebook: UIImage?
var _twitter: UIImage?
var _google: UIImage?
public init(logo:UIImage, tooltip:UIImage?, btnNext: UIImage, facebook:UIImage?,twitter:UIImage?, google:UIImage?) {
_logo = logo
_tooltip = tooltip
_btnNext = btnNext
_facebook = facebook
_twitter = twitter
_google = google
}
}
/*
public struct EmailOrPhoneAsset {
public let isResetUsingEmail: Bool
public let emailorPhone: String
init(isResetUsingEmail: Bool, emailorPhone: String) {
self.isResetUsingEmail = isResetUsingEmail
self.emailorPhone = emailorPhone
}
}*/
public struct ResetPassUsingPhoneAsset {
public let pass: String
public let confirmPass: String
public let verificationCode: String
init(pass: String, confirmPass: String, verificationCode: String) {
self.pass = pass
self.confirmPass = confirmPass
self.verificationCode = verificationCode
}
}
public struct BasicInfo{
public var name: String
public var email: String?
public var city: String
public var isSaudiNational: Bool
public var selectedGenderIndex: Int
public var dateOfBirth: Date
public var iqamaOrSaudiId: String
public var isHijriDob: Bool
init() {
name = ""
email = nil
city = ""
isSaudiNational = true
selectedGenderIndex = 0
dateOfBirth = Date()
iqamaOrSaudiId = ""
isHijriDob = true
}
}
public struct VehicleDetails{
public var make: String
public var model: String
public var year: Int
public var plateType: Int
public var licensePlate: String
public var sequenceNo: String
public var selectedCapacityIndex: Int
init() {
make = ""
model = ""
year = 0
plateType = 0
licensePlate = ""
sequenceNo = ""
selectedCapacityIndex = 0
}
}
public protocol RegisterationTemplateViewControllerDataSource{
func viewType() -> RegisterationViewType
func assests() -> RegisterationAssets
}
@objc public protocol RegisterationTemplateViewControllerDelegate{
func actionNext(sender: UIButton)
@objc optional func actionPrimary(sender: UIButton)
@objc optional func actionGoogleLogin(sender: UIButton)
@objc optional func actionFacbookLogin(sender: UIButton)
@objc optional func actionTwitterLogin(sender: UIButton)
@objc optional func actionTooltipBottom(sender: UIButton)
@objc optional func actionTooltipTop(sender: UIButton)
@objc optional func actionBackToSignup(sender: UIButton)
@objc optional func showCitiesList()
}
open class RegisterationTemplateViewController: UIViewController, NibLoadableView {
// override open func loadView() {
// let name = "RegisterationTemplateViewController"
// let bundle = Bundle(for: type(of: self))
// guard let view = bundle.loadNibNamed(name, owner: self, options: nil)?.first as? UIView else {
// fatalError("Nib not found.")
// }
// self.view = view
// }
//
static public let minValidYear = 1997
public var dataSource: RegisterationTemplateViewControllerDataSource!
public var delegate: RegisterationTemplateViewControllerDelegate?
@IBOutlet weak var socialLoginsView: UIView!
@IBOutlet weak var fieldsView: UIView!
@IBOutlet weak var logoView: UIView!
@IBOutlet weak public var logo: UIImageView!
@IBOutlet weak public var orLoginWithLabel: UILabel!
//Fields View
@IBOutlet weak var phoneCodeWidth: NSLayoutConstraint!
@IBOutlet weak var fieldSecondLeading: NSLayoutConstraint!
@IBOutlet weak var firstFieldHeight: NSLayoutConstraint!
@IBOutlet weak var thirdFieldHeight: NSLayoutConstraint!
@IBOutlet weak var fourthFieldHeight: NSLayoutConstraint!
@IBOutlet weak var fifthFieldHeight: NSLayoutConstraint!
@IBOutlet weak var sixthFieldHeight: NSLayoutConstraint!
@IBOutlet weak var seventhFieldHeight: NSLayoutConstraint!
@IBOutlet weak var stackViewHeight: NSLayoutConstraint!
@IBOutlet weak var stackViewReqHeight: NSLayoutConstraint!
@IBOutlet weak var subtitleHeight: NSLayoutConstraint!
@IBOutlet weak var titleViewHeight: NSLayoutConstraint!
@IBOutlet weak var actionButtonHeight: NSLayoutConstraint!
@IBOutlet weak var driverNationalityViewHeight: NSLayoutConstraint!
@IBOutlet weak var vehicleRegisterationContainerHeight: NSLayoutConstraint!
@IBOutlet weak public var labelTitle: HeadlineLabel!
@IBOutlet weak public var labelSubtitle: CaptionLabel!
@IBOutlet weak var btnTooltip: UIButton!
@IBOutlet weak var fieldPhoneCode: BottomBorderTextField!
@IBOutlet weak public var fieldFirst: BottomBorderTextField!
@IBOutlet weak public var fieldSecond: BottomBorderTextField!
@IBOutlet weak public var fieldThird: BottomBorderTextField!
@IBOutlet weak public var fieldFourth: BottomBorderTextField!
@IBOutlet weak public var fieldFifth: BottomBorderTextField!
@IBOutlet weak public var fieldSixth: BottomBorderTextField!
@IBOutlet weak public var fieldSeventh: BottomBorderTextField!
@IBOutlet weak var btnNext: UIButton!
@IBOutlet weak var btnAction: UIButton!
@IBOutlet weak var btnBackToSigup: UIButton!
@IBOutlet weak var driverNationalitySwitch: UISwitch!
@IBOutlet weak var labelDriverNationality: UILabel!
@IBOutlet weak var driverNationalityView: UIView!
public var vehicleRegisterationView: VehicleRegisterationView!
@IBOutlet weak var vehicleRegisterationContainerView: UIView!
var genderPickerView: UIPickerView?
var plateTypePickerView: UIPickerView?
//Social Logins View
@IBOutlet weak public var btnFacbook: UIButton!
@IBOutlet weak public var btnGoogle: UIButton!
@IBOutlet weak public var btnTwitter: UIButton!
@IBOutlet weak var btnBottomTooltip: UIButton!
public var activityIndicatoryFb:UIActivityIndicatorView!
public var activityIndicatoryGoogle:UIActivityIndicatorView!
public var activityIndicatoryTwitter:UIActivityIndicatorView!
var type: RegisterationViewType = .PhoneNumber
var capacityArray = [String]()
var gendersArray = [Bundle.localizedStringFor(key: "Male"),Bundle.localizedStringFor(key: "Female")]
var plateTypeArray = [PlateType]()
var selectedGenderIndex = 0
var selectedCapacityIndex: Int = 0
var selectedPlateTypeIndex: Int = 0
var driverDOB: Date?
var isHijriDob = true
override open func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(actionHideKeyboard))
self.view.addGestureRecognizer(tapGesture)
//text fields delegate
fieldFirst.delegate = self
fieldSecond.delegate = self
fieldThird.delegate = self
fieldFourth.delegate = self
fieldFifth.delegate = self
fieldPhoneCode.delegate = self
fieldSixth.delegate = self
btnTooltip.isHidden = true
fieldFirst.returnKeyType = .done
fieldSecond.returnKeyType = .done
fieldThird.returnKeyType = .done
fieldFourth.returnKeyType = .done
fieldFifth.returnKeyType = .done
fieldSixth.returnKeyType = .done
self.navigationController?.navigationBar.topItem?.title = ""
guard let type = dataSource?.viewType() else {
fatalError("Missing registeration view controller datasource method viewType")
}
guard let assets = dataSource?.assests() else {
fatalError("Missing registeration view controller datasource assets")
}
config(type: type, assets: assets)
configViews(type: type)
addTargets()
configurationsCompleted()
orLoginWithLabel.text = Bundle.localizedStringFor(key: "or Login with")
}
open func configurationsCompleted() { }
func actionHideKeyboard() {
self.view.endEditing(true)
}
func config(type: RegisterationViewType, assets:RegisterationAssets) {
self.type = type
self.logo.image = assets._logo.withRenderingMode(.alwaysTemplate)
self.logo.tintColor = UIColor.appColor(color: .Primary)
// btnTooltip.setImage(assets._tooltip, for: .normal)
btnBottomTooltip.setImage(assets._tooltip, for: .normal)
btnNext.setImage(assets._btnNext, for: .normal)
btnGoogle.setImage(assets._google, for: .normal)
btnFacbook.setImage(assets._facebook, for: .normal)
btnTwitter.setImage(assets._twitter, for: .normal)
btnAction.tintColor = UIColor.appColor(color: .Secondary)
if type != .PasswordAndConfirmPassword && type != .AddVehicleDetails && type != .BasicInfo && type != .ResetPassUsingPhone && type != .NameAndEmail{
removeFirstField()
}
if type != .PhoneNumber{
removeSocialLoginsView()
}else{
addActivityIndicatorsOverSocialLogins()
self.socialLoginsView.isHidden = false
removeTitleView()
}
if type == .PasswordAndConfirmPassword || type == .PhoneNumber || type == .AddVehicleDetails || type == .BasicInfo || type == .ForgotPassword || type == .NameAndEmail{
removeActionButton()
}
if type != .InviteCode && type != .ForgotPassword{
removeSubtitle()
}
if type == .VerificationCode{
// btnTooltip.isHidden = false
}
if type == .AddVehicleDetails{
addThirdField()
addFourthField()
addFifthField()
addSixthField()
addSeventhField()
}
if type == .BasicInfo{
addThirdField()
addFourthField()
addFifthField()
addSixthField()
addDriverNationalityView()
}
if type == .ResetPassUsingPhone{
addThirdField()
}
self.logoView.isHidden = false
self.fieldsView.isHidden = false
}
public func configViews(type: RegisterationViewType) {
btnBackToSigup.setTitle(Bundle.localizedStringFor(key: "auth-btn-back-to-signup"), for: .normal)
switch type {
case .PhoneNumber:
showPhoneNoCode()
fieldPhoneCode.text = Bundle.localizedStringFor(key: "auth-country-code")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-enter-phone-no")
fieldSecond.keyboardType = .numberPad
case .VerificationCode:
labelTitle.text = Bundle.localizedStringFor(key: "auth-verification-code")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-enter-here")
btnAction.setTitle(Bundle.localizedStringFor(key: "auth-resend-code"), for: .normal)
fieldSecond.keyboardType = .numberPad
btnBackToSigup.isHidden = false
case .NameAndEmail:
labelTitle.text = Bundle.localizedStringFor(key: "Name")
fieldFirst.placeholder = Bundle.localizedStringFor(key: "Name")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "Gender")
genderPickerView = showGenderPicker()
fieldSecond.inputView = genderPickerView
// fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-email")
// fieldSecond.keyboardType = .emailAddress
case.Password:
labelTitle.text = Bundle.localizedStringFor(key: "auth-password")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-password")
btnAction.setTitle(Bundle.localizedStringFor(key: "auth-btn-forgot-pass"), for: .normal)
fieldSecond.isSecureTextEntry = true
case .PasswordAndConfirmPassword:
labelTitle.text = Bundle.localizedStringFor(key: "auth-password")
fieldFirst.placeholder = Bundle.localizedStringFor(key: "Password (must be 6 digits)")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-password-confirm")
fieldFirst.isSecureTextEntry = true
fieldSecond.isSecureTextEntry = true
case .InviteCode:
labelTitle.text = Bundle.localizedStringFor(key: "auth-invite-code")
labelSubtitle.text = Bundle.localizedStringFor(key: "auth-invite-code-msg")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-invite-code")
btnAction.setTitle(Bundle.localizedStringFor(key: "auth-skip"), for: .normal)
case .ForgotPassword:
labelTitle.text = Bundle.localizedStringFor(key: "auth-forgot-pass")
labelSubtitle.text = Bundle.localizedStringFor(key: "auth-forgot-pass-msg")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-enter-phone-no")
fieldSecond.keyboardType = .numberPad
case .AddVehicleDetails:
labelTitle.text = Bundle.localizedStringFor(key: "auth-add-vehicle-details")
fieldFirst.placeholder = Bundle.localizedStringFor(key: "auth-make")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-model")
fieldThird.placeholder = Bundle.localizedStringFor(key: "auth-year")
fieldFourth.placeholder = Bundle.localizedStringFor(key: "Plate Type")
fieldFifth.placeholder = Bundle.localizedStringFor(key: "auth-license-plate")
.appending("(ى-و-ھ-١٢٣٤)")
fieldSixth.placeholder = Bundle.localizedStringFor(key: "Sequence Number")
fieldSeventh.placeholder = Bundle.localizedStringFor(key: "auth-capacity")
addVehicleRegisterationView()
fieldThird.keyboardType = .numberPad
fieldSixth.keyboardType = .numberPad
capacityArray = carCapcaityArray()
plateTypePickerView = showPlateTypePicker()
fieldFourth.inputView = plateTypePickerView
plateTypeArray = createPlateTypeArray()
fieldFourth.text = plateTypeArray[selectedPlateTypeIndex].title
fieldSeventh.inputView = showPicker()
fieldSeventh.text = capacityArray[selectedCapacityIndex]
case .BasicInfo:
labelTitle.text = Bundle.localizedStringFor(key: "auth-basic-info")
fieldFirst.placeholder = Bundle.localizedStringFor(key: "Name")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-email")
fieldThird.placeholder = Bundle.localizedStringFor(key: "auth-city")
fieldFourth.placeholder = Bundle.localizedStringFor(key: "Gender")
fieldFifth.placeholder = Bundle.localizedStringFor(key: "Date Of Birth")
fieldSixth.placeholder = Bundle.localizedStringFor(key: "Saudi Id/Iqama Id")
fieldSixth.keyboardType = .numberPad
let datePickerView = DatePickerView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 170))
datePickerView.dateUpdateCallback = { [weak self] (date,isHijri) in
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd YYYY"
if isHijri{
dateFormatter.calendar = Calendar(identifier: .islamicUmmAlQura)
}else {
dateFormatter.calendar = Calendar(identifier: .gregorian)
}
let dateString = dateFormatter.string(from: date)
self?.fieldFifth.text = dateString
self?.driverDOB = date
self?.isHijriDob = isHijri
}
fieldFifth.inputView = datePickerView
labelDriverNationality.text = Bundle.localizedStringFor(key: "auth-saudi-national")
fieldSecond.keyboardType = .emailAddress
genderPickerView = showGenderPicker()
fieldFourth.inputView = genderPickerView
case .ResetPassUsingPhone:
labelTitle.text = Bundle.localizedStringFor(key: "auth-reset-pass")
fieldFirst.placeholder = Bundle.localizedStringFor(key: "auth-password")
fieldSecond.placeholder = Bundle.localizedStringFor(key: "auth-password-confirm")
fieldFirst.isSecureTextEntry = true
fieldSecond.isSecureTextEntry = true
fieldThird.keyboardType = .numberPad
fieldThird.placeholder = Bundle.localizedStringFor(key: "auth-verification-code")
btnAction.setTitle(Bundle.localizedStringFor(key: "auth-resend-code"), for: .normal)
}
}
open func carCapcaityArray() -> [String]{
return [String]()
}
public struct PlateType {
var title: String
var id: Int
}
private func localisedValue(for key: String) -> String {
return Bundle.localizedStringFor(key: key)
}
public func createPlateTypeArray() -> [PlateType] {
var arr = [PlateType]()
arr.append(PlateType(title: localisedValue(for: "Private Car"), id: 1))
arr.append(PlateType(title: localisedValue(for: "Public Transport"), id: 2))
arr.append(PlateType(title: localisedValue(for: "Private Transport"), id: 3))
arr.append(PlateType(title: localisedValue(for: "Public Bus"), id: 4))
arr.append(PlateType(title: localisedValue(for: "Private Bus"), id: 5))
arr.append(PlateType(title: localisedValue(for: "Taxi"), id: 6))
arr.append(PlateType(title: localisedValue(for: "Heavy equipment"), id: 7))
arr.append(PlateType(title: localisedValue(for: "Export"), id: 8))
arr.append(PlateType(title: localisedValue(for: "Diplomatic"), id: 9))
arr.append(PlateType(title: localisedValue(for: "Motorcycle"), id: 10))
arr.append(PlateType(title: localisedValue(for: "Temporary"), id: 11))
return arr
}
public func setFirstFieldText(text: String){
guard fieldFirst != nil else {
return
}
fieldFirst.text = text
}
public func setSecondFieldText(text: String){
guard fieldSecond != nil else {
return
}
fieldSecond.text = text
}
public func setThirdFieldText(text: String){
guard fieldThird != nil else {
return
}
fieldThird.text = text
}
public func setFouthFieldText(text: String){
guard fieldFourth != nil else {
return
}
fieldFourth.text = text
}
public func setFifthFieldText(text: String){
guard fieldFifth != nil else {
return
}
fieldFifth.text = text
}
func addActivityIndicatorsOverSocialLogins(){
activityIndicatoryFb = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatoryFb.hidesWhenStopped = true
activityIndicatoryFb.center = btnFacbook.center
btnFacbook.addSubview(activityIndicatoryFb)
activityIndicatoryGoogle = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatoryGoogle.hidesWhenStopped = true
activityIndicatoryGoogle.center = btnGoogle.center
btnGoogle.addSubview(activityIndicatoryGoogle)
activityIndicatoryTwitter = UIActivityIndicatorView(activityIndicatorStyle: .gray)
activityIndicatoryTwitter.hidesWhenStopped = true
activityIndicatoryTwitter.center = btnTwitter.center
btnTwitter.addSubview(activityIndicatoryTwitter)
}
func addTargets() {
btnAction.addTarget(self, action: #selector(actPrimary(sender:)), for: .touchUpInside)
btnNext.addTarget(self, action: #selector(actNext(sender:)), for: .touchUpInside)
btnGoogle.addTarget(self, action: #selector(actGoogleLogin(sender:)), for: .touchUpInside)
btnFacbook.addTarget(self, action: #selector(actFacebookLogin(sender:)), for: .touchUpInside)
btnTwitter.addTarget(self, action: #selector(actTwitterLogin(sender:)), for: .touchUpInside)
btnTooltip.addTarget(self, action: #selector(actTooltipTop(sender:)), for: .touchUpInside)
btnBottomTooltip.addTarget(self, action: #selector(actBottomTooltip(sender:)), for: .touchUpInside)
btnBackToSigup.addTarget(self, action: #selector(actBackToSignup(sender:)), for: .touchUpInside)
}
func removeFirstField() {
firstFieldHeight.constant = 0
stackViewHeight.constant = 76-30
stackViewReqHeight.constant = 64-30
fieldFirst.isHidden = true
}
func removeTitleView() {
titleViewHeight.constant = 0
}
func removeSubtitle() {
subtitleHeight.constant = 0
}
func removeActionButton() {
actionButtonHeight.constant = 0
}
func showPhoneNoCode() {
fieldSecondLeading.constant = 12
phoneCodeWidth.constant = 40
fieldPhoneCode.clearButtonMode = .never
}
func addThirdField() {
thirdFieldHeight.constant = 30
fieldThird.isHidden = false
stackViewHeight.constant = 76+30
stackViewReqHeight.constant = 64+30
}
func addFourthField() {
fourthFieldHeight.constant = 30
fieldFourth.isHidden = false
stackViewHeight.constant = 76+30+30
stackViewReqHeight.constant = 64+30+30
}
func addFifthField() {
fifthFieldHeight.constant = 30
fieldFifth.isHidden = false
stackViewHeight.constant = 76+30+30+30
stackViewReqHeight.constant = 64+30+30+30
}
func addSixthField() {
sixthFieldHeight.constant = 30
fieldSixth.isHidden = false
stackViewHeight.constant = 76+30+30+30+30
stackViewReqHeight.constant = 64+30+30+30+30
}
func addSeventhField() {
seventhFieldHeight.constant = 30
fieldSixth.isHidden = false
stackViewHeight.constant = 76+150
stackViewReqHeight.constant = 64+150
}
func addVehicleRegisterationView() {
vehicleRegisterationContainerHeight.constant = 30
vehicleRegisterationContainerView.isHidden = false
vehicleRegisterationView = VehicleRegisterationView(frame: CGRect(x: 0, y: 0, width: 210, height: 30))
vehicleRegisterationContainerView.addSubview(vehicleRegisterationView)
stackViewHeight.constant = 76+30+30+30+30
stackViewReqHeight.constant = 64+30+30+30+30
}
func addDriverNationalityView() {
driverNationalityViewHeight.constant = 30
driverNationalityView.isHidden = false
stackViewHeight.constant = 76+30+30
stackViewReqHeight.constant = 64+30+30
}
public func removeSocialLoginsView() {
self.socialLoginsView.removeFromSuperview()
// let bottom = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: self.fieldsView, attribute: .bottom, multiplier: 1, constant: 44)
let centerY = NSLayoutConstraint(item: fieldsView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
self.view.addConstraint(centerY)
// self.view.addConstraint(bottom)
}
public func configPrimaryButton(btnTitle:String? = nil,image:UIImage? = nil){
if let _btnTitle = btnTitle{
self.btnAction.setTitle(_btnTitle, for: .normal)
}
if let _img = image{
self.btnAction.setImage(_img, for: .normal)
}
}
//MARK:- Actions
func actNext(sender: UIButton) {
delegate?.actionNext(sender: sender)
}
func actPrimary(sender: UIButton) {
delegate?.actionPrimary?(sender: sender)
}
func actGoogleLogin(sender: UIButton) {
delegate?.actionGoogleLogin?(sender: sender)
}
func actFacebookLogin(sender: UIButton) {
delegate?.actionFacbookLogin?(sender: sender)
}
func actTwitterLogin(sender: UIButton) {
delegate?.actionTwitterLogin?(sender: sender)
}
func actBottomTooltip(sender: UIButton) {
delegate?.actionTooltipBottom?(sender: sender)
}
func actTooltipTop(sender: UIButton) {
delegate?.actionTooltipTop?(sender: sender)
}
func actBackToSignup(sender: UIButton) {
delegate?.actionBackToSignup?(sender: sender)
}
}
//MARK:- Handle TextField delegates
extension RegisterationTemplateViewController: UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == fieldSeventh && type == .AddVehicleDetails{
let picker = fieldSeventh.inputView as! UIPickerView
picker.selectRow(selectedCapacityIndex, inComponent: 0, animated: false)
}else if textField == fieldThird && type == .BasicInfo{
delegate?.showCitiesList?()
return false
}else if (textField == fieldSecond && type == .NameAndEmail) {
let picker = fieldSecond.inputView as! UIPickerView
picker.selectRow(selectedGenderIndex, inComponent: 0, animated: false)
textField.text = gendersArray[selectedGenderIndex]
}else if (textField == fieldFourth && type == .BasicInfo) {
let picker = fieldFourth.inputView as! UIPickerView
picker.selectRow(selectedGenderIndex, inComponent: 0, animated: false)
textField.text = gendersArray[selectedGenderIndex]
}
return true
}
//MARK:- Picker
func showPicker() -> UIPickerView {
let picker = UIPickerView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 100))
picker.dataSource = self
picker.delegate = self
return picker
}
func showGenderPicker() -> UIPickerView {
let picker = UIPickerView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 100))
picker.dataSource = self
picker.delegate = self
return picker
}
func showDatePicker(calendarIdentifier: Calendar.Identifier) -> UIDatePicker {
let picker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 200))
picker.datePickerMode = .date
picker.date = Date()
picker.calendar = Calendar(identifier: calendarIdentifier)
picker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged)
// picker.autoresizingMask = UIViewAutoresizing.flexibleRightMargin
return picker
}
func showPlateTypePicker() -> UIPickerView {
let picker = UIPickerView(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 200))
picker.dataSource = self
picker.delegate = self
return picker
}
func dateChanged(_ datePicker: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd YYYY"
dateFormatter.calendar = Calendar(identifier: .islamicUmmAlQura)
// dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateString = dateFormatter.string(from: datePicker.date)
fieldFifth.text = dateString
driverDOB = datePicker.date
}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == genderPickerView {
return gendersArray.count
}else if pickerView == plateTypePickerView {
return plateTypeArray.count
}
return capacityArray.count
}
public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 22
}
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == genderPickerView {
return gendersArray[row]
}else if pickerView == plateTypePickerView {
return plateTypeArray[row].title
}
return capacityArray[row]
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView == genderPickerView {
selectedGenderIndex = row
if type == .NameAndEmail {
fieldSecond.text = gendersArray[row]
}else if type == .BasicInfo {
fieldFourth.text = gendersArray[row]
}
}else if pickerView == plateTypePickerView {
selectedPlateTypeIndex = row
fieldFourth.text = plateTypeArray[row].title
}else {
selectedCapacityIndex = row
fieldSeventh.text = capacityArray[row]
}
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch type {
case .PhoneNumber:
if textField == fieldPhoneCode{
return RegisterationTemplateViewController.handlePhoneCode(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
}
return RegisterationTemplateViewController.handlePhoneNumber(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
case .VerificationCode:
return !(textField.text!.count > 3 && (string.count) > range.length)
case .ForgotPassword:
// guard fieldSecond.placeholder?.caseInsensitiveCompare("Email") != .orderedSame else {
// return true
// }
return RegisterationTemplateViewController.handlePhoneNumber(textField: textField, shouldChangeCharactersIn: range, replacementString: string)
case .ResetPassUsingPhone:
if textField == fieldThird{
return !(textField.text!.count > 5 && (string.count) > range.length)
}
return true
case .AddVehicleDetails:
if textField == fieldThird{
return !(textField.text!.count > 3 && (string.count) > range.length)
}else if textField == fieldFifth {
return handleLicencePlate(textField: textField,shouldChangeCharactersInRange: range, replacementString: string)
}else if textField == fieldFourth {
return false
} else if textField == fieldSeventh {
return false
}
case .BasicInfo:
if textField == fieldFirst{
return handleName(textField: textField,shouldChangeCharactersIn: range, replacementString: string)
}else if textField == fieldFourth {
return false
}else if textField == fieldSixth {
return handleIqamaId(textField: textField,shouldChangeCharactersIn: range, replacementString: string)
}
case .NameAndEmail:
if textField == fieldSecond {
return false
}
default:
return !(textField.text!.count > 119 && (string.count) > range.length)
}
return !(textField.text!.count > 119 && (string.count) > range.length)
}
func handleName(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if string == " "{
return !(textField.text!.count > 119 && (string.count) > range.length)
}else if string.count > 0 {
let lettersOnly = CharacterSet.letters
guard let scalar = UnicodeScalar.init(string) else{
return false
}
let strValid = lettersOnly.contains(scalar)
return strValid && !(textField.text!.count > 119 && (string.count) > range.length)
}
return true
}
public func handleIqamaId(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !(textField.text!.count > 9 && (string.count) > range.length)
}
public func handleLicencePlate(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
// check the chars length dd -->2 at the same time calculate the dd-MM --> 5
let replaced = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if replaced.count <= 5 && !isLicenceInitialCharacter(string: string) && !(string == "") {
return false
}else if replaced.count > 5 && !isArabicNumber(string: string) && !(string == "") {
return false
}
if (textField.text!.count == 1) || (textField.text!.count == 3 ) || (textField.text!.count == 5) {
//Handle backspace being pressed
if !(string == "") {
// append the text
textField.text = textField.text! + "-"
}
}
return !(textField.text!.count > 9 && (string.count ) > range.length)
}
private func isLicenceInitialCharacter(string: String) -> Bool {
let allowedCharacters = ["ا", "ب", "ح", "د", "ر", "س", "ص", "ط", "ع", "ق", "ك", "ل", "م", "ن", "ھ", "و", "ى"]
for ch in allowedCharacters {
if ch == string {
return true
}
}
return false
}
private func isArabicNumber(string: String) -> Bool {
let allowedCharacters = ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
for ch in allowedCharacters {
if ch == string {
return true
}
}
return false
}
public static func handlePhoneCode(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !(textField.text!.count > 3 && (string.count) > range.length)
}
public static func handlePhoneNumber(textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// if textField.text!.count == 0 && string == "0"{
// textField.text! = "92"
// return false
// }else if textField.text!.count == 2 && string == "" {
// textField.text! = ""
// }
return !(textField.text!.count > 9 && (string.count) > range.length)
}
}
//MARK:- Validations
public extension RegisterationTemplateViewController{
public func getPhoneNo() -> String? {
let phoneNo = RegisterationTemplateViewController.getValidPhoneNoFrom(fieldCode: fieldPhoneCode, fieldPhoneNo: fieldSecond)
if phoneNo == nil{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-phone-must-be-twelve-digits"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
}else{
self.view.endEditing(true)
}
return phoneNo
}
public static func getValidPhoneNoFrom(fieldCode: UITextField, fieldPhoneNo: UITextField) -> String? {
var isValid = true
var code = fieldCode.text ?? Bundle.localizedStringFor(key: "auth-country-code")
if !code.isEmpty{
code.remove(at: code.startIndex)
}
var noWithoutCode = fieldPhoneNo.text ?? ""
if noWithoutCode.count == 10 && noWithoutCode.first! == "0"{
noWithoutCode = noWithoutCode.substring(from: noWithoutCode.index(after: noWithoutCode.startIndex))
}
let phoneNumber = "\(code)\(noWithoutCode)"
if phoneNumber.isEmpty {
isValid = false
}else if phoneNumber.count != 12{
isValid = false
}
if !isValid{
return nil
}else{
return phoneNumber
}
}
public func getNameAndGender() -> (name: String, gender: Int)?{
let name = fieldFirst.text ?? ""
let gender = fieldSecond.text ?? ""
if name.isEmpty{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-name-is-required"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else if gender.isEmpty {
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-fill-all-fields"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else {
self.view.endEditing(true)
return (name,selectedGenderIndex)
}/*else if email.isEmpty{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "constant-invalid-input"), msg: Bundle.localizedStringFor(key: "auth-email-is-required"))
return nil
}else if !fieldSecond.isValid(exp: .email){
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "constant-invalid-input"), msg: Bundle.localizedStringFor(key: "auth-enter-valid-email"))
return nil
}*/
}
public func getPasswordAndConfirmPassword() -> [String]? {
let pass = fieldFirst.text ?? ""
let confirmPass = fieldSecond.text ?? ""
var msg = ""
if pass.count <= 5{
msg = Bundle.localizedStringFor(key: "Password must be more than 5 characters")
}else if pass.compare(confirmPass) != .orderedSame{
msg = Bundle.localizedStringFor(key: "auth-pass-and-confirm-pass-donot-match")
}
if msg.isEmpty{
self.view.endEditing(true)
return [pass,confirmPass]
}else{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: msg, dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}
}
public func getPin() -> String? {
let pin = fieldSecond.text ?? ""
if pin.count == 4 {
self.view.endEditing(true)
return pin
}else{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Pin"), msg: Bundle.localizedStringFor(key: "Pin must have 4 digits"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}
}
public func getPassword() -> String? {
let pass = fieldSecond.text ?? ""
if pass.count <= 5{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "Password must be more than 5 characters"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else{
self.view.endEditing(true)
return pass
}
}
func getResetPassUsingPhoneAsset() -> ResetPassUsingPhoneAsset? {
let passAndConfirmPass = getPasswordAndConfirmPassword()
let verificationCode = fieldThird.text ?? ""
if passAndConfirmPass == nil{
return nil
}else if verificationCode.count != 4{
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Pin"), msg: Bundle.localizedStringFor(key: "Pin must have 4 digits"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else{
self.view.endEditing(true)
return ResetPassUsingPhoneAsset(pass: passAndConfirmPass![0], confirmPass: passAndConfirmPass![1], verificationCode: verificationCode)
}
}
public func getInviteCode() -> String? {
let pin = fieldSecond.text ?? ""
if pin.count == 0 {
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key:"auth-invalid-invite-code-title"), msg: Bundle.localizedStringFor(key:"auth-invalid-invite-code-msg"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else{
self.view.endEditing(true)
return pin
}
}
public func getBasicInfo() -> BasicInfo? {
var email: String?
if let emailString = fieldSecond.text, !emailString.isEmpty {
email = emailString
}
let isSaudiNational = driverNationalitySwitch.isOn
if (fieldFirst.text ?? "").isEmpty || (fieldThird.text ?? "").isEmpty || (fieldFourth.text ?? "" ).isEmpty || driverDOB == nil || (fieldSixth.text ?? "").count != 10 {
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-fill-all-fields"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else if let emailString = email, !UITextField.isValid(text: emailString, forExp: .email){
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-fill-all-fields"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
} else{
self.view.endEditing(true)
var info = BasicInfo()
info.name = fieldFirst.text ?? ""
info.email = email
info.city = fieldThird.text ?? ""
info.isSaudiNational = isSaudiNational
info.selectedGenderIndex = selectedGenderIndex
info.dateOfBirth = driverDOB ?? Date()
info.isHijriDob = isHijriDob
info.iqamaOrSaudiId = fieldSixth.text ?? ""
return info
}
}
public func getVehicleDetails() -> VehicleDetails? {
let make = fieldFirst.text ?? ""
let model = fieldSecond.text ?? ""
let yearString = fieldThird.text ?? ""
let licensePlate = fieldFifth.text ?? ""
let plateType = fieldFourth.text ?? ""
let sequenceNo = fieldSixth.text ?? ""
let currentYear = getCurrentYear()
guard let year = Int(yearString),year <= currentYear else {
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-invalid-year"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}
if year < RegisterationTemplateViewController.minValidYear{
let format = Bundle.localizedStringFor(key: "auth-year-must-be-greater-than")
let minValue = RegisterationTemplateViewController.minValidYear - 1
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: String(format: format,minValue), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else if make.isEmpty || model.isEmpty || plateType.isEmpty || sequenceNo.isEmpty || licensePlate.count != 10 {
Alert.showMessage(viewController: self, title: Bundle.localizedStringFor(key: "Invalid Input"), msg: Bundle.localizedStringFor(key: "auth-fill-all-fields"), dismissBtnTitle: Bundle.localizedStringFor(key: "Dismiss"))
return nil
}else{
self.view.endEditing(true)
var info = VehicleDetails()
info.make = make
info.model = model
info.year = year
info.plateType = plateTypeArray[selectedPlateTypeIndex].id
info.licensePlate = licensePlate
info.sequenceNo = sequenceNo
info.selectedCapacityIndex = selectedCapacityIndex
return info
}
}
func getCurrentYear() -> Int {
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: date)
return components.year ?? 0
}
}
class DatePickerView: UIView {
var selectedIndex = 0 {
didSet {
if selectedIndex == 0 {
gregorianPicker.isHidden = true
hijriPicker.isHidden = false
}else {
gregorianPicker.isHidden = false
hijriPicker.isHidden = true
}
}
}
var segmentedControl: UISegmentedControl!
var hijriPicker: UIDatePicker!
var gregorianPicker: UIDatePicker!
var date = Date()
var isHijriDate = true
var dateUpdateCallback: ((Date,Bool) ->Void)?
override init(frame: CGRect) {
super.init(frame: frame)
customizeUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
customizeUI()
}
//MARK: UI
private func customizeUI () {
// segmentedControl = DarkBorderSegmentedControl()
// segmentedControl.insertSegment(withTitle: "Hijri", at: 0, animated: false)
// segmentedControl.insertSegment(withTitle: "Gregorian", at: 1, animated: false)
segmentedControl = UISegmentedControl(items: ["Hijri", "Gregorian"])
segmentedControl.tintColor = UIColor.appColor(color: .Primary)
segmentedControl.selectedSegmentIndex = selectedIndex
segmentedControl.addTarget(self, action: #selector(segmentUpdated(_:)), for: .valueChanged)
add(segmentedControl: segmentedControl, to: self)
hijriPicker = createDatePicker(calendarIdentifier: .islamicUmmAlQura)
hijriPicker.addTarget(self, action: #selector(dateUpdated(_:)), for: .valueChanged)
add(datePicker: hijriPicker, to: self, topView: segmentedControl)
gregorianPicker = createDatePicker(calendarIdentifier: .gregorian)
gregorianPicker.addTarget(self, action: #selector(dateUpdated(_:)), for: .valueChanged)
add(datePicker: gregorianPicker, to: self, topView: segmentedControl)
selectedIndex = segmentedControl.selectedSegmentIndex
// self.backgroundColor = UIColor.black
}
private func add(segmentedControl child: UISegmentedControl, to parent: UIView) {
child.translatesAutoresizingMaskIntoConstraints = false
parent.addSubview(child)
child.heightAnchor.constraint(equalToConstant: 30).isActive = true
child.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true
parent.trailingAnchor.constraint(equalTo: child.trailingAnchor).isActive = true
}
private func add(datePicker child: UIDatePicker, to parent: UIView, topView: UISegmentedControl) {
child.translatesAutoresizingMaskIntoConstraints = false
parent.addSubview(child)
child.heightAnchor.constraint(equalToConstant: 140).isActive = true
child.topAnchor.constraint(equalTo: topView.bottomAnchor).isActive = true
child.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true
parent.trailingAnchor.constraint(equalTo: child.trailingAnchor).isActive = true
parent.bottomAnchor.constraint(equalTo: child.bottomAnchor).isActive = true
}
func createDatePicker(calendarIdentifier: Calendar.Identifier) -> UIDatePicker {
let picker = UIDatePicker()
picker.datePickerMode = .date
picker.date = Date()
picker.calendar = Calendar(identifier: calendarIdentifier)
return picker
}
@objc private func segmentUpdated(_ sender: UISegmentedControl) {
selectedIndex = sender.selectedSegmentIndex
}
@objc private func dateUpdated(_ sender: UIDatePicker) {
if sender == hijriPicker {
isHijriDate = true
}else if sender == gregorianPicker {
isHijriDate = false
}
date = sender.date
dateUpdateCallback?(sender.date,isHijriDate)
}
}
| 2fc4d850f4fb144a82e25151954b0f60 | 38.855184 | 251 | 0.682527 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | refs/heads/develop | Pod/Classes/Common/Model/AdModels.swift | lgpl-3.0 | 1 | //
// AdModels.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 15/04/2020.
//
public struct Ad: Codable {
let advertiserId: Int
let publisherId: Int
let moat: Float
var campaignId: Int? = 0
let campaignType: Int
let isVpaid: Bool?
let showPadlock: Bool
public let lineItemId: Int
let test: Bool
let app: Int
let device: String
public let creative: Creative
let ksfRequest: String?
enum CodingKeys: String, CodingKey {
case advertiserId
case publisherId
case moat
case campaignId = "campaign_id"
case campaignType = "campaign_type"
case isVpaid = "is_vpaid"
case showPadlock = "show_padlock"
case lineItemId = "line_item_id"
case test
case app
case device
case creative
case ksfRequest
}
}
struct AdQuery: Codable {
let test: Bool
let sdkVersion: String
let random: Int
let bundle: String
let name: String
let dauid: Int
let connectionType: ConnectionType
let lang: String
let device: String
let position: Int
let skip: Int
let playbackMethod: Int
let startDelay: Int
let instl: Int
let width: Int
let height: Int
enum CodingKeys: String, CodingKey {
case test
case sdkVersion
case random = "rnd"
case bundle
case name
case dauid
case connectionType = "ct"
case lang
case device
case position = "pos"
case skip
case playbackMethod = "playbackmethod"
case startDelay = "startDelay"
case instl
case width = "w"
case height = "h"
}
}
public struct AdRequest: Codable {
let test: Bool
let position: Position
let skip: Skip
let playbackMethod: Int
let startDelay: StartDelay
let instl: FullScreen
let width: Int
let height: Int
enum CodingKeys: String, CodingKey {
case test
case position = "pos"
case skip
case playbackMethod = "playbackmethod"
case startDelay = "startdelay"
case instl
case width = "w"
case height = "h"
}
}
class AdResponse {
let placementId: Int
let advert: Ad
var html: String?
var vast: VastAd?
var baseUrl: String?
var filePath: String?
init(_ placementId: Int, _ advert: Ad) {
self.placementId = placementId
self.advert = advert
}
/// Returns the aspect ratio of the ad's creative
func aspectRatio() -> CGFloat {
let width = advert.creative.details.width
let height = advert.creative.details.height
return CGFloat(width) / CGFloat(height)
}
/// Returns if the type of the ad is Vpaid
var isVpaid: Bool {
advert.isVpaid ?? false
}
}
extension AdRequest {
/// Specify if the ad is in full screen or not
enum FullScreen: Int, Codable {
case on = 1
case off = 0
}
/// Playback method to enable sound at the beginning
enum Playback: Int, Codable {
/// Start with sound on
case soundOn = 5
/// Start with sound off
case soundOff = 2
static func from(_ muted: Bool) -> Playback {
return muted ? soundOff : soundOn
}
}
/// Start delay cases
@objc
public enum StartDelay: Int, Codable {
case postRoll = -2
case genericMidRoll = -1
case preRoll = 0
case midRoll = 1
}
/// Specify the position of the ad
enum Position: Int, Codable {
case aboveTheFold = 1
case belowTheFold = 3
case fullScreen = 7
}
/// Specify if the ad can be skipped
enum Skip: Int, Codable {
case no = 0
case yes = 1
}
}
@objc
public class StartDelayHelper: NSObject {
/// Creates `StartDelay` enum from `int` value.
@objc
public class func from(_ value: Int) -> AdRequest.StartDelay {
AdRequest.StartDelay(rawValue: value) ?? Constants.defaultStartDelay
}
}
/**
* This enum holds all the possible callback values that an ad sends during its lifetime
* - adLoaded: ad was loaded successfully and is ready
* to be displayed
* - adEmpty the ad server returned an empty response
* - adFailedToLoad: ad was not loaded successfully and will not be
* able to play
* - adAlreadyLoaded ad was previously loaded in an interstitial, video or
* app wall queue
* - adShown: triggered once when the ad first displays
* - adFailedToShow: for some reason the ad failed to show; technically
* this should never happen nowadays
* - adClicked: triggered every time the ad gets clicked
* - adEnded: triggerd when a video ad ends
* - adClosed: triggered once when the ad is closed;
*/
@objc(SAEvent)
public enum AdEvent: Int {
case adLoaded = 0
case adEmpty = 1
case adFailedToLoad = 2
case adAlreadyLoaded = 3
case adShown = 4
case adFailedToShow = 5
case adClicked = 6
case adEnded = 7
case adClosed = 8
/// Gets the name of the event
public func name() -> String {
switch self {
case .adLoaded: return "adLoaded"
case .adEmpty: return "adEmpty"
case .adFailedToLoad: return "adFailedToLoad"
case .adAlreadyLoaded: return "adAlreadyLoaded"
case .adShown: return "adShown"
case .adFailedToShow: return "adFailedToShow"
case .adClicked: return "adClicked"
case .adEnded: return "adEnded"
case .adClosed: return "adClosed"
default: return "\(self.rawValue)"
}
}
}
/// Callback function for completable events
public typealias AdEventCallback = (_ placementId: Int, _ event: AdEvent) -> Void
struct AdvertiserSignatureDTO: Equatable, Codable {
let signature: String
let campaignID: Int
let itunesItemID: Int
let sourceAppID: Int
let impressionID: String
let timestamp: String
let version: String
let adNetworkID: String
let fidelityType: Int
enum CodingKeys: String, CodingKey {
case campaignID = "campaignId"
case itunesItemID = "itunesItemId"
case sourceAppID = "sourceAppId"
case impressionID = "impressionId"
case adNetworkID = "adNetworkId"
case signature
case timestamp
case version
case fidelityType
}
}
| 5df3645a6945666f4bf28acb59e7b982 | 25.350806 | 88 | 0.60964 | false | false | false | false |
devpunk/velvet_room | refs/heads/master | Source/View/Basic/VGradient.swift | mit | 1 | import UIKit
final class VGradient:UIView
{
private static let kLocationStart:NSNumber = 0
private static let kLocationEnd:NSNumber = 1
class func diagonal(
colourLeftBottom:UIColor,
colourTopRight:UIColor) -> VGradient
{
let colours:[CGColor] = [
colourLeftBottom.cgColor,
colourTopRight.cgColor]
let locations:[NSNumber] = [
kLocationStart,
kLocationEnd]
let startPoint:CGPoint = CGPoint(x:0, y:1)
let endPoint:CGPoint = CGPoint(x:1, y:0)
let gradient:VGradient = VGradient(
colours:colours,
locations:locations,
startPoint:startPoint,
endPoint:endPoint)
return gradient
}
class func horizontal(
colourLeft:UIColor,
colourRight:UIColor) -> VGradient
{
let colours:[CGColor] = [
colourLeft.cgColor,
colourRight.cgColor]
let locations:[NSNumber] = [
kLocationStart,
kLocationEnd]
let startPoint:CGPoint = CGPoint(x:0, y:0.5)
let endPoint:CGPoint = CGPoint(x:1, y:0.5)
let gradient:VGradient = VGradient(
colours:colours,
locations:locations,
startPoint:startPoint,
endPoint:endPoint)
return gradient
}
class func vertical(
colourTop:UIColor,
colourBottom:UIColor) -> VGradient
{
let colours:[CGColor] = [
colourTop.cgColor,
colourBottom.cgColor]
let locations:[NSNumber] = [
kLocationStart,
kLocationEnd]
let startPoint:CGPoint = CGPoint(x:0.5, y:0)
let endPoint:CGPoint = CGPoint(x:0.5, y:1)
let gradient:VGradient = VGradient(
colours:colours,
locations:locations,
startPoint:startPoint,
endPoint:endPoint)
return gradient
}
private init(
colours:[CGColor],
locations:[NSNumber],
startPoint:CGPoint,
endPoint:CGPoint)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
isUserInteractionEnabled = false
guard
let gradientLayer:CAGradientLayer = self.layer as? CAGradientLayer
else
{
return
}
gradientLayer.startPoint = startPoint
gradientLayer.endPoint = endPoint
gradientLayer.locations = locations
gradientLayer.colors = colours
}
required init?(coder:NSCoder)
{
return nil
}
override open class var layerClass:AnyClass
{
get
{
return CAGradientLayer.self
}
}
}
| cf74bb4d12cfefb3a09a53cba6212a98 | 25 | 78 | 0.55582 | false | false | false | false |
CaptainTeemo/IGKit | refs/heads/master | IGKit/Utils/JSON.swift | mit | 1 | //
// JSON.swift
// IGKit
//
// Created by CaptainTeemo on 5/13/16.
// Copyright © 2016 CaptainTeemo. All rights reserved.
//
import Foundation
public struct JSON {
let object: AnyObject?
init(_ object: AnyObject?) {
self.object = object
}
init(_ data: NSData?) {
self.init(JSON.objectWithData(data))
}
static func objectWithData(data: NSData?) -> AnyObject? {
if let data = data {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: [])
} catch {
return nil
}
}
return nil
}
subscript(key: String) -> JSON {
guard let object = object else { return self }
if let dictionary = object as? [String: AnyObject] {
return JSON(dictionary[key])
}
return JSON(nil)
}
}
// MARK: - String
extension JSON {
var string: String? { return object as? String }
var stringValue: String { return string ?? "" }
}
// MARK: - Integer
extension JSON {
var int: Int? { return object as? Int }
var intValue: Int { return int ?? 0 }
}
// MARK: - Bool
extension JSON {
var bool: Bool? { return object as? Bool }
var boolValue: Bool { return bool ?? false }
}
// MARK: - Dictionary
extension JSON {
var dictionary: [String: AnyObject]? { return object as? [String: AnyObject] }
var dictionaryValue: [String: AnyObject] { return dictionary ?? [:] }
var jsonDictionary: [String: JSON]? { return dictionary?.reduceValues{ JSON($0) }}
var jsonDictionaryValue: [String: JSON] { return jsonDictionary ?? [:] }
}
// MARK: - Array
extension JSON {
var array: [AnyObject]? { return object as? [AnyObject] }
var arrayValue: [AnyObject] { return array ?? [] }
var jsonArray: [JSON]? { return array?.map { JSON($0) } }
var jsonArrayValue: [JSON] { return jsonArray ?? [] }
}
internal extension Dictionary {
func reduceValues <T: Any>(transform: (value: Value) -> T) -> [Key: T] {
return reduce([Key: T]()) { (dictionary, kv) in
var dictionary = dictionary
dictionary[kv.0] = transform(value: kv.1)
return dictionary
}
}
} | 78fcca28291a39b1169f5e36b0123203 | 22.729167 | 86 | 0.574001 | false | false | false | false |
anzfactory/QiitaCollection | refs/heads/master | QiitaCollection/NSURL+App.swift | mit | 1 | //
// NSURL+App.swift
// QiitaCollection
//
// Created by ANZ on 2015/03/05.
// Copyright (c) 2015年 anz. All rights reserved.
//
import UIKit
extension NSURL {
enum Signin: String {
case
Host = "anz-note.tumblr.com",
Path = "/qiitacollection-signin",
Query = "code",
Scope = "read_qiita write_qiita"
}
class func qiitaAuthorizeURL() -> NSURL {
let scope: String = Signin.Scope.rawValue.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
return NSURL(string: "https://qiita.com/api/v2/oauth/authorize?scope=" + scope + "&client_id=" + ThirdParty.Qiita.ClientID.rawValue)!
}
func isQittaAfterSignIn() -> Bool {
return Signin.Host.rawValue == self.host && Signin.Path.rawValue == self.path
}
func getAccessCode() -> String? {
if let queryString = self.query {
let queries:[String] = queryString.componentsSeparatedByString("&")
for pairString in queries {
let pair:[String] = pairString.componentsSeparatedByString("=")
if Signin.Query.rawValue == pair[0] {
return pair[1]
}
}
return nil
} else {
return nil
}
}
func parse() -> (entryId: String?, userId: String?) {
var result: (entryId: String?, userId: String?) = (entryId: nil, userId: nil)
if let h = self.host {
if h != "qiita.com" {
return result
}
} else {
return result
}
if var components = self.pathComponents {
// 初めが url separator か
if components[0] as! String == "/" {
components.removeAtIndex(0)
}
if (components.count == 1) {
// ユーザーページの可能性
let path = components[0] as! String
// qiita の静的ページチェック
if !contains(["about", "tags", "advent-calendar", "organizations", "users", "license", "terms", "privacy", "asct", "drafts"], path) {
result.userId = path
}
} else if (components.count >= 3) {
// 記事の可能性
let path2 = components[1] as! String
if path2 == "items" {
result.entryId = components[2] as? String
}
}
}
return result
}
} | e5d943f6d95fd1622f5cae8056486588 | 28.677778 | 149 | 0.48427 | false | false | false | false |
Baza207/AlamofireImage | refs/heads/master | Example/ImageViewController.swift | mit | 18 | // ImageViewController.swift
//
// Copyright (c) 2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 AlamofireImage
import Foundation
import UIKit
class ImageViewController : UIViewController {
var gravatar: Gravatar!
var imageView: UIImageView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setUpInstanceProperties()
setUpImageView()
}
// MARK: - Private - Setup Methods
private func setUpInstanceProperties() {
title = gravatar.email
edgesForExtendedLayout = UIRectEdge.None
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
}
private func setUpImageView() {
imageView = UIImageView()
imageView.contentMode = .ScaleAspectFit
let URL = gravatar.URL(size: view.bounds.size.width)
imageView.af_setImageWithURL(
URL,
placeholderImage: nil,
filter: CircleFilter(),
imageTransition: .FlipFromBottom(0.5)
)
view.addSubview(imageView)
imageView.frame = view.bounds
imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
}
}
| c67e1633373b41c0f50b28f5c5affaf2 | 33.272727 | 80 | 0.705128 | false | false | false | false |
nextcloud/ios | refs/heads/master | iOSClient/Settings/NCEndToEndInitialize.swift | gpl-3.0 | 1 | //
// NCEndToEndInitialize.swift
// Nextcloud
//
// Created by Marino Faggiana on 03/04/17.
// Copyright © 2017 Marino Faggiana. All rights reserved.
//
// Author Marino Faggiana <[email protected]>
//
// 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
import NextcloudKit
@objc protocol NCEndToEndInitializeDelegate {
func endToEndInitializeSuccess()
}
class NCEndToEndInitialize: NSObject {
@objc weak var delegate: NCEndToEndInitializeDelegate?
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var extractedPublicKey: String?
override init() {
}
// --------------------------------------------------------------------------------------------
// MARK: Initialize
// --------------------------------------------------------------------------------------------
@objc func initEndToEndEncryption() {
// Clear all keys
CCUtility.clearAllKeysEnd(toEnd: appDelegate.account)
self.getPublicKey()
}
func getPublicKey() {
NextcloudKit.shared.getE2EECertificate { account, certificate, data, error in
if error == .success && account == self.appDelegate.account {
CCUtility.setEndToEndCertificate(account, certificate: certificate)
self.extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate)
// Request PrivateKey chiper to Server
self.getPrivateKeyCipher()
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorResourceNotFound:
guard let csr = NCEndToEndEncryption.sharedManager().createCSR(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData()) else {
let error = NKError(errorCode: error.errorCode, errorDescription: "Error to create Csr")
NCContentPresenter.shared.messageNotification("E2E Csr", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
return
}
NextcloudKit.shared.signE2EECertificate(certificate: csr) { account, certificate, data, error in
if error == .success && account == self.appDelegate.account {
// TEST publicKey
let extractedPublicKey = NCEndToEndEncryption.sharedManager().extractPublicKey(fromCertificate: certificate)
if extractedPublicKey != NCEndToEndEncryption.sharedManager().generatedPublicKey {
let error = NKError(errorCode: error.errorCode, errorDescription: "error: the public key is incorrect")
NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
} else {
CCUtility.setEndToEndCertificate(account, certificate: certificate)
// Request PrivateKey chiper to Server
self.getPrivateKeyCipher()
}
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "conflict: a public key for the user already exists")
NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E sign publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the public keys")
NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E get publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
}
func getPrivateKeyCipher() {
// Request PrivateKey chiper to Server
NextcloudKit.shared.getE2EEPrivateKey { account, privateKeyChiper, data, error in
if error == .success && account == self.appDelegate.account {
// request Passphrase
var passphraseTextField: UITextField?
let alertController = UIAlertController(title: NSLocalizedString("_e2e_passphrase_request_title_", comment: ""), message: NSLocalizedString("_e2e_passphrase_request_message_", comment: ""), preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: { _ -> Void in
let passphrase = passphraseTextField?.text
let publicKey = CCUtility.getEndToEndCertificate(self.appDelegate.account)
guard let privateKey = (NCEndToEndEncryption.sharedManager().decryptPrivateKey(privateKeyChiper, passphrase: passphrase, publicKey: publicKey)) else {
let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "Serious internal error to decrypt Private Key")
NCContentPresenter.shared.messageNotification("E2E decrypt privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
return
}
// privateKey
print(privateKey)
// Save to keychain
CCUtility.setEndToEndPrivateKey(self.appDelegate.account, privateKey: privateKey)
CCUtility.setEndToEndPassphrase(self.appDelegate.account, passphrase: passphrase)
// request server publicKey
NextcloudKit.shared.getE2EEPublicKey { account, publicKey, data, error in
if error == .success && account == self.appDelegate.account {
CCUtility.setEndToEndPublicKey(account, publicKey: publicKey)
// Clear Table
NCManageDatabase.shared.clearTable(tableDirectory.self, account: account)
NCManageDatabase.shared.clearTable(tableE2eEncryption.self, account: account)
self.delegate?.endToEndInitializeSuccess()
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorResourceNotFound:
let error = NKError(errorCode: error.errorCode, errorDescription: "Server publickey doesn't exists")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the Server publickey")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
})
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ -> Void in
}
alertController.addAction(ok)
alertController.addAction(cancel)
alertController.addTextField { textField -> Void in
passphraseTextField = textField
passphraseTextField?.placeholder = NSLocalizedString("_enter_passphrase_", comment: "")
}
self.appDelegate.window?.rootViewController?.present(alertController, animated: true)
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorResourceNotFound:
// message
guard let e2ePassphrase = NYMnemonic.generateString(128, language: "english") else { return }
let message = "\n" + NSLocalizedString("_e2e_settings_view_passphrase_", comment: "") + "\n\n" + e2ePassphrase
let alertController = UIAlertController(title: NSLocalizedString("_e2e_settings_title_", comment: ""), message: NSLocalizedString(message, comment: ""), preferredStyle: .alert)
let OKAction = UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default) { _ in
self.createNewE2EE(e2ePassphrase: e2ePassphrase, error: error, copyPassphrase: false)
}
let copyAction = UIAlertAction(title: NSLocalizedString("_ok_copy_passphrase_", comment: ""), style: .default) { _ in
self.createNewE2EE(e2ePassphrase: e2ePassphrase, error: error, copyPassphrase: true)
}
alertController.addAction(OKAction)
alertController.addAction(copyAction)
self.appDelegate.window?.rootViewController?.present(alertController, animated: true)
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the private key")
NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E get privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
}
func createNewE2EE(e2ePassphrase: String, error: NKError, copyPassphrase: Bool) {
var privateKeyString: NSString?
guard let privateKeyChiper = NCEndToEndEncryption.sharedManager().encryptPrivateKey(self.appDelegate.userId, directory: CCUtility.getDirectoryUserData(), passphrase: e2ePassphrase, privateKey: &privateKeyString) else {
let error = NKError(errorCode: error.errorCode, errorDescription: "Serious internal error to create PrivateKey chiper")
NCContentPresenter.shared.messageNotification("E2E privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
return
}
// privateKeyChiper
print(privateKeyChiper)
NextcloudKit.shared.storeE2EEPrivateKey(privateKey: privateKeyChiper) { account, privateKey, data, error in
if error == .success && account == self.appDelegate.account {
CCUtility.setEndToEndPrivateKey(account, privateKey: privateKeyString! as String)
CCUtility.setEndToEndPassphrase(account, passphrase: e2ePassphrase)
// request server publicKey
NextcloudKit.shared.getE2EEPublicKey { account, publicKey, data, error in
if error == .success && account == self.appDelegate.account {
CCUtility.setEndToEndPublicKey(account, publicKey: publicKey)
// Clear Table
NCManageDatabase.shared.clearTable(tableDirectory.self, account: account)
NCManageDatabase.shared.clearTable(tableE2eEncryption.self, account: account)
if copyPassphrase {
UIPasteboard.general.string = e2ePassphrase
}
self.delegate?.endToEndInitializeSuccess()
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorResourceNotFound:
let error = NKError(errorCode: error.errorCode, errorDescription: "Server publickey doesn't exists")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "forbidden: the user can't access the Server publickey")
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E Server publicKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
} else if error != .success {
switch error.errorCode {
case NCGlobal.shared.errorBadRequest:
let error = NKError(errorCode: error.errorCode, errorDescription: "bad request: unpredictable internal error")
NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
case NCGlobal.shared.errorConflict:
let error = NKError(errorCode: error.errorCode, errorDescription: "conflict: a private key for the user already exists")
NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
default:
NCContentPresenter.shared.messageNotification("E2E store privateKey", error: error, delay: NCGlobal.shared.dismissAfterSecond, type: NCContentPresenter.messageType.error, priority: .max)
}
}
}
}
}
| 56574005ac1598beb1dade49dcd79887 | 54.432927 | 229 | 0.623584 | false | false | false | false |
Jinxiaoming/ExSwift | refs/heads/master | ExSwiftTests/RangeExtensionsTests.swift | bsd-2-clause | 25 | //
// RangeExtensionsTests.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Quick
import Nimble
class RangeExtensionsSpec: QuickSpec {
override func spec() {
/**
* Range.times
*/
it("times") {
var count: Int = 0
(2..<4).times { count++ }
expect(count) == 2
count = 0
(2...4).times { count++ }
expect(count) == 3
}
/**
* Range.each
*/
it("each") {
var items = [Int]()
(0..<2).each(items.append)
expect(items) == [0, 1]
(0..<0).each { (current: Int) in
fail()
}
}
}
}
| 3a74bd0a82b9f579cc50020b9284e85a | 16.057692 | 49 | 0.361894 | false | false | false | false |
wordlessj/Bamboo | refs/heads/master | Tests/Auto/ItemsChain/ItemsDistributeTests.swift | mit | 1 | //
// ItemsDistributeTests.swift
// Bamboo
//
// Copyright (c) 2017 Javier Zhang (https://wordlessj.github.io/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
import Bamboo
class ItemsDistributeTests: BaseTestCase {
private let inset: CGFloat = 5
private var distributeXConstraints: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: view2, attribute: .leading,
toItem: view1, toAttribute: .trailing,
constant: value),
NSLayoutConstraint(item: view3, attribute: .leading,
toItem: view2, toAttribute: .trailing,
constant: value)
]
}
private var distributeYConstraints: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: view2, attribute: .top, toItem: view1, toAttribute: .bottom, constant: value),
NSLayoutConstraint(item: view3, attribute: .top, toItem: view2, toAttribute: .bottom, constant: value)
]
}
private var insetXConstraints: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: view1, attribute: .leading, toItem: superview, constant: inset),
NSLayoutConstraint(item: view3, attribute: .trailing, toItem: superview, constant: -inset)
]
}
private var insetYConstraints: [NSLayoutConstraint] {
return [
NSLayoutConstraint(item: view1, attribute: .top, toItem: superview, constant: inset),
NSLayoutConstraint(item: view3, attribute: .bottom, toItem: superview, constant: -inset)
]
}
func testDistributeX() {
let constraints = subviews.bb.distributeX(spacing: value).constraints
XCTAssertEqual(constraints, distributeXConstraints)
}
func testDistributeXWithInsetSpacing() {
let constraints = subviews.bb.distributeX(spacing: value, inset: .fixed(inset)).constraints
XCTAssertEqual(constraints, distributeXConstraints + insetXConstraints)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeXWithEqualInset() {
let constraints = subviews.bb.distributeX(spacing: value, inset: .equal).constraints
XCTAssertEqual(constraints.count, 3)
XCTAssertEqual(Array(constraints[0..<2]), distributeXConstraints)
XCTAssertNil(constraints[2].firstItem)
}
func testDistributeY() {
let constraints = subviews.bb.distributeY(spacing: value).constraints
XCTAssertEqual(constraints, distributeYConstraints)
}
func testDistributeYWithInsetSpacing() {
let constraints = subviews.bb.distributeY(spacing: value, inset: .fixed(inset)).constraints
XCTAssertEqual(constraints, distributeYConstraints + insetYConstraints)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeYWithEqualInset() {
let constraints = subviews.bb.distributeY(spacing: value, inset: .equal).constraints
XCTAssertEqual(constraints.count, 3)
XCTAssertEqual(Array(constraints[0..<2]), distributeYConstraints)
XCTAssertNil(constraints[2].firstItem)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeXEqualSpacing() {
let constraints = subviews.bb.distributeXEqualSpacing().constraints
XCTAssertEqual(constraints.count, 1)
XCTAssertNil(constraints[0].firstItem)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeXEqualSpacingWithInsetSpacing() {
let constraints = subviews.bb.distributeXEqualSpacing(inset: .fixed(inset)).constraints
XCTAssertEqual(constraints.count, 3)
XCTAssertNil(constraints[0].firstItem)
XCTAssertEqual(Array(constraints[1..<3]), insetXConstraints)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeXEqualSpacingWithEqualInset() {
let constraints = subviews.bb.distributeXEqualSpacing(inset: .equal).constraints
XCTAssertEqual(constraints.count, 3)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeYEqualSpacing() {
let constraints = subviews.bb.distributeYEqualSpacing().constraints
XCTAssertEqual(constraints.count, 1)
XCTAssertNil(constraints[0].firstItem)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeYEqualSpacingWithInsetSpacing() {
let constraints = subviews.bb.distributeYEqualSpacing(inset: .fixed(inset)).constraints
XCTAssertEqual(constraints.count, 3)
XCTAssertNil(constraints[0].firstItem)
XCTAssertEqual(Array(constraints[1..<3]), insetYConstraints)
}
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
func testDistributeYEqualSpacingWithEqualInset() {
let constraints = subviews.bb.distributeYEqualSpacing(inset: .equal).constraints
XCTAssertEqual(constraints.count, 3)
}
}
| bdcbe479cc648c0cdc9398d3e9d674d1 | 41.624113 | 115 | 0.690849 | false | true | false | false |
huangboju/Moots | refs/heads/master | Examples/Lumia/Lumia/Component/Parade/ParallaxCells/Views/ProgressDotView.swift | mit | 1 | //
// IntroProgressDotView.swift
// PDAnimator-Demo
//
// Created by Anton Doudarev on 3/30/18.
// Copyright © 2018 ELEPHANT. All rights reserved.
//
import Foundation
import UIKit
class ProgressDotView : UIView {
var needsLayout = true
var dotViews = [UIView]()
var shadowView : ShadowView?
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
clipsToBounds = true
for x in 0...20
{
let view = UIView(frame: CGRect.zero)
view.frame = CGRect(x:0, y: 10 * x, width:4, height:4)
view.backgroundColor = UIColor.white
view.layer.cornerRadius = 2.0
view.layer.masksToBounds = true
addSubview(view)
dotViews.append(view)
}
shadowView = ShadowView(frame: bounds)
addSubview(shadowView!)
}
override func layoutSubviews()
{
super.layoutSubviews()
shadowView?.frame = bounds
}
}
class ShadowView : UIView {
var isDrawn = false
override public init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext(), !rect.equalTo(CGRect.zero) else {
return
}
let gradientColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
var red1: CGFloat = 1.0, green1: CGFloat = 1.0, blue1: CGFloat = 1.0, alpha1: CGFloat = 1.0
var red2: CGFloat = 1.0, green2: CGFloat = 1.0, blue2: CGFloat = 1.0, alpha2: CGFloat = 1.0
UIColor.clear.getRed(&red1, green: &green1, blue: &blue1, alpha: &alpha1)
gradientColor.getRed(&red2, green: &green2, blue: &blue2, alpha: &alpha2)
let fraction : CGFloat = 0.5
let blendedColor = UIColor(red : red1 * (1 - fraction) + red2 * fraction,
green: green1 * (1 - fraction) + green2 * fraction,
blue : blue1 * (1 - fraction) + blue2 * fraction,
alpha: alpha1 * (1 - fraction) + alpha2 * fraction);
let gradientColors = [gradientColor.cgColor, blendedColor.cgColor, gradientColor.cgColor] as CFArray
guard let gradient = CGGradient(colorsSpace : CGColorSpaceCreateDeviceRGB(),
colors : gradientColors,
locations : [0.0, 0.5, 1.0]) else
{
return
}
let rectanglePath = UIBezierPath(rect: rect)
context.saveGState()
rectanglePath.addClip()
context.drawLinearGradient(gradient,
start : CGPoint(x: 0, y: rect.height),
end : CGPoint(x: 0, y: 0),
options : CGGradientDrawingOptions())
context.restoreGState()
}
}
| 5db609f0343fa91b242ed0bce7976cb7 | 29.891892 | 108 | 0.53135 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | refs/heads/master | Frameworks/TBAData/Sources/Event/WLT.swift | mit | 1 | import Foundation
@objc(WLT)
public class WLT: NSObject, NSSecureCoding {
public static var supportsSecureCoding: Bool {
return true
}
public var wins: Int
public var losses: Int
public var ties: Int
public init(wins: Int, losses: Int, ties: Int) {
self.wins = wins
self.losses = losses
self.ties = ties
}
public required convenience init?(coder aDecoder: NSCoder) {
let wins = aDecoder.decodeInteger(forKey: "wins")
let losses = aDecoder.decodeInteger(forKey: "losses")
let ties = aDecoder.decodeInteger(forKey: "ties")
self.init(wins: wins, losses: losses, ties: ties)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(wins, forKey: "wins")
aCoder.encode(losses, forKey: "losses")
aCoder.encode(ties, forKey: "ties")
}
public var stringValue: String {
return "\(wins)-\(losses)-\(ties)"
}
public override var hash: Int {
var hasher = Hasher()
hasher.combine(wins)
hasher.combine(losses)
hasher.combine(ties)
return hasher.finalize()
}
}
@objc(WLTTransformer)
class WLTTransformer: NSSecureUnarchiveFromDataTransformer {
override class var allowedTopLevelClasses: [AnyClass] {
return [WLT.self]
}
}
| a084efccec1074da27ff9e53b4013942 | 23.254545 | 64 | 0.628936 | false | false | false | false |
alexcurylo/ScreamingParty | refs/heads/develop | ScreamingParty/ScreamingParty/Classes/Then.swift | mit | 1 | /*
Then.swift
Source:
https://github.com/devxoul/Then v1.0.3
References:
http://khanlou.com/2016/06/configuration-in-swift/
*/
// The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// 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 protocol Then {}
extension Then where Self: Any {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
- parameter block: Closure operating on Self
- returns: Self
*/
public func then(_ block: @noescape (inout Self) -> Void) -> Self {
var copy = self
block(©)
return copy
}
}
///* 'Type of expression is ambiguous without more context' in Swift 3???
extension Then where Self: AnyObject {
/**
Makes it available to set properties with closures just after initializing.
let label = UILabel().then {
$0.textAlignment = .Center
$0.textColor = UIColor.blackColor()
$0.text = "Hello, World!"
}
- parameter block: Closure operating on Self
- returns: Self
*/
public func then(_ block: @noescape (Self) -> Void) -> Self {
block(self)
return self
}
}
//*/
extension NSObject: Then {}
| 119c0f921bf50bd1a2b8668041c309ed | 29.567901 | 81 | 0.664782 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/CougarCash/model/CougarCashPayment.swift | apache-2.0 | 2 | //
// CougarCashPayment.swift
// byuSuite
//
// Created by Erik Brady on 9/12/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
private let HEADER_FONT_SIZE: CGFloat = 17
private let BODY_FONT_SIZE: CGFloat = 14
private let LINE_HEIGHT_MULTIPLE: CGFloat = 1.25
class CougarCashPayment {
var invoiceId: String
var legaleseHeader: String?
var legaleseBody: String?
var legaleseAgreement: String?
var legaleseNotes: String?
var legaleseFees: Double
init(dict: [String: Any]) throws {
guard let tempId = (dict["invoice_id"] as? Int)?.toString() else {
throw InvalidModelError()
}
invoiceId = tempId
legaleseHeader = dict[keyPath: "legalees.header"] as? String
legaleseBody = (dict[keyPath: "legalees.body"] as? String)?.replacingOccurrences(of: "\n", with: " ")
legaleseAgreement = dict[keyPath: "legalees.agreement"] as? String
legaleseNotes = dict[keyPath: "legalees.notes"] as? String
legaleseFees = dict[keyPath: "legalees.fees"] as? Double ?? 0
}
func getFormattedLegaleesText() -> NSAttributedString? {
var string = ""
if let header = legaleseHeader {
string.append(contentsOf: "<center><h2>\(header)</h2></center>")
}
if let body = legaleseBody {
string.append(contentsOf: "<p>\(body)</p>")
}
if let notes = legaleseNotes, notes != "" {
string.append(contentsOf: "<p><b>Notes: </b></p><p>\(notes)</p>")
}
if let agreement = legaleseAgreement, agreement != "" {
string.append(contentsOf: "<p><b>\(agreement)</b></p>")
}
return try? NSAttributedString(html: string)
}
}
| a43f646cbc9b6e67ad4c95739e2ba7f2 | 29.25 | 103 | 0.684043 | false | false | false | false |
danielpi/Swift-Playgrounds | refs/heads/master | Swift-Playgrounds/Swift Stanard Library/Undocumented.playground/section-1.swift | mit | 2 | // http://practicalswift.com/2014/06/14/the-swift-standard-library-list-of-built-in-functions/
import Cocoa
abs(-1)
abs(42)
var languages = ["Swift", "Objective-C"]
contains(languages, "Swift")
contains(languages, "Java")
contains([29, 85, 42, 96, 75], 42)
var oldLanguagees = dropFirst(languages)
languages
languages = ["Swift", "Objective-C"]
var newLanguages = dropLast(languages)
languages
languages = ["Swift", "Objective-C"]
dump(languages)
equal(languages, ["Swift", "Objective-C"])
for i in filter(1...100, { $0 % 10 == 0 }) {
println(i)
}
find(languages, "Swift")
indices([29, 85, 42])
join(":", ["A", "B", "C"])
map(1...3, { $0 * 5 })
for i in map(1...10, { $0 * 10 }) {
println(i)
assert(contains([10, 20, 30, 40, 50, 60, 70, 80, 90, 100],i))
}
max(1, 3, 8, 2)
maxElement(1...10)
maxElement(languages)
minElement(1...10)
minElement(languages)
let reducedLanguages = reduce(languages, "", { $0 + $1 })
reducedLanguages
let reducedArray = reduce([10, 20, 5], 1, { $0 * $1 })
reducedArray
reverse([1,2,3])
startsWith("foobar", "foo")
startsWith(10..<100, 10..<15)
startsWith(languages, ["Swift"])
/*
abs(...)
advance(...)
alignof(...)
alignofValue(...)
assert(...)
bridgeFromObjectiveC(...)
bridgeFromObjectiveCUnconditional(...)
bridgeToObjectiveC(...)
bridgeToObjectiveCUnconditional(...)
c_malloc_size(...)
c_memcpy(...)
c_putchar(...)
contains(...)
count(...)
countElements(...)
countLeadingZeros(...)
debugPrint(...)
debugPrintln(...)
distance(...)
dropFirst(...)
dropLast(...)
dump(...)
encodeBitsAsWords(...)
enumerate(...)
equal(...)
filter(...)
find(...)
getBridgedObjectiveCType(...)
getVaList(...)
indices(...)
insertionSort(...)
isBridgedToObjectiveC(...)
isBridgedVerbatimToObjectiveC(...)
isUniquelyReferenced(...)
join(...)
lexicographicalCompare(...)
map(...)
max(...)
maxElement(...)
min(...)
minElement(...)
numericCast(...)
partition(...)
posix_read(...)
posix_write(...)
print(...)
println(...)
quickSort(...)
reduce(...)
reflect(...)
reinterpretCast(...)
reverse(...)
roundUpToAlignment(...)
sizeof(...)
sizeofValue(...)
sort(...)
split(...)
startsWith(...)
strideof(...)
strideofValue(...)
swap(...)
swift_MagicMirrorData_summaryImpl(...)
swift_bufferAllocate(...)
swift_keepAlive(...)
toString(...)
transcode(...)
underestimateCount(...)
unsafeReflect(...)
withExtendedLifetime(...)
withObjectAtPlusZero(...)
withUnsafePointer(...)
withUnsafePointerToObject(...)
withUnsafePointers(...)
withVaList(...)
*/
| b195612d0405d2b67c072344f84286ad | 16.429577 | 94 | 0.645657 | false | false | false | false |
railsware/Sleipnir | refs/heads/master | Sleipnir/Sleipnir/Matchers/ShouldSyntax.swift | mit | 1 | //
// ShouldSyntax.swift
// Sleipnir
//
// Created by Artur Termenji on 7/15/14.
// Copyright (c) 2014 railsware. All rights reserved.
//
import Foundation
public extension NSObject {
var should: NSObjectMatch { return match(true) }
var shouldNot: NSObjectMatch { return match(false) }
private func match(positive: Bool) -> NSObjectMatch {
if self is NSSet {
return SleipnirContainerMatch<NSSet>(value: self, positive: positive)
} else if self is NSArray {
return SleipnirOrderedContainerMatch<NSArray>(value: self, positive: positive)
} else {
return NSObjectMatch(value: self, positive: positive)
}
}
}
extension Array {
var should: ArrayMatch<Element, NSArray> { return ArrayMatch(value: self, positive: true) }
var shouldNot: ArrayMatch<Element, NSArray> { return ArrayMatch(value: self, positive: false) }
}
public extension String {
var should: StringMatch { return StringMatch(value: self, positive: true) }
var shouldNot: StringMatch { return StringMatch(value: self, positive: false) }
}
extension Optional {
var should: OptionalMatch { return OptionalMatch(value: self, positive: true) }
var shouldNot: OptionalMatch { return OptionalMatch(value: self, positive: false) }
}
public extension Int {
var should: IntMatch { return IntMatch(value: self, positive: true) }
var shouldNot: IntMatch { return IntMatch(value: self, positive: false) }
}
public extension Double {
var should: DoubleMatch { return DoubleMatch(value: self, positive: true) }
var shouldNot: DoubleMatch { return DoubleMatch(value: self, positive: false) }
}
public extension Float {
var should: FloatMatch { return FloatMatch(value: self, positive: true) }
var shouldNot: FloatMatch { return FloatMatch(value: self, positive: false) }
}
public extension Bool {
var should: BoolMatch { return BoolMatch(value: self, positive: true) }
var shouldNot: BoolMatch { return BoolMatch(value: self, positive: false) }
}
public class StringMatch {
var value: String
var positive: Bool
init(value: String, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: String, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
// public func contain(item: String, file: String = __FILE__, line: Int = __LINE__) {
// let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
// if positive {
// actualValue.to(Contain(stringItem: item))
// } else {
// actualValue.toNot(Contain(stringItem: item))
// }
// }
//
// public func beginWith(item: String, file: String = __FILE__, line: Int = __LINE__) {
// let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
// if positive {
// actualValue.to(BeginWith(stringItem: item))
// } else {
// actualValue.toNot(BeginWith(stringItem: item))
// }
// }
//
// public func endWith(item: String, file: String = __FILE__, line: Int = __LINE__) {
// let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
// if positive {
// actualValue.to(EndWith(stringItem: item))
// } else {
// actualValue.toNot(EndWith(stringItem: item))
// }
// }
//
// public func beEmpty(file: String = __FILE__, line: Int = __LINE__) {
// let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
// if positive {
// actualValue.to(BeEmpty())
// } else {
// actualValue.toNot(BeEmpty())
// }
// }
}
public class OptionalMatch {
var value: Any?
var positive: Bool
init(value: Any?, positive: Bool) {
self.value = value
self.positive = positive
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue<Any>(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
}
public class IntMatch {
var value: Int
var positive: Bool
init(value: Int, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: Int, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beGreaterThan(expected: Int, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThan(expected: expected))
} else {
actualValue.toNot(BeGreaterThan(expected: expected))
}
}
public func beGreaterThanOrEqualTo(expected: Int, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeGreaterThanOrEqualTo(expected: expected))
}
}
public func beLessThan(expected: Int, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThan(expected: expected))
} else {
actualValue.toNot(BeLessThan(expected: expected))
}
}
public func beLessThanOrEqualTo(expected: Int, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeLessThanOrEqualTo(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
public func beTrue(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeTrue())
} else {
actualValue.toNot(BeTrue())
}
}
public func beFalse(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeFalse())
} else {
actualValue.toNot(BeFalse())
}
}
}
public class DoubleMatch {
var value: Double
var positive: Bool
init(value: Double, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: Double, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beGreaterThan(expected: Double, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThan(expected: expected))
} else {
actualValue.toNot(BeGreaterThan(expected: expected))
}
}
public func beGreaterThanOrEqualTo(expected: Double, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeGreaterThanOrEqualTo(expected: expected))
}
}
public func beLessThan(expected: Double, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThan(expected: expected))
} else {
actualValue.toNot(BeLessThan(expected: expected))
}
}
public func beLessThanOrEqualTo(expected: Double, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeLessThanOrEqualTo(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
public func beTrue(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeTrue())
} else {
actualValue.toNot(BeTrue())
}
}
public func beFalse(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeFalse())
} else {
actualValue.toNot(BeFalse())
}
}
}
public class FloatMatch {
var value: Float
var positive: Bool
init(value: Float, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: Float, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beGreaterThan(expected: Float, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThan(expected: expected))
} else {
actualValue.toNot(BeGreaterThan(expected: expected))
}
}
public func beGreaterThanOrEqualTo(expected: Float, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeGreaterThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeGreaterThanOrEqualTo(expected: expected))
}
}
public func beLessThan(expected: Float, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThan(expected: expected))
} else {
actualValue.toNot(BeLessThan(expected: expected))
}
}
public func beLessThanOrEqualTo(expected: Float, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeLessThanOrEqualTo(expected: expected))
} else {
actualValue.toNot(BeLessThanOrEqualTo(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
public func beTrue(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeTrue())
} else {
actualValue.toNot(BeTrue())
}
}
public func beFalse(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeFalse())
} else {
actualValue.toNot(BeFalse())
}
}
}
public class BoolMatch {
var value: Bool
var positive: Bool
init(value: Bool, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: Bool, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
public func beTrue(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeTrue())
} else {
actualValue.toNot(BeTrue())
}
}
public func beFalse(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeFalse())
} else {
actualValue.toNot(BeFalse())
}
}
}
public class ArrayMatch<T, S: SleipnirOrderedContainer> {
var value: Array<T>
var positive: Bool
init(value: Array<T>, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: Array<T>, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func contain(item: AnyObject, file: String = #file, line: Int = #line) {
let nsValue : NSArray = value._bridgeToObjectiveC()
let actualValue = ActualValue(value: nsValue as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSContain(item: item))
} else {
actualValue.toNot(NSContain(item: item))
}
}
public func beginWith(item: AnyObject, file: String = #file, line: Int = #line) {
let nsValue : NSArray = value._bridgeToObjectiveC()
let actualValue = ActualValue(value: nsValue as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSBeginWith(item: item))
} else {
actualValue.toNot(NSBeginWith(item: item))
}
}
public func endWith(item: AnyObject, file: String = #file, line: Int = #line) {
let nsValue : NSArray = value._bridgeToObjectiveC()
let actualValue = ActualValue(value: nsValue as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSEndWith(item: item))
} else {
actualValue.toNot(NSEndWith(item: item))
}
}
public func beEmpty(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeEmpty())
} else {
actualValue.toNot(BeEmpty())
}
}
}
public class NSObjectMatch {
var value: NSObjectProtocol
var positive: Bool
init(value: NSObjectProtocol, positive: Bool) {
self.value = value
self.positive = positive
}
public func equal(expected: NSObject, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? NSObject, fileName: file, lineNumber: line)
if positive {
actualValue.to(Equal(expected: expected))
} else {
actualValue.toNot(Equal(expected: expected))
}
}
public func beNil(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeNil())
} else {
actualValue.toNot(BeNil())
}
}
public func beTrue(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeTrue())
} else {
actualValue.toNot(BeTrue())
}
}
public func beFalse(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeFalse())
} else {
actualValue.toNot(BeFalse())
}
}
public func contain(item: AnyObject, file: String = #file, line: Int = #line) {
fail("Not implemented!", file: file, line: line)
}
public func beginWith(item: AnyObject, file: String = #file, line: Int = #line) {
fail("Not implemented!", file: file, line: line)
}
public func endWith(item: AnyObject, file: String = #file, line: Int = #line) {
fail("Not implemented!", file: file, line: line)
}
public func beEmpty(file: String = #file, line: Int = #line) {
fail("Not implemented!", file: file, line: line)
}
}
public class SleipnirContainerMatch<S: SleipnirContainer> : NSObjectMatch {
init(value: NSObject, positive: Bool) {
super.init(value: value, positive: positive)
}
override public func contain(item: AnyObject, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSContain(item: item))
} else {
actualValue.toNot(NSContain(item: item))
}
}
override public func beEmpty(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeEmpty())
} else {
actualValue.toNot(BeEmpty())
}
}
}
public class SleipnirOrderedContainerMatch<S: SleipnirOrderedContainer> : NSObjectMatch {
init(value: NSObject, positive: Bool) {
super.init(value: value, positive: positive)
}
override public func contain(item: AnyObject, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSContain(item: item))
} else {
actualValue.toNot(NSContain(item: item))
}
}
override public func beginWith(item: AnyObject, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSBeginWith(item: item))
} else {
actualValue.toNot(NSBeginWith(item: item))
}
}
override public func endWith(item: AnyObject, file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(NSEndWith(item: item))
} else {
actualValue.toNot(NSEndWith(item: item))
}
}
override public func beEmpty(file: String = #file, line: Int = #line) {
let actualValue = ActualValue(value: value as? S, fileName: file, lineNumber: line)
if positive {
actualValue.to(BeEmpty())
} else {
actualValue.toNot(BeEmpty())
}
}
} | 62383b4a1e0c1f22c377f40f663b881e | 31.808282 | 99 | 0.590323 | false | false | false | false |
eure/SpringFlowLayoutExample | refs/heads/master | SpringFlowLayoutExample/ViewController.swift | mit | 1 | // ViewController.swift
//
// Copyright (c) 2015 Shunki Tan
//
// 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
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
private let springFlowLayout: SpringFlowLayout = {
let flowLayout = SpringFlowLayout()
flowLayout.scrollDirection = .Vertical
return flowLayout
}()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.backgroundColor = ViewController.grayColor
self.collectionView.dataSource = self
self.collectionView.collectionViewLayout = self.springFlowLayout
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.springFlowLayout.itemSize = CGSize(width: self.collectionView.bounds.size.width, height: ViewController.cellHeight)
}
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 30
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ViewController.cellIdentifier, forIndexPath: indexPath)
cell.contentView.backgroundColor = ViewController.darkBlueColor
return cell
}
private static let grayColor = UIColor(red: 0.91, green: 0.91, blue: 0.91, alpha: 1)
private static let darkBlueColor = UIColor(red: 0.14, green: 0.18, blue: 0.22, alpha: 1)
private static let cellIdentifier = "Cell"
private static let cellHeight: CGFloat = 44
}
| dcf277f8ea8a48c270e5710750389be7 | 39.310811 | 130 | 0.725444 | false | false | false | false |
antrix1989/ANPlayerController | refs/heads/master | ANPlayerController/Classes/ANPlayerController.swift | mit | 1 | //
// ANPlayerController.swift
// Pods
//
// Created by Sergey Demchenko on 6/14/16.
//
//
import UIKit
import AVFoundation
import SnapKit
open class ANPlayerController: NSObject, UIGestureRecognizerDelegate, ANMediaPlayback
{
open var playable: ANPlayable?
/// The player view.
open lazy var view: UIView = ({
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 160))
view.backgroundColor = UIColor.black
if let activityIndicatorView = self.activityIndicatorView {
activityIndicatorView.hidesWhenStopped = true
view.addSubview(activityIndicatorView)
activityIndicatorView.snp_makeConstraints { (make) -> Void in
make.center.equalTo(view.snp_center)
}
}
view.addObserver(self, forKeyPath: "bounds", options: [], context: &self.playerKVOContext)
return view
})()
/// A view that confiorms to the <code>ANPlayerControls</code> protocol.
open var controlsView: ANPlayerControlsView?
/// Hide controls after interval.
open var hidingControlsInterval: TimeInterval = 3
/// Video loading indciator view.
open var activityIndicatorView: UIActivityIndicatorView?
open var onPlayableDidFinishPlayingBlock : ((ANPlayable?) -> Void) = { (playable) -> Void in }
open var onViewTappedBlock : (() -> Void) = { () -> Void in }
open var onReadyToPlayBlock : (() -> Void) = { () -> Void in }
open var volume: Float {
get { return player?.volume ?? 0 }
set { player?.volume = newValue }
}
open var isFullScreen = false
open var isPlaying: Bool = false { willSet { self.willChangeValue(forKey: "isPlaying") } didSet { self.didChangeValue(forKey: "isPlaying") } }
var player: AVPlayer?
var playerLayer: AVPlayerLayer?
var hideControlsTimer: Timer?
var restoreAfterScrubbingRate: Float = 0
var playbackTimeObserver: AnyObject?
var tapRecognizer: UITapGestureRecognizer?
var fullScreenViewController: ANFullScreenViewController?
fileprivate var playerKVOContext = 0
public override init()
{
super.init()
}
deinit
{
view.removeObserver(self, forKeyPath: "bounds")
removePlayer()
}
// MARK: - Public
open func mute(_ mute: Bool)
{
player?.volume = mute ? 0 : 1
}
open func prepare()
{
removePlayer()
resetControlsView()
mute(false)
if let videoUrl = playable?.videoUrl {
createPlayer(videoUrl as URL)
}
if let controlsView = controlsView {
controlsView.frame = view.bounds
view.addSubview(controlsView)
controlsView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_top)
make.bottom.equalTo(view.snp_bottom)
make.left.equalTo(view.snp_left)
make.right.equalTo(view.snp_right)
}
controlsView.state = .pause
controlsView.isHidden = true
controlsView.playButton?.addTarget(self, action: #selector(onPlayButtonTapped(_:)), for: .touchUpInside)
controlsView.pauseButton?.addTarget(self, action: #selector(onPauseButtonTapped(_:)), for: .touchUpInside)
controlsView.seekSlider?.addTarget(self, action: #selector(onScrub(_:)), for: .valueChanged)
controlsView.seekSlider?.addTarget(self, action: #selector(onBeginScrubbing(_:)), for: .touchDown)
controlsView.seekSlider?.addTarget(self, action: #selector(onEndScrubbing(_:)), for: .touchUpInside)
controlsView.seekSlider?.addTarget(self, action: #selector(onEndScrubbing(_:)), for: .touchUpOutside)
}
addTapGestureRecognizer()
}
open func setFullscreen(_ fullscreen: Bool, animated: Bool)
{
func closeFullScreenController()
{
stop()
fullScreenViewController?.dismiss(animated: true, completion: { self.isFullScreen = false; })
}
if fullscreen {
view.removeFromSuperview()
fullScreenViewController = ANFullScreenViewController()
fullScreenViewController!.player = self
let _ = fullScreenViewController!.view // Load view.
fullScreenViewController!.fullScreenView.playerContainerView.addSubview(view)
view.snp_makeConstraints { (make) in
make.top.equalTo(self.fullScreenViewController!.fullScreenView.playerContainerView.snp_top)
make.bottom.equalTo(self.fullScreenViewController!.fullScreenView.playerContainerView.snp_bottom)
make.left.equalTo(self.fullScreenViewController!.fullScreenView.playerContainerView.snp_left)
make.right.equalTo(self.fullScreenViewController!.fullScreenView.playerContainerView.snp_right)
}
fullScreenViewController!.onCloseButtonTapped = { () -> Void in
closeFullScreenController()
}
isFullScreen = true
UIApplication.shared.keyWindow?.rootViewController?.present(fullScreenViewController!, animated: animated, completion: nil)
} else {
closeFullScreenController()
}
}
// MARK: - ANMediaPlayback
open func play()
{
controlsView?.state = .play
activityIndicatorView?.startAnimating()
addPlaybackTimeObserver()
player?.play()
isPlaying = true
}
open func pause()
{
stopHideControllsTimer()
controlsView?.state = .pause
controlsView?.isHidden = false
player?.pause()
isPlaying = false
}
open func stop()
{
player?.pause()
seekToTime(0)
resetControlsView()
isPlaying = false
}
open func seekToTime(_ time: TimeInterval)
{
player?.seek(to: CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)))
}
// MARK: - KVO
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
{
if context != &playerKVOContext {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
return
}
if let player = object as? AVPlayer , player == self.player && keyPath == "status" {
activityIndicatorView?.stopAnimating()
if player.status == .failed {
debugPrint(player.error)
} else if player.status == .readyToPlay {
onReadyToPlayBlock()
}
updateControlsView()
} else if keyPath == "bounds" {
playerLayer?.frame = view.bounds
}
}
// MARK: - Protected
func onItemDidFinishPlayingNotification(_ notification: Notification)
{
player?.currentItem?.seek(to: kCMTimeZero)
player?.play()
}
func createPlayer(_ contentVideoUrl: URL)
{
let playerItem = AVPlayerItem(url: contentVideoUrl)
NotificationCenter.default.addObserver(self, selector: #selector(onItemDidFinishPlayingNotification(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
player = AVPlayer(playerItem: playerItem)
player!.addObserver(self, forKeyPath: "status", options: [], context: &playerKVOContext)
playerLayer = AVPlayerLayer(player: player)
playerLayer!.videoGravity = AVLayerVideoGravityResizeAspect
playerLayer?.frame = view.bounds
view.layer.addSublayer(playerLayer!)
}
func removePlayer()
{
if let playerItem = player?.currentItem {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
}
player?.removeObserver(self, forKeyPath: "status")
player = nil
playerLayer?.removeFromSuperlayer()
playerLayer = nil
removePlaybackTimeObserver()
}
func minutes(_ totalSeconds: Double) -> Int { return Int(floor(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60)) }
func seconds(_ totalSeconds: Double) -> Int { return Int(floor(totalSeconds.truncatingRemainder(dividingBy: 3600).truncatingRemainder(dividingBy: 60))) }
func resetControlsView()
{
setCurrentTimeLabelValue(kCMTimeZero)
controlsView?.state = .pause
controlsView?.seekSlider?.minimumValue = 0
controlsView?.seekSlider?.maximumValue = 0
controlsView?.seekSlider?.value = 0
updateControlsView()
}
func updateControlsView()
{
if let duration = player?.currentItem?.asset.duration {
let durationTotalSeconds = CMTimeGetSeconds(duration)
controlsView?.totalTimeLabel?.text = String(format: "%02lu:%02lu", minutes(durationTotalSeconds), seconds(durationTotalSeconds))
controlsView?.seekSlider?.maximumValue = Float(durationTotalSeconds)
}
}
func stopHideControllsTimer()
{
hideControlsTimer?.invalidate()
hideControlsTimer = nil
}
func removePlaybackTimeObserver()
{
if let playbackTimeObserver = playbackTimeObserver {
player?.removeTimeObserver(playbackTimeObserver)
self.playbackTimeObserver = nil
}
}
func setCurrentTimeLabelValue(_ time: CMTime)
{
let currentTimeTotalSeconds = CMTimeGetSeconds(time)
controlsView?.currentTimeLabel?.text = String(format: "%02lu:%02lu", minutes(currentTimeTotalSeconds), seconds(currentTimeTotalSeconds))
}
func addPlaybackTimeObserver()
{
if let _ = playbackTimeObserver { return }
let interval = CMTimeMakeWithSeconds(1.0, Int32(NSEC_PER_SEC)) // 1 second
playbackTimeObserver = player?.addPeriodicTimeObserver(forInterval: interval, queue: nil, using: { [weak self] (time) in
if let rate = self?.player?.rate , rate == 0 { return }
self?.setCurrentTimeLabelValue(time)
let currentTimeTotalSeconds = CMTimeGetSeconds(time)
self?.controlsView?.seekSlider?.value = Float(currentTimeTotalSeconds)
}) as AnyObject?
}
func hideControlsView(_ hide: Bool, afterInterval interval: TimeInterval)
{
hideControlsTimer = Timer.schedule(delay: interval) { [weak self] (timer) in
self?.controlsView?.isHidden = hide
self?.hideControlsTimer?.invalidate()
self?.hideControlsTimer = nil
}
}
// MARK: - UITapGestureRecognizer
func removeTapGestureRecognizer()
{
if let tapRecognizer = self.tapRecognizer {
view.removeGestureRecognizer(tapRecognizer)
self.tapRecognizer = nil
}
}
func addTapGestureRecognizer()
{
removeTapGestureRecognizer()
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTapGesture(_:)))
tapRecognizer?.cancelsTouchesInView = false
tapRecognizer?.delegate = self
view.addGestureRecognizer(tapRecognizer!)
}
func onTapGesture(_ recognizer: UITapGestureRecognizer)
{
onViewTappedBlock()
controlsView?.isHidden = false
stopHideControllsTimer()
if let controlsView = controlsView , hideControlsTimer == nil && !controlsView.isHidden {
hideControlsView(true, afterInterval: hidingControlsInterval)
}
}
// MARK: - UIGestureRecognizerDelegate
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool
{
return view == touch.view
}
// MARK: - IBAction
@IBAction func onPlayButtonTapped(_ sender: AnyObject)
{
play()
}
@IBAction func onPauseButtonTapped(_ sender: AnyObject)
{
pause()
}
/// User is dragging the movie controller thumb to scrub through the movie.
@IBAction func onBeginScrubbing(_ slider: UISlider)
{
stopHideControllsTimer()
if let player = player {
restoreAfterScrubbingRate = player.rate
player.rate = 0
}
removePlaybackTimeObserver()
}
@IBAction func onScrub(_ slider: UISlider)
{
if let playerDuration = player?.currentItem?.asset.duration , CMTIME_IS_INVALID(playerDuration) { return }
if let timeScale = player?.currentItem?.asset.duration.timescale {
let time = CMTimeMakeWithSeconds(Float64(slider.value), timeScale)
player?.seek(to: time)
setCurrentTimeLabelValue(time)
}
}
@IBAction func onEndScrubbing(_ slider: UISlider)
{
if restoreAfterScrubbingRate != 0 {
player?.rate = restoreAfterScrubbingRate
restoreAfterScrubbingRate = 0
}
addPlaybackTimeObserver()
hideControlsView(true, afterInterval: hidingControlsInterval)
}
}
| c6e220fffc6c38632997b87dddd8ed28 | 32.459259 | 189 | 0.618405 | false | false | false | false |
hsavit1/LeetCode-Solutions-in-Swift | refs/heads/master | Solutions/Solutions/Medium/Medium_024_Swap_Nodes_In_Pairs.swift | mit | 4 | /*
https://leetcode.com/problems/swap-nodes-in-pairs/
#24 Swap Nodes in Pairs
Level: medium
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Inspired by @mike3 at https://leetcode.com/discuss/3608/seeking-for-a-better-solution
*/
import Foundation
class Medium_024_Swap_Nodes_In_Pairs {
class Node {
var value: Int
var next: Node?
init(value: Int, next: Node?) {
self.value = value
self.next = next
}
}
class func swap(next1 next1: Node, next2: Node) -> Node {
next1.next = next2.next
next2.next = next1
return next2
}
class func swapPairs(head: Node?) -> Node? {
let dummy: Node = Node(value: 0, next: nil)
dummy.next = head
for var curr: Node? = dummy; curr?.next != nil && curr?.next?.next != nil; curr = curr?.next?.next {
curr?.next = swap(next1: curr!.next!, next2: curr!.next!.next!)
}
return dummy.next
}
} | 669bad1a556c062e3c651fb81ea5bdbc | 26.318182 | 123 | 0.613655 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Geometry/Buffer/BufferOptionsViewController.swift | apache-2.0 | 1 | // Copyright 2018 Esri.
//
// 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
protocol BufferOptionsViewControllerDelegate: AnyObject {
func bufferOptionsViewController(_ bufferOptionsViewController: BufferOptionsViewController, bufferDistanceChangedTo bufferDistance: Measurement<UnitLength>)
}
class BufferOptionsViewController: UITableViewController {
@IBOutlet private weak var distanceSlider: UISlider?
@IBOutlet private weak var distanceLabel: UILabel?
weak var delegate: BufferOptionsViewControllerDelegate?
private let measurementFormatter: MeasurementFormatter = {
// use a measurement formatter so the value is automatically localized
let formatter = MeasurementFormatter()
// don't show decimal places
formatter.numberFormatter.maximumFractionDigits = 0
return formatter
}()
var bufferDistance = Measurement(value: 0, unit: UnitLength.miles) {
didSet {
updateUIForBufferRadius()
}
}
override func viewDidLoad() {
super.viewDidLoad()
updateUIForBufferRadius()
}
private func updateUIForBufferRadius() {
// update the slider and label to match the buffer distance
distanceSlider?.value = Float(bufferDistance.value)
distanceLabel?.text = measurementFormatter.string(from: bufferDistance)
}
@IBAction func bufferSliderAction(_ sender: UISlider) {
// update the buffer distance for the slider value
bufferDistance.value = Double(sender.value)
// notify the delegate with the new value
delegate?.bufferOptionsViewController(self, bufferDistanceChangedTo: bufferDistance)
}
}
| 933b41a5d6dc4ca445af91bf54ebb4a2 | 37.293103 | 161 | 0.723548 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/API/Requests/Message/ReadReceiptsRequest.swift | mit | 1 | //
// ReadReceiptsRequest.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 6/12/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import SwiftyJSON
import Foundation
final class ReadReceiptsRequest: APIRequest {
typealias APIResourceType = ReadReceiptsResource
let requiredVersion = Version(0, 63, 0)
var path: String = "/api/v1/chat.getMessageReadReceipts"
var query: String? {
return "messageId=\(messageId)"
}
let messageId: String
init(messageId: String) {
self.messageId = messageId
}
}
class ReadReceiptsResource: APIResource {
var users: [UnmanagedUser] {
return raw?["receipts"].arrayValue.map { $0["user"] }.compactMap {
let user = User()
user.map($0, realm: nil)
return user.unmanaged
} ?? []
}
}
| 9a5562fb30c4719e24ef852178b51a8c | 21.263158 | 74 | 0.634752 | false | false | false | false |
alex-alex/ASAttributedLabelNode | refs/heads/master | ASAttributedLabelNode-Demo/ASAttributedLabelNode-Demo/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// ASAttributedLabelNode-Demo
//
// Created by Alex Studnicka on 17/08/14.
// Copyright (c) 2014 astudnicka. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
/* Pick a size for the scene */
let scene = GameScene(size: self.view.frame.size)
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.presentScene(scene)
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return UIInterfaceOrientationMask.allButUpsideDown
} else {
return UIInterfaceOrientationMask.all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden : Bool {
return true
}
}
| a71367fca650e5f5d0465efb999482cf | 24.361702 | 78 | 0.650168 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Elements/TextField/TextFieldElement+IBAN.swift | mit | 1 | //
// TextFieldElement+IBAN.swift
// StripePaymentSheet
//
// Created by Yuki Tokuhiro on 5/23/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
@_spi(STP) import StripeUICore
@_spi(STP) import StripeCore
extension TextFieldElement {
static func makeIBAN(theme: ElementsUITheme = .default) -> TextFieldElement {
return TextFieldElement(configuration: IBANConfiguration(), theme: theme)
}
// MARK: - IBANError
enum IBANError: TextFieldValidationError, Equatable {
case incomplete
case shouldStartWithCountryCode
case invalidCountryCode(countryCode: String)
/// A catch-all for things like incorrect length, invalid characters, bad checksum.
case invalidFormat
var localizedDescription: String {
switch self {
case .incomplete:
return STPLocalizedString("The IBAN you entered is incomplete.", "An error message.")
case .shouldStartWithCountryCode:
return STPLocalizedString("Your IBAN should start with a two-letter country code.", "An error message.")
case .invalidCountryCode(let countryCode):
let localized = STPLocalizedString("The IBAN you entered is invalid, \"%@\" is not a supported country code.", "An error message.")
return String(format: localized, countryCode)
case .invalidFormat:
return NSError.stp_invalidBankAccountIban
}
}
func shouldDisplay(isUserEditing: Bool) -> Bool {
switch self {
case .incomplete, .invalidFormat:
return !isUserEditing
case .shouldStartWithCountryCode, .invalidCountryCode:
return true
}
}
}
// MARK: IBANConfiguration
/**
A text field configuration for an IBAN, or International Bank Account Number, as defined in ISO 13616-1.
- Seealso: https://en.wikipedia.org/wiki/International_Bank_Account_Number
*/
struct IBANConfiguration: TextFieldElementConfiguration {
let label: String = STPLocalizedString("IBAN", "Label for an IBAN field")
func maxLength(for text: String) -> Int {
return 34
}
/// Ensure it's at least the minimum size assumed by the algorith. Note: ideally, this length depends on the country.
let minLength: Int = 8
let disallowedCharacters: CharacterSet = CharacterSet.stp_asciiLetters
.union(CharacterSet.stp_asciiDigit)
.inverted
func makeDisplayText(for text: String) -> NSAttributedString {
let firstTwoCapitalized = text.prefix(2).uppercased() + text.dropFirst(2)
let attributed = NSMutableAttributedString(string: firstTwoCapitalized, attributes: [.kern: 0])
// Put a space between every 4th character
for i in stride(from: 3, to: attributed.length, by: 4) {
attributed.addAttribute(.kern, value: 5, range: NSRange(location: i, length: 1))
}
return attributed
}
/**
The IBAN structure is defined in ISO 13616-1 and consists of a two-letter ISO 3166-1 country code,
followed by two check digits and up to thirty alphanumeric characters for a BBAN (Basic Bank Account Number)
which has a fixed length per country and, included within it, a bank identifier with a fixed position and a fixed length per country.
The check digits are calculated based on the scheme defined in ISO/IEC 7064 (MOD97-10).
We perform the algorithm as described in https://en.wikipedia.org/wiki/International_Bank_Account_Number#Validating_the_IBAN
*/
func validate(text: String, isOptional: Bool) -> ValidationState {
let iBAN = text.uppercased()
guard !iBAN.isEmpty else {
return isOptional ? .valid : .invalid(Error.empty)
}
// Validate starts with a two-letter country code
let countryValidationResult = Self.validateCountryCode(iBAN)
guard case .valid = countryValidationResult else {
return countryValidationResult
}
// Validate that the total IBAN length is correct
guard iBAN.count > minLength else {
return .invalid(IBANError.incomplete)
}
// Validate it's up to 34 alphanumeric characters long
guard
iBAN.count <= maxLength(for: text),
iBAN.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber)}) else {
return .invalid(IBANError.invalidFormat)
}
// Move the four initial characters to the end of the string
// e.g. "GB1234" -> "34GB12"
let reorderedIBAN = iBAN.dropFirst(4) + iBAN.prefix(4)
// Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35
// e.g., "GB82" -> "161182"
let oneBigNumber = Self.transformToASCIIDigits(String(reorderedIBAN))
// Interpret the string as a decimal integer and compute the remainder of that number on division by 97
// If the IBAN is valid, the remainder equals 1.
// e.g., "00001011" -> Int(1011)
guard Self.mod97(oneBigNumber) == 1 else {
return .invalid(IBANError.invalidFormat)
}
return .valid
}
// MARK: - Helper methods
/// Validates that the iBAN begins with a two-letter country code
static func validateCountryCode(_ iBAN: String) -> ValidationState {
let countryCode = String(iBAN.prefix(2))
guard countryCode.allSatisfy({ $0.isASCII && $0.isLetter }) else {
// The user put in numbers or something weird; let them know the iban should start with a country code
return .invalid(IBANError.shouldStartWithCountryCode)
}
guard countryCode.count == 2 else {
return .invalid(IBANError.incomplete)
}
// Validate that the country code exists
guard NSLocale.isoCountryCodes.contains(countryCode) else {
return .invalid(IBANError.invalidCountryCode(countryCode: countryCode))
}
return .valid
}
/// Interprets `bigNumber` as a decimal integer and compute the remainder of that number on division by 97
/// - Note: Does not handle empty strings
static func mod97(_ bigNumber: String) -> Int? {
return bigNumber.reduce(0) { (previousMod, char) in
guard let previousMod = previousMod,
let value = Int(String(char)) else {
return nil
}
let factor = value < 10 ? 10 : 100
return (factor * previousMod + value) % 97
}
}
/// Replaces each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35
/// e.g., "GB82" -> "161182"
/// - Note: Assumes the string is alphanumeric
static func transformToASCIIDigits(_ string: String) -> String {
return string.reduce("") { result, character in
if character.isLetter {
guard let asciiValue = character.asciiValue else {
return ""
}
let digit = Int(asciiValue) - asciiValueOfA + 10
return result + String(digit)
} else if character.isNumber {
return result + String(character)
} else {
return ""
}
}
}
}
}
fileprivate let asciiValueOfA: Int = Int(Character("A").asciiValue!)
| 82806e6e914aacfb2cc62dd05491464e | 43.393443 | 147 | 0.585672 | false | false | false | false |
muyang00/YEDouYuTV | refs/heads/master | YEDouYuZB/YEDouYuZB/Home/ViewModels/RecommendViewModel.swift | apache-2.0 | 1 | //
// RecommendViewModel.swift
// YEDouYuZB
//
// Created by yongen on 17/2/15.
// Copyright © 2017年 yongen. All rights reserved.
//
/*
1> 请求0/1数组,并转成模型数组
2> 对数据进行排序
3> 显示的HeaderView中的内容
*/
import UIKit
class RecommendViewModel: BaseViewModel {
//MARK:- 懒加载属性
lazy var cycleModels :[CycleModel] = [CycleModel]()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
}
//MARK:- 发送网络请求
extension RecommendViewModel {
//请求推荐数据
func requestData(_ finishCallback : @escaping() ->()){
//1. 定义参数
let parmaeters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
//2. 创建group
let dGroup = DispatchGroup()
//3. 请求第一部分推荐数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime()]){
(result) in
//1. 将result转成字典类型
guard let resultDict = result as? [String : NSObject] else {return}
//2. 根据data该key, 获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//3. 遍历字典,并且转成模型对象
//3.1 设置组的属性
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
//3.2 获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.bigDataGroup.anchors.append(anchor)
}
//3.3离开组
dGroup.leave()
}
//4. 请求第二部分颜值数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parmaeters){
(result) in
//1. 将result转成字典类型
guard let resultDict = result as? [String : NSObject] else {return}
//2. 根据data该key, 获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else {return}
//3. 遍历字典,并且转成模型对象
//3.1 设置组的属性
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
//3.2 获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
//3.3离开组
dGroup.leave()
}
//5. 请求2-12 部分游戏数据
dGroup.enter()
loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parmaeters){
dGroup.leave()
}
//6. 所有数据都请求到, 之后进行排序
dGroup.notify(queue: DispatchQueue.main){
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
// 请求无线轮播的数据
func requestCycleData(_ finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
// 1.获取整体字典数据
guard let resultDict = result as? [String : NSObject] else { return }
// 2.根据data的key获取数据
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
// 3.字典转模型对象
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}
}
| 47c8fb1bf2fc4acaf34b9802c6c620a7 | 33.102804 | 145 | 0.552754 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Authentication/SocialLogin/SocialLoginButtonFactory.swift | apache-2.0 | 1 | //
// Copyright 2020 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
@objc
enum SocialLoginButtonMode: Int {
case `continue`
case signIn
case signUp
}
/// `SocialLoginButtonFactory` builds SocialLoginButton and apply dedicated theme if needed.
class SocialLoginButtonFactory {
// MARK - Public
func build(with identityProvider: MXLoginSSOIdentityProvider, mode: SocialLoginButtonMode) -> SocialLoginButton {
let button = SocialLoginButton()
let defaultStyle: SocialLoginButtonStyle
var styles: [String: SocialLoginButtonStyle] = [:]
let buildDefaultButtonStyles: () -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) = {
let image: SourceImage?
if let imageStringURL = identityProvider.icon, let imageURL = URL(string: imageStringURL) {
image = .remote(imageURL)
} else {
image = nil
}
return self.buildDefaultButtonStyles(with: image)
}
if let idpBrandIdentifier = identityProvider.brand {
let idpBrand = MXLoginSSOIdentityProviderBrand(rawValue: idpBrandIdentifier)
switch idpBrand {
case .gitlab:
(defaultStyle, styles) = self.buildGitLabButtonStyles()
case .github:
(defaultStyle, styles) = self.buildGitHubButtonStyles()
case .apple:
(defaultStyle, styles) = self.buildAppleButtonStyles()
case .google:
(defaultStyle, styles) = self.buildGoogleButtonStyles()
case .facebook:
(defaultStyle, styles) = self.buildFacebookButtonStyles()
case .twitter:
(defaultStyle, styles) = self.buildTwitterButtonStyles()
default:
(defaultStyle, styles) = buildDefaultButtonStyles()
}
} else {
(defaultStyle, styles) = buildDefaultButtonStyles()
}
let title = self.buildButtonTitle(with: identityProvider.name, mode: mode)
let viewData = SocialLoginButtonViewData(identifier: identityProvider.identifier,
title: title,
defaultStyle: defaultStyle,
themeStyles: styles)
button.fill(with: viewData)
return button
}
// MARK - Private
private func buildButtonTitle(with providerTitle: String, mode: SocialLoginButtonMode) -> String {
let buttonTitle: String
switch mode {
case .signIn:
buttonTitle = VectorL10n.socialLoginButtonTitleSignIn(providerTitle)
case .signUp:
buttonTitle = VectorL10n.socialLoginButtonTitleSignUp(providerTitle)
case .continue:
buttonTitle = VectorL10n.socialLoginButtonTitleContinue(providerTitle)
}
return buttonTitle
}
private func buildAppleButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
var lightImage: SourceImage?
let appleLogo = Asset.Images.socialLoginButtonApple.image
if let appleLogoLightStyle = appleLogo.vc_tintedImage(usingColor: .white) {
lightImage = .local(appleLogoLightStyle)
}
let lightStyle = SocialLoginButtonStyle(logo: lightImage,
titleColor: .white,
backgroundColor: .black,
borderColor: nil)
var darkImage: SourceImage?
if let appleLogoDarkStyle = appleLogo.vc_tintedImage(usingColor: .black) {
darkImage = .local(appleLogoDarkStyle)
}
let darkStyle = SocialLoginButtonStyle(logo: darkImage,
titleColor: .black,
backgroundColor: .white,
borderColor: nil)
let defaultStyle: SocialLoginButtonStyle = lightStyle
let styles: [String: SocialLoginButtonStyle] = [
ThemeIdentifier.light.rawValue: lightStyle,
ThemeIdentifier.dark.rawValue: darkStyle,
ThemeIdentifier.black.rawValue: darkStyle
]
return (defaultStyle, styles)
}
private func buildGoogleButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
let logo = Asset.Images.socialLoginButtonGoogle.image
let lightImage: SourceImage = .local(logo)
let lightStyle = SocialLoginButtonStyle(logo: lightImage,
titleColor: UIColor(white: 0, alpha: 0.54),
backgroundColor: .white,
borderColor: .black)
var darkImage: SourceImage?
if let logoDarkStyle = logo.vc_tintedImage(usingColor: .white) {
darkImage = .local(logoDarkStyle)
}
let darkStyle = SocialLoginButtonStyle(logo: darkImage,
titleColor: .white,
backgroundColor: UIColor(rgb: 0x4285F4),
borderColor: nil)
let defaultStyle: SocialLoginButtonStyle = lightStyle
let styles: [String: SocialLoginButtonStyle] = [
ThemeIdentifier.light.rawValue: lightStyle,
ThemeIdentifier.dark.rawValue: darkStyle,
ThemeIdentifier.black.rawValue: darkStyle
]
return (defaultStyle, styles)
}
private func buildTwitterButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
let defaultStyle = SocialLoginButtonStyle(logo: .local(Asset.Images.socialLoginButtonTwitter.image),
titleColor: .white,
backgroundColor: UIColor(rgb: 0x47ACDF),
borderColor: nil)
return (defaultStyle, [:])
}
private func buildFacebookButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
let defaultStyle = SocialLoginButtonStyle(logo: .local(Asset.Images.socialLoginButtonFacebook.image),
titleColor: .white,
backgroundColor: UIColor(rgb: 0x3C5A99),
borderColor: nil)
return (defaultStyle, [:])
}
private func buildGitHubButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
var lightImage: SourceImage?
let githubLogo = Asset.Images.socialLoginButtonGithub.image
if let githubLogoLightStyle = githubLogo.vc_tintedImage(usingColor: .black) {
lightImage = .local(githubLogoLightStyle)
}
let lightStyle = SocialLoginButtonStyle(logo: lightImage,
titleColor: .black,
backgroundColor: .white,
borderColor: .black)
var darkImage: SourceImage?
if let githubLogoDarkStyle = githubLogo.vc_tintedImage(usingColor: .white) {
darkImage = .local(githubLogoDarkStyle)
}
let darkStyle = SocialLoginButtonStyle(logo: darkImage,
titleColor: .white,
backgroundColor: .black,
borderColor: .white)
let defaultStyle: SocialLoginButtonStyle = lightStyle
let styles: [String: SocialLoginButtonStyle] = [
ThemeIdentifier.light.rawValue: lightStyle,
ThemeIdentifier.dark.rawValue: darkStyle,
ThemeIdentifier.black.rawValue: darkStyle
]
return (defaultStyle, styles)
}
private func buildGitLabButtonStyles() -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
let logo: SourceImage = .local(Asset.Images.socialLoginButtonGitlab.image)
let lightStyle = SocialLoginButtonStyle(logo: logo,
titleColor: .black,
backgroundColor: .white,
borderColor: .black)
let darkStyle = SocialLoginButtonStyle(logo: logo,
titleColor: .white,
backgroundColor: .black,
borderColor: .white)
let defaultStyle: SocialLoginButtonStyle = lightStyle
let styles: [String: SocialLoginButtonStyle] = [
ThemeIdentifier.light.rawValue: lightStyle,
ThemeIdentifier.dark.rawValue: darkStyle,
ThemeIdentifier.black.rawValue: darkStyle
]
return (defaultStyle, styles)
}
private func buildDefaultButtonStyles(with image: SourceImage?) -> (SocialLoginButtonStyle, [String: SocialLoginButtonStyle]) {
let lightStyle = SocialLoginButtonStyle(logo: image,
titleColor: .black,
backgroundColor: .white,
borderColor: .black)
let darkStyle = SocialLoginButtonStyle(logo: image,
titleColor: .white,
backgroundColor: .black,
borderColor: .white)
let defaultStyle: SocialLoginButtonStyle = lightStyle
let styles: [String: SocialLoginButtonStyle] = [
ThemeIdentifier.light.rawValue: lightStyle,
ThemeIdentifier.dark.rawValue: darkStyle,
ThemeIdentifier.black.rawValue: darkStyle
]
return (defaultStyle, styles)
}
}
| 0f670d7b1e4462eaa204c8c9d5b0e291 | 40.351648 | 131 | 0.53654 | false | false | false | false |
ashfurrow/Nimble-Snapshots | refs/heads/master | Nimble_Snapshots/DynamicType/PrettyDynamicTypeSyntax.swift | mit | 1 | import Nimble
import UIKit
// MARK: - Nicer syntax using == operator
public struct DynamicTypeSnapshot {
let name: String?
let identifier: String?
let record: Bool
let sizes: [UIContentSizeCategory]
let deviceAgnostic: Bool
init(name: String?, identifier: String?, record: Bool, sizes: [UIContentSizeCategory], deviceAgnostic: Bool) {
self.name = name
self.identifier = identifier
self.record = record
self.sizes = sizes
self.deviceAgnostic = deviceAgnostic
}
}
public func dynamicTypeSnapshot(_ name: String? = nil,
identifier: String? = nil,
sizes: [UIContentSizeCategory] = allContentSizeCategories(),
deviceAgnostic: Bool = false) -> DynamicTypeSnapshot {
return DynamicTypeSnapshot(name: name,
identifier: identifier,
record: false,
sizes: sizes,
deviceAgnostic: deviceAgnostic)
}
public func recordDynamicTypeSnapshot(_ name: String? = nil,
identifier: String? = nil,
sizes: [UIContentSizeCategory] = allContentSizeCategories(),
deviceAgnostic: Bool = false) -> DynamicTypeSnapshot {
return DynamicTypeSnapshot(name: name,
identifier: identifier,
record: true,
sizes: sizes,
deviceAgnostic: deviceAgnostic)
}
public func ==<Expectation: Nimble.Expectation>(lhs: Expectation, rhs: DynamicTypeSnapshot) where Expectation.Value: Snapshotable {
if let name = rhs.name {
if rhs.record {
lhs.to(recordDynamicTypeSnapshot(named: name, sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic))
} else {
lhs.to(haveValidDynamicTypeSnapshot(named: name, sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic))
}
} else {
if rhs.record {
lhs.to(recordDynamicTypeSnapshot(sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic))
} else {
lhs.to(haveValidDynamicTypeSnapshot(sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic))
}
}
}
| 1ad077b1a164a9e8979431498aa6542c | 39.338983 | 131 | 0.571008 | false | false | false | false |
Schatzjason/cs212 | refs/heads/master | Homework-1.playground/Contents.swift | mit | 1 | /*:
## 1. Optional String
The var `s` might be a string, or it might be nil. Conditionally unwrap s using a `if let` statement. If `s` can be safely unwraped then print it using `print(s)`.
*/
let s: String?
s = generateStringOrNil()
// Your code for question 1 here.
/*:
---
## 2. Counting nils
The `generateRandomArrayOfIntsAndNils` function creates an array that is a random mix of Int values and nils.
Write code that counts the number of nil values in array1
*/
let array1: [Int?]
array1 = generateRandomArrayOfIntsAndNils()
var total: Int = 0
// Your code for question 2 here
for value: Int? in array1 {
}
/*:
---
## 3. Mean
Write code that calculates the mean value of the non nil elements in array1.
*/
let array2 = generateRandomArrayOfIntsAndNils()
/*:
---
## 4. New Array
Write code that adds values to the array named nilFree3 so that it has the same elements
as array3, except without the nil values. The elements in nilFree3 should be
Ints, not Int optionals.
*/
let array3 = generateRandomArrayOfIntsAndNils()
var nilFree3 = [Int]()
// Your code for question 4 here.
/*:
---
## 5. Sort array
Write code that will sort array4 using your own logic. You might want to
review the logic for Selection Sort or even Bubble Sort. Find a sort
algorithm that you like in a language that you are familiar with and then
translate it to Swift. Resist the temptation to find a sort online that
is already written in swift. Do not use Swift's sort method.
Note that array4 is declared with var, so that it is a mutable array.
*/
var array4 = generateRandomArrayOfIntsAndNils()
// Your code for question 5 here.
| f0cfc8af6db300130fbf2cc2c811ddec | 21.726027 | 164 | 0.723327 | false | false | false | false |
lkzhao/YetAnotherAnimationLibrary | refs/heads/master | Sources/YetAnotherAnimationLibrary/Extensions/NSObject+YAAL.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension NSObject {
internal class YaalState {
internal init() {}
internal var animations: [String: Any] = [:]
}
internal var yaalState: YaalState {
struct AssociatedKeys {
internal static var yaalState = "yaalState"
}
if let state = objc_getAssociatedObject(self, &AssociatedKeys.yaalState) as? YaalState {
return state
} else {
let state = YaalState()
objc_setAssociatedObject(self, &AssociatedKeys.yaalState, state, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return state
}
}
}
extension Yaal where Base: NSObject {
public func animationFor<Value>(key: String,
getter: @escaping () -> Value?,
setter: @escaping (Value) -> Void) -> MixAnimation<Value> {
if let anim = base.yaalState.animations[key] as? MixAnimation<Value> {
return anim
} else {
let anim = MixAnimation(getter: getter, setter: setter)
base.yaalState.animations[key] = anim
return anim
}
}
@discardableResult public func register<Value>(key: String,
getter: @escaping () -> Value?,
setter: @escaping (Value) -> Void) -> MixAnimation<Value> {
return animationFor(key: key, getter: getter, setter: setter)
}
public func animationFor<Value>(key: String) -> MixAnimation<Value>? {
return base.yaalState.animations[key] as? MixAnimation<Value>
}
public func animationForKeyPath<Value>(_ keyPath: String) -> MixAnimation<Value> {
return animationFor(key: keyPath,
getter: { [weak base] in base?.value(forKeyPath: keyPath) as? Value },
setter: { [weak base] in base?.setValue($0, forKeyPath: keyPath) })
}
}
| f300d2415094a35fa55275fad3d6d028 | 41.479452 | 112 | 0.637859 | false | false | false | false |
hakeemsyd/twitter | refs/heads/master | twitter/HomeViewController.swift | apache-2.0 | 1 | //
// HomeViewController.swift
// twitter
//
// Created by Syed Hakeem Abbas on 9/26/17.
// Copyright © 2017 codepath. All rights reserved.
//
import UIKit
import NSDateMinimalTimeAgo
enum Mode {
case PROFILE, HOME, MENTIONS, SOMEONES_PROFILE
}
enum Update {
case RESET, APPEND
}
class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let MAX_TWEETS = 5
@IBOutlet weak var tweetButton: UIBarButtonItem!
@IBOutlet weak var logoutButton: UIBarButtonItem!
var mode: Mode = Mode.PROFILE
var isMoreDataLoading = false
var refreshControl: UIRefreshControl = UIRefreshControl()
@IBOutlet weak var tableView: UITableView!
var userTweets: [Tweet] = [Tweet]()
var loadingView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
var user: User = User.currentUser!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
if( mode == Mode.PROFILE || mode == Mode.SOMEONES_PROFILE) {
setupHeader()
}
// pull to refresh
refreshControl.addTarget(self, action: #selector(onUserInitiatedRefresh(_:)), for: UIControlEvents.valueChanged)
tableView.insertSubview(refreshControl, at: 0)
//update()
//infinite scroll
// infinite scroll
let tableFooterView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
loadingView.center = tableFooterView.center
tableFooterView.addSubview(loadingView)
self.tableView.tableFooterView = tableFooterView
}
override func viewWillAppear(_ animated: Bool) {
update(mode: Update.RESET)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func onLogoutClicked(_ sender: UIBarButtonItem) {
if mode == Mode.SOMEONES_PROFILE {
//close this view
dismiss(animated: true, completion: nil)
return
}
TwitterClient.sharedInstance.logout()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userTweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if(userTweets.count - indexPath.row <= MAX_TWEETS && !self.isMoreDataLoading){
self.isMoreDataLoading = true;
loadingView.startAnimating()
update(mode: Update.APPEND)
}
let cell = tableView.dequeueReusableCell(withIdentifier: "tweetCell") as? TweetCell
let t = userTweets[indexPath.row]
cell?.tweet = t
cell?.update()
cell?.onOpenProfile = { (user: User) in
print("\(user.name ?? "")")
self.handleProfPicTap(user: user)
}
return cell!
}
func onUserInitiatedRefresh(_ refreshControl: UIRefreshControl) {
update(mode: Update.RESET)
}
private func update(mode: Update) {
var lasttweeId = -1
if userTweets.count > 0 && mode == Update.APPEND {
lasttweeId = (userTweets.last?.id)!
}
TwitterClient.sharedInstance.timeline(userId: (user.id)!, mode: self.mode, lastTweetId: lasttweeId, maxCount: MAX_TWEETS, success: { (tweets: [Tweet]) in
if mode == Update.RESET {
self.userTweets = tweets
} else if mode == Update.APPEND {
self.userTweets += tweets
}
self.tableView.reloadData()
self.refreshControl.endRefreshing()
self.isMoreDataLoading = false
self.loadingView.stopAnimating()
}) { (error: Error) in
self.refreshControl.endRefreshing()
self.loadingView.stopAnimating()
self.isMoreDataLoading = false
print(error.localizedDescription)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "viewTweetSegue") {
let destinationViewController = segue.destination as! TweetDetailViewController
let s = sender as! TweetCell
destinationViewController.tweetId = (s.tweet?.id)!
} else if (segue.identifier == "tweetSegue"){
}
}
private func setupHeader() {
let header = tableView.dequeueReusableCell(withIdentifier: "profileHeader") as! ProfileHeader
header.user = user
tableView.tableHeaderView = header
if mode == Mode.SOMEONES_PROFILE {
logoutButton.title = "close"
tweetButton.isEnabled = false
} else {
logoutButton.title = "Log Out"
tweetButton.isEnabled = true
}
}
private func handleProfPicTap(user: User) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let profileVC = storyboard.instantiateViewController(withIdentifier: "homeViewController") as! HomeViewController
profileVC.user = user;
profileVC.mode = Mode.SOMEONES_PROFILE
self.present(profileVC, animated: true, completion: nil)
}
}
| 6c83053f563da898fcf10f5063646327 | 32.466667 | 161 | 0.622963 | false | false | false | false |
artursDerkintis/YouTube | refs/heads/master | YouTube/SmallVideoCell.swift | mit | 1 | //
// SmallVideoCell.swift
// YouTube
//
// Created by Arturs Derkintis on 1/10/16.
// Copyright © 2016 Starfly. All rights reserved.
//
import UIKit
import AsyncDisplayKit
class SmallVideoCell: UICollectionViewCell {
var imageContainer : ParallaxView!
var thumbnailImageView : ASImageNode!
var durationLabel : UILabel!
var viewsCountLabel : UILabel!
var channelTitleLabel : UILabel!
var videoTitleLabel : UILabel!
var created = false
override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
imageContainer = ParallaxView(frame: .zero)
contentView.addSubview(imageContainer)
imageContainer.snp_makeConstraints { (make) -> Void in
make.top.equalTo(10)
make.centerX.equalTo(self)
make.height.equalTo(105)
make.width.equalTo(200)
}
thumbnailImageView = ASImageNode()
imageContainer.addSubview(thumbnailImageView.view)
thumbnailImageView.view.snp_makeConstraints { (make) -> Void in
make.top.left.equalTo(5)
make.right.bottom.equalTo(-5)
}
durationLabel = UILabel(frame: .zero)
imageContainer.addSubview(durationLabel)
durationLabel.tag = hidableViewTag
durationLabel.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(-10).priority(1000)
make.right.equalTo(-10).priority(1000)
make.height.equalTo(20).priority(1000)
}
channelTitleLabel = UILabel(frame: .zero)
channelTitleLabel.tag = hidableViewTag
imageContainer.addSubview(channelTitleLabel)
channelTitleLabel.snp_makeConstraints { (make) -> Void in
make.left.equalTo(5)
make.right.equalTo(-5)
make.top.equalTo(5)
make.height.equalTo(20)
}
viewsCountLabel = UILabel(frame: .zero)
viewsCountLabel.tag = hidableViewTag
imageContainer.addSubview(viewsCountLabel)
viewsCountLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(5)
make.right.equalTo(-5)
make.height.equalTo(20)
make.width.equalTo(50)
}
videoTitleLabel = UILabel(frame: .zero)
videoTitleLabel.tag = hidableViewTag
imageContainer.addSubview(videoTitleLabel)
videoTitleLabel.snp_makeConstraints { (make) -> Void in
make.top.equalTo(thumbnailImageView.view.snp_bottomMargin).offset(13)
make.height.equalTo(25)
make.width.equalTo(self.snp_width).multipliedBy(0.9)
make.centerX.equalTo(self.snp_centerX)
}
design()
}
override func prepareForReuse() {
super.prepareForReuse()
durationLabel.text = ""
viewsCountLabel.text = ""
thumbnailImageView.image = nil
channelTitleLabel.text = ""
}
func design(){
imageContainer.backgroundColor = UIColor.whiteColor()
imageContainer.layer.cornerRadius = 3
imageContainer.layer.shadowOffset = CGSize(width: 1, height: 2)
imageContainer.layer.shadowColor = UIColor.blackColor().CGColor
imageContainer.layer.shadowOpacity = 0.17
imageContainer.layer.shadowRadius = 2
imageContainer.layer.rasterizationScale = UIScreen.mainScreen().scale
imageContainer.layer.shouldRasterize = true
channelTitleLabel.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.8)
channelTitleLabel.font = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium)
channelTitleLabel.textColor = .blackColor()
viewsCountLabel.textColor = .blackColor()
viewsCountLabel.font = UIFont.systemFontOfSize(12, weight: UIFontWeightMedium)
viewsCountLabel.textAlignment = NSTextAlignment.Center
durationLabel.textColor = .whiteColor()
durationLabel.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
durationLabel.layer.cornerRadius = 2
durationLabel.font = UIFont.systemFontOfSize(10, weight: UIFontWeightBold)
durationLabel.layer.borderWidth = 0.5
durationLabel.layer.masksToBounds = true
durationLabel.layer.borderColor = UIColor.whiteColor().colorWithAlphaComponent(0.8).CGColor
thumbnailImageView.placeholderColor = UIColor(white: 0.9, alpha: 1.0)
thumbnailImageView.contentMode = .ScaleAspectFill
thumbnailImageView.layer.masksToBounds = true
videoTitleLabel.textAlignment = .Center
videoTitleLabel.font = UIFont.systemFontOfSize(13, weight: UIFontWeightRegular)
}
func setDurationLabelSize(){
let contentSize = (durationLabel.text! as NSString).sizeWithAttributes([NSFontAttributeName: durationLabel.font])
durationLabel.frame.size = CGSize(width: contentSize.width, height: 20)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 42f2d7a0aab7628b04c97e43a2b940ff | 36.992647 | 121 | 0.651829 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/Platform/Sources/PlatformUIKit/Components/SelectionButtonView/SelectionButtonViewModel.swift | lgpl-3.0 | 1 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxDataSources
import RxRelay
import RxSwift
/// A view model for selection-view to use throughout the app
public final class SelectionButtonViewModel: IdentifiableType {
// MARK: - Types
public struct AccessibilityContent {
public let id: String
public let label: String
fileprivate static var empty: AccessibilityContent {
AccessibilityContent(id: "", label: "")
}
fileprivate var accessibility: Accessibility {
Accessibility(
id: id,
label: label,
traits: .button,
isAccessible: !id.isEmpty
)
}
public init(id: String, label: String) {
self.id = id
self.label = label
}
}
public enum LeadingContent {
case badgeImage(BadgeImageViewModel)
case label(LabelContent)
case none
}
public enum TrailingContent {
case transaction(TransactionDescriptorViewModel)
case image(ImageViewContent)
case empty
var transaction: TransactionDescriptorViewModel? {
switch self {
case .transaction(let value):
return value
case .image, .empty:
return nil
}
}
var image: ImageViewContent? {
switch self {
case .image(let value):
return value
case .transaction, .empty:
return nil
}
}
}
public enum LeadingContentType {
public struct Image {
let image: ImageResource
let background: Color
let cornerRadius: BadgeImageViewModel.CornerRadius
let offset: CGFloat
let size: CGSize
let renderingMode: ImageViewContent.RenderingMode
public init(
image: ImageResource,
background: Color,
offset: CGFloat = 4,
cornerRadius: BadgeImageViewModel.CornerRadius,
size: CGSize,
renderingMode: ImageViewContent.RenderingMode = .normal
) {
self.image = image
self.background = background
self.offset = offset
self.cornerRadius = cornerRadius
self.size = size
self.renderingMode = renderingMode
}
}
case image(Image)
case text(String)
}
private typealias AccessibilityId = Accessibility.Identifier.SelectionButtonView
// MARK: - Public Properties
public var identity: AnyHashable {
titleRelay.value + (subtitleRelay.value ?? "")
}
/// Title Relay: title describing the selection
public let titleRelay = BehaviorRelay<String>(value: "")
/// Title Font Relay: Font of the leading title
public let titleFontRelay = BehaviorRelay<UIFont>(value: .main(.semibold, 16))
/// Title Color Relay: Color of the title
public let titleFontColor = BehaviorRelay<UIColor>(value: .titleText)
/// Subtitle Relay: The subtitle describing the selection
///
/// A nil value represents the inexistence of a subtitle, in which case a view may react to this by changing its layout.
public let subtitleRelay = BehaviorRelay<String?>(value: "")
/// Subtitle Font Relay: Font of the leading subtitle
public let subtitleFontRelay = BehaviorRelay<UIFont>(value: .main(.medium, 14))
/// Subtitle Color Relay: Color of the subtitle
public let subtitleFontColor = BehaviorRelay<UIColor>(value: .descriptionText)
/// Image Name Relay: A `String` for image asset name.
public let leadingContentTypeRelay = BehaviorRelay<LeadingContentType?>(value: nil)
/// The leading content's size
public var leadingImageViewSize: Driver<CGSize> {
leadingContentTypeRelay
.asDriver()
.map { type in
switch type {
case .image(let image):
return image.size
case .text, .none:
return CGSize(edge: 1)
}
}
}
/// Accessibility for the title
public let titleAccessibilityRelay = BehaviorRelay<Accessibility>(
value: .id(Accessibility.Identifier.ContentLabelView.title)
)
/// Accessibility for the subtitle
public let subtitleAccessibilityRelay = BehaviorRelay<Accessibility>(
value: .id(Accessibility.Identifier.ContentLabelView.description)
)
/// Accessibility content relay
public let accessibilityContentRelay = BehaviorRelay<AccessibilityContent>(value: .empty)
/// Trailing content relay
public let trailingContentRelay = BehaviorRelay<TrailingContent>(value: .empty)
/// Title Relay: title describing the selection
public let shouldShowSeparatorRelay = BehaviorRelay(value: false)
/// Horizontal offset relay
public let horizontalOffsetRelay = BehaviorRelay<CGFloat>(value: 24)
/// Vertical offset relay
public let verticalOffsetRelay = BehaviorRelay<CGFloat>(value: 16)
/// Allows any component to observe taps
public var tap: Signal<Void> {
tapRelay.asSignal()
}
/// Determines if the button accepts touches
public let isButtonEnabledRelay = BehaviorRelay(value: true)
var isButtonEnabled: Driver<Bool> {
isButtonEnabledRelay.asDriver()
}
// MARK: - Internal Properties
/// A tap relay that accepts taps on the button
let tapRelay = PublishRelay<Void>()
/// The horizontal offset of the content
var horizontalOffset: Driver<CGFloat> {
horizontalOffsetRelay.asDriver()
}
/// The vertical offset of the content
var verticalOffset: Driver<CGFloat> {
verticalOffsetRelay.asDriver()
}
/// Streams the leading image
var shouldShowSeparator: Driver<Bool> {
shouldShowSeparatorRelay.asDriver()
}
/// Streams the leading content
var leadingContent: Driver<LeadingContent> {
leadingContentRelay.asDriver()
}
/// Streams the title
var title: Driver<LabelContent> {
Observable
.combineLatest(
titleRelay.asObservable(),
titleAccessibilityRelay.asObservable(),
titleFontRelay.asObservable(),
titleFontColor.asObservable()
)
.map { title, accessibility, font, color in
LabelContent(
text: title,
font: font,
color: color,
accessibility: accessibility
)
}
.asDriver(onErrorJustReturn: .empty)
}
/// Streams the title
var subtitle: Driver<LabelContent?> {
Observable
.combineLatest(
subtitleRelay.asObservable(),
subtitleAccessibilityRelay.asObservable(),
subtitleFontRelay.asObservable(),
subtitleFontColor.asObservable()
)
.map { subtitle, accessibility, font, color in
guard let subtitle = subtitle else {
return nil
}
return LabelContent(
text: subtitle,
font: font,
color: color,
adjustsFontSizeToFitWidth: .true(factor: 0.7),
accessibility: accessibility
)
}
.asDriver(onErrorJustReturn: .empty)
}
/// Streams the trailing content
var trailingContent: Driver<TrailingContent> {
trailingContentRelay
.asDriver()
}
/// Streams the accessibility
var accessibility: Driver<Accessibility> {
accessibilityContentRelay
.asDriver()
.map(\.accessibility)
}
// MARK: - Private Properties
private let leadingContentRelay = BehaviorRelay<LeadingContent>(value: .none)
private let disposeBag = DisposeBag()
public init(showSeparator: Bool = false) {
shouldShowSeparatorRelay.accept(showSeparator)
leadingContentTypeRelay
.map { type in
switch type {
case .image(let image):
let imageViewContent = ImageViewContent(
imageResource: image.image,
renderingMode: image.renderingMode
)
let badgeViewModel = BadgeImageViewModel()
badgeViewModel.set(
theme: .init(
backgroundColor: image.background,
cornerRadius: image.cornerRadius,
imageViewContent: imageViewContent,
marginOffset: image.offset
)
)
return .badgeImage(badgeViewModel)
case .text(let text):
return .label(
LabelContent(
text: text,
font: .main(.medium, 30),
color: .black
)
)
case .none:
return .none
}
}
.bindAndCatch(to: leadingContentRelay)
.disposed(by: disposeBag)
}
}
| a5fad179b1b04d6606ad7f9747ee7911 | 30.883333 | 125 | 0.570099 | false | false | false | false |
couchbase/couchbase-lite-ios | refs/heads/master | Swift/Tests/LogTest.swift | apache-2.0 | 1 | //
// LogTest.swift
// CouchbaseLite
//
// Copyright (c) 2018 Couchbase, Inc 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 XCTest
@testable import CouchbaseLiteSwift
class LogTest: CBLTestCase {
var logFileDirectory: String!
var backup: FileLoggerBackup?
var backupConsoleLevel: LogLevel?
var backupConsoleDomains: LogDomains?
override func setUp() {
super.setUp()
let folderName = "LogTestLogs_\(Int.random(in: 1...1000))"
logFileDirectory = (NSTemporaryDirectory() as NSString).appendingPathComponent(folderName)
backupLoggerConfig()
}
override func tearDown() {
super.tearDown()
try? FileManager.default.removeItem(atPath: logFileDirectory)
restoreLoggerConfig()
}
func logFileConfig() -> LogFileConfiguration {
return LogFileConfiguration(directory: logFileDirectory)
}
func backupLoggerConfig() {
backup = FileLoggerBackup(config: Database.log.file.config,
level: Database.log.file.level)
backupConsoleLevel = Database.log.console.level
backupConsoleDomains = Database.log.console.domains
}
func restoreLoggerConfig() {
if let backup = self.backup {
Database.log.file.config = backup.config
Database.log.file.level = backup.level
self.backup = nil
}
if let consoleLevel = self.backupConsoleLevel {
Database.log.console.level = consoleLevel
}
if let consoleDomains = self.backupConsoleDomains {
Database.log.console.domains = consoleDomains
}
Database.log.custom = nil
}
func getLogsInDirectory(_ directory: String,
properties: [URLResourceKey] = [],
onlyInfoLogs: Bool = false) throws -> [URL]
{
let url = URL(fileURLWithPath: directory)
let files = try FileManager.default.contentsOfDirectory(at: url,
includingPropertiesForKeys: properties,
options: .skipsSubdirectoryDescendants)
return files.filter({ $0.pathExtension == "cbllog" &&
(onlyInfoLogs ? $0.lastPathComponent.starts(with: "cbl_info_") : true) })
}
func writeOneKiloByteOfLog() {
let message = "11223344556677889900" // 44Byte line
for _ in 0..<23 { // 1012 Bytes
Log.log(domain: .database, level: .error, message: "\(message)")
Log.log(domain: .database, level: .warning, message: "\(message)")
Log.log(domain: .database, level: .info, message: "\(message)")
Log.log(domain: .database, level: .verbose, message: "\(message)")
Log.log(domain: .database, level: .debug, message: "\(message)")
}
writeAllLogs("1") // ~25Bytes
}
func writeAllLogs(_ message: String) {
Log.log(domain: .database, level: .error, message: message)
Log.log(domain: .database, level: .warning, message: message)
Log.log(domain: .database, level: .info, message: message)
Log.log(domain: .database, level: .verbose, message: message)
Log.log(domain: .database, level: .debug, message: message)
}
func isKeywordPresentInAnyLog(_ keyword: String, path: String) throws -> Bool {
for file in try getLogsInDirectory(path) {
let contents = try String(contentsOf: file, encoding: .ascii)
if contents.contains(keyword) {
return true
}
}
return false
}
func testCustomLoggingLevels() throws {
Log.log(domain: .database, level: .info, message: "IGNORE")
let customLogger = CustomLogger()
Database.log.custom = customLogger
for i in (1...5).reversed() {
customLogger.reset()
customLogger.level = LogLevel(rawValue: UInt8(i))!
Database.log.custom = customLogger
Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE")
Log.log(domain: .database, level: .info, message: "TEST INFO")
Log.log(domain: .database, level: .warning, message: "TEST WARNING")
Log.log(domain: .database, level: .error, message: "TEST ERROR")
XCTAssertEqual(customLogger.lines.count, 5 - i)
}
Database.log.custom = nil
}
func testFileLoggingLevels() throws {
let config = self.logFileConfig()
config.usePlainText = true
Database.log.file.config = config
for i in (1...5).reversed() {
Database.log.file.level = LogLevel(rawValue: UInt8(i))!
Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE")
Log.log(domain: .database, level: .info, message: "TEST INFO")
Log.log(domain: .database, level: .warning, message: "TEST WARNING")
Log.log(domain: .database, level: .error, message: "TEST ERROR")
}
let files = try FileManager.default.contentsOfDirectory(atPath: config.directory)
for file in files {
let log = (config.directory as NSString).appendingPathComponent(file)
let content = try NSString(contentsOfFile: log, encoding: String.Encoding.utf8.rawValue)
var lineCount = 0
content.enumerateLines { (line, stop) in
lineCount = lineCount + 1
}
let sfile = file as NSString
if sfile.range(of: "verbose").location != NSNotFound {
XCTAssertEqual(lineCount, 2)
} else if sfile.range(of: "info").location != NSNotFound {
XCTAssertEqual(lineCount, 3)
} else if sfile.range(of: "warning").location != NSNotFound {
XCTAssertEqual(lineCount, 4)
} else if sfile.range(of: "error").location != NSNotFound {
XCTAssertEqual(lineCount, 5)
}
}
}
func testFileLoggingDefaultBinaryFormat() throws {
let config = self.logFileConfig()
Database.log.file.config = config
Database.log.file.level = .info
Log.log(domain: .database, level: .info, message: "TEST INFO")
let files = try getLogsInDirectory(config.directory,
properties: [.contentModificationDateKey],
onlyInfoLogs: true)
let sorted = files.sorted { (url1, url2) -> Bool in
guard let date1 = try! url1
.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate
else {
fatalError("modification date is missing for the URL")
}
guard let date2 = try! url2
.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate
else {
fatalError("modification date is missing for the URL")
}
return date1.compare(date2) == .orderedAscending
}
guard let last = sorted.last else {
fatalError("last item shouldn't be empty")
}
let handle = try FileHandle.init(forReadingFrom: last)
let data = handle.readData(ofLength: 4)
let bytes = [UInt8](data)
XCTAssert(bytes[0] == 0xcf && bytes[1] == 0xb2 && bytes[2] == 0xab && bytes[3] == 0x1b,
"because the log should be in binary format");
}
func testFileLoggingUsePlainText() throws {
let config = self.logFileConfig()
XCTAssertEqual(config.usePlainText, LogFileConfiguration.defaultUsePlainText)
config.usePlainText = true
XCTAssert(config.usePlainText)
Database.log.file.config = config
Database.log.file.level = .info
let inputString = "SOME TEST INFO"
Log.log(domain: .database, level: .info, message: inputString)
let files = try getLogsInDirectory(config.directory,
properties: [.contentModificationDateKey],
onlyInfoLogs: true)
let sorted = files.sorted { (url1, url2) -> Bool in
guard let date1 = try! url1
.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate
else {
fatalError("modification date is missing for the URL")
}
guard let date2 = try! url2
.resourceValues(forKeys: [.contentModificationDateKey])
.contentModificationDate
else {
fatalError("modification date is missing for the URL")
}
return date1.compare(date2) == .orderedAscending
}
guard let last = sorted.last else {
fatalError("last item shouldn't be empty")
}
let contents = try String(contentsOf: last, encoding: .ascii)
XCTAssert(contents.contains(inputString))
}
func testFileLoggingLogFilename() throws {
let config = self.logFileConfig()
Database.log.file.config = config
Database.log.file.level = .debug
let regex = "cbl_(debug|verbose|info|warning|error)_\\d+\\.cbllog"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
for file in try getLogsInDirectory(config.directory) {
XCTAssert(predicate.evaluate(with: file.lastPathComponent))
}
}
func testEnableAndDisableCustomLogging() throws {
Log.log(domain: .database, level: .info, message: "IGNORE")
let customLogger = CustomLogger()
Database.log.custom = customLogger
customLogger.level = .none
Database.log.custom = customLogger
Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE")
Log.log(domain: .database, level: .info, message: "TEST INFO")
Log.log(domain: .database, level: .warning, message: "TEST WARNING")
Log.log(domain: .database, level: .error, message: "TEST ERROR")
XCTAssertEqual(customLogger.lines.count, 0)
customLogger.level = .verbose
Database.log.custom = customLogger
Log.log(domain: .database, level: .verbose, message: "TEST VERBOSE")
Log.log(domain: .database, level: .info, message: "TEST INFO")
Log.log(domain: .database, level: .warning, message: "TEST WARNING")
Log.log(domain: .database, level: .error, message: "TEST ERROR")
XCTAssertEqual(customLogger.lines.count, 4)
}
func testFileLoggingMaxSize() throws {
let config = self.logFileConfig()
XCTAssertEqual(config.maxSize, LogFileConfiguration.defaultMaxSize)
XCTAssertEqual(config.maxRotateCount, LogFileConfiguration.defaultMaxRotateCount)
config.usePlainText = true
config.maxSize = 1024
config.maxRotateCount = 2
XCTAssertEqual(config.maxSize, 1024)
XCTAssertEqual(config.maxRotateCount, 2)
Database.log.file.config = config
Database.log.file.level = .debug
XCTAssertEqual(Database.log.file.config?.maxSize, 1024)
XCTAssertEqual(Database.log.file.config?.maxRotateCount, 2)
// this should create three files(per level) => 2KB logs + extra
writeOneKiloByteOfLog()
writeOneKiloByteOfLog()
guard let maxRotateCount = Database.log.file.config?.maxRotateCount else {
fatalError("Config should be present!!")
}
var totalFilesShouldBeInDirectory = 15 /* (maxRotateCount + 1) * 5(levels) */
#if !DEBUG
totalFilesShouldBeInDirectory = totalFilesShouldBeInDirectory - 1
#endif
let totalLogFilesSaved = try getLogsInDirectory(config.directory)
XCTAssertEqual(totalLogFilesSaved.count, totalFilesShouldBeInDirectory)
}
func testFileLoggingDisableLogging() throws {
let config = self.logFileConfig()
config.usePlainText = true
Database.log.file.config = config
Database.log.file.level = .none
let message = UUID().uuidString
writeAllLogs(message)
XCTAssertFalse(try isKeywordPresentInAnyLog(message, path: config.directory))
}
func testFileLoggingReEnableLogging() throws {
let config = self.logFileConfig()
config.usePlainText = true
Database.log.file.config = config
// DISABLE LOGGING
Database.log.file.level = .none
let message = UUID().uuidString
writeAllLogs(message)
XCTAssertFalse(try isKeywordPresentInAnyLog(message, path: config.directory))
// ENABLE LOGGING
Database.log.file.level = .verbose
writeAllLogs(message)
for file in try getLogsInDirectory(config.directory) {
if file.lastPathComponent.starts(with: "cbl_debug_") {
continue
}
let contents = try String(contentsOf: file, encoding: .ascii)
XCTAssert(contents.contains(message))
}
}
func testFileLoggingHeader() throws {
let config = self.logFileConfig()
config.usePlainText = true
Database.log.file.config = config
Database.log.file.level = .verbose
writeOneKiloByteOfLog()
for file in try getLogsInDirectory(config.directory) {
let contents = try String(contentsOf: file, encoding: .ascii)
guard let firstLine = contents.components(separatedBy: "\n").first else {
fatalError("log contents should be empty and needs header section")
}
XCTAssert(firstLine.contains("CouchbaseLite/"))
XCTAssert(firstLine.contains("Build/"))
XCTAssert(firstLine.contains("Commit/"))
}
}
func testNonASCII() throws {
let customLogger = CustomLogger()
customLogger.level = .verbose
Database.log.custom = customLogger
Database.log.console.domains = .all
Database.log.console.level = .verbose
let hebrew = "מזג האוויר נחמד היום" // The weather is nice today.
let doc = MutableDocument()
doc.setString(hebrew, forKey: "hebrew")
try db.saveDocument(doc)
let q = QueryBuilder
.select(SelectResult.all())
.from(DataSource.database(db))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 1);
let expectedHebrew = "[{\"hebrew\":\"\(hebrew)\"}]"
var found: Bool = false
for line in customLogger.lines {
if line.contains(expectedHebrew) {
found = true
}
}
XCTAssert(found)
}
func testPercentEscape() throws {
let customLogger = CustomLogger()
customLogger.level = .info
Database.log.custom = customLogger
Database.log.console.domains = .all
Database.log.console.level = .info
Log.log(domain: .database, level: .info, message: "Hello %s there")
var found: Bool = false
for line in customLogger.lines {
if line.contains("Hello %s there") {
found = true
}
}
XCTAssert(found)
}
}
struct FileLoggerBackup {
var config: LogFileConfiguration?
var level: LogLevel
}
| 5b09994feb191f50d9948363f51f2c5a | 38.302885 | 103 | 0.593272 | false | true | false | false |
eddieespinal/GarageAutomationSystem | refs/heads/master | iOS App/Garage/SwiftMQTT/SwiftMQTT/Models/MQTTSubPacket.swift | mit | 1 | //
// MQTTSubPacket.swift
// SwiftMQTT
//
// Created by Ankit Aggarwal on 12/11/15.
// Copyright © 2015 Ankit. All rights reserved.
//
import Foundation
class MQTTSubPacket: MQTTPacket {
let topics: [String: MQTTQoS]
let messageID: UInt16
init(topics: [String : MQTTQoS], messageID: UInt16) {
self.topics = topics
self.messageID = messageID
super.init(header: MQTTPacketFixedHeader(packetType: .Subscribe, flags: 0x02))
}
override func networkPacket() -> NSData {
//Variable Header
let variableHeader = NSMutableData()
variableHeader.mqtt_appendUInt16(self.messageID)
//Payload
let payload = NSMutableData()
for (key, value) in self.topics {
payload.mqtt_appendString(key)
let qos = value.rawValue & 0x03
payload.mqtt_appendUInt8(qos)
}
return self.finalPacket(variableHeader, payload: payload)
}
}
| d9f1d85e13eb9894f0170eabc7afa6fc | 25.184211 | 86 | 0.613065 | false | false | false | false |
davidgatti/IoT-Garage-Opener | refs/heads/master | GarageOpener/GarageState.swift | apache-2.0 | 3 | //
// Settings.swift
// GarageOpener
//
// Created by David Gatti on 6/8/15.
// Copyright (c) 2015 David Gatti. All rights reserved.
//
import Foundation
import Parse
class GarageState {
//MARK: Static
static let sharedInstance = GarageState()
//MARK: Variables
var user: PFUser!
var isOpen: Int = 0
var useCount: Int = 0
var lastUsed: NSDate = NSDate.distantPast() as NSDate
//MARK: Get
func get(completition:() -> ()) {
var count: Int = 0
getLastUser { (result) -> Void in
count++
}
getUseCount { (result) -> Void in
count++
}
while true {
if count == 2 {
return completition()
}
}
}
private func getLastUser(completition:() -> ()) {
let qHistory = PFQuery(className: "History")
qHistory.orderByDescending("createdAt")
qHistory.getFirstObjectInBackgroundWithBlock { (lastEntry: PFObject?, error) -> Void in
self.isOpen = (lastEntry?.objectForKey("state") as? Int)!
self.lastUsed = lastEntry!.createdAt!
self.user = lastEntry?.objectForKey("user") as? PFUser
self.user?.fetch()
return completition()
}
}
private func getUseCount(completition:() -> ()) {
let qGarageDoor = PFQuery(className:"GarageDoor")
qGarageDoor.getObjectInBackgroundWithId("eX9QCJGga5") { (garage: PFObject?, error: NSError?) -> Void in
self.useCount = (garage!.objectForKey("useCount") as! Int)
return completition()
}
}
//MARK: Set
func set(completition: (result: String) -> Void) {
setHistory { (result) -> Void in }
setGarageDoor { (result) -> Void in }
}
private func setHistory(completition: (result: String) -> Void) {
let user = PFUser.currentUser()
let history = PFObject(className: "History")
history["user"] = user
history["applianceID"] = "eX9QCJGga5"
history["state"] = self.isOpen
history.saveInBackground()
}
private func setGarageDoor(completition: (result: String) -> Void) {
let query = PFObject(withoutDataWithClassName: "GarageDoor", objectId: "eX9QCJGga5")
query["useCount"] = self.useCount
query.saveInBackground()
}
}
| 5bf7b58e366e4a9fd923bcf90b5cbac1 | 25.291667 | 111 | 0.548336 | false | false | false | false |
atrick/swift | refs/heads/main | test/SourceKit/CursorInfo/cursor_info_multi_module.swift | apache-2.0 | 7 | #if MOD_PARTIALA
/// Comment from A
public func someFunc() {}
#endif
#if MOD_PARTIALB
public func funcBeforeLoc() {}
/// Comment from B
public func anotherFuncBeforeLoc() {}
#sourceLocation(file: "doesnotexist.swift", line: 10)
public func funcInLoc() {}
/// Comment from #sourceLocation
public func anotherFuncInLoc() {}
#sourceLocation()
public func funcAfterLoc() {}
/// Comment from B
public func anotherFuncAfterLoc() {}
#endif
#if MOD_USE
import somemod
func test() {
someFunc()
anotherFuncBeforeLoc()
anotherFuncInLoc()
anotherFuncAfterLoc()
}
#endif
// This test depends on line numbers, hence RUN lines being underneath the
// code.
// RUN: %empty-directory(%t)
// RUN: %empty-directory(%t/mods)
// RUN: %target-swift-frontend -emit-module -emit-module-source-info -o %t/mods/somemoda.partial.swiftmodule -D MOD_PARTIALA -module-name somemod %s
// RUN: %target-swift-frontend -emit-module -emit-module-source-info -o %t/mods/somemodb.partial.swiftmodule -D MOD_PARTIALB -module-name somemod %s
// RUN: %target-swift-frontend -emit-module -emit-module-source-info -o %t/mods/somemod.swiftmodule -module-name somemod %t/mods/somemoda.partial.swiftmodule %t/mods/somemodb.partial.swiftmodule
// RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=24:3 %s -- -D MOD_USE -I %t/mods -target %target-triple %s | %FileCheck --check-prefix=CHECK-NORMAL %s
// CHECK-NORMAL: source.lang.swift.ref.function.free (3:13-3:21)
// CHECK-NORMAL-NEXT: someFunc()
// CHECK-NORMAL-NEXT: s:7somemod8someFuncyyF
// CHECK-NORMAL: "docComment": {
// CHECK-NORMAL-NEXT: "lines": [
// CHECK-NORMAL-NEXT: {
// CHECK-NORMAL-NEXT: "range": {
// CHECK-NORMAL-NEXT: "end": {
// CHECK-NORMAL-NEXT: "character": 18,
// CHECK-NORMAL-NEXT: "line": 1
// CHECK-NORMAL-NEXT: },
// CHECK-NORMAL-NEXT: "start": {
// CHECK-NORMAL-NEXT: "character": 4,
// CHECK-NORMAL-NEXT: "line": 1
// CHECK-NORMAL-NEXT: }
// CHECK-NORMAL-NEXT: },
// CHECK-NORMAL-NEXT: "text": "Comment from A"
// CHECK-NORMAL-NEXT: }
// CHECK-NORMAL-NEXT: ]
// CHECK-NORMAL-NEXT: },
// CHECK-NORMAL: "location": {
// CHECK-NORMAL-NEXT: "position": {
// CHECK-NORMAL-NEXT: "character": 12,
// CHECK-NORMAL-NEXT: "line": 2
// CHECK-NORMAL-NEXT: },
// CHECK-NORMAL-NEXT: "uri": "file://{{.*}}cursor_info_multi_module.swift"
// CHECK-NORMAL-NEXT: }
// RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=25:3 %s -- -D MOD_USE -I %t/mods -target %target-triple %s | %FileCheck --check-prefix=CHECK-BEFORE %s
// CHECK-BEFORE: source.lang.swift.ref.function.free (9:13-9:33)
// CHECK-BEFORE-NEXT: anotherFuncBeforeLoc()
// CHECK-BEFORE-NEXT: s:7somemod20anotherFuncBeforeLocyyF
// CHECK-BEFORE: "docComment": {
// CHECK-BEFORE-NEXT: "lines": [
// CHECK-BEFORE-NEXT: {
// CHECK-BEFORE-NEXT: "range": {
// CHECK-BEFORE-NEXT: "end": {
// CHECK-BEFORE-NEXT: "character": 18,
// CHECK-BEFORE-NEXT: "line": 7
// CHECK-BEFORE-NEXT: },
// CHECK-BEFORE-NEXT: "start": {
// CHECK-BEFORE-NEXT: "character": 4,
// CHECK-BEFORE-NEXT: "line": 7
// CHECK-BEFORE-NEXT: }
// CHECK-BEFORE-NEXT: },
// CHECK-BEFORE-NEXT: "text": "Comment from B"
// CHECK-BEFORE-NEXT: }
// CHECK-BEFORE-NEXT: ]
// CHECK-BEFORE-NEXT: },
// CHECK-BEFORE: "location": {
// CHECK-BEFORE-NEXT: "position": {
// CHECK-BEFORE-NEXT: "character": 12,
// CHECK-BEFORE-NEXT: "line": 8
// CHECK-BEFORE-NEXT: },
// CHECK-BEFORE-NEXT: "uri": "file://{{.*}}cursor_info_multi_module.swift"
// CHECK-BEFORE-NEXT: }
// Cursor info ignores #sourceLocation, symbol graph does not
// RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=26:3 %s -- -D MOD_USE -I %t/mods -target %target-triple %s | %FileCheck --check-prefix=CHECK-IN %s
// CHECK-IN: source.lang.swift.ref.function.free (13:13-13:29)
// CHECK-IN-NEXT: anotherFuncInLoc()
// CHECK-IN-NEXT: s:7somemod16anotherFuncInLocyyF
// CHECK-IN: "docComment": {
// CHECK-IN-NEXT: "lines": [
// CHECK-IN-NEXT: {
// CHECK-IN-NEXT: "range": {
// CHECK-IN-NEXT: "end": {
// CHECK-IN-NEXT: "character": 32,
// CHECK-IN-NEXT: "line": 10
// CHECK-IN-NEXT: },
// CHECK-IN-NEXT: "start": {
// CHECK-IN-NEXT: "character": 4,
// CHECK-IN-NEXT: "line": 10
// CHECK-IN-NEXT: }
// CHECK-IN-NEXT: },
// CHECK-IN-NEXT: "text": "Comment from #sourceLocation"
// CHECK-IN-NEXT: }
// CHECK-IN-NEXT: ]
// CHECK-IN-NEXT: },
// CHECK-IN: "location": {
// CHECK-IN-NEXT: "position": {
// CHECK-IN-NEXT: "character": 12,
// CHECK-IN-NEXT: "line": 11
// CHECK-IN-NEXT: },
// CHECK-IN-NEXT: "uri": "file://doesnotexist.swift"
// CHECK-IN-NEXT: }
// RUN: %sourcekitd-test -req=cursor -req-opts=retrieve_symbol_graph=1 -pos=27:3 %s -- -D MOD_USE -I %t/mods -target %target-triple %s | %FileCheck --check-prefix=CHECK-AFTER %s
// CHECK-AFTER: source.lang.swift.ref.function.free (17:13-17:32)
// CHECK-AFTER-NEXT: anotherFuncAfterLoc()
// CHECK-AFTER-NEXT: s:7somemod19anotherFuncAfterLocyyF
// CHECK-AFTER: "docComment": {
// CHECK-AFTER-NEXT: "lines": [
// CHECK-AFTER-NEXT: {
// CHECK-AFTER-NEXT: "range": {
// CHECK-AFTER-NEXT: "end": {
// CHECK-AFTER-NEXT: "character": 18,
// CHECK-AFTER-NEXT: "line": 15
// CHECK-AFTER-NEXT: },
// CHECK-AFTER-NEXT: "start": {
// CHECK-AFTER-NEXT: "character": 4,
// CHECK-AFTER-NEXT: "line": 15
// CHECK-AFTER-NEXT: }
// CHECK-AFTER-NEXT: },
// CHECK-AFTER-NEXT: "text": "Comment from B"
// CHECK-AFTER-NEXT: }
// CHECK-AFTER-NEXT: ]
// CHECK-AFTER-NEXT: },
// CHECK-AFTER: "location": {
// CHECK-AFTER-NEXT: "position": {
// CHECK-AFTER-NEXT: "character": 12,
// CHECK-AFTER-NEXT: "line": 16
// CHECK-AFTER-NEXT: },
// CHECK-AFTER-NEXT: "uri": "file://{{.*}}cursor_info_multi_module.swift"
// CHECK-AFTER-NEXT: }
| e70f1bd5bdbc7f06b4a5ef07d453a500 | 38.229299 | 194 | 0.613411 | false | false | false | false |
kmomma/Calculator | refs/heads/master | Calculator/ViewController.swift | gpl-2.0 | 1 | //
// ViewController.swift
// Calculator
//
// Created by K on 3/12/15.
// Copyright (c) 2015 KNM. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypeingANumber: Bool = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypeingANumber {
display.text = display.text! + digit
} else{
display.text = digit
userIsInTheMiddleOfTypeingANumber = true
}
//println("digit= \(digit)")
}
@IBAction func enter() {
userIsInTheMiddleOfTypeingANumber = false
}
}
| 0810bcd6604f4f52f0234f40d43b19a6 | 20.818182 | 55 | 0.630556 | false | false | false | false |
lb2281075105/LBXiongMaoTV | refs/heads/master | LBXiongMaoTV/LBXiongMaoTV/Entertainment(娱乐)/LBXMYuLeViewModel/LBXMYuLeViewModel.swift | apache-2.0 | 1 | //
// LBXMYuLeViewModel.swift
// LBXiongMaoTV
//
// Created by 云媒 on 2017/4/14.
// Copyright © 2017年 YunMei. All rights reserved.
//
import UIKit
class LBXMYuLeViewModel: NSObject {
///户外直播
var outdoorModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]()
func outdoorRequest(isLiveData:Bool,complete:@escaping (_ resultArray:[LBXMYuLeModel]) -> ()){
LBXMNetWork.netWorkRequest(requestType: .GET, urlString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=hwzb&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore") { (result) in
guard let dic = result as? [String : Any],
let data = dic["data"] as? [String : Any],
let items = data["items"] as? [[String:AnyObject]] else {
return
}
print("户外直播:\(items)")
for dic in items {
let yuleModel = LBXMYuLeModel()
yuleModel.yy_modelSet(with: dic)
self.outdoorModelArray.append(yuleModel)
}
complete(self.outdoorModelArray)
}
}
///萌宠乐园
var petModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]()
func petRequest(isLiveData:Bool,complete:@escaping (_ resultArray:[LBXMYuLeModel]) -> ()){
LBXMNetWork.netWorkRequest(requestType: .GET, urlString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=pets&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore") { (result) in
guard let dic = result as? [String : Any],
let data = dic["data"] as? [String : Any],
let items = data["items"] as? [[String:AnyObject]] else {
return
}
print("萌宠乐园:\(items)")
for dic in items {
let yuleModel = LBXMYuLeModel()
yuleModel.yy_modelSet(with: dic)
self.petModelArray.append(yuleModel)
}
complete(self.petModelArray)
}
}
///熊猫星秀
///星秀模型数组
var xingXiuModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]()
func xinXiuRequest(isLiveData:Bool,complete:@escaping (_ resultArray:[LBXMYuLeModel]) -> ()){
LBXMNetWork.netWorkRequest(requestType: .GET, urlString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=yzdr&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore") { (result) in
guard let dic = result as? [String : Any],
let data = dic["data"] as? [String : Any],
let items = data["items"] as? [[String:AnyObject]] else {
return
}
print("熊猫星秀:\(items)")
for dic in items {
let yuleModel = LBXMYuLeModel()
yuleModel.yy_modelSet(with: dic)
self.xingXiuModelArray.append(yuleModel)
}
complete(self.xingXiuModelArray)
}
}
///音乐
var musicModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]()
func musicRequest(isLiveData:Bool,complete:@escaping (_ resultArray:[LBXMYuLeModel]) -> ()){
LBXMNetWork.netWorkRequest(requestType: .GET, urlString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=music&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore") { (result) in
guard let dic = result as? [String : Any],
let data = dic["data"] as? [String : Any],
let items = data["items"] as? [[String:AnyObject]] else {
return
}
print("音乐:\(items)")
for dic in items {
let yuleModel = LBXMYuLeModel()
yuleModel.yy_modelSet(with: dic)
self.musicModelArray.append(yuleModel)
}
complete(self.musicModelArray)
}
}
///桌游
var youModelArray:[LBXMYuLeModel] = [LBXMYuLeModel]()
func youRequest(isLiveData:Bool,complete:@escaping (_ resultArray:[LBXMYuLeModel]) -> ()){
LBXMNetWork.netWorkRequest(requestType: .GET, urlString: "http://api.m.panda.tv/ajax_get_live_list_by_cate?cate=boardgames&pageno=1&pagenum=20&order=person_num&status=2&__version=1.1.7.1305&__plat=ios&__channel=appstore") { (result) in
guard let dic = result as? [String : Any],
let data = dic["data"] as? [String : Any],
let items = data["items"] as? [[String:AnyObject]] else {
return
}
print("桌游:\(items)")
for dic in items {
let yuleModel = LBXMYuLeModel()
yuleModel.yy_modelSet(with: dic)
self.youModelArray.append(yuleModel)
}
complete(self.youModelArray)
}
}
}
| c63c630c83eea11e47e94f94013dbc01 | 41.067227 | 243 | 0.553536 | false | false | false | false |
MaddTheSane/WWDC | refs/heads/master | WWDC/TranscriptSearchResultsController.swift | bsd-2-clause | 2 | //
// TranscriptSearchResultsController.swift
// WWDC
//
// Created by Guilherme Rambo on 05/10/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RealmSwift
class TranscriptSearchResultsController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
var playCallback: ((startTime: Double) -> Void)?
var lines: Results<TranscriptLine>? {
didSet {
guard lines != nil && lines?.count > 0 else {
view.hidden = true
return
}
view.hidden = false
tableView.reloadData()
}
}
@IBOutlet weak var tableView: NSTableView! {
didSet {
tableView.setDelegate(self)
tableView.setDataSource(self)
}
}
private struct Storyboard {
static let transcriptLineCellIdentifier = "transcriptLine"
}
init() {
super.init(nibName: "TranscriptSearchResultsController", bundle: nil)!
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
// MARK: Table View
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return lines?.count ?? 0
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeViewWithIdentifier(Storyboard.transcriptLineCellIdentifier, owner: tableView) as! TranscriptLineTableCellView
cell.line = lines![row]
cell.playCallback = playCallback
return cell
}
}
| 604b2a872e2bcefa28fb4895e7f20db1 | 24.940299 | 142 | 0.605869 | false | false | false | false |
featherweightlabs/FeatherweightRouter | refs/heads/master | Demo/AppCoordinator.swift | apache-2.0 | 1 | import UIKit
import FeatherweightRouter
typealias UIPresenter = Presenter<UIViewController>
func appCoordinator() -> UIViewController {
var router: Router<UIViewController, String>!
let store = AppStore() { _ = router.setRoute($0) }
router = createRouter(store)
store.setPath("welcome")
return router.presentable
}
func createRouter(_ store: AppStore) -> Router<UIViewController, String> {
return Router(tabBarPresenter()).junction([
Router(navigationPresenter("Welcome")).stack([
Router(welcomePresenter(store)).route(predicate: {$0 == "welcome"}, children: [
Router(registrationPresenter(store)).route(predicate: {$0 == "welcome/register"}, children: [
Router(step2Presenter(store)).route(predicate: {$0 == "welcome/register/step2"}),
]),
Router(loginPresenter(store)).route(predicate: {$0 == "welcome/login"}),
])
]),
Router(aboutPresenter(store)).route(predicate: {$0 == "about"}),
])
}
| 5ffe7d1e1ac959dba0d7424545948176 | 31.625 | 109 | 0.633142 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/compiler_crashers_fixed/00339-swift-clangimporter-implementation-mapselectortodeclname.swift | apache-2.0 | 10 | // RUN: not %target-swift-frontend %s -parse
// REQUIRES: asserts
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
}
}
}
typealias e : A.Type) -> Int {
class A {
func g.b : Int {
typealias B<T>()
init(false))() {
}
return d
}
case b {
var c: AnyObject.E == T>](("
protocol P {
print() -> (n: A? = b<T where H) -> U, b in a {
return { c: T>() {
return self.E == nil
}
import Foundation
enum A where T) ->(array: AnyObject, object1, AnyObject) -> [T: String {
}
let v: a = [T> Void>>>(c>Bool)
func call("A> Self {
protocol P {
typealias e == D>(false)
}
return nil
b: C) -> U, f.E
let c, V>(t: T) -> S("\() -> V>()
return self.d.b = F>()
let i: a {
var b in a {
typealias F
}
super.init(")
struct c = e: a = {
import Foundation
class func b: c> : C> ()
typealias R = 0)
func b: NSObject {
typealias R
return g, U)
}
return $0
struct e == F
func g.a("")
}
for b in
protocol A : T
enum S() {
}
}
import Foundation
self.d
f = 0
}
}
}
}(t: T -> {
private let h> {
func a(c) {
}
if c == { c: B<T>()
init <T) {
}
self.init("")
}
init <T>)
}
return nil
let g = {
typealias E
return [unowned self.init(g: T {
}
return g: A? {
let c(f<C) {
let t: U : ()
return $0
class A where I.d: B()
self.init(AnyObject) {
}
private let d<T>(t: AnyObject, g: NSObject {
0
class A : NSManagedObject {
protocol C {
d.Type) -> {
}
var e: C {
S<T>(c
}
}
return $0)
func a(array: C<T.c : d where g: d = c
protocol d = nil
func f.B : c(self.E == c>>) {
struct D : A? = A? = Int
protocol c == "")
typealias h> U, object1, AnyObject) -> Void>() -> T) -> {
typealias E
struct e = {
protocol A {
import Foundation
}
return self.e where T>) -> Void>(x: P {
return b<Q<I : String {
import Foundation
}
if c = 0
}
var f = {
let h == f<c: C) {
}
let i: () -> ()"A? = {
}
init()
var b {
}
}
struct e {
}
typealias h> T) -> {
var b = 0
typealias F>: NSObject {
}
struct c == nil
return d
import Foundation
}
}
return "A> {
protocol P {
}
typealias R = T.d
}
let d
}
struct B<T where g: I) {
}
S<U : c(#object2)
func g, U)() -> : A"")
typealias h: I.h
}
typealias F = b
var b()
var f = B) -> {
}
}
func compose()
}
let d<A: Int {
}
let i: A: A? = e, V, object1
return nil
let c(f<T>() {
}
enum S<C
}
class func f.E == a
class A : d where T
protocol P {
return $0
}
typealias h: B? {
}
}
var e
| a488c20a2ef7ac70c4b72849b4faed86 | 12.716763 | 87 | 0.576907 | false | false | false | false |
Takanu/Pelican | refs/heads/master | Sources/Pelican/API/Request/Codable+String.swift | mit | 1 | //
// Codable+String.swift
// Pelican
//
// Created by Takanu Kyriako on 16/03/2018.
//
import Foundation
extension Encodable {
/**
A convenience method to convert any codable type into a JSON format, or a single descriptive
string of the type if it contains only one variable.
*/
func encodeToUTF8() throws -> String? {
var jsonData = Data()
do {
jsonData = try JSONEncoder().encode(self)
} catch {
if self is String {
let result = self as! String
return result
}
else if self is Int {
let result = self as! Int
return result.description
}
else if self is Double {
let result = self as! Double
return result.description
}
else if self is Decimal {
let result = self as! Decimal
return result.description
}
else if self is Bool {
let result = self as! Bool
if result == true { return "true" }
else { return "false" }
}
PLog.error("Serialisation Error - \(error)")
return nil
}
return String(data: jsonData, encoding: .utf8)
}
}
| 69a27cd8470d6b02dde9a2e0fab7dcc0 | 17.465517 | 93 | 0.62465 | false | false | false | false |
iceVeryCold/DouYuZhiBo | refs/heads/master | DYDemo/DYDemo/Classes/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// DYDemo
//
// Created by 这个夏天有点冷 on 2017/3/9.
// Copyright © 2017年 YLT. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView : PageContentView, prog : CGFloat, sourceIndex : Int, targetIndex : Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView {
// 定义属性
var childVCs : [UIViewController] = [UIViewController]()
weak var parentViewController : UIViewController?
var startOffsetX : CGFloat = 0
var isForbidScrollDelegate : Bool = false
weak var delegate : PageContentViewDelegate?
// MARK:懒加载属性
lazy var collectionView : UICollectionView = { [weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout.init()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
// 2.创建collectionView
let collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: 0, height: 0), collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
// MARK:自定义构造函数
init(frame: CGRect, childVCs : [UIViewController], parentViewController : UIViewController?) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:设置UI界面
extension PageContentView {
func setupUI() {
// 1.将所有子控制器添加到父控制器中
for childVC in self.childVCs {
parentViewController?.addChildViewController(childVC)
}
// 2.添加UICollectionView,用于在cell中存放控制器的view
addSubview(collectionView)
collectionView.frame = bounds
}
}
// MARK:遵守UICollectionViewDataSource协议
extension PageContentView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
// 2.给cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVC = childVCs[indexPath.item]
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
return cell
}
}
// MARK: -遵守UICollectionViewDelegate协议
extension PageContentView : UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 判断是否是点击事件
if isForbidScrollDelegate {
return
}
// 1.获取需要的数据
var prog : CGFloat = 0
var sourcrIndex : Int = 0
var tagetIndex : Int = 0
// 判断是左滑还是右滑
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑
// 1.计算progress
prog = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourcrIndex
sourcrIndex = Int(currentOffsetX / scrollViewW)
// 3.计算tagetIndex
tagetIndex = sourcrIndex + 1
if tagetIndex >= childVCs.count {
tagetIndex = childVCs.count - 1
}
// 4.完全滑过去
if currentOffsetX - startOffsetX == scrollViewW {
prog = 1
tagetIndex = sourcrIndex
}
} else { // 右滑
// 1.计算progress
prog = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算tagetIndex
tagetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourcrIndex
sourcrIndex = tagetIndex + 1
if sourcrIndex >= childVCs.count {
sourcrIndex = childVCs.count - 1
}
}
// 传递prog、sourcrIndex、tagetIndex
delegate?.pageContentView(contentView: self, prog: prog, sourceIndex: sourcrIndex, targetIndex: tagetIndex)
}
}
// MARK: 对外暴露的方法
extension PageContentView {
func setCurrentIndex(currentIndex : Int) {
// 1.记录需要禁止执行代理方法
isForbidScrollDelegate = true
// 2.滚到正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.contentOffset = CGPoint.init(x: offsetX, y: 0)
}
}
| 3816ff0f616dec1d8049205f8b5563e0 | 30.340909 | 133 | 0.614938 | false | false | false | false |
poetmountain/MotionMachine | refs/heads/master | Sources/EasingTypes/EasingBounce.swift | mit | 1 | //
// EasingBounce.swift
// MotionMachine
//
// Created by Brett Walker on 5/3/16.
// Copyright © 2016-2018 Poet & Mountain, LLC. 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
/**
* EasingBounce provides easing equations that have successively smaller value peaks, like a bouncing ball.
*
* - remark: See http://easings.net for visual examples.
*
*/
public struct EasingBounce {
static let magic100 = 1.70158 * 10
public static func easeIn() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
let easing_closure = EasingBounce.easeOut()
let time = duration - elapsedTime
let easing_value = valueRange - easing_closure(time, 0.0, valueRange, duration) + startValue
return easing_value
}
return easing
}
public static func easeOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
var time = elapsedTime / duration
let easing_value: Double
if (time < (1/2.75)) {
easing_value = valueRange * (7.5625 * time*time) + startValue;
} else if (time < (2 / 2.75)) {
time -= (1.5 / 2.75);
easing_value = valueRange * (7.5625 * time*time + 0.75) + startValue;
} else if (time < (2.5/2.75)) {
time -= (2.25/2.75);
easing_value = valueRange * (7.5625 * time*time + 0.9375) + startValue;
} else {
time -= (2.625/2.75);
easing_value = valueRange * (7.5625 * time*time + 0.984375) + startValue;
}
return easing_value
}
return easing
}
public static func easeInOut() -> EasingUpdateClosure {
func easing (_ elapsedTime: TimeInterval, startValue: Double, valueRange: Double, duration: TimeInterval) -> Double {
let easing_value: Double
let easing_closure = EasingBounce.easeOut()
if (elapsedTime < (duration * 0.5)) {
easing_value = easing_closure((elapsedTime*2), 0, valueRange, duration) * 0.5 + startValue;
} else {
easing_value = easing_closure((elapsedTime*2-duration), 0, valueRange, duration) * 0.5 + (valueRange*0.5) + startValue;
}
return easing_value
}
return easing
}
}
| ba7dce61a64463dcde8f886c8f96a9c1 | 37.96875 | 135 | 0.612136 | false | false | false | false |
panadaW/MyNews | refs/heads/master | MyWb完善首页数据/MyWb/Class/Tool/FFlable.swift | mit | 1 | //
// FFlable.swift
// MyWb
//
// Created by 王明申 on 15/10/26.
// Copyright © 2015年 晨曦的Mac. All rights reserved.
//
import UIKit
@objc
public protocol FFLabelDelegate: NSObjectProtocol {
optional func labelDidSelectedLinkText(label: FFLabel, text: String)
}
public class FFLabel: UILabel {
public var linkTextColor = UIColor.blueColor()
public var selectedBackgroudColor = UIColor.lightGrayColor()
public weak var labelDelegate: FFLabelDelegate?
// MARK: - override properties
override public var text: String? {
didSet {
updateTextStorage()
}
}
override public var attributedText: NSAttributedString? {
didSet {
updateTextStorage()
}
}
override public var font: UIFont! {
didSet {
updateTextStorage()
}
}
override public var textColor: UIColor! {
didSet {
updateTextStorage()
}
}
// MARK: - upadte text storage and redraw text
private func updateTextStorage() {
if attributedText == nil {
return
}
let attrStringM = addLineBreak(attributedText!)
regexLinkRanges(attrStringM)
addLinkAttribute(attrStringM)
textStorage.setAttributedString(attrStringM)
setNeedsDisplay()
}
/// add link attribute
private func addLinkAttribute(attrStringM: NSMutableAttributedString) {
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range)
attributes[NSFontAttributeName] = font!
attributes[NSForegroundColorAttributeName] = textColor
attrStringM.addAttributes(attributes, range: range)
attributes[NSForegroundColorAttributeName] = linkTextColor
for r in linkRanges {
attrStringM.setAttributes(attributes, range: r)
}
}
/// use regex check all link ranges
private let patterns = ["[a-zA-Z]*://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"]
private func regexLinkRanges(attrString: NSAttributedString) {
linkRanges.removeAll()
let regexRange = NSRange(location: 0, length: attrString.string.characters.count)
for pattern in patterns {
let regex = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
let results = regex.matchesInString(attrString.string, options: NSMatchingOptions(rawValue: 0), range: regexRange)
for r in results {
linkRanges.append(r.rangeAtIndex(0))
}
}
}
/// add line break mode
private func addLineBreak(attrString: NSAttributedString) -> NSMutableAttributedString {
let attrStringM = NSMutableAttributedString(attributedString: attrString)
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributesAtIndex(0, effectiveRange: &range)
var paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle
if paragraphStyle != nil {
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
} else {
// iOS 8.0 can not get the paragraphStyle directly
paragraphStyle = NSMutableParagraphStyle()
paragraphStyle!.lineBreakMode = NSLineBreakMode.ByWordWrapping
attributes[NSParagraphStyleAttributeName] = paragraphStyle
attrStringM.setAttributes(attributes, range: range)
}
return attrStringM
}
public override func drawTextInRect(rect: CGRect) {
let range = glyphsRange()
let offset = glyphsOffset(range)
layoutManager.drawBackgroundForGlyphRange(range, atPoint: offset)
layoutManager.drawGlyphsForGlyphRange(range, atPoint: CGPointZero)
}
private func glyphsRange() -> NSRange {
return NSRange(location: 0, length: textStorage.length)
}
private func glyphsOffset(range: NSRange) -> CGPoint {
let rect = layoutManager.boundingRectForGlyphRange(range, inTextContainer: textContainer)
let height = (bounds.height - rect.height) * 0.5
return CGPoint(x: 0, y: height)
}
// MARK: - touch events
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInView(self)
selectedRange = linkRangeAtLocation(location)
modifySelectedAttribute(true)
}
public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let location = touches.first!.locationInView(self)
if let range = linkRangeAtLocation(location) {
if !(range.location == selectedRange?.location && range.length == selectedRange?.length) {
modifySelectedAttribute(false)
selectedRange = range
modifySelectedAttribute(true)
}
} else {
modifySelectedAttribute(false)
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if selectedRange != nil {
let text = (textStorage.string as NSString).substringWithRange(selectedRange!)
labelDelegate?.labelDidSelectedLinkText!(self, text: text)
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC)))
dispatch_after(when, dispatch_get_main_queue()) {
self.modifySelectedAttribute(false)
}
}
}
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
modifySelectedAttribute(false)
}
private func modifySelectedAttribute(isSet: Bool) {
if selectedRange == nil {
return
}
var attributes = textStorage.attributesAtIndex(0, effectiveRange: nil)
attributes[NSForegroundColorAttributeName] = linkTextColor
let range = selectedRange!
if isSet {
attributes[NSBackgroundColorAttributeName] = selectedBackgroudColor
} else {
attributes[NSBackgroundColorAttributeName] = UIColor.clearColor()
selectedRange = nil
}
textStorage.addAttributes(attributes, range: range)
setNeedsDisplay()
}
private func linkRangeAtLocation(location: CGPoint) -> NSRange? {
if textStorage.length == 0 {
return nil
}
let offset = glyphsOffset(glyphsRange())
let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y)
let index = layoutManager.glyphIndexForPoint(point, inTextContainer: textContainer)
for r in linkRanges {
if index >= r.location && index <= r.location + r.length {
return r
}
}
return nil
}
// MARK: - init functions
override public init(frame: CGRect) {
super.init(frame: frame)
prepareLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareLabel()
}
public override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
private func prepareLabel() {
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0
userInteractionEnabled = true
}
// MARK: lazy properties
private lazy var linkRanges = [NSRange]()
private var selectedRange: NSRange?
private lazy var textStorage = NSTextStorage()
private lazy var layoutManager = NSLayoutManager()
private lazy var textContainer = NSTextContainer()
}
| cbfc544ef279822053e6370322214eec | 32.04878 | 128 | 0.621033 | false | false | false | false |
xuech/OMS-WH | refs/heads/master | OMS-WH/Classes/Message/Controler/MessageViewController.swift | mit | 1 | //
// MessageViewController.swift
// OMSOwner
//
// Created by xuech on 2017/6/15.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import CoreData
//import INSPersistentContainer
class MessageViewController: UITableViewController {
@IBOutlet weak var rightItem: UIBarButtonItem!
lazy var messageArray:[MessageMO] = []
var fc : NSFetchedResultsController<MessageMO>!
var messageMO : MessageMO!
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var persistentContainer: NSPersistentContainer {
return ((UIApplication.shared.delegate as? AppDelegate)?.persistentContainer)!
}
var context: NSManagedObjectContext?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 70
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView()
fetchUpdateData()
}
//MARK: -获取方法
private func fetchUpdateData() {
//1、设置请求结果类型
let request : NSFetchRequest<MessageMO> = MessageMO.fetchRequest()
//2、设置请求结果的排序方式
request.sortDescriptors = [NSSortDescriptor(key: "messageDate", ascending: false)]
let context = appDelegate.persistentContainer.viewContext
fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fc.delegate = self
do {
try fc.performFetch()
if let object = fc.fetchedObjects {
messageArray.removeAll()
messageArray = object
rightItem.isEnabled = messageArray.count > 0 ? true : false
}
} catch {
print(error)
}
}
/// 清空所有数据
private func deleteAllMessage(){
let context = appDelegate.persistentContainer.viewContext
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try context.execute(deleteRequest)
try context.save()
messageArray.removeAll()
tableView.reloadData()
rightItem.isEnabled = messageArray.count > 0 ? true : false
} catch {
print ("There was an error")
}
}
@IBAction func insert(_ sender: UIBarButtonItem) {
let alertView = XCHAlertController(frame:CGRect(x: 0, y: 0, width: view.width, height: view.height + 64), title: "提示", message: "是否清空所有消息?")
let action = XCHAlertAction.init(title: "清空", style: XCHAlertActionStyle.normal) {
self.deleteAllMessage()
}
let cancelAction = XCHAlertAction.init(title: "取消", style: XCHAlertActionStyle.cancel)
alertView.addAction(action: cancelAction)
alertView.addAction(action: action)
KeyWindow.addSubview(alertView)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let nameLabel = cell.viewWithTag(-1) as? UILabel
let orderTitle = cell.viewWithTag(1) as? UILabel
let timeLabel = cell.viewWithTag(2) as? UILabel
let msg = messageArray[indexPath.row]
nameLabel?.text = msg.messageTitle
orderTitle?.text = msg.categoryName
let date = msg.messageDate?.components(separatedBy: " ")
timeLabel?.text = date?.first
nameLabel?.textColor = msg.isRead ? UIColor.lightGray : UIColor.black
orderTitle?.textColor = msg.isRead ? UIColor.lightGray : UIColor.black
timeLabel?.textColor = msg.isRead ? UIColor.lightGray : UIColor.black
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMessage"{
let dest = segue.destination as! MessageNotificationViewController
dest.msg = messageArray[tableView.indexPathForSelectedRow!.row]
dest.msg?.isRead = true
appDelegate.saveContext()
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
//删除数据源
deleteData(indexPath)
}
}
//MARK: -删除方法
private func deleteData(_ index: IndexPath) {
let context = appDelegate.persistentContainer.viewContext
context.delete(self.fc.object(at: index))
appDelegate.saveContext()
}
}
extension MessageViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
tableView.endUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?){
switch type {
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .automatic)
default:
break
}
//数据发生变化就同步到数组中去
if let object = controller.fetchedObjects {
messageArray = object as! [MessageMO]
}
}
}
| b5dfda092a00d325d4f4da0bb7010cc0 | 35.895706 | 199 | 0.651812 | false | false | false | false |
BluDotz/MenuDelDiaData | refs/heads/master | Eatery.swift | mit | 1 | //
// Eatery.swift
// MenuDelDiaData
//
// Created by hartpj on 14/01/2017.
// Copyright © 2017 BluDotz Ltd. All rights reserved.
//
import Foundation
import RealmSwift
public class Eatery: Object {
dynamic var name:String = ""
dynamic var latitude:Double = 0.0
dynamic var longitude:Double = 0.0
}
/**
Retrieve the path for a given file name in the documents directory
:param: fileName the name of the file in the documents directory
:returns: path of given fileName
*/
public func EateriesDocumentFilePathWithName(fileName: String) -> String {
#if os(iOS)
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
#else
var path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
if (ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil) {
var identifier = Bundle.main.bundleIdentifier
if (identifier == nil) {
identifier = (Bundle.main.executablePath! as NSString).lastPathComponent
}
path = path.appendingPathComponent(identifier!) as NSString
try! FileManager.default.createDirectory(atPath: (path as String), withIntermediateDirectories: true, attributes: nil)
}
#endif
return path.appendingPathComponent(fileName)
}
/**
Retrieve the path for the prebuilt MenuDelDiaEateries Realm file
:returns: path to MenuDelDiaEateries.realm
*/
public func MenuDelDiaEateriesPath() -> String {
let fileInDocuments = EateriesDocumentFilePathWithName(fileName: "MenuDelDiaEateries.realm")
if (!FileManager.default.fileExists(atPath: fileInDocuments)) {
let fileInBundle = Bundle(for: Eatery.self).path(forResource: "MenuDelDiaEateries", ofType: "realm")
let fileManager = FileManager.default
do {
try fileManager.copyItem(atPath: fileInBundle!, toPath: fileInDocuments)
} catch {
print("Copy File Error: \(error)")
}
do {
try fileManager.setAttributes([FileAttributeKey.posixPermissions : 0o644], ofItemAtPath: fileInDocuments)
} catch {
print("File Permission Error: \(error)")
}
}
return fileInDocuments
}
| 1782fa61205f078f99f1ca337ff0c612 | 31.576923 | 185 | 0.672963 | false | false | false | false |
StachkaConf/ios-app | refs/heads/develop | StachkaIOS/StachkaIOS/Classes/User Stories/Talks/PresentationInfo/View/PresentationInfoViewController.swift | mit | 1 | //
// FeedViewController.swift
// StachkaIOS
//
// Created by m.rakhmanov on 26.03.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import RxDataSources
class PresentationInfoViewController: UIViewController {
enum Constants {
static let title = "О докладе"
}
typealias PresentationDataSource = RxCustomTableViewDelegateDataSource<CellSectionModel>
fileprivate let heightCalculator = TableViewHeightCalculatorImplementation()
var viewModel: PresentationInfoViewModel?
private let disposeBag = DisposeBag()
private let dataSource = PresentationDataSource()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = Constants.title
setupTableView()
setupBindings()
}
private func setupTableView() {
tableView.register(PresentationInfoCell.self)
tableView.register(AuthorInfoCell.self)
tableView.register(AuthorBriefInfoCell.self)
tableView.register(PresentationDescriptionCell.self)
tableView.register(AuthorImageCell.self)
dataSource.configureCell = { (dataSource: TableViewSectionedDataSource<CellSectionModel>,
tableView: UITableView,
indexPath: IndexPath,
item: CellViewModel) in
let cell = tableView.dequeueCell(item.associatedCell)
cell.configure(with: item)
return cell as! UITableViewCell
}
dataSource.configureCellHeight = { [weak self] item, tableView, indexPath in
guard let strongSelf = self else { return 0 }
return strongSelf.heightCalculator.height(for: indexPath.row, viewModel: item, tableView: tableView)
}
//dataSource.titleForHeaderInSection = nil
}
private func setupBindings() {
viewModel?
.presentationModels
.bindTo(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx
.setDelegate(dataSource)
.disposed(by: disposeBag)
}
}
extension PresentationInfoViewController: PresentationInfoView {
}
| 23c91fa7757d90f50f471fedd4de92de | 30.465753 | 112 | 0.65825 | false | false | false | false |
danielsaidi/KeyboardKit | refs/heads/master | Sources/KeyboardKit/Keyboard/StandardKeyboardBehavior.swift | mit | 1 | //
// StandardKeyboardBehavior.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2020-12-28.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Foundation
/**
This class defines how a standard, Western keyboard behaves.
This class makes heavy use of default logic in for instance
the text document proxy. However, having this makes it easy
to change the actual behavior, if you want or need to.
You can inherit this class and override any open properties
and functions to customize the standard behavior.
*/
open class StandardKeyboardBehavior: KeyboardBehavior {
public init(
context: KeyboardContext,
doubleTapThreshold: TimeInterval = 0.2,
endSentenceThreshold: TimeInterval = 3.0) {
self.context = context
self.doubleTapThreshold = doubleTapThreshold
self.endSentenceThreshold = endSentenceThreshold
}
private let context: KeyboardContext
private let doubleTapThreshold: TimeInterval
private let endSentenceThreshold: TimeInterval
var lastShiftCheck = Date()
var lastSpaceTap = Date()
public func preferredKeyboardType(
after gesture: KeyboardGesture,
on action: KeyboardAction) -> KeyboardType {
if shouldSwitchToCapsLock(after: gesture, on: action) { return .alphabetic(.capsLocked) }
switch action {
case .shift: return context.keyboardType
default: return context.preferredKeyboardType
}
}
open func shouldEndSentence(
after gesture: KeyboardGesture,
on action: KeyboardAction) -> Bool {
guard gesture == .tap, action == .space else { return false }
let proxy = context.textDocumentProxy
let isNewWord = proxy.isCursorAtNewWord
let isNewSentence = proxy.isCursorAtNewSentence
let isClosable = (proxy.documentContextBeforeInput ?? "").hasSuffix(" ")
let isEndingTap = Date().timeIntervalSinceReferenceDate - lastSpaceTap.timeIntervalSinceReferenceDate < endSentenceThreshold
let shouldClose = isEndingTap && isNewWord && !isNewSentence && isClosable
lastSpaceTap = Date()
return shouldClose
}
open func shouldSwitchToCapsLock(
after gesture: KeyboardGesture,
on action: KeyboardAction) -> Bool {
guard action.isShift else { return false }
guard context.keyboardType.isAlphabetic else { return false }
let isDoubleTap = Date().timeIntervalSinceReferenceDate - lastShiftCheck.timeIntervalSinceReferenceDate < doubleTapThreshold
lastShiftCheck = Date()
return isDoubleTap
}
open func shouldSwitchToPreferredKeyboardType(
after gesture: KeyboardGesture,
on action: KeyboardAction) -> Bool {
switch action {
case .shift: return true
default: return context.keyboardType != context.preferredKeyboardType
}
}
public func shouldSwitchToPreferredKeyboardTypeAfterTextDidChange() -> Bool {
context.keyboardType != context.preferredKeyboardType
}
}
| a71ee083aadd863aa2d719c48847c8f7 | 35.388235 | 132 | 0.696088 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/FeatureApp/Sources/FeatureAppDomain/User/UserAdapter.swift | lgpl-3.0 | 1 | // Copyright © 2021 Blockchain Luxembourg S.A. All rights reserved.
import Combine
import FeatureProductsDomain
import Foundation
import PlatformKit
import ToolKit
/// A protocol to fetch and monitor changes in `UserState`
public protocol UserAdapterAPI {
/// A publisher that streams `UserState` values on subscription and on change.
var userState: AnyPublisher<Result<UserState, UserStateError>, Never> { get }
}
private typealias RawUserData = (
kycStatus: UserState.KYCStatus,
paymentMethods: [UserState.PaymentMethod],
hasEverPurchasedCrypto: Bool,
products: [ProductValue]
)
public final class UserAdapter: UserAdapterAPI {
public let userState: AnyPublisher<Result<UserState, UserStateError>, Never>
public init(
kycTiersService: KYCTiersServiceAPI,
paymentMethodsService: PaymentMethodTypesServiceAPI,
productsService: ProductsServiceAPI,
ordersService: OrdersServiceAPI
) {
let streams = kycTiersService.kycStatusStream
.combineLatest(
paymentMethodsService.paymentMethodsStream,
ordersService.hasPurchasedAnyCryptoStream
)
.combineLatest(productsService.productsStream)
userState = streams
.map { results -> Result<RawUserData, UserStateError> in
let (r1, r2) = results
let (kycStatusResult, paymentMethodsResult, hasEverPurchasedCryptoResult) = r1
let products = r2
return kycStatusResult.zip(
paymentMethodsResult,
hasEverPurchasedCryptoResult,
products
)
.map { $0 } // this makes the compiler happy by making a generic tuple be casted to RawUserData
}
.map { zippedResult -> Result<UserState, UserStateError> in
zippedResult.map { kycStatus, paymentMethods, hasEverPurchasedCrypto, products in
UserState(
kycStatus: kycStatus,
linkedPaymentMethods: paymentMethods,
hasEverPurchasedCrypto: hasEverPurchasedCrypto,
products: products
)
}
}
.removeDuplicates()
.shareReplay()
}
}
// MARK: - Helpers
extension UserState.KYCStatus {
fileprivate init(userTiers: KYC.UserTiers, isSDDVerified: Bool) {
if userTiers.isTier2Approved {
self = .gold
} else if userTiers.isTier2Pending {
self = .inReview
} else if userTiers.isTier1Approved, isSDDVerified {
self = .silverPlus
} else if userTiers.isTier1Approved {
self = .silver
} else {
self = .unverified
}
}
}
extension KYCTiersServiceAPI {
fileprivate var kycStatusStream: AnyPublisher<Result<UserState.KYCStatus, UserStateError>, Never> {
let checkSDDVerification = checkSimplifiedDueDiligenceVerification(for:pollUntilComplete:)
return tiersStream
.mapError(UserStateError.missingKYCInfo)
.flatMap { tiers -> AnyPublisher<(KYC.UserTiers, Bool), UserStateError> in
Just(tiers)
.setFailureType(to: UserStateError.self)
.zip(
checkSDDVerification(tiers.latestApprovedTier, false)
.mapError(UserStateError.missingKYCInfo)
)
.eraseToAnyPublisher()
}
.map(UserState.KYCStatus.init)
.mapToResult()
}
}
extension PaymentMethodTypesServiceAPI {
fileprivate var paymentMethodsStream: AnyPublisher<Result<[UserState.PaymentMethod], UserStateError>, Never> {
paymentMethodTypesValidForBuyPublisher
.mapError(UserStateError.missingPaymentInfo)
.map { paymentMethods -> [UserState.PaymentMethod] in
paymentMethods.compactMap { paymentMethodType -> UserState.PaymentMethod? in
guard !paymentMethodType.isSuggested else {
return nil
}
return UserState.PaymentMethod(
id: paymentMethodType.id,
label: paymentMethodType.label
)
}
}
.mapToResult()
}
}
extension OrdersServiceAPI {
fileprivate var hasPurchasedAnyCryptoStream: AnyPublisher<Result<Bool, UserStateError>, Never> {
hasUserMadeAnyPurchases
.mapError(UserStateError.missingPurchaseHistory)
.mapToResult()
}
}
extension ProductsServiceAPI {
fileprivate var productsStream: AnyPublisher<Result<[ProductValue], UserStateError>, Never> {
streamProducts().map { result in
result.mapError(UserStateError.missingProductsInfo)
}
.eraseToAnyPublisher()
}
}
| 6171de9e75afd4db5ca269634450ecf0 | 33.965035 | 114 | 0.6134 | false | false | false | false |
Laurensesss/Learning-iOS-Programming-with-Swift | refs/heads/master | Project05_DynamicGravity/DynamicGravity/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// DynamicGravity
//
// Created by 石韬 on 16/4/8.
// Copyright © 2016年 石韬. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var dynamicAnimator = UIDynamicAnimator()
@IBAction func buttonTapped(sender: UIButton) {
dynamicAnimator = UIDynamicAnimator(referenceView: self.view)
//创造并添加重力行为
let gravityBehavior = UIGravityBehavior(items: [self.imageView])
dynamicAnimator.addBehavior(gravityBehavior)
//创建并添加碰撞行为
let collisionBehavior = UICollisionBehavior(items: [self.imageView])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
dynamicAnimator.addBehavior(collisionBehavior)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 26e7cc22aa2b553ea78efb744b2dc2b5 | 23.170732 | 72 | 0.731584 | false | false | false | false |
tianbinbin/DouYuShow | refs/heads/master | DouYuShow/DouYuShow/Classes/Main/View/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/5/30.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85) // 灰色
private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0) // 橘色
//协议代理
protocol PageTitleViewDelegate:class{
// selectindex index selectindex 作为外部参数 index 作为内部参数
func pageTitle(titleView:PageTitleView,selectindex index:Int)
}
class PageTitleView: UIView {
// mark: 定义属性
fileprivate var titles : [String]
fileprivate var currentIndex:Int = 0
weak var delegate : PageTitleViewDelegate?
// mark: 懒加载属性
fileprivate lazy var titlelabels:[UILabel] = [UILabel]()
fileprivate lazy var scrollView:UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.isPagingEnabled = false
scrollView.bounces = false
return scrollView
}()
// mark: 滚动的线
fileprivate lazy var ScrollLine:UIView = {
let ScrollLine = UIView()
ScrollLine.backgroundColor = UIColor.orange
return ScrollLine
}()
// mark: 自定义构造函数
init(frame: CGRect,titles:[String]) {
self.titles = titles
super.init(frame:frame)
//1.设置UI界面
SetUPUI()
}
// 重写 init 构造函数一定要实现这个方法
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
fileprivate func SetUPUI(){
// 1.添加scrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2.添加label
SetUpTitleLabels()
// 3.设置底线和滚动的滑块
SetUpBootomlineAndScrollLine()
}
private func SetUpTitleLabels(){
let labelW:CGFloat = frame.width/CGFloat(titles.count)
let labelH:CGFloat = frame.height - kScrollLineH
let labelY:CGFloat = 0
for (index,title) in titles.enumerated() {
// 1.创建lb
let label = UILabel()
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 )
label.textAlignment = .center
let labelX:CGFloat = labelW * CGFloat(index)
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titlelabels.append(label)
// 2.给lb添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titltLabelClick(_:)))
label.addGestureRecognizer(tapGes)
}
}
private func SetUpBootomlineAndScrollLine(){
//1.添加底线
let bootomLine = UIView()
bootomLine.backgroundColor = UIColor.lightGray
let lineH:CGFloat = 0.5
bootomLine.frame = CGRect(x: 0, y: frame.height-lineH, width: frame.width, height: lineH)
addSubview(bootomLine)
//2.添加滚动的线
//2.1 获取第一个lable
guard let firstlabel = titlelabels.first else { return }
firstlabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//2.2 设置ScrollLine的属性
scrollView.addSubview(ScrollLine)
ScrollLine.frame = CGRect(x: firstlabel.frame.origin.x, y: frame.height-kScrollLineH, width: firstlabel.frame.width, height: kScrollLineH)
}
}
extension PageTitleView{
@objc fileprivate func titltLabelClick(_ tapGes:UITapGestureRecognizer){
//1. 获取当前label 的 下标值
guard let currentlb = tapGes.view as? UILabel else { return }
//2. 获取之前的lb
let olderLabel = titlelabels[currentIndex]
//3. 保存最新lb的下标值
currentIndex = currentlb.tag
//4. 切换文字的颜色
currentlb.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
olderLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2 )
//5. 滚动条的位置发生改变
let scrollLinePosition = CGFloat(currentlb.tag) * ScrollLine.frame.width
UIView.animate(withDuration: 0.25) {
self.ScrollLine.frame.origin.x = scrollLinePosition
}
//6.通知代理
delegate?.pageTitle(titleView: self, selectindex: currentIndex)
}
}
// 对外暴漏的方法
extension PageTitleView{
func SetTitleViewProgress(progress:CGFloat,sourceIndex:Int,targetIndex:Int) {
//1.取出对应的sourcelabel/targetlabel
let sourcelabel = titlelabels[sourceIndex]
let targetlabel = titlelabels[targetIndex]
//2.处理滑块逻辑
let moveTotalX = targetlabel.frame.origin.x - sourcelabel.frame.origin.x
let moveX = moveTotalX * progress
ScrollLine.frame.origin.x = sourcelabel.frame.origin.x + moveX
//3.颜色渐变( 复杂 )
let colorDelta = (kSelectColor.0-kNormalColor.0,kSelectColor.1-kNormalColor.1,kSelectColor.2-kNormalColor.2)
sourcelabel.textColor = UIColor(r: kSelectColor.0 - colorDelta.0 * progress, g: kSelectColor.1 - colorDelta.0 * progress, b: kSelectColor.2 - colorDelta.0 * progress)
targetlabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.0 * progress, b: kNormalColor.2 - colorDelta.0 * progress)
currentIndex = targetIndex
}
}
| 0af3a5bb81ff8a1af78349f9a298921e | 30.07027 | 174 | 0.622129 | false | false | false | false |
Matthijn/swift8 | refs/heads/master | Swift8/Keyboard.swift | mit | 1 | //
// Keyboard.swift
// Swift8
//
// Created by Matthijn Dijkstra on 18/08/15.
// Copyright © 2015 Matthijn Dijkstra. All rights reserved.
//
import Cocoa
class Keyboard
{
// Mapping ASCII keycodes to the Chip8 key codes
let mapping : [UInt8: Int8] = [
18: 0x1, // 1
19: 0x2, // 2
20: 0x3, // 3
21: 0xC, // 4
12: 0x4, // q
13: 0x5, // w
14: 0x6, // e
15: 0xD, // r
0: 0x7, // a
1: 0x8, // s
2: 0x9, // d
3: 0xE, // f
6: 0xA, // z
7: 0x0, // x
8: 0xB, // c
9: 0xF, // v
]
var currentKey : Int8 = -1
func keyUp(_ event: NSEvent)
{
// Key stopped being pressed so setting current key to -1 to represent nothing
self.currentKey = -1
}
func keyDown(_ event: NSEvent)
{
// Setting the current key as the mapped key
if let mappedKey = self.mapping[UInt8(event.keyCode)]
{
self.currentKey = mappedKey
}
}
}
| aee80872e84634daab248bbb28b23913 | 19.823529 | 86 | 0.475518 | false | false | false | false |
CocoaHeadsConference/CHConferenceApp | refs/heads/develop | NSBrazilConf/Views/Home/Feed/TitleHeaderView.swift | mit | 1 |
import SwiftUI
struct TitleHeaderView: View {
init?(feedItem: FeedItem) {
guard let item = feedItem as? SubtitleFeedItem else { return nil }
title = item.text
subtitle = item.subtext
}
init(title: String, subtitle: String) {
self.title = title
self.subtitle = subtitle
}
var title: String
var subtitle: String
var body: some View {
ZStack(alignment: .leading) {
VStack(alignment: .leading, spacing: 8) {
Text(title)
.font(.largeTitle)
.fontWeight(.bold)
.minimumScaleFactor(0.5)
.frame(minHeight: 0, maxHeight: 90)
Text(subtitle)
.font(.body)
.foregroundColor(.gray)
}
}
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 10)
}
}
struct TitleHeaderView_Previews: PreviewProvider {
static var previews: some View {
TitleHeaderView(title: "Pra você que chegou até aqui:", subtitle: "Eu vou escrever um texto grande pra ocupar bastante espaço mas eu acho que tá tudo bem porque o texto é bem grande mesmo sabe")
}
}
| 2bbf991e5039cc26bff3a085f80c1add | 28.833333 | 202 | 0.56664 | false | false | false | false |
smittysmee/NetworkNotifier | refs/heads/master | NetworkNotfier.swift | apache-2.0 | 1 | //
// NetworkNotifier.swift
// E-App
//
// Created by Alex Smith on 2/17/16.
// Copyright © 2016 Alex Smith. All rights reserved.
// See LICENSE for licensing information
//
import Foundation
class NetworkNotifier:NSObject{
let kNetworkNotifierNotification = "kNetworkNotifierNotificationKey"
var remoteHostName:String!
private var _currentStatus:NetworkStatus!
var currentStatus:NetworkStatus!{
get{
return _currentStatus
}set(newStatus){
/* Check if it is the same status as previous */
if newStatus == _currentStatus{
return
}
/* The status is not the same */
_currentStatus = newStatus
/* Post notifications */
networkStatusChanged()
}
}
private var notifierEnabled:Bool = false
private var reachables:[Reachability]!
init(withHost host:String) {
/* Call the super */
super.init()
/* Initialize the array */
reachables = [Reachability]()
remoteHostName = host
/* Setup Notifiers */
setupNotifiers()
}
deinit {
/* Remove the notifiers */
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func startNotifier(){
notifierEnabled = true
}
func stopNotifier(){
notifierEnabled = false
}
func setupNotifiers(){
/* Create the notifcations for reachability */
NSNotificationCenter.defaultCenter().addObserver(self, selector:"reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
/* Remote Host */
let hostReachability:Reachability = Reachability(hostName: remoteHostName)
hostReachability.startNotifier()
reachables.append(hostReachability)
// /* Internet Connection */
// let internetReachability:Reachability = Reachability.reachabilityForInternetConnection()
// internetReachability.startNotifier()
// reachables.append(internetReachability)
//
// /* Wifi */
// let wifiReachability = Reachability.reachabilityForLocalWiFi()
// wifiReachability.startNotifier()
// reachables.append(wifiReachability)
}
func reachabilityChanged(notification: NSNotification) {
/* Grab the reachability object */
if let reachability = notification.object as? Reachability{
/* Perform updates on the UI */
let networkStatus = reachability.currentReachabilityStatus()
/* Set the newtwork Status */
currentStatus = networkStatus
}
}
func networkStatusChanged(){
/* Ensure that have the notification post enabled */
if !notifierEnabled{
return
}
/* Update the status */
switch(currentStatus){
case NotReachable:
print("not reachable")
break
case ReachableViaWiFi:
print("wifi")
break
case ReachableViaWWAN:
print("wan")
break
default:
break
}
/* Create the user dictionary */
let userInfo:Dictionary<String, AnyObject> = [
"networkStatus": currentStatus.rawValue
]
/* Post the notification */
NSNotificationCenter.defaultCenter().postNotificationName(kNetworkNotifierNotification, object: nil, userInfo: userInfo)
}
}
| 286214b13253b709feed3bdf27f6f838 | 28.040323 | 148 | 0.59178 | false | false | false | false |
ajsnow/Shear | refs/heads/master | Shear/Transform.swift | mit | 1 | // Copyright 2016 The Shear Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
import Foundation
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
public extension TensorProtocol {
/// Returns a new Tensor with the contents of `self` with `shape`.
func reshape(_ shape: [Int]) -> Tensor<Element> {
// REMOVE DEFENSIVE CONVERSION LATER
return Tensor(shape: shape, tensor: Tensor(self))
}
/// Returns a new Tensor with the contents of `self` as a vector.
func ravel() -> Tensor<Element> {
return reshape([Int(allElements.count)])
}
/// Reverse the order of Elements along the last axis (columns).
func reverse() -> Tensor<Element> {
return self.vectorMap(byRows: true, transform: { $0.reversed() } )
}
/// Reverse the order of Elements along the first axis.
func flip() -> Tensor<Element> {
return self.vectorMap(byRows: false, transform: { $0.reversed() } )
}
/// Returns a Tensor whose dimensions are reversed.
func transpose() -> Tensor<Element> {
return Tensor(shape: shape.reversed(), cartesian: {indices in
self[indices.reversed()]
})
}
/// Returns a Tensor whose dimensions map to self's dimensions specified each member of `axes`.
/// The axes array must have the same count as self's rank, and must contain all 0...axes.maxElement()
func transpose(_ axes: [Int]) -> Tensor<Element> {
guard axes.max() < rank else { fatalError("Yo") }
guard axes.count == rank else { fatalError("Yo") }
var alreadySeen: Set<Int> = []
let newShape = axes.flatMap { axis -> Int? in
if alreadySeen.contains(axis) { return nil }
alreadySeen.insert(axis)
return shape[axis]
}
guard alreadySeen.elementsEqual(0...axes.max()!) else { fatalError("Yo") }
return Tensor(shape: newShape, cartesian: { indices in
let originalIndices = axes.map { indices[$0] }
return self[originalIndices]
})
}
/// Returns a DenseTensor whose columns are shifted `count` times.
func rotate(_ count: Int) -> Tensor<Element> {
return vectorMap(byRows: true, transform: {$0.rotate(count)})
}
/// Returns a DenseTensor whose first dimension's elements are shifted `count` times.
func rotateFirst(_ count: Int) -> Tensor<Element> {
return vectorMap(byRows: false, transform: {$0.rotate(count)})
}
}
| 4bc4f093167939c98d0fd92ca280ca45 | 34.91358 | 106 | 0.621863 | false | false | false | false |
segej87/ecomapper | refs/heads/master | iPhone/EcoMapper/EcoMapper/LoginViewController.swift | gpl-3.0 | 2 | //
// LoginViewController.swift
// EcoMapper
//
// Created by Jon on 6/29/16.
// Copyright © 2016 Sege Industries. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate {
// MARK: Class Variables
/*
UI References
*/
@IBOutlet weak var usernameView: UITextField!
@IBOutlet weak var passwordView: UITextField!
@IBOutlet weak var activityView: UIActivityIndicatorView!
@IBOutlet weak var loginButton: UIButton!
// MARK: Initialization
override func viewDidLoad() {
super.viewDidLoad()
if NetworkTests.reachability == nil {
NetworkTests.setupReachability(nil)
}
// Set up the login form.
usernameView.delegate = self
passwordView.delegate = self
// Set targets to monitor the text fields for changes.
for t in [usernameView, passwordView] {
t?.addTarget(self, action: #selector(LoginViewController.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
}
// Deactivate the login button when username and password are blank
loginButton.isEnabled = false
}
// MARK: UITextField Delegates
// Method to allow activation of the login button as the text fields change
func textFieldDidChange(_ textField: UITextField) {
// If a username and password have been provided, enable the login button
if usernameView.text != "" && passwordView.text != "" {
loginButton.isEnabled = true
} else {
loginButton.isEnabled = false
}
}
// Hides the keyboard when the text field is returned
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
//Hide the keyboard.
textField.resignFirstResponder()
if usernameView.text != "" && passwordView.text != "" {
loginButton.isEnabled = true
} else {
loginButton.isEnabled = false
}
return true
}
// MARK: Navigation
// Actions to perform before segue away from login view controller
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Print login status to log.
NSLog("Logging in to username \(UserVars.UName!) with \(sender!)")
}
// MARK: Actions
@IBAction func tryLogin(_ sender: UIButton) {
// Start the activity indicator
activityView.startAnimating()
// Try to login
self.attemptLogin()
}
// MARK: Login authentication
func attemptLogin() {
// Get user-entered info from text fields
let uname = usernameView.text
let pword = passwordView.text
// Check if the device is connected. If not, stop and present an error
guard let reach = NetworkTests.reachability
else {
NetworkTests.setupReachability(nil)
return
}
if reach.isReachable() {
checkCredentialsAndGetUUID(uname!, pword: pword!)
} else {
// Stop the activity indicator
self.activityView.stopAnimating()
// Present an error message indicating that there is no connection
showAlertDialog(title: "Network Error", message: "Make sure you are connected to the Internet")
}
}
// MARK: Server Ops
func checkCredentialsAndGetUUID(_ uname: String, pword: String) {
// Initialize a request to the server-side PHP script, and define the method as POST
let request = NSMutableURLRequest(url: URL(string: UserVars.authScript)!)
request.httpMethod = "POST"
// Create the POST string with necessary variables, and put in HTTP body
let postString = "username=\(uname)&password=\(pword)"
request.httpBody = postString.data(using: String.Encoding.utf8)
// Create a session with the PHP script, and attempt to login
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
// Make sure there are no errors creating the session and that some data is being passed
guard error == nil && data != nil else {
NSLog("Login error: \(error!)")
return
}
// Check if HTTP response code is 200 ("OK"). If not, print an error
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 {
NSLog("Unexpected http status code: \(httpStatus.statusCode)")
NSLog("Login server response: \(response!)")
}
// Get the PHP script's response to the session
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
// Perform rest of login procedure after background server session finishes
DispatchQueue.main.async {
// Boolean to check whether the server's response was nil, or whether an error was returned
let loginSuccess = responseString != nil && !responseString!.contains("Error")
/* If the login attempt was successful, set the UUID User Variable and load lists. If the attempt was unsuccessful, present an alert with the login error.
*/
if loginSuccess {
// Set the instance property loginString to the server's response
UserVars.UUID = responseString?.lowercased
if UserVars.loadUserVars(uuid: UserVars.UUID!) {
NSLog("Loading user variables")
}
UserVars.UName = self.usernameView.text
self.getListsUsingUUID(UserVars.UUID!, sender: "new login")
} else {
// Stop the activity indicator
self.activityView.stopAnimating()
/* If the login wasn't successful, check if the response contains the word Error,
as configured on the PHP server
*/
var errorString: String?
if responseString!.contains("Error") {
errorString = responseString!.replacingOccurrences(of: "Error: ", with: "")
} else {
errorString = "Network Error - check your Internet connection"
}
// Present the error to the user
self.showAlertDialog(title: "Login Error", message: errorString!)
}
}
})
task.resume()
}
func getListsUsingUUID(_ uuid: String, sender: String) {
// Establish a request to the server-side PHP script, and define the method as POST
let request = NSMutableURLRequest(url: URL(string: UserVars.listScript)!)
request.httpMethod = "POST"
// Create the POST string with necessary variables, and put in HTTP body
let postString = "GUID=\(uuid)"
request.httpBody = postString.data(using: String.Encoding.utf8)
// Create a session with the PHP script, and attempt to login
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
// Make sure there are no errors creating the session and that some data is being passed
guard error == nil && data != nil else {
print("Login list retrieve error: \(error!)")
return
}
// Check if HTTP response code is 200 ("OK"). If not, print an error
if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 {
print("Unexpected http status code: \(httpStatus.statusCode)")
print("Login list response: \(response!)")
}
// Get the PHP script's response to the session
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
// Perform rest of login procedure after background server session finishes
DispatchQueue.main.async {
// For reference, print the response string to the log
NSLog("List server response: \(responseString!)")
// Boolean to check whether the server's response was nil, or whether an error was returned
let listSuccess = responseString! != "" && !responseString!.contains("Error")
// If the attempt was successful, set the User Variables and segue to the notebook view controller. If the attempt was unsuccessful, present an alert dialog.
if listSuccess {
do {
// Encode the response string as data, then parse JSON
let responseData = responseString!.data(using: String.Encoding.utf8.rawValue)
let responseArray = try JSONSerialization.jsonObject(with: responseData!, options: JSONSerialization.ReadingOptions()) as! [String:AnyObject]
// Mesh the server's response with saved user variables
UserVars.meshUserVars(array: responseArray)
// Write the user variables to the login object and save
UserVars.saveLogin(loginInfo: LoginInfo(uuid: UserVars.UUID))
// Save the user variables
UserVars.saveUserVars()
// Stop the activity indicator
self.activityView.stopAnimating()
// Perform a segue to the notebook view controller
self.performSegue(withIdentifier: "Notebook", sender: sender)
} catch let error as NSError {
NSLog("Login list retrieve parse error: \(error.localizedDescription)")
}
} else {
// Stop the activity indicator
self.activityView.stopAnimating()
// Show the error to the user as an alert controller
var errorString: String?
if responseString!.contains("Error") {
errorString = responseString!.replacingOccurrences(of: "Error: ",with: "")
} else {
errorString = "Network Error - check your Internet connection"
}
self.showAlertDialog(title: "Login Error", message: errorString!)
}
}
})
task.resume()
}
// MARK: Helper Methods
func showAlertDialog(title: String, message: String) {
if #available(iOS 9.0, *) {
let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertVC.addAction(okAction)
self.present(alertVC, animated: true, completion: nil)
} else {
let alertVC = UIAlertView(title: title, message: message, delegate: self, cancelButtonTitle: "OK")
alertVC.show()
}
}
}
| e5de93aeea5bf5aa29a9dc8c156ada3f | 41.384342 | 173 | 0.559278 | false | false | false | false |
Osis/cf-apps-ios | refs/heads/master | CF Apps/AppDelegate.swift | mit | 1 | import UIKit
import CFoundry
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
if let account = Session.account() {
CFApi.login(account: account) { error in
if error == nil {
let _ = self.showAppsScreen()
}
}
}
return true
}
internal func showAppsScreen() -> AppsViewController {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let navController = storyboard.instantiateViewController(withIdentifier: "NavController") as! UINavigationController
let appsController = storyboard.instantiateViewController(withIdentifier: "AppsView") as! AppsViewController
self.window!.rootViewController = navController
navController.pushViewController(appsController, animated: false)
return appsController
}
}
| 51587a4799c5bf4b7f917ffc34af6056 | 33.090909 | 151 | 0.656 | false | false | false | false |
dymx101/Gamers | refs/heads/master | Gamers/Service/LiveBL.swift | apache-2.0 | 1 | //
// LiveBL.swift
// Gamers
//
// Created by 虚空之翼 on 15/8/12.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import Foundation
import Alamofire
import Bolts
import SwiftyJSON
class LiveBL: NSObject {
// 单例模式
static let sharedSingleton = LiveBL()
// 直播列表
func getLive(#page: Int, limit: Int) -> BFTask {
var fetchTask = BFTask(result: nil)
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return LiveDao.getLive(page: page, limit: limit)
})
fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in
if let games = task.result as? [Live] {
return BFTask(result: games)
}
if let response = task.result as? Response {
return BFTask(result: response)
}
return task
})
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return task
})
return fetchTask
}
// 获取twitch直播地址
func getTwitchStreamsURL(#channelId: String) -> BFTask {
var fetchTask = BFTask(result: nil)
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return LiveDao.getStreamsToken(channelId: channelId)
})
fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in
if let token = task.result as? TwitchToken {
var customAllowedSet = NSCharacterSet(charactersInString:"\",:[]{}").invertedSet
var escapedString = token.token.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
var streamsURLString = "http://usher.twitch.tv/api/channel/hls/\(channelId).m3u8?player=twitchweb&token=\(escapedString!)&sig=\(token.sig)"
//println(streamsURLString)
return BFTask(result: streamsURLString)
}
return task
})
fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in
return task
})
return fetchTask
}
}
| ea7c5d64dbcdc725d4c009d2bd16b7e0 | 28.473684 | 155 | 0.562054 | false | false | false | false |
RxSwiftCommunity/RxMKMapView | refs/heads/development | Carthage/Carthage/Checkouts/Nimble/Sources/Nimble/Matchers/SatisfyAnyOf.swift | mit | 7 | /// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
public func satisfyAnyOf<T>(_ predicates: Predicate<T>...) -> Predicate<T> {
return satisfyAnyOf(predicates)
}
/// A Nimble matcher that succeeds when the actual value matches with any of the matchers
/// provided in the variable list of matchers.
@available(*, deprecated, message: "Use Predicate instead")
public func satisfyAnyOf<T, U>(_ matchers: U...) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return satisfyAnyOf(matchers.map { $0.predicate })
}
internal func satisfyAnyOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return Predicate.define { actualExpression in
var postfixMessages = [String]()
var matches = false
for predicate in predicates {
let result = try predicate.satisfies(actualExpression)
if result.toBoolean(expectation: .toMatch) {
matches = true
}
postfixMessages.append("{\(result.message.expectedMessage)}")
}
var msg: ExpectationMessage
if let actualValue = try actualExpression.evaluate() {
msg = .expectedCustomValueTo(
"match one of: " + postfixMessages.joined(separator: ", or "),
actual: "\(actualValue)"
)
} else {
msg = .expectedActualValueTo(
"match one of: " + postfixMessages.joined(separator: ", or ")
)
}
return PredicateResult(bool: matches, message: msg)
}
}
public func || <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
@available(*, deprecated, message: "Use Predicate instead")
public func || <T>(left: NonNilMatcherFunc<T>, right: NonNilMatcherFunc<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
@available(*, deprecated, message: "Use Predicate instead")
public func || <T>(left: MatcherFunc<T>, right: MatcherFunc<T>) -> Predicate<T> {
return satisfyAnyOf(left, right)
}
#if canImport(Darwin)
import class Foundation.NSObject
extension NMBPredicate {
@objc public class func satisfyAnyOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
return NMBPredicate { actualExpression in
if matchers.isEmpty {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
fail: "satisfyAnyOf must be called with at least one matcher"
)
)
}
var elementEvaluators = [Predicate<NSObject>]()
for matcher in matchers {
let elementEvaluator = Predicate<NSObject> { expression in
if let predicate = matcher as? NMBPredicate {
// swiftlint:disable:next line_length
return predicate.satisfies({ try expression.evaluate() }, location: actualExpression.location).toSwift()
} else {
let failureMessage = FailureMessage()
let success = matcher.matches(
// swiftlint:disable:next force_try
{ try! expression.evaluate() },
failureMessage: failureMessage,
location: actualExpression.location
)
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
}
}
elementEvaluators.append(elementEvaluator)
}
return try satisfyAnyOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
| d5db34eaba24c396f164c2cc9b46ad50 | 39.701031 | 128 | 0.576494 | false | false | false | false |
lizhaojie001/TestCode | refs/heads/master | 项目主体---农事无忧/CollectionViewDemo-swift/CollectionViewDemo-swift/FlickrPhotosViewController.swift | apache-2.0 | 1 | import UIKit
final class FlickrPhotosViewController: UICollectionViewController {
// MARK: - Properties
fileprivate let reuseIdentifier = "FlickrCell"
fileprivate let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)
fileprivate var searches = [FlickrSearchResults]()
fileprivate let flickr = Flickr()
fileprivate let itemsPerRow: CGFloat = 3
}
// MARK: - Private
private extension FlickrPhotosViewController {
func photoForIndexPath(indexPath: IndexPath) -> FlickrPhoto {
return searches[(indexPath as NSIndexPath).section].searchResults[(indexPath as IndexPath).row]
}
}
extension FlickrPhotosViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// 1
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
textField.addSubview(activityIndicator)
activityIndicator.frame = textField.bounds
activityIndicator.startAnimating()
flickr.searchFlickrForTerm(textField.text!) {
results, error in
activityIndicator.removeFromSuperview()
if let error = error {
// 2
print("Error searching : \(error)")
return
}
if let results = results {
// 3
print("Found \(results.searchResults.count) matching \(results.searchTerm)")
self.searches.insert(results, at: 0)
// 4
self.collectionView?.reloadData()
}
}
textField.text = nil
textField.resignFirstResponder()
return true
}
}
// MARK: - UICollectionViewDataSource
extension FlickrPhotosViewController {
//1
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return searches.count
}
//2
override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return searches[section].searchResults.count
}
//3
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//1
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
for: indexPath) as! FilikrPhotoCell
//2
let flickrPhoto = photoForIndexPath(indexPath: indexPath)
cell.backgroundColor = UIColor.white
//3
cell.imageView.image = flickrPhoto.thumbnail
return cell
}
}
extension FlickrPhotosViewController : UICollectionViewDelegateFlowLayout {
//1
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
//2
let paddingSpace = sectionInsets.left * (itemsPerRow + 1)
let availableWidth = view.frame.width - paddingSpace
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: widthPerItem)
}
//3
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
// 4
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return sectionInsets.left
}
}
| af3323d2bdd56d206ed77ce48c8ff914 | 33.776786 | 130 | 0.616431 | false | false | false | false |
BananosTeam/CreativeLab | refs/heads/master | OAuthSwift-0.5.2/OAuthSwiftDemo/Services.swift | mit | 3 | //
// Services.swift
// OAuthSwift
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
// Class which contains services parameters like consumer key and secret
typealias ServicesValue = String
class Services {
var parameters : [String: [String: ServicesValue]]
init() {
self.parameters = [:]
}
subscript(service: String) -> [String:ServicesValue]? {
get {
return parameters[service]
}
set {
if let value = newValue where !Services.parametersEmpty(value) {
parameters[service] = value
}
}
}
func loadFromFile(path: String) {
if let newParameters = NSDictionary(contentsOfFile: path) as? [String: [String: ServicesValue]] {
for (service, dico) in newParameters {
if parameters[service] != nil && Services.parametersEmpty(dico) { // no value to set
continue
}
updateService(service, dico: dico)
}
}
}
func updateService(service: String, dico: [String: ServicesValue]) {
var resultdico = dico
if let oldDico = self.parameters[service] {
resultdico = oldDico
resultdico += dico
}
self.parameters[service] = resultdico
}
static func parametersEmpty(dico: [String: ServicesValue]) -> Bool {
return Array(dico.values).filter({ (p) -> Bool in !p.isEmpty }).isEmpty
}
var keys: [String] {
return Array(self.parameters.keys)
}
}
func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
} | 547f1c8d7b8940fa03839517808f0bb9 | 26.584615 | 114 | 0.577567 | false | false | false | false |
followmoe/EMA02 | refs/heads/master | EMA02_ToDoApp/ManageCategorysTableViewController.swift | mit | 1 | //
// ManageCategorysTableViewController.swift
// EMA02_ToDoApp
//
// Created by Moritz Müller on 28.05.17.
// Copyright © 2017 Moritz Müller. All rights reserved.
//
import UIKit
import RealmSwift
class ManageCategorysTableViewController: UITableViewController, CategoryDetailDelegate {
var category: Results<Category>?
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
if let category = category, category.count > 0 {
tableView.reloadData()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
category = realm.objects(Category.self)
if let category = category, category.count > 0 {
tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func saveButtonTapped(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if let category = category {
return category.count
} else {
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "showCategories", for: indexPath) as! ShowAllCategorysTableViewCell
if let category = category {
cell.textLabel?.text = category[indexPath.row].title
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let category = category {
let newCategory = category[indexPath.row]
performSegue(withIdentifier: "editCategory", sender: newCategory)
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Categories"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "editCategory" {
if let navigationController = segue.destination as? UINavigationController, let destination = navigationController.topViewController as? DetailCategoryTableViewController {
if let category = sender as? Category {
destination.category = category
}
destination.editLabel = "Edit the Category:"
destination.title = "Edit Category"
destination.delegate = self
}
}
if segue.identifier == "addCategory" {
if let navigationController = segue.destination as? UINavigationController, let destination = navigationController.topViewController as? DetailCategoryTableViewController {
destination.delegate = self
destination.title = "Add Category"
destination.editLabel = "Add a Category:"
}
}
}
func detailViewDidCancel(_ controller: UIViewController) {
if let detailVC = controller as? DetailCategoryTableViewController {
detailVC.dismiss(animated: true, completion: nil)
}
}
func detailView(_ controller: UIViewController, didFinishAdding category: Category) {
if let detailVC = controller as? DetailCategoryTableViewController {
try! realm.write {
realm.add(category)
}
detailVC.dismiss(animated: true, completion: {
self.tableView.reloadData()
})
}
}
func detailView(_ controller: UIViewController, didFinishEditing category: Category) {
if let detailVC = controller as? DetailCategoryTableViewController {
try! realm.write {
realm.add(category, update: true)
}
detailVC.dismiss(animated: true, completion: {
self.tableView.reloadData()
})
}
}
}
| 8945cf27f32a34115a0d707569e44bac | 33.846715 | 184 | 0.621701 | false | false | false | false |
bravelocation/yeltzland-ios | refs/heads/main | yeltzland/ViewModels/YouTubeData.swift | mit | 1 | //
// YeltzTVData.swift
// Yeltzland
//
// Created by John Pollard on 17/10/2021.
// Copyright © 2021 John Pollard. All rights reserved.
//
import Foundation
#if canImport(SwiftUI)
import SwiftUI
import Combine
#endif
@available(iOS 13.0, tvOS 15.0, *)
class YouTubeData: ObservableObject {
let dataProvider: YouTubeDataProvider
@Published private(set) var videos: [YouTubeVideo] = []
@Published private(set) var state: ViewLoadingState = ViewLoadingState.idle
@Published private(set) var images: [String: UIImage] = [:]
let imageCache: ExternalImageCache = ExternalImageCache()
var imageSink: AnyCancellable?
init(channelId: String) {
self.dataProvider = YouTubeDataProvider(channelId: channelId)
self.setupImageSink()
self.refreshData()
}
public func refreshData() {
print("Refreshing YouTube data ...")
self.setState(.isLoading)
// Fetch the data from the server
self.dataProvider.refreshData() { [weak self] result in
switch result {
case .success(let videos):
DispatchQueue.main.async { [self] in
self?.videos = videos
}
self?.fetchVideoImages(videos)
case .failure:
print("Failed to fetch YouTube videos")
}
self?.setState(.loaded)
}
}
func videoImage(_ video: YouTubeVideo) -> Image {
let placeholder = self.imageCache.imageWithColor(color: .systemGray)
return self.imageCache.currentImage(imageUrl: video.thumbnail,
placeholderImage: placeholder)
}
private func setupImageSink() {
// Setup subscriber for image updates
self.imageSink = self.imageCache.$images.sink(
receiveValue: { [self] updatedImages in
self.updateImages(updatedImages)
}
)
}
private func updateImages(_ updatedImages: [String: UIImage]) {
DispatchQueue.main.async {
self.images = updatedImages
}
}
private func setState(_ state: ViewLoadingState) {
DispatchQueue.main.async {
self.state = state
}
}
private func fetchVideoImages(_ videos: [YouTubeVideo]) {
for video in videos {
self.imageCache.fetchImage(imageUrl: video.thumbnail)
}
}
}
| 1d915ddf0256d563fee68262f71e4ac1 | 27.704545 | 79 | 0.583531 | false | false | false | false |
groschovskiy/firebase-for-banking-app | refs/heads/master | Barclays/Pods/CircleMenu/CircleMenuLib/CircleMenuLoader/CircleMenuLoader.swift | apache-2.0 | 2 | //
// CircleMenuLoader.swift
// CircleMenu
//
// Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.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
import UIKit
internal class CircleMenuLoader: UIView {
// MARK: properties
var circle: CAShapeLayer?
// MARK: life cycle
internal init(radius: CGFloat, strokeWidth: CGFloat, platform: UIView, color: UIColor?) {
super.init(frame: CGRect(x: 0, y: 0, width: radius, height: radius))
platform.addSubview(self)
circle = createCircle(radius, strokeWidth: strokeWidth, color: color)
createConstraints(platform: platform, radius: radius)
let circleFrame = CGRect(
x: radius * 2 - strokeWidth,
y: radius - strokeWidth / 2,
width: strokeWidth,
height: strokeWidth)
createRoundView(circleFrame, color: color)
backgroundColor = UIColor.clear
}
required internal init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: create
fileprivate func createCircle(_ radius: CGFloat, strokeWidth: CGFloat, color: UIColor?) -> CAShapeLayer {
let circlePath = UIBezierPath(
arcCenter: CGPoint(x: radius, y: radius),
radius: CGFloat(radius) - strokeWidth / 2.0,
startAngle: CGFloat(0),
endAngle:CGFloat(M_PI * 2),
clockwise: true)
let circle = Init(CAShapeLayer()) {
$0.path = circlePath.cgPath
$0.fillColor = UIColor.clear.cgColor
$0.strokeColor = color?.cgColor
$0.lineWidth = strokeWidth
}
self.layer.addSublayer(circle)
return circle
}
fileprivate func createConstraints(platform: UIView, radius: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
// added constraints
let sizeConstraints = [NSLayoutAttribute.width, .height].map {
NSLayoutConstraint(item: self,
attribute: $0,
relatedBy: .equal,
toItem: nil,
attribute: $0,
multiplier: 1,
constant: radius * 2.0)
}
addConstraints(sizeConstraints)
let centerConstaraints = [NSLayoutAttribute.centerY, .centerX].map {
NSLayoutConstraint(item: platform,
attribute: $0,
relatedBy: .equal,
toItem: self,
attribute: $0,
multiplier: 1,
constant:0)
}
platform.addConstraints(centerConstaraints)
}
internal func createRoundView(_ rect: CGRect, color: UIColor?) {
let roundView = Init(UIView(frame: rect)) {
$0.backgroundColor = UIColor.black
$0.layer.cornerRadius = rect.size.width / 2.0
$0.backgroundColor = color
}
addSubview(roundView)
}
// MARK: animations
internal func fillAnimation(_ duration: Double, startAngle: Float, completion: @escaping () -> Void) {
guard circle != nil else {
return
}
let rotateTransform = CATransform3DMakeRotation(CGFloat(startAngle.degrees), 0, 0, 1)
layer.transform = rotateTransform
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
let animation = Init(CABasicAnimation(keyPath: "strokeEnd")) {
$0.duration = CFTimeInterval(duration)
$0.fromValue = (0)
$0.toValue = (1)
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
circle?.add(animation, forKey: nil)
CATransaction.commit()
}
internal func hideAnimation(_ duration: CGFloat, delay: Double, completion: @escaping () -> Void) {
let scale = Init(CABasicAnimation(keyPath: "transform.scale")) {
$0.toValue = 1.2
$0.duration = CFTimeInterval(duration)
$0.fillMode = kCAFillModeForwards
$0.isRemovedOnCompletion = false
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
$0.beginTime = CACurrentMediaTime() + delay
}
layer.add(scale, forKey: nil)
UIView.animate(
withDuration: CFTimeInterval(duration),
delay: delay,
options: UIViewAnimationOptions.curveEaseIn,
animations: { () -> Void in
self.alpha = 0
},
completion: { (success) -> Void in
self.removeFromSuperview()
completion()
})
}
}
| 1abb5efbdb701a82b1cc9a2c1830e7f3 | 33.805031 | 107 | 0.640947 | false | false | false | false |
Erin-Mounts/BridgeAppSDK | refs/heads/master | BridgeAppSDK/WithdrawViewController.swift | bsd-3-clause | 10 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
class WithdrawViewController: ORKTaskViewController {
// MARK: Initialization
init() {
let instructionStep = ORKInstructionStep(identifier: "WithdrawlInstruction")
instructionStep.title = NSLocalizedString("Are you sure you want to withdraw?", comment: "")
instructionStep.text = NSLocalizedString("Withdrawing from the study will reset the app to the state it was in prior to you originally joining the study.", comment: "")
let completionStep = ORKCompletionStep(identifier: "Withdraw")
completionStep.title = NSLocalizedString("We appreciate your time.", comment: "")
completionStep.text = NSLocalizedString("Thank you for your contribution to this study. We are sorry that you could not continue.", comment: "")
let withdrawTask = ORKOrderedTask(identifier: "Withdraw", steps: [instructionStep, completionStep])
super.init(task: withdrawTask, taskRunUUID: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 645a5fb645558cb2d59756f3ae342a41 | 49.555556 | 176 | 0.765934 | false | false | false | false |
Mav3r1ck/Project-RainMan | refs/heads/master | Stormy/ViewController.swift | mit | 1 | //
// ViewController.swift
// Stormy
// Created by Aaron A
import UIKit
import AVFoundation
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
let swipeRec = UISwipeGestureRecognizer()
//Current Weather outlets
@IBOutlet weak var windBag: UIImageView!
@IBOutlet weak var umbrella: UIImageView!
@IBOutlet weak var rainDrop: UIImageView!
@IBOutlet weak var userLocationLabel: UILabel!
@IBOutlet weak var iconView: UIImageView!
//@IBOutlet weak var currentTimeLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var precipitationLabel: UILabel!
@IBOutlet weak var windSpeedLabel: UILabel!
@IBOutlet weak var summaryLabel: UILabel!
//@IBOutlet weak var refreshActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var degreeButton: UIButton!
@IBOutlet weak var swipeView: UIView!
@IBOutlet weak var heatIndex: UIImageView!
@IBOutlet weak var dayZeroTemperatureLowLabel: UILabel!
@IBOutlet weak var dayZeroTemperatureHighLabel: UILabel!
@IBOutlet weak var windUILabel: UILabel!
@IBOutlet weak var rainUILabel: UILabel!
@IBOutlet weak var humidityUILabel: UILabel!
//Daily Weather outlets
@IBOutlet weak var dayZeroTemperatureLow: UILabel!
@IBOutlet weak var dayZeroTemperatureHigh: UILabel!
@IBOutlet weak var dayOneWeekDayLabel: UILabel!
@IBOutlet weak var dayOneHighLow: UILabel!
@IBOutlet weak var dayOneImage: UIImageView!
@IBOutlet weak var dayTwoWeekDayLabel: UILabel!
@IBOutlet weak var dayTwoHighLow: UILabel!
@IBOutlet weak var dayTwoImage: UIImageView!
@IBOutlet weak var dayThreeWeekDayLabel: UILabel!
@IBOutlet weak var dayThreeHighLow: UILabel!
@IBOutlet weak var dayThreeImage: UIImageView!
@IBOutlet weak var dayFourWeekDayLabel: UILabel!
@IBOutlet weak var dayFourHighLow: UILabel!
@IBOutlet weak var dayFourImage: UIImageView!
@IBOutlet weak var dayFiveWeekDayLabel: UILabel!
@IBOutlet weak var dayFiveHighLow: UILabel!
@IBOutlet weak var dayFiveImage: UIImageView!
@IBOutlet weak var daySixWeekDayLabel: UILabel!
@IBOutlet weak var daySixHighLow: UILabel!
@IBOutlet weak var daySixImage: UIImageView!
//Alerts
@IBOutlet weak var wAlerts: UILabel!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
var locationManager: CLLocationManager!
var userLocation : String!
var userLatitude : Double!
var userLongitude : Double!
var userTemperatureCelsius : Bool!
private let apiKey = "YOUR API KEY" // https://developer.forecast.io
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Get user preference
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
userTemperatureCelsius = defaults.boolForKey("celsius")
print("defaults: celsius = \(userTemperatureCelsius)");
swipeRec.addTarget(self, action: "swipedView")
swipeRec.direction = UISwipeGestureRecognizerDirection.Down
swipeView.addGestureRecognizer(swipeRec)
refresh()
//PushNotifications
}
func swipedView(){
self.swooshsound()
refresh()
}
//LOCATION LOCATION LOCATION
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
locationManager.requestWhenInUseAuthorization()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
let pm = placemarks![0]
self.displayLocationInfo(pm)
})
if (locationFixAchieved == false) {
locationFixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as! CLLocation
var coord = locationObj.coordinate
self.userLatitude = coord.latitude
self.userLongitude = coord.longitude
getCurrentWeatherData()
}
}
func displayLocationInfo(placemark: CLPlacemark?) {
if let containsPlacemark = placemark {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
//println(locality)
//println(postalCode)
//println(administrativeArea)
//println(country)
self.userLocationLabel.text = "\(locality), \(administrativeArea)"
}
}
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
//WEATHER
func getCurrentWeatherData() -> Void {
userLocation = "\(userLatitude),\(userLongitude)"
let baseURL = NSURL(string: "https://api.forecast.io/forecast/\(apiKey)/")
let forecastURL = NSURL(string: "\(userLocation)", relativeToURL:baseURL)
//72.371224,-41.382676 GreenLand (Cold Place!)
//\(userLocation) (YOUR LOCATION!)
//println(userLocation)
let sharedSession = NSURLSession.sharedSession()
let downloadTask: NSURLSessionDownloadTask = sharedSession.downloadTaskWithURL(forecastURL!, completionHandler: { (location: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
if (error == nil) {
let dataObject = NSData(contentsOfURL: location!)
let weatherDictionary: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(dataObject!, options: [])) as! NSDictionary
let currentWeather = Current(weatherDictionary: weatherDictionary)
let weeklyWeather = Weekly(weatherDictionary: weatherDictionary)
var alertWeather = WeatherAlerts(weatherDictionary: weatherDictionary)
//Test Connection and API with the folllowing
//println(currentWeather.temperature)
//println(currentWeather.currentTime!)
print(weatherDictionary)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//Current outlook
// self.userTemperatureCelsius = true
if self.userTemperatureCelsius == true {
self.temperatureLabel.text = "\(Fahrenheit2Celsius(currentWeather.temperature))"
} else {
self.temperatureLabel.text = "\(currentWeather.temperature)"
}
self.iconView.image = currentWeather.icon
//self.currentTimeLabel.text = "\(currentWeather.currentTime!)"
self.humidityLabel.text = "\(currentWeather.humidity)"
self.precipitationLabel.text = "\(currentWeather.precipProbability)"
self.summaryLabel.text = "\(currentWeather.summary)"
self.windSpeedLabel.text = "\(currentWeather.windSpeed)"
if self.userTemperatureCelsius == true {
self.dayZeroTemperatureHigh.text = "\(Fahrenheit2Celsius(weeklyWeather.dayZeroTemperatureMax))"
self.dayZeroTemperatureLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayZeroTemperatureMin))"
} else {
self.temperatureLabel.text = "\(currentWeather.temperature)"
self.dayZeroTemperatureHigh.text = "\(weeklyWeather.dayZeroTemperatureMax)"
self.dayZeroTemperatureLow.text = "\(weeklyWeather.dayZeroTemperatureMin)"
}
// Notification Statements
if currentWeather.precipProbability == 1.0 {
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Project RainMan"
localNotification.alertBody = "Don't forget your umbrella today!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 8)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
if currentWeather.windSpeed > 38.0 {
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Project RainMan"
localNotification.alertBody = "It's going to be windy today!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 8)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
if weeklyWeather.dayZeroTemperatureMax > 90 {
var localNotification:UILocalNotification = UILocalNotification()
localNotification.alertAction = "Project RainMan"
localNotification.alertBody = "It's going to be Hot today!"
localNotification.fireDate = NSDate(timeIntervalSinceNow: 8)
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
//HEAT INDEX
if currentWeather.temperature < 60 {
self.heatIndex.image = UIImage(named: "heatindexWinter")
self.dayZeroTemperatureLow.textColor = UIColor(red: 0/255.0, green: 121/255.0, blue: 255/255.0, alpha: 1.0)
self.dayZeroTemperatureHigh.textColor = UIColor(red: 245/255.0, green: 6/255.0, blue: 93/255.0, alpha: 1.0)
} else {
self.heatIndex.image = UIImage(named:"heatindex")
}
//7 day out look
if self.userTemperatureCelsius == true {
self.dayOneHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayOneTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.dayOneTemperatureMax))°"
self.dayTwoHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayTwoTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.dayTwoTemperatureMax))°"
self.dayThreeHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayThreeTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.dayThreeTemperatureMax))°"
self.dayFourHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayFourTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.dayFourTemperatureMax))°"
self.dayFiveHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.dayFiveTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.dayFiveTemperatureMax))°"
self.daySixHighLow.text = "\(Fahrenheit2Celsius(weeklyWeather.daySixTemperatureMin))°/ \(Fahrenheit2Celsius(weeklyWeather.daySixTemperatureMax))°"
} else {
self.dayOneHighLow.text = "\(weeklyWeather.dayOneTemperatureMin)°/ \(weeklyWeather.dayOneTemperatureMax)°"
self.dayTwoHighLow.text = "\(weeklyWeather.dayTwoTemperatureMin)°/ \(weeklyWeather.dayTwoTemperatureMax)°"
self.dayThreeHighLow.text = "\(weeklyWeather.dayThreeTemperatureMin)°/ \(weeklyWeather.dayThreeTemperatureMax)°"
self.dayFourHighLow.text = "\(weeklyWeather.dayFourTemperatureMin)°/ \(weeklyWeather.dayFourTemperatureMax)°"
self.dayFiveHighLow.text = "\(weeklyWeather.dayFiveTemperatureMin)°/ \(weeklyWeather.dayFiveTemperatureMax)°"
self.daySixHighLow.text = "\(weeklyWeather.daySixTemperatureMin)°/ \(weeklyWeather.daySixTemperatureMax)°"
}
self.dayOneWeekDayLabel.text = "\(weeklyWeather.dayOneTime!)"
self.dayOneImage.image = weeklyWeather.dayOneIcon
self.dayTwoWeekDayLabel.text = "\(weeklyWeather.dayTwoTime!)"
self.dayTwoImage.image = weeklyWeather.dayTwoIcon
self.dayThreeWeekDayLabel.text = "\(weeklyWeather.dayThreeTime!)"
self.dayThreeImage.image = weeklyWeather.dayThreeIcon
self.dayFourWeekDayLabel.text = "\(weeklyWeather.dayFourTime!)"
self.dayFourImage.image = weeklyWeather.dayFourIcon
self.dayFiveWeekDayLabel.text = "\(weeklyWeather.dayFiveTime!)"
self.dayFiveImage.image = weeklyWeather.dayFiveIcon
self.daySixWeekDayLabel.text = "\(weeklyWeather.daySixTime!)"
self.daySixImage.image = weeklyWeather.dayFiveIcon
//Weather Alerts
self.wAlerts.text = ""
self.wAlerts.text = "\(alertWeather.userAlert)"
})
} else {
let networkIssueController = UIAlertController(title: "NO API KEY", message: "Hello! Looks like you forgot to add the API KEY on line 79", preferredStyle: .Alert)
let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
networkIssueController.addAction(okButton)
let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
networkIssueController.addAction(cancelButton)
self.presentViewController(networkIssueController, animated: true, completion: nil)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
}
})
downloadTask.resume()
}
func refresh() {
initLocationManager()
self.temperatureLabel.alpha = 0
self.dayOneImage.alpha = 0
self.dayTwoImage.alpha = 0
self.dayThreeImage.alpha = 0
self.dayFourImage.alpha = 0
self.dayFiveImage.alpha = 0
self.daySixImage.alpha = 0
self.dayZeroTemperatureLow.alpha = 0
self.dayZeroTemperatureHigh.alpha = 0
self.windSpeedLabel.alpha = 0
self.humidityLabel.alpha = 0
self.precipitationLabel.alpha = 0
self.rainUILabel.alpha = 0
self.dayOneWeekDayLabel.alpha = 0
self.dayOneHighLow.alpha = 0
self.dayTwoWeekDayLabel.alpha = 0
self.dayTwoHighLow.alpha = 0
self.dayThreeWeekDayLabel.alpha = 0
self.dayThreeHighLow.alpha = 0
self.dayFourWeekDayLabel.alpha = 0
self.dayFourHighLow.alpha = 0
self.dayFiveWeekDayLabel.alpha = 0
self.dayFiveHighLow.alpha = 0
self.daySixWeekDayLabel.alpha = 0
self.daySixHighLow.alpha = 0
self.wAlerts.alpha = 0
self.weeklyForcastAnimation()
UIView.animateWithDuration(1.5, animations: {
self.temperatureLabel.alpha = 1.0
self.heatIndex.alpha = 1.0
self.dayOneImage.alpha = 1.0
self.dayTwoImage.alpha = 1.0
self.dayThreeImage.alpha = 1.0
self.dayFourImage.alpha = 1.0
self.dayFiveImage.alpha = 1.0
self.daySixImage.alpha = 1.0
self.dayZeroTemperatureLow.alpha = 1.0
self.dayZeroTemperatureHigh.alpha = 1.0
self.windSpeedLabel.alpha = 1.0
self.humidityLabel.alpha = 1.0
self.precipitationLabel.alpha = 1.0
self.rainUILabel.alpha = 1.0
self.dayOneWeekDayLabel.alpha = 1.0
self.dayOneHighLow.alpha = 1.0
self.dayTwoWeekDayLabel.alpha = 1.0
self.dayTwoHighLow.alpha = 1.0
self.dayThreeWeekDayLabel.alpha = 1.0
self.dayThreeHighLow.alpha = 1.0
self.dayFourWeekDayLabel.alpha = 1.0
self.dayFourHighLow.alpha = 1.0
self.dayFiveWeekDayLabel.alpha = 1.0
self.dayFiveHighLow.alpha = 1.0
self.daySixWeekDayLabel.alpha = 1.0
self.daySixHighLow.alpha = 1.0
self.wAlerts.alpha = 1.0
})
}
func weeklyForcastAnimation() {
//DAILY
self.dayZeroTemperatureLowLabel.transform = CGAffineTransformMakeTranslation(-300, 0)
self.dayZeroTemperatureHighLabel.transform = CGAffineTransformMakeTranslation(300, 0)
self.windBag.transform = CGAffineTransformMakeTranslation(0, -600)
self.umbrella.transform = CGAffineTransformMakeTranslation(0, -600)
self.rainDrop.transform = CGAffineTransformMakeTranslation(0, -600)
self.iconView.transform = CGAffineTransformMakeTranslation(-200, 0)
self.temperatureLabel.transform = CGAffineTransformMakeTranslation(300, 0)
self.summaryLabel.transform = CGAffineTransformMakeTranslation(0, -200)
self.heatIndex.transform = CGAffineTransformMakeTranslation(-350, 0)
//self.currentTimeLabel.transform = CGAffineTransformMakeTranslation(350,0)
self.userLocationLabel.transform = CGAffineTransformMakeTranslation(350, 0)
self.degreeButton.transform = CGAffineTransformMakeTranslation(350,0)
self.windUILabel.transform = CGAffineTransformMakeTranslation(-350,0)
self.humidityUILabel.transform = CGAffineTransformMakeTranslation(350,0)
self.degreeButton.transform = CGAffineTransformMakeTranslation(350, 0)
//WEEKLY
self.dayOneImage.transform = CGAffineTransformMakeTranslation(0, 100)
self.dayTwoImage.transform = CGAffineTransformMakeTranslation(0, 100)
self.dayThreeImage.transform = CGAffineTransformMakeTranslation(0, 100)
self.dayFourImage.transform = CGAffineTransformMakeTranslation(0, 100)
self.dayFiveImage.transform = CGAffineTransformMakeTranslation(0, 100)
self.daySixImage.transform = CGAffineTransformMakeTranslation(0, 100)
//DAILY SPRING ACTION
springWithDelay(0.9, delay: 0.45, animations: {
self.userLocationLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.60, animations: {
self.degreeButton.transform = CGAffineTransformMakeTranslation(0, 0)
})
//springWithDelay(0.9, 0.45, {
// self.currentTimeLabel.transform = CGAffineTransformMakeTranslation(0, 0)
//})
springWithDelay(0.9, delay: 0.25, animations: {
self.windBag.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.35, animations: {
self.umbrella.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.rainDrop.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.iconView.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.temperatureLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.60, animations: {
self.summaryLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.heatIndex.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.dayZeroTemperatureLowLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.dayZeroTemperatureHighLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.userLocationLabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.windUILabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.humidityUILabel.transform = CGAffineTransformMakeTranslation(0, 0)
})
//WEEKLY FORCAST SPRING ACTION
springWithDelay(0.9, delay: 0.25, animations: {
self.dayOneImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.35, animations: {
self.dayTwoImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.45, animations: {
self.dayThreeImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.55, animations: {
self.dayFourImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.65, animations: {
self.dayFiveImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
springWithDelay(0.9, delay: 0.75, animations: {
self.daySixImage.transform = CGAffineTransformMakeTranslation(0, 0)
})
}
@IBAction func degreeButtonPressed(sender: AnyObject) {
print("TemperatureMode \(userTemperatureCelsius)");
}
//SOUNDS
func swooshsound() {
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("swoosh", ofType: "wav")!)
print(alertSound)
var error:NSError?
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: alertSound)
} catch var error1 as NSError {
error = error1
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "infotab"{
let _ = segue.destinationViewController as! InfoTabViewController
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 64cb1823f048d2261e9d1533bede9d16 | 40.856209 | 194 | 0.597205 | false | false | false | false |
omise/omise-ios | refs/heads/master | QuickStart.playground/Pages/Credit Card Form.xcplaygroundpage/Contents.swift | mit | 1 | import UIKit
import OmiseSDK
import PlaygroundSupport
let publicKey = "pkey_test_<#Omise Public Key#>"
/*: credit-card-form
To get going quickly, the SDK provides ready-made credit card form that you can integrate directly into your application's checkout process.
Additionally, to provide consistent experience for the form, we recommend wrapping the form in a `UINavigationController`.
Let's make a simple view checkout button to try this out:
*/
let checkoutController = CheckoutViewController()
checkoutController.delegate = checkoutController
let navigationController = UINavigationController(rootViewController: checkoutController)
PlaygroundPage.current.liveView = navigationController
PlaygroundPage.current.needsIndefiniteExecution = true
/*: implement-delegate
The form will automatically tokenizes credit card data for you as the user click on the submit button. To receive the resulting token data, implement the `CreditCardFormDelegate` methods on your view controller.
*/
extension CheckoutViewController: CreditCardFormViewControllerDelegate {
public func creditCardFormViewController(_ controller: CreditCardFormViewController, didSucceedWithToken token: Token) {
dismiss(animated: true, completion: nil)
print("token created: \(token.id )")
let alert = UIAlertController(title: "Token", message: token.id, preferredStyle: .alert)
present(alert, animated: true, completion: nil)
}
public func creditCardFormViewController(_ controller: CreditCardFormViewController, didFailWithError error: Error) {
dismiss(animated: true, completion: nil)
print("error: \(error)")
let alert = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert)
present(alert, animated: true, completion: nil)
}
public func creditCardFormViewControllerDidCancel(_ controller: CreditCardFormViewController) {
dismiss(animated: true, completion: nil)
}
}
extension CheckoutViewController: CheckoutViewControllerDelegate {
public func checkoutViewControllerDidTapCheckout(_ checkoutViewController: CheckoutViewController) {
let creditCardForm = CreditCardFormViewController.makeCreditCardFormViewController(withPublicKey: publicKey)
creditCardForm.delegate = self
let navigationController = UINavigationController(rootViewController: creditCardForm)
present(navigationController, animated: true, completion: nil)
}
}
| c756a81d387db6c36e874da1da3b1233 | 38.5 | 212 | 0.785627 | false | false | false | false |
PjGeeroms/IOSRecipeDB | refs/heads/master | Carthage/Checkouts/Bond/Carthage/Checkouts/ReactiveKit/Sources/Observer.swift | mit | 5 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Srdan Rasic (@srdanrasic)
//
// 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
/// Represents a type that receives events.
public typealias Observer<Element, Error: Swift.Error> = (Event<Element, Error>) -> Void
/// Represents a type that receives events.
public protocol ObserverProtocol {
/// Type of elements being received.
associatedtype Element
/// Type of error that can be received.
associatedtype Error: Swift.Error
/// Send the event to the observer.
func on(_ event: Event<Element, Error>)
}
/// Represents a type that receives events. Observer is just a convenience
/// wrapper around a closure observer `Observer<Element, Error>`.
public struct AnyObserver<Element, Error: Swift.Error>: ObserverProtocol {
private let observer: Observer<Element, Error>
/// Creates an observer that wraps a closure observer.
public init(observer: @escaping Observer<Element, Error>) {
self.observer = observer
}
/// Calles wrapped closure with the given element.
public func on(_ event: Event<Element, Error>) {
observer(event)
}
}
/// Observer that ensures events are sent atomically.
public class AtomicObserver<Element, Error: Swift.Error>: ObserverProtocol {
private let observer: Observer<Element, Error>
private let disposable: Disposable
private let lock = NSRecursiveLock(name: "com.reactivekit.signal.atomicobserver")
private var terminated = false
/// Creates an observer that wraps given closure.
public init(disposable: Disposable, observer: @escaping Observer<Element, Error>) {
self.disposable = disposable
self.observer = observer
}
/// Calles wrapped closure with the given element.
public func on(_ event: Event<Element, Error>) {
lock.lock(); defer { lock.unlock() }
guard !disposable.isDisposed && !terminated else { return }
if event.isTerminal {
terminated = true
observer(event)
disposable.dispose()
} else {
observer(event)
}
}
}
// MARK: - Extensions
public extension ObserverProtocol {
/// Convenience method to send `.next` event.
public func next(_ element: Element) {
on(.next(element))
}
/// Convenience method to send `.failed` event.
public func failed(_ error: Error) {
on(.failed(error))
}
/// Convenience method to send `.completed` event.
public func completed() {
on(.completed)
}
/// Convenience method to send `.next` event followed by a `.completed` event.
public func completed(with element: Element) {
next(element)
completed()
}
/// Converts the receiver to the Observer closure.
public func toObserver() -> Observer<Element, Error> {
return on
}
}
| f6d16823aa5089fbdf27522bf9384a94 | 31.316239 | 88 | 0.715155 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | fixed/00200-swift-parser-parsestmtreturn.swift | mit | 12 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class n<j : n> {
}
func k<d {
m k {
func m
k _ = m
}
}
protocol o {
class func k()
}
class m: o {
class func k() { }
}
(m() as o).l n {
{
f m = m
d.j = {
}
{
n) {
o }
}
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol h g
}
} {
}
class l<r, l> {
}
protocol n {
j q
}
protocol k : k {
}
class k<f : l, qT> {
let a: [(T, () -> ())] = []
}
rn z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
func a<d>() -> [c{ enum b {
case c
| b0de510c3fb9d395dd6d21143aa4e67c | 13.140351 | 87 | 0.451613 | false | false | false | false |
Lves/LLRefresh | refs/heads/master | LLRefreshDemo/Demos/ArrowRefreshViewController.swift | mit | 1 | //
// ArrowRefreshViewController.swift
// LLRefreshDemo
//
// Created by lixingle on 2017/5/16.
// Copyright © 2017年 com.lvesli. All rights reserved.
//
import UIKit
import LLRefresh
class ArrowRefreshViewController: UITableViewController {
var dataArray:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
setRefreshByBlock()
tableView.ll_header?.beginRefreshing()
}
//MARK: Block实现方式
func setRefreshByBlock(){
//1.0
let header = LLRefreshNormalHeader(refreshingBlock: {[weak self] _ in
self?.loadNewData()
})
// header.setLastUpdatedTimeLabelHidden(isHidden: true) //只隐藏状态label
header.setStateLabelHidden(isHidden: true) //隐藏状态和时间label
tableView.ll_header = header
}
func loadNewData() {
//update data
let format = DateFormatter()
format.dateFormat = "HH:mm:ss"
for _ in 0...2 {
dataArray.insert(format.string(from: Date()), at: 0)
}
sleep(2)
//end refreshing
tableView.ll_header?.endRefreshing()
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
cell?.textLabel?.text = dataArray[indexPath.row]
return cell!
}
}
| e8001a8476e193d38e100a6b8cfbf0b6 | 28.587302 | 109 | 0.625 | false | false | false | false |
Legoless/iOS-Course | refs/heads/master | 2015-1/Lesson14/Gamebox/Gamebox/Game.swift | mit | 1 | //
// Game.swift
// Gamebox
//
// Created by Dal Rupnik on 21/10/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import Foundation
struct GameConstants {
static var formatter : NSDateFormatter {
let format = NSDateFormatter()
format.dateStyle = .FullStyle
return format
}
}
class Game {
var name : String
var dateAdded : NSDate = NSDate()
var dateModified : NSDate = NSDate()
var priority : UInt
var status : Status = .Wishlist
var notes : String?
init (name: String, priority: UInt = 0)
{
self.name = name
self.priority = priority
}
init (dictionary: [String : AnyObject]) {
self.name = dictionary["name"] as! String
self.priority = dictionary["priority"] as! UInt
self.dateAdded = GameConstants.formatter.dateFromString(dictionary["added"] as! String)!
self.dateModified = GameConstants.formatter.dateFromString(dictionary["modified"] as! String)!
self.status = Status(rawValue: (dictionary["status"] as! UInt))!
if let notes = dictionary["notes"] as? String {
self.notes = notes
}
}
func description () -> String {
return "Game: \(name) status: \(status)"
}
func toDictionary () -> [String : AnyObject] {
var data : [String : AnyObject] = ["name" : self.name, "modified" : GameConstants.formatter.stringFromDate(self.dateModified), "added" : GameConstants.formatter.stringFromDate(self.dateAdded), "priority" : self.priority, "status" : self.status.rawValue ]
if self.notes != nil {
data["notes"] = self.notes!
}
return data
}
} | 6e62ad4832d40081824af0a191ba7bed | 28.457627 | 262 | 0.602188 | false | false | false | false |
jakubknejzlik/GNGradientView | refs/heads/master | GNGradientView/Classes/GNGradientView.swift | mit | 1 | //
// GNGradientView.swift
// Pods
//
// Created by Jakub Knejzlik on 19/09/16.
//
//
import UIKit
@IBDesignable class GNGradientView: UIView {
@IBInspectable var topAlpha: CGFloat = 1 {
didSet {
updateAlphas()
}
}
@IBInspectable var middleAlpha: CGFloat = 0.5 {
didSet {
updateAlphas()
}
}
@IBInspectable var bottomAlpha: CGFloat = 0 {
didSet {
updateAlphas()
}
}
@IBInspectable var vertical: Bool = true {
didSet {
gradientView_setMaskDirection(value: vertical ? .vertical : .horizontal)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
func initialize() {
updateAlphas()
gradientView_setMaskDirection(value: .vertical)
}
func updateAlphas() {
gradientView_setMaskAlphaChannels([topAlpha,middleAlpha,bottomAlpha])
}
override func layoutSubviews() {
super.layoutSubviews()
gradientView_updateMaskFrame()
}
override func prepareForInterfaceBuilder() {
// backgroundColor = UIColor.green
}
}
| 542ef5aa41d685771fa1d33e957c3f57 | 20.52459 | 84 | 0.573496 | false | false | false | false |
lllyyy/LY | refs/heads/master | ScrollableGraphView-master(折线图)/Classes/Plots/LinePlot.swift | mit | 1 |
import UIKit
open class LinePlot : Plot {
// Public settings for the LinePlot
// ################################
/// Specifies how thick the graph of the line is. In points.
open var lineWidth: CGFloat = 2
/// The color of the graph line. UIColor.
open var lineColor: UIColor = UIColor.black
/// Whether the line is straight or curved.
open var lineStyle_: Int {
get { return lineStyle.rawValue }
set {
if let enumValue = ScrollableGraphViewLineStyle(rawValue: newValue) {
lineStyle = enumValue
}
}
}
/// Whether or not the line should be rendered using bezier curves are straight lines.
open var lineStyle = ScrollableGraphViewLineStyle.straight
/// How each segment in the line should connect. Takes any of the Core Animation LineJoin values.
open var lineJoin: String = kCALineJoinRound
/// The line caps. Takes any of the Core Animation LineCap values.
open var lineCap: String = kCALineCapRound
open var lineCurviness: CGFloat = 0.5
// Fill Settings
// #############
/// Specifies whether or not the plotted graph should be filled with a colour or gradient.
open var shouldFill: Bool = false
var fillType_: Int {
get { return fillType.rawValue }
set {
if let enumValue = ScrollableGraphViewFillType(rawValue: newValue) {
fillType = enumValue
}
}
}
/// Specifies whether to fill the graph with a solid colour or gradient.
open var fillType = ScrollableGraphViewFillType.solid
/// If fillType is set to .Solid then this colour will be used to fill the graph.
open var fillColor: UIColor = UIColor.black
/// If fillType is set to .Gradient then this will be the starting colour for the gradient.
open var fillGradientStartColor: UIColor = UIColor.white
/// If fillType is set to .Gradient, then this will be the ending colour for the gradient.
open var fillGradientEndColor: UIColor = UIColor.black
open var fillGradientType_: Int {
get { return fillGradientType.rawValue }
set {
if let enumValue = ScrollableGraphViewGradientType(rawValue: newValue) {
fillGradientType = enumValue
}
}
}
/// If fillType is set to .Gradient, then this defines whether the gradient is rendered as a linear gradient or radial gradient.
open var fillGradientType = ScrollableGraphViewGradientType.linear
// Private State
// #############
private var lineLayer: LineDrawingLayer?
private var fillLayer: FillDrawingLayer?
private var gradientLayer: GradientDrawingLayer?
public init(identifier: String) {
super.init()
self.identifier = identifier
}
override func layers(forViewport viewport: CGRect) -> [ScrollableGraphViewDrawingLayer?] {
createLayers(viewport: viewport)
return [lineLayer, fillLayer, gradientLayer]
}
private func createLayers(viewport: CGRect) {
// Create the line drawing layer.
lineLayer = LineDrawingLayer(frame: viewport, lineWidth: lineWidth, lineColor: lineColor, lineStyle: lineStyle, lineJoin: lineJoin, lineCap: lineCap, shouldFill: shouldFill, lineCurviness: lineCurviness)
// Depending on whether we want to fill with solid or gradient, create the layer accordingly.
// Gradient and Fills
switch (self.fillType) {
case .solid:
if(shouldFill) {
// Setup fill
fillLayer = FillDrawingLayer(frame: viewport, fillColor: fillColor, lineDrawingLayer: lineLayer!)
}
case .gradient:
if(shouldFill) {
gradientLayer = GradientDrawingLayer(frame: viewport, startColor: fillGradientStartColor, endColor: fillGradientEndColor, gradientType: fillGradientType, lineDrawingLayer: lineLayer!)
}
}
lineLayer?.owner = self
fillLayer?.owner = self
gradientLayer?.owner = self
}
}
@objc public enum ScrollableGraphViewLineStyle : Int {
case straight
case smooth
}
@objc public enum ScrollableGraphViewFillType : Int {
case solid
case gradient
}
@objc public enum ScrollableGraphViewGradientType : Int {
case linear
case radial
}
| 910e378ad81e0c3ad22f23e0f5ca205a | 32.894737 | 211 | 0.63709 | false | false | false | false |
ReactiveX/RxSwift | refs/heads/develop | Example/Pods/RxSwift/RxSwift/Observables/Generate.swift | gpl-3.0 | 8 | //
// Generate.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/2/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
public static func generate(initialState: Element, condition: @escaping (Element) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (Element) throws -> Element) -> Observable<Element> {
Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
}
final private class GenerateSink<Sequence, Observer: ObserverType>: Sink<Observer> {
typealias Parent = Generate<Sequence, Observer.Element>
private let parent: Parent
private var state: Sequence
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
self.state = parent.initialState
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return self.parent.scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in
do {
if !isFirst {
self.state = try self.parent.iterate(self.state)
}
if try self.parent.condition(self.state) {
let result = try self.parent.resultSelector(self.state)
self.forwardOn(.next(result))
recurse(false)
}
else {
self.forwardOn(.completed)
self.dispose()
}
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
}
}
}
final private class Generate<Sequence, Element>: Producer<Element> {
fileprivate let initialState: Sequence
fileprivate let condition: (Sequence) throws -> Bool
fileprivate let iterate: (Sequence) throws -> Sequence
fileprivate let resultSelector: (Sequence) throws -> Element
fileprivate let scheduler: ImmediateSchedulerType
init(initialState: Sequence, condition: @escaping (Sequence) throws -> Bool, iterate: @escaping (Sequence) throws -> Sequence, resultSelector: @escaping (Sequence) throws -> Element, scheduler: ImmediateSchedulerType) {
self.initialState = initialState
self.condition = condition
self.iterate = iterate
self.resultSelector = resultSelector
self.scheduler = scheduler
super.init()
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = GenerateSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| 51163ad83662729ca458b11ddfb72de2 | 39.758621 | 243 | 0.642414 | false | false | false | false |
thinkclay/FlourishUI | refs/heads/master | Pod/Classes/InputText.swift | mit | 1 | import UIKit
@IBDesignable
open class InputText: UITextField
{
@IBInspectable open var padding: CGSize = CGSize(width: 8, height: 5)
@IBInspectable open var borderRadius = CGFloat(5)
@IBInspectable open var borderColor = UIColor.lightGray.cgColor
@IBInspectable open var borderWidth = CGFloat(1)
@IBInspectable open var icon = UIImage()
override open func layoutSubviews()
{
super.layoutSubviews()
layer.cornerRadius = borderRadius
layer.borderColor = borderColor
layer.borderWidth = borderWidth
}
override open func textRect(forBounds bounds: CGRect) -> CGRect
{
let rect = super.textRect(forBounds: bounds)
let newRect = CGRect(
x: rect.origin.x + padding.width,
y: rect.origin.y + padding.height,
width: rect.size.width - (2 * padding.width),
height: rect.size.height - (2 * padding.height)
)
return newRect
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds: bounds)
}
}
| 9cc5c8d3922771a442d82bc38aee2168 | 24.9 | 71 | 0.687259 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | refs/heads/master | Modules/BlockchainNamespace/Tests/BlockchainNamespaceTests/Session/Session+RemoteConfigurationTests.swift | lgpl-3.0 | 1 | @testable import BlockchainNamespace
import Combine
import Extensions
import FirebaseProtocol
import XCTest
@available(iOS 15.0, macOS 12.0, *) // Replace with `async()` API when merged
final class SessionRemoteConfigurationTests: XCTestCase {
var preferences: Mock.UserDefaults!
var app: AppProtocol!
var session: ImmediateURLSession!
var scheduler: TestSchedulerOf<DispatchQueue>!
override func setUp() {
super.setUp()
scheduler = DispatchQueue.test
preferences = Mock.UserDefaults()
preferences.set(
[
blockchain.app.configuration.manual.login.is.enabled(\.id): false
],
forKey: blockchain.session.configuration(\.id)
)
session = URLSession.test
session.data = Data(
"""
{
"experiment-1": 0,
"experiment-2": 2
}
""".utf8
)
app = App(
remoteConfiguration: Session.RemoteConfiguration(
remote: Mock.RemoteConfiguration(
[
.remote: [
"ios_app_maintenance": true,
"ios_ff_apple_pay": true,
"ios_ff_app_superapp": true,
"blockchain_app_configuration_announcements": ["1", "2", "3"],
"blockchain_app_configuration_deep_link_rules": [],
"blockchain_app_configuration_customer_support_is_enabled": [
"{returns}": [
"experiment": [
"experiment-1": [
"0": true,
"1": false
]
]
]
],
"blockchain_app_configuration_customer_support_url": [
"{returns}": [
"experiment": [
"experiment-2": [
"0": "https://support.blockchain.com?group=0",
"1": "https://support.blockchain.com?group=1",
"2": "https://support.blockchain.com?group=2"
]
]
],
"default": "https://support.blockchain.com?group=default"
],
"blockchain_ux_onboarding_promotion_cowboys_verify_identity_announcement": [
"title": "Cowboys Promotion",
"message": [
"{returns}": [
"experiment": [
"experiment-1": [
"0": "Message 1",
"1": "Message 2"
]
]
]
]
]
]
]
),
session: session,
preferences: preferences,
scheduler: scheduler.eraseToAnyScheduler()
)
)
}
func test_fetch() async throws {
let announcements = try await app.publisher(for: blockchain.app.configuration.announcements, as: [String].self)
.await()
.get()
XCTAssertEqual(announcements, ["1", "2", "3"])
try XCTAssertEqual(app.remoteConfiguration.get(blockchain.app.configuration.announcements), ["1", "2", "3"])
}
func test_fetch_with_underscore() async throws {
let rules: [App.DeepLink.Rule] = try await app.publisher(for: blockchain.app.configuration.deep_link.rules)
.await()
.get()
XCTAssertEqual(rules, [])
}
func test_fetch_fallback() async throws {
let isEnabled = try await app.publisher(for: blockchain.app.configuration.apple.pay.is.enabled, as: Bool.self)
.await()
.get()
XCTAssertTrue(isEnabled)
}
func test_fetch_fallback_alternative() async throws {
let isEnabled = try await app.publisher(for: blockchain.app.configuration.app.maintenance, as: Bool.self)
.await()
.get()
XCTAssertTrue(isEnabled)
}
func test_fetch_type_mismatch() async throws {
let announcements = try await app.publisher(for: blockchain.app.configuration.announcements, as: Bool.self)
.await()
XCTAssertThrowsError(try announcements.get())
}
func test_fetch_missing_value() async throws {
let announcements = try await app.publisher(for: blockchain.user.email.address, as: String.self)
.await()
XCTAssertThrowsError(try announcements.get())
}
func test_fetch_then_override() async throws {
var announcements = try await app.publisher(for: blockchain.app.configuration.announcements, as: [String].self)
.await()
.get()
XCTAssertEqual(announcements, ["1", "2", "3"])
app.remoteConfiguration.override(blockchain.app.configuration.announcements, with: ["4", "5", "6"])
announcements = try await app.publisher(for: blockchain.app.configuration.announcements, as: [String].self)
.await()
.get()
XCTAssertEqual(announcements, ["4", "5", "6"])
}
func test_all_keys() async throws {
try await app.publisher(for: blockchain.app.configuration.apple.pay.is.enabled, as: Bool.self)
.await()
XCTAssertEqual(
app.remoteConfiguration.allKeys.set,
[
"ios_app_maintenance",
"ios_ff_apple_pay",
"ios_ff_app_superapp",
"!blockchain.app.configuration.manual.login.is.enabled",
"blockchain_app_configuration_announcements",
"blockchain_app_configuration_deep_link_rules",
"blockchain_app_configuration_customer_support_is_enabled",
"blockchain_app_configuration_customer_support_url",
"blockchain_ux_onboarding_promotion_cowboys_verify_identity_announcement"
].set
)
}
func test_with_default() async throws {
let app = App(
remoteConfiguration: .init(
remote: Mock.RemoteConfiguration(),
session: URLSession.test,
preferences: Mock.Preferences(),
scheduler: scheduler.eraseToAnyScheduler(),
default: [
blockchain.app.configuration.apple.pay.is.enabled: true
]
)
)
var isEnabled = try await app.publisher(for: blockchain.app.configuration.apple.pay.is.enabled, as: Bool.self)
.await()
.get()
XCTAssertTrue(isEnabled)
XCTAssertEqual(
app.remoteConfiguration.allKeys.set,
["blockchain.app.configuration.apple.pay.is.enabled"].set
)
app.remoteConfiguration.override(blockchain.app.configuration.apple.pay.is.enabled, with: false)
isEnabled = try await app.publisher(for: blockchain.app.configuration.apple.pay.is.enabled, as: Bool.self)
.await()
.get()
XCTAssertEqual(
app.remoteConfiguration.allKeys.set,
[
"blockchain.app.configuration.apple.pay.is.enabled",
"!blockchain.app.configuration.apple.pay.is.enabled"
].set
)
XCTAssertFalse(isEnabled)
app.remoteConfiguration.clear(blockchain.app.configuration.apple.pay.is.enabled)
isEnabled = try await app.publisher(for: blockchain.app.configuration.apple.pay.is.enabled, as: Bool.self)
.await()
.get()
XCTAssertTrue(isEnabled)
}
func test_with_preferences() async throws {
do {
let isEnabled = try await app.publisher(
for: blockchain.app.configuration.manual.login.is.enabled,
as: Bool.self
)
.await()
.get()
XCTAssertFalse(isEnabled)
}
app.remoteConfiguration.override(blockchain.app.configuration.manual.login.is.enabled, with: true)
do {
let isEnabled = try await app.publisher(
for: blockchain.app.configuration.manual.login.is.enabled,
as: Bool.self
)
.await()
.get()
XCTAssertTrue(isEnabled)
await scheduler.advance(by: .seconds(1))
let preference = preferences.dictionary(
forKey: blockchain.session.configuration(\.id)
)?[blockchain.app.configuration.manual.login.is.enabled(\.id)]
XCTAssertTrue(preference as? Bool == true)
}
}
func test_fetch_superapp_feature_flag() async throws {
let enabled = try await app.get(blockchain.app.configuration.app.superapp.is.enabled, as: Bool.self)
XCTAssertTrue(enabled)
}
func test_experiment() async throws {
let enabled = try await app.publisher(for: blockchain.app.configuration.customer.support.is.enabled, as: Bool.self).await().get()
XCTAssertTrue(enabled)
var url: URL = try await app.publisher(for: blockchain.app.configuration.customer.support.url).await().get()
XCTAssertEqual(url, "https://support.blockchain.com?group=2")
app.state.set(blockchain.ux.user.nabu.experiment["experiment-2"].group, to: 0)
url = try await app.publisher(for: blockchain.app.configuration.customer.support.url).await().get()
XCTAssertEqual(url, "https://support.blockchain.com?group=0")
app.state.set(blockchain.ux.user.nabu.experiment["experiment-2"].group, to: 1)
url = try await app.publisher(for: blockchain.app.configuration.customer.support.url).await().get()
XCTAssertEqual(url, "https://support.blockchain.com?group=1")
app.state.set(blockchain.ux.user.nabu.experiment["experiment-2"].group, to: 666)
url = try await app.publisher(for: blockchain.app.configuration.customer.support.url).await().get()
XCTAssertEqual(url, "https://support.blockchain.com?group=default")
struct Announcement: Decodable {
let title: String
let message: String
}
var announcement = try await app.publisher(
for: blockchain.ux.onboarding.promotion.cowboys.verify.identity.announcement,
as: Announcement.self
)
.await()
.get()
XCTAssertEqual(announcement.message, "Message 1")
app.state.set(blockchain.ux.user.nabu.experiment["experiment-1"].group, to: 1)
announcement = try await app.publisher(
for: blockchain.ux.onboarding.promotion.cowboys.verify.identity.announcement,
as: Announcement.self
)
.await()
.get()
XCTAssertEqual(announcement.message, "Message 2")
}
func test_concurrency() async throws {
let limit = 100
DispatchQueue.concurrentPerform(iterations: limit) { i in
app.remoteConfiguration.override(blockchain.db.collection[String(i)], with: i)
}
let results = try await (0..<limit).map { i in
app.remoteConfiguration.publisher(for: blockchain.db.collection[String(i)]).decode(Int.self).compactMap(\.value)
}
.combineLatest()
.await()
for i in 0..<limit {
try XCTAssertEqual(app.remoteConfiguration.get(blockchain.db.collection[String(i)]), i)
}
XCTAssertNotNil(results)
}
}
| c0e1a397989b11bb13f675dee837834c | 35.603604 | 137 | 0.53458 | false | true | false | false |
bryansum/LDL | refs/heads/master | LDL/StoriesViewController.swift | mit | 1 | //
// StoriesViewController.swift
// LDL
//
// Created by Bryan Summersett on 12/9/16.
// Copyright © 2016 Bryan Summersett. All rights reserved.
//
import Foundation
import UIKit
class StoriesViewController: UITableViewController {
init() {
super.init(style: .plain)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Stories"
navigationController?.toolbar.addSubview(audioPlayer)
tableView.register(StoriesTableViewCell.self, forCellReuseIdentifier: StoriesTableViewCell.CellIdentifier)
tableView.rowHeight = 44
fetchStories()
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return stories.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: StoriesTableViewCell.CellIdentifier, for: indexPath) as! StoriesTableViewCell
// Configure the cell...
let story = stories[indexPath.row]
cell.textLabel?.text = story.name
cell.detailTextLabel?.text = story.description
return cell
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let story = stories[indexPath.row]
let storyVC = StoryViewController(story: story)
navigationController?.pushViewController(storyVC, animated: true)
}
// MARK: Documents
var documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
var stories = [Story]()
func fetchStories() {
DispatchQueue.global().async {
let stories = self.urls(in: self.documentsDir).filter { _, values in
values.isDirectory!
}.map { dir, values -> Story in
let name = values.name!
let subDir = self.urls(in: dir)
let docs = subDir.filter { file, _ in
return file.pathExtension == "pdf"
}
.map { $0.url }
.sorted {
$0.fileName.localizedStandardCompare($1.fileName) == .orderedAscending
}
let audio = subDir.filter { file, _ in
return file.pathExtension == "mp3"
}
.map { $0.url }
.sorted {
$0.fileName.localizedStandardCompare($1.fileName) == .orderedAscending
}
return Story(name: name, docs: docs, audio: audio)
}
DispatchQueue.main.async {
self.stories = stories
self.tableView.reloadData()
}
}
}
typealias URLs = (url: URL, values: URLResourceValues)
let directoryKeys: [URLResourceKey] = [.isDirectoryKey, .nameKey]
func urls(in directory: URL) -> [URLs] {
let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: directoryKeys, options: [.skipsSubdirectoryDescendants], errorHandler: nil)!
var urls = [URLs]()
for case let url as URL in enumerator {
guard let resourceValues = try? url.resourceValues(forKeys: Set(directoryKeys)) else {
continue
}
urls.append((url, resourceValues))
}
return urls
}
}
| 2db93c19dfc8ce9e30f6d224a838faa2 | 27.433333 | 171 | 0.663834 | false | false | false | false |
Masteryyz/CSYMicroBlockSina | refs/heads/master | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewController.swift | mit | 1 | //
// HomeTableViewController.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/8.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import AFNetworking
import SDWebImage
import SVProgressHUD
private let cellID = "BlogCell"
class HomeTableViewController: CSYBasicTableViewController {
//为什么要加括号
lazy var blogDataArray = [CSYMyMicroBlogModel]()
//想要上拉加载更多数据需要使用自定义的小菊花View --> 然后使用since_id刷新数据
lazy var upDragActivityView : UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
var array = [1,2,3,45]
override func loadView() {
super.loadView()
}
override func viewDidLoad() {
super.viewDidLoad()
if !GetUserInfoModel().isLogin{
visitorView?.setViewItems(nil, tipsInfo: "关注一些人,回这里看看有什么惊喜")
return
}
refreshControl = UIRefreshControl()
refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
tableView.estimatedRowHeight = 200
tableView.rowHeight = UITableViewAutomaticDimension
let footerView : UIView = UIView(frame: CGRectMake(0, 0, screen_Width, 44))
footerView.backgroundColor = UIColor.lightGrayColor()
footerView.addSubview(upDragActivityView)
upDragActivityView.snp_makeConstraints { (make) -> Void in
make.centerX.equalTo(footerView.snp_centerX)
make.centerY.equalTo(footerView.snp_centerY)
}
tableView.tableFooterView = footerView
tableView.tableFooterView?.backgroundColor = UIColor.whiteColor()
registCell()
loadData()
}
@objc private func loadData(){
//定义一个参数来获取最新的微博
var since_id : Int64 = 0
//定义一个参数来获取旧的微博
var max_id : Int64 = 0
if upDragActivityView.isAnimating(){
since_id = 0
max_id = blogDataArray.last?.id ?? 0
}else{
max_id = 0
since_id = blogDataArray.first?.id ?? 0
}
//在传入的方法中来添加这两个参数
GetMainPageMessageModel.loadUserData(since_id: since_id, max_id: max_id) { (array) -> () in
SVProgressHUD.dismiss()
self.refreshControl?.endRefreshing()
if array == nil{
UIView.animateWithDuration(1.25, animations: { () -> Void in
print("________没有数据了")
SVProgressHUD.showErrorWithStatus("哎呀..没有新的数据呢..", maskType: SVProgressHUDMaskType.Black)
}, completion: { (_) -> Void in
SVProgressHUD.dismiss()
self.upDragActivityView.stopAnimating()
})
return
}
if since_id > 0 {
self.blogDataArray = array! + self.blogDataArray
}else if max_id > 0 {
self.blogDataArray += array!
self.upDragActivityView.stopAnimating()
print(self.blogDataArray.count)
}else{
self.blogDataArray = array!
}
self.tableView.reloadData()
}
}
private func registCell() {
self.tableView.registerClass(CSYHomeTableViewCell.self, forCellReuseIdentifier: cellID)
tableView.separatorStyle = .None
}
// MARK: - Table view delegate
// override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//
// return 44
//
// }
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.blogDataArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! CSYHomeTableViewCell
let model = blogDataArray[indexPath.row]
cell.blogModel = model
if indexPath.row == blogDataArray.count - 1{
upDragActivityView.startAnimating()
loadData()
SVProgressHUD.showWithStatus("加载更多数据", maskType: SVProgressHUDMaskType.Black)
}
return cell
}
//加载网络数据
}
| 345a24183c126402096c888bdf54957e | 25.490099 | 142 | 0.531303 | false | false | false | false |
diwu/BeijingAirWatch | refs/heads/master | CommonUtil/CommonUtil.swift | mit | 1 | //
// CommonUtil.swift
// BeijingAirWatch
//
// Created by Di Wu on 10/15/15.
// Copyright © 2015 Beijing Air Watch. All rights reserved.
//
import Foundation
let DEBUG_LOCAL_NOTIFICATION : Bool = true
let TIME_OUT_LIMIT: Double = 15.0;
let TIME_OUT_LIMIT_IOS: Double = 30.0;
enum City: String {
case Beijing = "Beijing"
case Chengdu = "Chengdu"
case Guangzhou = "Guangzhou"
case Shanghai = "Shanghai"
case Shenyang = "Shenyang"
}
func parseTime(data: String) -> String {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
// print("data = \(escapedString)")
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%0D%0A%09%09%09%09%09%09%09%09%3C")
for s in arr {
let subArr = s.components(separatedBy: "%3E%0D%0A%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
if (tmp.contains("PM") || tmp.contains("AM")) && tmp.characters.count <= 40 {
return tmp.removingPercentEncoding!
}
}
}
}
return "Invalid Time"
}
func parseAQI(data: String) -> Int {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%20AQI%0D%0A")
for s in arr {
let subArr = s.components(separatedBy: "%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
guard let intValue = Int(tmp) else {
continue
}
guard intValue >= 0 else {
continue
}
return intValue
}
}
}
return -1
}
func parseConcentration(data: String) -> Double {
let escapedString: String? = data.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
if let unwrapped = escapedString {
let arr = unwrapped.components(separatedBy: "%20%C3%82%C2%B5g%2Fm%C3%82%C2%B3%20%0D%0A%09%09%09%09%09%09%09%09")
for s in arr {
let subArr = s.components(separatedBy: "%09%09%09%09%09%09%09%09%09")
if let tmp = subArr.last {
guard let doubleValue = Double(tmp) else {
return -1.0
}
guard doubleValue >= 0.0 else {
return -1
}
return doubleValue
}
}
}
return -1.0
}
func sharedSessionForIOS() -> URLSession {
let session = URLSession.shared
session.configuration.timeoutIntervalForRequest = TIME_OUT_LIMIT_IOS
session.configuration.timeoutIntervalForResource = TIME_OUT_LIMIT_IOS
return session
}
func sessionForWatchExtension() -> URLSession {
let session = URLSession.shared
session.configuration.timeoutIntervalForRequest = TIME_OUT_LIMIT
session.configuration.timeoutIntervalForResource = TIME_OUT_LIMIT
return session
}
func createHttpGetDataTask(session: URLSession?, request: URLRequest!, callback: @escaping (String, String?) -> Void) -> URLSessionDataTask? {
let task = session?.dataTask(with: request){
(data, response, error) -> Void in
if error != nil {
callback("", error!.localizedDescription)
} else {
let result = String(data: data!, encoding: .ascii)!
callback(result, nil)
}
}
return task
}
func createRequest() -> URLRequest {
return URLRequest(url: URL(string: sourceURL(city: selectedCity()))!)
}
func sourceURL(city: City) -> String {
switch city {
case .Beijing:
return "http://www.stateair.net/web/post/1/1.html";
case .Chengdu:
return "http://www.stateair.net/web/post/1/2.html";
case .Guangzhou:
return "http://www.stateair.net/web/post/1/3.html";
case .Shanghai:
return "http://www.stateair.net/web/post/1/4.html";
case .Shenyang:
return "http://www.stateair.net/web/post/1/5.html";
}
}
func selectedCity() -> City {
let sc: String? = UserDefaults.standard.string(forKey:"selected_city")
if sc == nil {
return .Beijing
} else {
return City(rawValue: sc!)!
}
}
func sourceDescription() -> String {
return "\(selectedCity()): \(sourceURL(city:selectedCity()))"
}
let CitiesList: [City] = [.Beijing, .Chengdu, .Guangzhou, .Shanghai, .Shenyang]
func currentHour() -> Int {
let date = Date()
let gregorianCal = Calendar(identifier: .gregorian)
let comps = gregorianCal.dateComponents(in: TimeZone(abbreviation: "HKT")!, from: date)
return comps.hour!
}
func currentMinute() -> Int {
let date = Date()
let gregorianCal = Calendar(identifier: .gregorian)
let comps = gregorianCal.dateComponents(in: TimeZone(abbreviation: "HKT")!, from: date)
return comps.minute!
}
| 418cde855aaf63c65f5436ceaf4a76d0 | 30.806452 | 142 | 0.611359 | false | false | false | false |
Xiomara7/bookiao-ios | refs/heads/master | bookiao-ios/ProfileViewController.swift | mit | 1 | //
// ProfileViewController.swift
// bookiao-ios
//
// Created by Xiomara on 10/17/14.
// Copyright (c) 2014 UPRRP. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class ProfileViewController: UIViewController {
var customDesign = CustomDesign()
var nameLabel: UILabel = CustomDesign.getProfileLabel
var emailLabel: UILabel = CustomDesign.getProfileLabel
var phoneLabel: UILabel = CustomDesign.getProfileLabel
let rButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
let application = UIApplication.sharedApplication().delegate as AppDelegate
override func viewDidLoad() {
self.view.backgroundColor = customDesign.UIColorFromRGB(0xE4E4E4)
let application = UIApplication.sharedApplication().delegate as AppDelegate
super.viewDidLoad()
let userinfo = DataManager.sharedManager.userInfo
nameLabel.frame = CGRectMake(20, 205, self.view.bounds.width - 40, 40)
nameLabel.text = userinfo["name"] as String!
emailLabel.frame = CGRectMake(20, 260, self.view.bounds.width - 40, 40)
emailLabel.text = userinfo["email"] as String!
phoneLabel.frame = CGRectMake(20, 315, self.view.bounds.width - 40, 40)
phoneLabel.text = userinfo["phone_number"] as String!
rButton.frame = CGRectMake(20, 440, self.view.bounds.width - 40, 40)
rButton.backgroundColor = customDesign.UIColorFromRGB(0x34A3DB)
rButton.tintColor = UIColor.whiteColor()
rButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16.0)
rButton.setTitle("Editar", forState: UIControlState.Normal)
rButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(nameLabel)
self.view.addSubview(phoneLabel)
self.view.addSubview(emailLabel)
self.view.addSubview(rButton)
}
func buttonAction(sender:UIButton!){
println("Button tapped")
let edit = EditProfileViewController(nibName: nil, bundle: nil)
self.presentViewController(edit, animated: true, completion: nil)
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.navigationItem.title = "Perfil"
self.tabBarController?.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.tabBarController?.navigationController?.navigationBar.backgroundColor = UIColor.whiteColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
} | ed683d812c4c1fa316e77f93dd800b55 | 37.535211 | 105 | 0.684826 | false | false | false | false |
github/Quick | refs/heads/master | Quick/DSL/World+DSL.swift | apache-2.0 | 1 | /**
Adds methods to World to support top-level DSL functions (Swift) and
macros (Objective-C). These functions map directly to the DSL that test
writers use in their specs.
*/
extension World {
public func beforeSuite(closure: BeforeSuiteClosure) {
suiteHooks.appendBefore(closure)
}
public func afterSuite(closure: AfterSuiteClosure) {
suiteHooks.appendAfter(closure)
}
public func sharedExamples(name: String, closure: SharedExampleClosure) {
registerSharedExample(name, closure: closure)
}
public func describe(description: String, closure: () -> ()) {
var group = ExampleGroup(description: description)
currentExampleGroup!.appendExampleGroup(group)
currentExampleGroup = group
closure()
currentExampleGroup = group.parent
}
public func context(description: String, closure: () -> ()) {
describe(description, closure: closure)
}
public func beforeEach(closure: BeforeExampleClosure) {
currentExampleGroup!.hooks.appendBefore(closure)
}
public func beforeEach(#closure: BeforeExampleWithMetadataClosure) {
currentExampleGroup!.hooks.appendBefore(closure)
}
public func afterEach(closure: AfterExampleClosure) {
currentExampleGroup!.hooks.appendAfter(closure)
}
public func afterEach(#closure: AfterExampleWithMetadataClosure) {
currentExampleGroup!.hooks.appendAfter(closure)
}
@objc(itWithDescription:file:line:closure:)
public func it(description: String, file: String, line: Int, closure: () -> ()) {
let callsite = Callsite(file: file, line: line)
let example = Example(description, callsite, closure)
currentExampleGroup!.appendExample(example)
}
@objc(itBehavesLikeSharedExampleNamed:sharedExampleContext:file:line:)
public func itBehavesLike(name: String, sharedExampleContext: SharedExampleContext, file: String, line: Int) {
let callsite = Callsite(file: file, line: line)
let closure = World.sharedWorld().sharedExample(name)
var group = ExampleGroup(description: name)
currentExampleGroup!.appendExampleGroup(group)
currentExampleGroup = group
closure(sharedExampleContext)
currentExampleGroup!.walkDownExamples { (example: Example) in
example.isSharedExample = true
example.callsite = callsite
}
currentExampleGroup = group.parent
}
public func pending(description: String, closure: () -> ()) {
NSLog("Pending: %@", description)
}
}
| 3912fbb3c92637836d4ac145dd58253b | 34.256757 | 114 | 0.687236 | false | false | false | false |
antlr/antlr4 | refs/heads/dev | runtime/Swift/Sources/Antlr4/atn/Transition.swift | bsd-3-clause | 7 | ///
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
/// Use of this file is governed by the BSD 3-clause license that
/// can be found in the LICENSE.txt file in the project root.
///
///
/// An ATN transition between any two ATN states. Subclasses define
/// atom, set, epsilon, action, predicate, rule transitions.
///
/// This is a one way link. It emanates from a state (usually via a list of
/// transitions) and has a target state.
///
/// Since we never have to change the ATN transitions once we construct it,
/// we can fix these transitions as specific classes. The DFA transitions
/// on the other hand need to update the labels as it adds transitions to
/// the states. We'll use the term Edge for the DFA to distinguish them from
/// ATN transitions.
///
import Foundation
public class Transition {
// constants for serialization
public static let EPSILON: Int = 1
public static let RANGE: Int = 2
public static let RULE: Int = 3
public static let PREDICATE: Int = 4
// e.g., {isType(input.LT(1))}?
public static let ATOM: Int = 5
public static let ACTION: Int = 6
public static let SET: Int = 7
// ~(A|B) or ~atom, wildcard, which convert to next 2
public static let NOT_SET: Int = 8
public static let WILDCARD: Int = 9
public static let PRECEDENCE: Int = 10
public let serializationNames: Array<String> =
["INVALID",
"EPSILON",
"RANGE",
"RULE",
"PREDICATE",
"ATOM",
"ACTION",
"SET",
"NOT_SET",
"WILDCARD",
"PRECEDENCE"]
public static let serializationTypes: Dictionary<String, Int> = [
String(describing: EpsilonTransition.self): EPSILON,
String(describing: RangeTransition.self): RANGE,
String(describing: RuleTransition.self): RULE,
String(describing: PredicateTransition.self): PREDICATE,
String(describing: AtomTransition.self): ATOM,
String(describing: ActionTransition.self): ACTION,
String(describing: SetTransition.self): SET,
String(describing: NotSetTransition.self): NOT_SET,
String(describing: WildcardTransition.self): WILDCARD,
String(describing: PrecedencePredicateTransition.self): PRECEDENCE,
]
///
/// The target of this transition.
///
public internal(set) final var target: ATNState
init(_ target: ATNState) {
self.target = target
}
public func getSerializationType() -> Int {
fatalError(#function + " must be overridden")
}
///
/// Determines if the transition is an "epsilon" transition.
///
/// The default implementation returns `false`.
///
/// - returns: `true` if traversing this transition in the ATN does not
/// consume an input symbol; otherwise, `false` if traversing this
/// transition consumes (matches) an input symbol.
///
public func isEpsilon() -> Bool {
return false
}
public func labelIntervalSet() -> IntervalSet? {
return nil
}
public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool {
fatalError(#function + " must be overridden")
}
}
| a402c0c861027fcad08fbfdd218de05a | 28.853211 | 94 | 0.642286 | false | false | false | false |
khoiln/SwiftlyExt | refs/heads/master | Source/StringExtensions.swift | mit | 1 | //
// StringExtensions.swift
// SwiftlyExt
//
// Created by Khoi Lai on 10/10/2016.
// Copyright © 2016 Khoi Lai. All rights reserved.
//
import Foundation
public extension String {
/// Find the string between two string.
///
/// - Parameters:
/// - left: The left bookend
/// - right: The right bookend
/// - Returns: Return the String if found else `nil`
func between(_ left: String, _ right: String) -> String? {
guard let leftRange = range(of: left),
let rightRange = range(of: right, options: .backwards),
left != right && leftRange.upperBound != rightRange.lowerBound else {
return nil
}
return self[leftRange.upperBound...index(before: rightRange.lowerBound)]
}
/// Count number of occurences for a substring
///
/// - Parameter str: The string to count
/// - Returns: Number of occurences
func count(_ str: String) -> Int {
return components(separatedBy: str).count - 1
}
/// Return a date from current string.
///
/// - parameter format: The date format
/// - parameter locale: The locale. default to `.current`
///
/// - returns: A Date.
func date(format: String, locale: Locale = .current) -> Date? {
let df = DateFormatter()
df.dateFormat = format
df.locale = locale
return df.date(from: self)
}
/// Check whether the string is an email or not.
var isEmail: Bool {
let regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let predicate = NSPredicate(format:"SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
/// Check whether the string contains one or more letters.
public var hasLetters: Bool {
return rangeOfCharacter(from: .letters, options: .literal) != nil
}
/// Check whether the string contains one or more numbers.
public var hasNumbers: Bool {
return rangeOfCharacter(from: .decimalDigits, options: .literal) != nil
}
/// Check whether the string contains only letters.
var isAlpha: Bool {
for c in characters {
if !(c >= "a" && c <= "z") && !(c >= "A" && c <= "Z") {
return false
}
}
return true
}
/// Check if string contains at least one letter and one number
var isAlphaNumeric: Bool {
return components(separatedBy: .alphanumerics).joined(separator: "").characters.isEmpty
}
/// Return the initials of the String
var initials: String {
return self.components(separatedBy: " ").reduce("") { $0 + $1[0...0] }
}
/// Decoded Base 64 String if applicable
var base64Decoded: String? {
guard let decodedData = Data(base64Encoded: self) else { return nil }
return String(data: decodedData, encoding: .utf8)
}
/// Encoded Base 64 String if applicable
var base64Encoded: String? {
return data(using: .utf8)?.base64EncodedString()
}
/// Reversed String
var reversed: String {
return String(self.characters.reversed())
}
/// A String without white spaces and new lines
var trimmed: String {
return trimmingCharacters(in: .whitespacesAndNewlines)
}
/// Decoded URL String
var urlDecoded: String {
return removingPercentEncoding ?? self
}
/// Encoded URL String
var urlEncoded: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? self
}
}
extension String {
subscript (r: CountableClosedRange<Int>) -> String {
get {
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return self[startIndex...endIndex]
}
}
}
| 0c18fe76f6d5be30e767d412482d4744 | 29.472441 | 95 | 0.603101 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/Constraints/unchecked_optional.swift | apache-2.0 | 14 | // RUN: %target-parse-verify-swift
class A {
func do_a() {}
func do_b(x: Int) {}
func do_b(x: Float) {}
func do_c(x x: Int) {}
func do_c(y y: Int) {}
}
func test0(a : A!) {
a.do_a()
a.do_b(1)
a.do_b(5.0)
a.do_c(1) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'do_c' exist with these partially matching parameter lists: (x: Int), (y: Int)}}
a.do_c(x: 1)
}
func test1(a : A!) {
a?.do_a()
a?.do_b(1)
a?.do_b(5.0)
a?.do_c(1) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'do_c' exist with these partially matching parameter lists: (x: Int), (y: Int)}}
a?.do_c(x: 1)
}
struct B {
var x : Int
}
func test2(b : B!) {
var b = b
let x = b.x
b.x = x
b = nil
}
struct Subscriptable {
subscript(x : Int) -> Int {
get {
return x
}
}
}
func test3(x: Subscriptable!) -> Int {
return x[0]
}
// Callable
func test4(f: (Int -> Float)!) -> Float {
return f(5)
}
func test5(value : Int!) {
let _ : Int? = value
}
func test6(value : Int!) {
let _ : Int? = value
}
class Test9a {}
class Test9b : Test9a {}
func test9_produceUnchecked() -> Test9b! { return Test9b() }
func test9_consume(foo : Test9b) {}
func test9() -> Test9a {
let foo = test9_produceUnchecked()
test9_consume(foo)
let _ : Test9a = foo
return foo
}
func test10_helper(x : Int!) -> Int? { return x }
func test10(x : Int?) -> Int! { return test10_helper(x) }
// Fall back to object type behind an implicitly-unwrapped optional.
protocol P11 { }
extension Int : P11 { }
func test11_helper<T : P11>(t: T) { }
func test11(i: Int!, j: Int!) {
var j = j
test11_helper(i)
test11_helper(j)
j = nil
}
| 6544a830cd7d28d2f8f0cde1e571814f | 18.031915 | 119 | 0.587479 | false | true | false | false |
KrishMunot/swift | refs/heads/master | test/SILGen/lazy_globals.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | FileCheck %s
// CHECK: sil private @globalinit_[[T:.*]]_func0 : $@convention(thin) () -> () {
// CHECK: alloc_global @_Tv12lazy_globals1xSi
// CHECK: [[XADDR:%.*]] = global_addr @_Tv12lazy_globals1xSi : $*Int
// CHECK: store {{%.*}} to [[XADDR]] : $*Int
// CHECK: sil hidden [global_init] @_TF12lazy_globalsau1xSi : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token0 : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func0 : $@convention(thin) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(thin) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_Tv12lazy_globals1xSi : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
// CHECK: }
var x: Int = 0
// CHECK: sil private @globalinit_[[T:.*]]_func1 : $@convention(thin) () -> () {
// CHECK: alloc_global @_TZvV12lazy_globals3Foo3fooSi
// CHECK: [[XADDR:%.*]] = global_addr @_TZvV12lazy_globals3Foo3fooSi : $*Int
// CHECK: store {{.*}} to [[XADDR]] : $*Int
// CHECK: return
struct Foo {
// CHECK: sil hidden [global_init] @_TFV12lazy_globals3Fooau3fooSi : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token1 : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func1 : $@convention(thin) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(thin) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_TZvV12lazy_globals3Foo3fooSi : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
static var foo: Int = 22
static var computed: Int {
return 33
}
static var initialized: Int = 57
}
// CHECK: sil private @globalinit_[[T:.*]]_func3 : $@convention(thin) () -> () {
// CHECK: alloc_global @_TZvO12lazy_globals3Bar3barSi
// CHECK: [[XADDR:%.*]] = global_addr @_TZvO12lazy_globals3Bar3barSi : $*Int
// CHECK: store {{.*}} to [[XADDR]] : $*Int
// CHECK: return
enum Bar {
// CHECK: sil hidden [global_init] @_TFO12lazy_globals3Barau3barSi : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: [[TOKEN_ADDR:%.*]] = global_addr @globalinit_[[T]]_token3 : $*Builtin.Word
// CHECK: [[TOKEN_PTR:%.*]] = address_to_pointer [[TOKEN_ADDR]] : $*Builtin.Word to $Builtin.RawPointer
// CHECK: [[INIT_FUNC:%.*]] = function_ref @globalinit_[[T]]_func3 : $@convention(thin) () -> ()
// CHECK: builtin "once"([[TOKEN_PTR]] : $Builtin.RawPointer, [[INIT_FUNC]] : $@convention(thin) () -> ()) : $()
// CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @_TZvO12lazy_globals3Bar3barSi : $*Int
// CHECK: [[GLOBAL_PTR:%.*]] = address_to_pointer [[GLOBAL_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: return [[GLOBAL_PTR]] : $Builtin.RawPointer
static var bar: Int = 33
}
// We only emit one initializer function per pattern binding, which initializes
// all of the bound variables.
func f() -> (Int, Int) { return (1, 2) }
// CHECK: sil private @globalinit_[[T]]_func4 : $@convention(thin) () -> () {
// CHECK: function_ref @_TF12lazy_globals1fFT_TSiSi_ : $@convention(thin) () -> (Int, Int)
// CHECK: sil hidden [global_init] @_TF12lazy_globalsau2a1Si : $@convention(thin) () -> Builtin.RawPointer
// CHECK: function_ref @globalinit_[[T]]_func4 : $@convention(thin) () -> ()
// CHECK: global_addr @_Tv12lazy_globals2a1Si : $*Int
// CHECK: sil hidden [global_init] @_TF12lazy_globalsau2b1Si : $@convention(thin) () -> Builtin.RawPointer {
// CHECK: function_ref @globalinit_[[T]]_func4 : $@convention(thin) () -> ()
// CHECK: global_addr @_Tv12lazy_globals2b1Si : $*Int
var (a1, b1) = f()
var computed: Int {
return 44
}
var initialized: Int = 57
| d50f56b526c5f0cba36a0a731b2822fd | 51.506173 | 114 | 0.621209 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.