repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
AnarchyTools/atfoundation | src/string/search.swift | 1 | 9370 | // Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Character and substring search
public extension String {
/// Search for a character in a string
///
/// - parameter character: character to search
/// - parameter index: (optional) start index, defaults to start or end of string depending on `reverse`
/// - parameter reverse: (optional) search backwards from the `index` or the end of the string
/// - returns: `String.Index` if character was found or `nil`
public func position(character: Character, index: String.Index? = nil, reverse: Bool = false) -> String.Index? {
if reverse {
var i = (index == nil) ? self.index(before: self.endIndex) : index!
while i >= self.startIndex {
if self.characters[i] == character {
return i
}
i = self.index(before: i)
}
} else {
var i = (index == nil) ? self.startIndex : index!
while i < self.endIndex {
if self.characters[i] == character {
return i
}
i = self.index(after: i)
}
}
return nil
}
/// Return array with string indices of found character positions
///
/// - parameter character: character to search
/// - returns: array of `String.Index` or empty array if character not found
public func positions(character: Character) -> [String.Index] {
var result = Array<String.Index>()
var p = self.position(character: character)
while p != nil {
result.append(p!)
p = self.position(character: character, index: self.index(after: p!))
}
return result
}
/// Search for a substring
///
/// - parameter string: substring to search
/// - parameter index: (optional) start index, defaults to start or end of string depending on `reverse`
/// - parameter reverse: (optional) search backwards from the `index` or the end of the string
/// - returns: `String.Index` if character was found or `nil`
public func position(string: String, index: String.Index? = nil, reverse: Bool = false) -> String.Index? {
if self.characters.count < string.characters.count {
// search term longer than self
return nil
}
if reverse {
if index != nil && self.distance(from: startIndex, to: index!) < string.characters.count {
// can not find match because string is too short for match
return nil
}
// start with index/self.endIndex and go back
var i = (index == nil) ? self.index(endIndex, offsetBy: -string.characters.count) : index!
while i >= self.startIndex {
var idx = i
// compare substring
var match = true
for character in string.characters {
if self.characters[idx] != character {
match = false
break
}
idx = self.index(after: idx)
}
if match {
return i
}
i = self.index(before: i)
}
} else {
if index != nil && self.distance(from: index!, to: self.endIndex) < string.characters.count {
// can not find match because string is too short for match
return nil
}
let start = (index == nil) ? self.startIndex : index!
var i = start
// iterate from start to end - search string length
while i < endIndex {
var idx = i
// compare substring
var match = true
for character in string.characters {
if self.characters[idx] != character {
match = false
break
}
idx = self.index(after: idx)
}
if match {
return i
}
i = self.index(after: i)
}
}
return nil
}
/// Return array with string indices of found substring positions
///
/// - parameter string: substring to search
/// - returns: array of `String.Index` or empty array if substring not found
public func positions(string: String) -> [String.Index] {
var result = Array<String.Index>()
var p = self.position(string: string)
while p != nil {
result.append(p!)
p = self.position(string: string, index: self.index(after: p!))
}
return result
}
/// Search for a substring
///
/// - parameter string: string to search
/// - returns: `true` if the string contains the substring
public func contains(string: String) -> Bool {
return self.position(string: string) != nil
}
/// Search for a character
///
/// - parameter char: character to search
/// - returns: `true` if the string contains the character
public func contains(character: Character) -> Bool {
return self.position(character: character) != nil
}
#if os(Linux)
/// Check if a string has a prefix
///
/// - parameter prefix: the prefix to check for
/// - returns: true if the prefix was an empty string or the string has the prefix
public func hasPrefix(_ prefix: String) -> Bool {
if prefix.characters.count == 0 {
// if the prefix has a length of zero every string is prefixed by that
return true
}
if self.characters.count < prefix.characters.count {
// if self is shorter than the prefix
return false
}
if prefix.characters.count == 1 {
// single char prefix is simple
return self.characters.first! == prefix.characters.first!
}
// quick check if first and last char match
if self.characters.first! == prefix.characters.first! && self.characters[self.index(self.startIndex, offsetBy: prefix.characters.count - 1)] == prefix.characters.last! {
// if prefix length == 2 instantly return true
if prefix.characters.count == 2 {
return true
}
// match, thorough check
var selfIndex = self.index(after:self.startIndex)
var prefixIndex = prefix.index(after:prefix.startIndex)
// first and last already checked
for _ in 1..<(prefix.characters.count - 1) {
if self.characters[selfIndex] != prefix.characters[prefixIndex] {
return false
}
selfIndex = self.index(after: selfIndex)
prefixIndex = prefix.index(after: prefixIndex)
}
return true
}
return false
}
/// Check if a string has a suffix
///
/// - parameter suffix: the suffix to check for
/// - returns: true if the suffix was an empty string or the string has the suffix
public func hasSuffix(_ suffix: String) -> Bool {
if suffix.characters.count == 0 {
// if the suffix has a length of zero every string is suffixed by that
return true
}
if self.characters.count < suffix.characters.count {
// if self is shorter than the suffix
return false
}
if suffix.characters.count == 1 {
// single char prefix is simple
return self.characters.last! == suffix.characters.first!
}
// quick check if first and last char match
if self.characters.last! == suffix.characters.last! && self.characters[self.index(self.startIndex, offsetBy: self.characters.count - suffix.characters.count)] == suffix.characters.first! {
// if suffix length == 2 instantly return true
if suffix.characters.count == 2 {
return true
}
// match, thorough check
var selfIndex = self.index(self.startIndex, offsetBy: self.characters.count - suffix.characters.count + 1)
var suffixIndex = suffix.index(after: suffix.startIndex)
// first and last already checked
for _ in 1..<(suffix.characters.count - 1) {
if self.characters[selfIndex] != suffix.characters[suffixIndex] {
return false
}
selfIndex = self.index(after: selfIndex)
suffixIndex = suffix.index(after: suffixIndex)
}
return true
}
return false
}
#endif
}
| apache-2.0 | c6feb59713850265d6549da18e855932 | 37.879668 | 196 | 0.557844 | 4.785495 | false | false | false | false |
diegocavalca/Studies | programming/Swift/QuizFinal/QuizFinal/ViewController.swift | 1 | 7561 | //
// ViewController.swift
// QuizFinal
//
// Created by Diego Cavalca on 11/12/15.
// Copyright (c) 2015 Diego Cavalca. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var lbQuestion: UILabel!
@IBOutlet weak var imgQuestion: UIImageView!
@IBOutlet weak var btnOption0: UIButton!
@IBOutlet weak var btnOption1: UIButton!
@IBOutlet weak var btnOption2: UIButton!
@IBOutlet weak var btnOption3: UIButton!
@IBOutlet weak var viewFeedback: UIView!
@IBOutlet weak var lbFeedback: UILabel!
@IBOutlet weak var btnFeedback: UIButton!
var questions : [Question]! // Questões do quiz...
var grade = 0.0 // Nota do quiz...
var quizEnded = false // Situacao atual do quiz...
var currentQuestion = 0 // Questão atual do usuario...
override func viewDidLoad() {
super.viewDidLoad()
// Questão 1...
let q0answer0 = Answer(pText: "Tigre", pIsCorrect: true)
let q0answer1 = Answer(pText: "Leão", pIsCorrect: false)
let q0answer2 = Answer(pText: "Onça", pIsCorrect: false)
let q0answer3 = Answer(pText: "Pantera", pIsCorrect: false)
let question0 = Question(pText: "Qual o maior felino do mundo (em dimensões)?", pImage: "gato", pAnswers: [q0answer0, q0answer1, q0answer2, q0answer3])
//let question0 = Question(pQuestion: "Quantos anos vive em média um elefante africano?", pImageFileName: "elefante", pAnswers: [q0answer0, q0answer1, q0answer2])
// Questão 2...
let q1answer0 = Answer(pText: "Crocodilo", pIsCorrect: true)
let q1answer1 = Answer(pText: "Lagarto", pIsCorrect: false)
let q1answer2 = Answer(pText: "Tartaruga", pIsCorrect: false)
let q1answer3 = Answer(pText: "Cobra", pIsCorrect: false)
let question1 = Question(pText: "Qual o maior réptil do mundo?", pImage: "reptil", pAnswers: [q1answer0, q1answer1, q1answer2, q1answer3])
// Questão 3...
let q2answer0 = Answer(pText: "Avestruz", pIsCorrect: true)
let q2answer1 = Answer(pText: "Urubu", pIsCorrect: false)
let q2answer2 = Answer(pText: "Ema", pIsCorrect: false)
let q2answer3 = Answer(pText: "Albatroz", pIsCorrect: false)
let question2 = Question(pText: "Qual a maior ave do mundo?", pImage: "galinha", pAnswers: [q2answer0, q2answer1, q2answer2, q2answer3])
// Questão 4...
let q3answer0 = Answer(pText: "Baleia Azul", pIsCorrect: true)
let q3answer1 = Answer(pText: "Rinorceronte", pIsCorrect: false)
let q3answer2 = Answer(pText: "Elefante-africano", pIsCorrect: false)
let q3answer3 = Answer(pText: "Tubarão-baleia", pIsCorrect: false)
let question3 = Question(pText: "Qual o maior animal vivo no planeta?", pImage: "humano", pAnswers: [q3answer0, q3answer1, q3answer2, q3answer3])
// Questão 5...
let q4answer0 = Answer(pText: "Píton", pIsCorrect: true)
let q4answer1 = Answer(pText: "Sucuri", pIsCorrect: false)
let q4answer2 = Answer(pText: "Anaconda", pIsCorrect: false)
let q4answer3 = Answer(pText: "Cascavel", pIsCorrect: false)
let question4 = Question(pText: "Qual a maior cobra do mundo?", pImage: "cobra", pAnswers: [q4answer0, q4answer1, q4answer2, q4answer3])
// Questão 6...
let q5answer0 = Answer(pText: "Anfíbios", pIsCorrect: true)
let q5answer1 = Answer(pText: "Répteis", pIsCorrect: false)
let q5answer2 = Answer(pText: "Aquáticos", pIsCorrect: false)
let q5answer3 = Answer(pText: "Terrestres", pIsCorrect: false)
let question5 = Question(pText: "Como se chamam as espécies que podem viver tanto em terra quanto na água?", pImage: "bulbasauro", pAnswers: [q5answer0, q5answer1, q5answer2, q5answer3])
// Juntando questões...
questions = [question0, question1, question2, question3, question4, question5]
startQuiz()
}
func startQuiz(){
questions.shuffle() // Embaralhando questoes...
for question in questions {
question.answers.shuffle() // Embaralhando opções de resposta...
}
// Resetando variaveis de controle do quiz...
quizEnded = false
grade = 0.0
currentQuestion = 0
showQuestion(0)
}
func showQuestion(pQuestionId: Int){
// Controlando componentes...
btnOption0.enabled = true
btnOption1.enabled = true
btnOption2.enabled = true
btnOption3.enabled = true
// Inicializando dados da questão...
lbQuestion.text = questions[pQuestionId].text
imgQuestion.image = questions[pQuestionId].image
btnOption0.setTitle(questions[pQuestionId].answers[0].text, forState: UIControlState.Normal)
btnOption1.setTitle(questions[pQuestionId].answers[1].text, forState: UIControlState.Normal)
btnOption2.setTitle(questions[pQuestionId].answers[2].text, forState: UIControlState.Normal)
btnOption3.setTitle(questions[pQuestionId].answers[3].text, forState: UIControlState.Normal)
}
@IBAction func chooseOption0(sender: AnyObject) {
selectAnswer(0)
}
@IBAction func chooseOption1(sender: AnyObject) {
selectAnswer(1)
}
@IBAction func chooseOption2(sender: AnyObject) {
selectAnswer(2)
}
@IBAction func chooseOption3(sender: AnyObject) {
selectAnswer(3)
}
func selectAnswer(pAnswerId: Int){
// Controlando componentes...
btnOption0.enabled = false
btnOption1.enabled = false
btnOption2.enabled = false
btnOption3.enabled = false
viewFeedback.hidden = false
var answer = questions[currentQuestion].answers[pAnswerId];
// Corrigir...
if(answer.isCorrect == true){
grade = grade + 1.0
lbFeedback.text = answer.text + "\n\nResposta Correta!"
}else{
lbFeedback.text = answer.text + "\n\nResposta errada..."
}
// Situação do quiz...
if(currentQuestion < questions.count-1){
btnFeedback.setTitle("PRÓXIMA PERGUNTA", forState: UIControlState.Normal)
}else{
btnFeedback.setTitle("VER PONTUAÇÃO", forState: UIControlState.Normal)
}
}
@IBAction func btnFeedbackAction(sender: AnyObject) {
viewFeedback.hidden = true
if(quizEnded){
startQuiz() // Recomeçar...
}else{
nextQuestion() // Próxima...
}
}
func nextQuestion(){
currentQuestion++
// Situação do quiz...
if(currentQuestion < questions.count){
showQuestion(currentQuestion)
}else{
endQuiz()
}
}
func endQuiz(){
var pGrade = grade / Double(questions.count) * 100
quizEnded = true
viewFeedback.hidden = false
lbFeedback.text = "Você acertou \(Int(grade)) de \(questions.count) questões!"
btnFeedback.setTitle("TENTAR DENOVO!", forState: UIControlState.Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cc0-1.0 | 96cd62c2701b827a68c6937d16a643ef | 35.892157 | 194 | 0.618655 | 3.727588 | false | false | false | false |
peantunes/swift-spritekit-tools | swift-sk-tools/animation/ScreenNode.swift | 1 | 1377 | //
// ScreenNode.swift
// Puzzle
//
// Created by Pedro Antunes on 06/01/2015.
// Copyright (c) 2015 Antunes. All rights reserved.
//
import SpriteKit
class ScreenNode:SKSpriteNode{
weak var mainScene:SKScene?
var clickable=true
class func screenInto(scene:SKScene, clickOutside:Bool) -> ScreenNode{
return self.screenInto(scene, clickOutside: clickOutside, alpha: 0.6)
}
class func screenInto(scene:SKScene, clickOutside:Bool, alpha:Double) -> ScreenNode{
let color = UIColor(white: 0, alpha: CGFloat(alpha))
let screen = ScreenNode(color: color, size: scene.size)
screen.mainScene = scene
screen.userInteractionEnabled = true
screen.clickable=clickOutside
screen.position = CGPointMake(CGRectGetMidX(scene.frame), CGRectGetMidY(scene.frame))
screen.zPosition = CGFloat(Constants.Position.Popup)
scene.addChild(screen)
return screen
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if (self.clickable){
let node:SKNode = self.children[0] as SKNode
AnimationUtil.removeAnimatedImage(node, callback: { () -> Void in
})
}
self.mainScene?.touchesBegan(touches, withEvent: event)
}
}
| mit | 9beb6d6cb831262ba9c22d8da226da82 | 28.297872 | 93 | 0.62382 | 4.441935 | false | false | false | false |
sunshineclt/NKU-Helper | NKU Helper/设置/AccountInfo/AccountLogInViewController.swift | 1 | 5692 | //
// AccountLogInViewController.swift
// NKU Helper
//
// Created by 陈乐天 on 15/3/3.
// Copyright (c) 2015年 陈乐天. All rights reserved.
//
import UIKit
import WebKit
import Alamofire
import Locksmith
class AccountLogInViewController: UIViewController, UIAlertViewDelegate, UITextFieldDelegate, UIWebViewDelegate {
@IBOutlet var userIDTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
@IBOutlet var validateCodeTextField: UITextField!
@IBOutlet var validateCodeImageView: UIImageView!
@IBOutlet var loginButton: UIButton!
@IBOutlet var imageLoadActivityIndicator: UIActivityIndicatorView! {didSet{imageLoadActivityIndicator.hidesWhenStopped = true}}
var progressHud:MBProgressHUD!
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
loginButton.layer.cornerRadius = 5
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshImage()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
userIDTextField.becomeFirstResponder()
}
var loginer: NKNetworkLoginHandler!
lazy var userInfoGetter = NKNetworkUserInfoHandler()
@IBAction func login(_ sender: AnyObject) {
guard let userID = userIDTextField.text,
let password = passwordTextField.text,
let validateCode = validateCodeTextField.text else {
present(ErrorHandler.alertWith(title: "信息错误", message: "用户名、密码、验证码不能为空", cancelButtonTitle: "好"), animated: true, completion: nil)
return
}
MBProgressHUD.showAdded(to: self.view, animated: true)
loginer = NKNetworkLoginHandler(ID: userID, password: password, validateCode: validateCode)
loginer.login(onView: self.view) { (result) in
MBProgressHUD.hide(for: self.view, animated: true)
switch result {
case .success:
NKNetworkUserInfoHandler.getAllAccountInfo(withBlock: { (result) in
switch result {
case .success(let name, let timeEnteringSchool, let departmentAdmitted, let majorAdmitted):
let saveSuccess = self.saveAccountInfo(name: name, timeEnteringSchool: timeEnteringSchool, departmentAdmitted: departmentAdmitted, majorAdmitted: majorAdmitted)
NKNetworkInfoHandler.registerUser()
if saveSuccess {
let _ = self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}
else {
self.present(ErrorHandler.alertWith(title: "在钥匙串中存储密码失败", message: "请重试或通知开发者", cancelButtonTitle: "好"), animated: true, completion: nil)
}
case .networkError:
self.present(ErrorHandler.alert(withError: ErrorHandler.NetworkError()), animated: true, completion: nil)
case .analyzeError:
self.refreshImage()
self.present(ErrorHandler.alert(withError: ErrorHandler.HtmlAnalyseFail()), animated: true, completion: nil)
}
})
case .userNameOrPasswordWrong:
self.present(ErrorHandler.alert(withError: ErrorHandler.UserNameOrPasswordWrong(), andHandler: { (action) in
self.userIDTextField.becomeFirstResponder()
}), animated: true, completion: nil)
case .validateCodeWrong:
self.refreshImage()
self.validateCodeTextField.text = ""
self.present(ErrorHandler.alert(withError: ErrorHandler.ValidateCodeWrong(), andHandler: { ( action) in
self.validateCodeTextField.becomeFirstResponder()
}), animated: true, completion: nil)
case .netWorkError:
self.present(ErrorHandler.alert(withError: ErrorHandler.NetworkError()), animated: true, completion: nil)
}
}
}
func saveAccountInfo(name:String, timeEnteringSchool:String, departmentAdmitted:String, majorAdmitted:String) -> Bool {
let user = User(userID: userIDTextField.text!, password: passwordTextField.text!, name: name, timeEnteringSchool: timeEnteringSchool, departmentAdmitted: departmentAdmitted, majorAdmitted: majorAdmitted)
do {
try UserAgent.sharedInstance.save(data: user)
} catch {
return false
}
return true
}
func refreshImage() {
imageLoadActivityIndicator.startAnimating()
NKNetworkValidateCodeGetter.getValidateCode { (data, err) in
self.imageLoadActivityIndicator.stopAnimating()
guard err == nil else {
self.present(ErrorHandler.alert(withError: ErrorHandler.NetworkError()), animated: true, completion: nil)
return
}
self.validateCodeImageView.image = UIImage(data: data!)
}
}
@IBAction func nameTextFieldDidEnd(_ sender: AnyObject) {
passwordTextField.becomeFirstResponder()
}
@IBAction func passwordTextFieldDidEnd(_ sender: AnyObject) {
validateCodeTextField.becomeFirstResponder()
}
@IBAction func validateCodeTextFieldDidEnd(_ sender: AnyObject) {
let _ = sender.resignFirstResponder()
login("FromReturnKey" as AnyObject)
}
}
| gpl-3.0 | a9709f25c150a12253f276c60d01afd8 | 43.428571 | 211 | 0.637192 | 5.276155 | false | false | false | false |
lightsprint09/LADVSwift | LADVSwift/Athlete/AgeClass.swift | 1 | 9737 | //
// AgeClass.swift
// Leichatletik
//
// Created by Lukas Schmidt on 13.02.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
public struct Age: Hashable {
public let name: String
public let shortName: String
public let ladvID: String
public let dlvID: String
public init(dlvID: String) {
if let newSelf = Age.all.first(where: { $0.dlvID == dlvID }) {
self = newSelf
} else {
self.name = dlvID
self.shortName = dlvID
self.ladvID = dlvID
self.dlvID = dlvID
}
}
init(any: String) {
if let newSelf = Age.all.first(where: { $0.dlvID == any }) ?? Age.all.first(where: { $0.shortName == any }) ?? Age.all.first(where: { $0.ladvID == any }) ?? Age.all.first(where: { any.contains($0.dlvID) }) {
self = newSelf
} else {
self.name = any
self.shortName = any
self.ladvID = any
self.dlvID = any
}
}
public init(name: String, shortName: String, ladvID: String, dlvID: String) {
self.name = name
self.shortName = shortName
self.ladvID = ladvID
self.dlvID = dlvID
}
public static let all: [Age] = [Age(name: "Kinder M3", shortName: "M03", ladvID: "M3", dlvID: "M3"),
Age(name: "Kinder M4", shortName: "M04", ladvID: "M4", dlvID: "M4"),
Age(name: "Kinder M5", shortName: "M05", ladvID: "M5", dlvID: "M5"),
Age(name: "Kinder M6", shortName: "M06", ladvID: "M6", dlvID: "M6"),
Age(name: "Kinder M7", shortName: "M07", ladvID: "M7", dlvID: "M7"),
Age(name: "Kinder M8", shortName: "M08", ladvID: "M8", dlvID: "M8"),
Age(name: "Kinder M9", shortName: "M09", ladvID: "M9", dlvID: "M9"),
Age(name: "Kinder M10", shortName: "M10", ladvID: "M10", dlvID: "M10"),
Age(name: "Kinder M11", shortName: "M11", ladvID: "M11", dlvID: "M11"),
Age(name: "Jugend M12", shortName: "M12", ladvID: "M12", dlvID: "M12"),
Age(name: "Jugend M13", shortName: "M13", ladvID: "M13", dlvID: "M13"),
Age(name: "Jugend M14", shortName: "M14", ladvID: "M14", dlvID: "M14"),
Age(name: "Jugend M15", shortName: "M15", ladvID: "M15", dlvID: "M15"),
Age(name: "männliche Kinder U8", shortName: "MK U8", ladvID: "MKU8", dlvID: "SE"),
Age(name: "männliche Kinder U10", shortName: "MK U10", ladvID: "MKU10", dlvID: "SD"),
Age(name: "männliche Kinder U12", shortName: "MK U12", ladvID: "MKU12", dlvID: "SC"),
Age(name: "männliche Jugend U14", shortName: "MJ U14", ladvID: "MJU14", dlvID: "SB"),
Age(name: "männliche Jugend U16", shortName: "MJ U16", ladvID: "MJU16", dlvID: "SA"),
Age(name: "männliche Jugend U18", shortName: "MJ U18", ladvID: "MJU18", dlvID: "MJB"),
Age(name: "männliche Jugend U20", shortName: "MJ U20", ladvID: "MJU20", dlvID: "MJA"),
Age(name: "Junioren U23", shortName: "M U23", ladvID: "MU23", dlvID: "J"),
Age(name: "Männer", shortName: "Männer", ladvID: "M", dlvID: "M"),
Age(name: "Senioren M30", shortName: "M30", ladvID: "M30", dlvID: "M30"),
Age(name: "Senioren M35", shortName: "M35", ladvID: "M35", dlvID: "M35"),
Age(name: "Senioren M40", shortName: "M40", ladvID: "M40", dlvID: "M40"),
Age(name: "Senioren M45", shortName: "M45", ladvID: "M45", dlvID: "M45"),
Age(name: "Senioren M50", shortName: "M50", ladvID: "M50", dlvID: "M50"),
Age(name: "Senioren M55", shortName: "M55", ladvID: "M55", dlvID: "M55"),
Age(name: "Senioren M60", shortName: "M60", ladvID: "M60", dlvID: "M60"),
Age(name: "Senioren M65", shortName: "M65", ladvID: "M65", dlvID: "M65"),
Age(name: "Senioren M70", shortName: "M70", ladvID: "M70", dlvID: "M70"),
Age(name: "Senioren M75", shortName: "M75", ladvID: "M75", dlvID: "M75"),
Age(name: "Senioren M80", shortName: "M80", ladvID: "M80", dlvID: "M80"),
Age(name: "Senioren M85", shortName: "M85", ladvID: "M85", dlvID: "M85"),
Age(name: "Senioren M90", shortName: "M90", ladvID: "M90", dlvID: "M90"),
Age(name: "Senioren M95", shortName: "M95", ladvID: "M95", dlvID: "M95"),
Age(name: "Kinder W3", shortName: "W03", ladvID: "W3", dlvID: "W3"),
Age(name: "Kinder W4", shortName: "W04", ladvID: "W4", dlvID: "W4"),
Age(name: "Kinder W5", shortName: "W05", ladvID: "W5", dlvID: "W5"),
Age(name: "Kinder W6", shortName: "W06", ladvID: "W6", dlvID: "W6"),
Age(name: "Kinder W7", shortName: "W07", ladvID: "W7", dlvID: "W7"),
Age(name: "Kinder W8", shortName: "W08", ladvID: "W8", dlvID: "W8"),
Age(name: "Kinder W9", shortName: "W09", ladvID: "W9", dlvID: "W9"),
Age(name: "Kinder W10", shortName: "W10", ladvID: "W10", dlvID: "W10"),
Age(name: "Kinder W11", shortName: "W11", ladvID: "W11", dlvID: "W11"),
Age(name: "Jugend W12", shortName: "W12", ladvID: "W12", dlvID: "W12"),
Age(name: "Jugend W13", shortName: "W13", ladvID: "W13", dlvID: "W13"),
Age(name: "Jugend W14", shortName: "W14", ladvID: "W14", dlvID: "W14"),
Age(name: "Jugend W15", shortName: "W15", ladvID: "W15", dlvID: "W15"),
Age(name: "weibliche Kinder U8", shortName: "WK U8", ladvID: "WKU8", dlvID: "SIE"),
Age(name: "weibliche Kinder U10", shortName: "WK U10", ladvID: "WKU10", dlvID: "SID"),
Age(name: "weibliche Kinder U12", shortName: "WK U12", ladvID: "WKU12", dlvID: "SIC"),
Age(name: "weibliche Jugend U14", shortName: "WJ U14", ladvID: "WJU14", dlvID: "SIB"),
Age(name: "weibliche Jugend U16", shortName: "WJ U16", ladvID: "WJU16", dlvID: "SIA"),
Age(name: "weibliche Jugend U18", shortName: "WJ U18", ladvID: "WJU18", dlvID: "WJB"),
Age(name: "weibliche Jugend U20", shortName: "WJ U20", ladvID: "WJU20", dlvID: "WJA"),
Age(name: "Juniorinnen U23", shortName: "W U23", ladvID: "WU23", dlvID: "JI"),
Age(name: "Frauen", shortName: "Frauen", ladvID: "W", dlvID: "W"),
Age(name: "Seniorinnen W30", shortName: "W30", ladvID: "W30", dlvID: "W30"),
Age(name: "Seniorinnen W35", shortName: "W35", ladvID: "W35", dlvID: "W35"),
Age(name: "Seniorinnen W40", shortName: "W40", ladvID: "W40", dlvID: "W40"),
Age(name: "Seniorinnen W45", shortName: "W45", ladvID: "W45", dlvID: "W45"),
Age(name: "Seniorinnen W50", shortName: "W50", ladvID: "W50", dlvID: "W50"),
Age(name: "Seniorinnen W55", shortName: "W55", ladvID: "W55", dlvID: "W55"),
Age(name: "Seniorinnen W60", shortName: "W60", ladvID: "W60", dlvID: "W60"),
Age(name: "Seniorinnen W65", shortName: "W65", ladvID: "W65", dlvID: "W65"),
Age(name: "Seniorinnen W70", shortName: "W70", ladvID: "W70", dlvID: "W70"),
Age(name: "Seniorinnen W75", shortName: "W75", ladvID: "W75", dlvID: "W75"),
Age(name: "Seniorinnen W80", shortName: "W80", ladvID: "W80", dlvID: "W80"),
Age(name: "Seniorinnen W85", shortName: "W85", ladvID: "W85", dlvID: "W85"),
Age(name: "Seniorinnen W90", shortName: "W90", ladvID: "W90", dlvID: "W90"),
Age(name: "Seniorinnen W95", shortName: "W95", ladvID: "W95", dlvID: "W95"),
Age(name: "Kinder T6", shortName: "Kinder T6", ladvID: "T6", dlvID: "T6"),
Age(name: "Kinder T7", shortName: "Kinder T7", ladvID: "T7", dlvID: "T7"),
Age(name: "Kinder T8", shortName: "Kinder T8", ladvID: "T8", dlvID: "T8"),
Age(name: "Kinder T9", shortName: "Kinder T9", ladvID: "T9", dlvID: "T9"),
Age(name: "Kinder T10", shortName: "Kinder T10", ladvID: "T10", dlvID: "T10"),
Age(name: "Kinder T11", shortName: "Kinder T11", ladvID: "T11", dlvID: "T11"),
Age(name: "Team U8", shortName: "Team U8", ladvID: "TU8", dlvID: "TU8"),
Age(name: "Team U10", shortName: "Team U10", ladvID: "TU10", dlvID: "TU10"),
Age(name: "Team U12", shortName: "Team U12", ladvID: "TU12", dlvID: "TU12")]
}
| mit | 00ccec63a071833b5d0f605ac82db5d7 | 75.590551 | 215 | 0.472705 | 3.035893 | false | false | false | false |
iWeslie/Ant | Ant/Ant/Tools/CustomButton.swift | 2 | 2606 | //
// CustomButton.swift
// E
//
// Created by LiuXinQiang on 17/3/21.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class CustomButton: UIButton {
fileprivate let kTitleRatio:CGFloat = 0.4
// 设置button内部image尺寸
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let imageX:CGFloat = contentRect.size.width * 0.3
let imageY:CGFloat = contentRect.size.height * 0.08
let imageWidth:CGFloat = contentRect.size.width * 0.4
let imageHeight:CGFloat = contentRect.size.height * (1 - kTitleRatio)
return CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
}
//设置button内部titlechicun
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let titleX : CGFloat = contentRect.size.width * 0.3
let titleHeight : CGFloat = contentRect.size.height * kTitleRatio
let titleY : CGFloat = contentRect.size.height - titleHeight * 0.9
let titleWidth : CGFloat = contentRect.size.width
return CGRect(x: titleX, y: titleY, width: titleWidth, height: titleHeight)
}
}
class MallButton: UIButton {
fileprivate let kTitleRatio:CGFloat = 0.4
// 设置button内部image尺寸
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
let imageX:CGFloat = contentRect.size.width * 0.3
let imageY:CGFloat = contentRect.size.height * 0.08
let imageWidth:CGFloat = contentRect.size.width * 0.6
let imageHeight:CGFloat = contentRect.size.height * (1 - kTitleRatio)
return CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.titleLabel?.textAlignment = .center
self.titleLabel?.font = UIFont.systemFont(ofSize: 13 * ((appdelgate?.fontSize)! - 0.15) )
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//设置button内部titlechicun
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
// let titleX : CGFloat = contentRect.size.width * 0.3
let titleHeight : CGFloat = contentRect.size.height * kTitleRatio
let titleY : CGFloat = contentRect.size.height - titleHeight * 0.9
let titleWidth : CGFloat = contentRect.size.width
return CGRect(x: (self.imageView?.center.x)! - ( titleWidth / 2), y: titleY, width: titleWidth, height: titleHeight)
}
}
| apache-2.0 | dd68eeb0e45269cb4af44f93efef4c5b | 37.833333 | 124 | 0.662895 | 4.133871 | false | false | false | false |
eliperkins/Dwifft | Dwifft/LCS.swift | 2 | 3728 | //
// LCS.swift
// Dwifft
//
// Created by Jack Flintermann on 3/14/15.
// Copyright (c) 2015 jflinter. All rights reserved.
//
import UIKit
/// These get returned from calls to LCS.diff(). They represent insertions or deletions that need to happen to transform array a into array b.
public enum ArrayDiffResult : DebugPrintable {
case Insert(Int)
case Delete(Int)
var isInsertion: Bool {
switch(self) {
case .Insert(let i):
return true
case .Delete(let i):
return false
}
}
public var debugDescription: String {
switch(self) {
case .Insert(let i):
return "+\(i)"
case .Delete(let i):
return "-\(i)"
}
}
var idx: Int {
switch(self) {
case .Insert(let i):
return i
case .Delete(let i):
return i
}
}
}
public class Diff<T: Equatable> {
/// Returns the sequence of ArrayDiffResults required to transform one array into another.
public static func calculate(x: [T], _ y: [T]) -> [ArrayDiffResult] {
let table = MemoizedSequenceComparison.buildTable(x, y, x.count, y.count)
return diffFromIndices(table, x.count, y.count)
}
/// Walks back through the generated table to generate the diff.
private static func diffFromIndices(table: [[Int]], _ i: Int, _ j: Int) -> [ArrayDiffResult] {
if i == 0 && j == 0 {
return []
} else if i == 0 {
return diffFromIndices(table, i, j-1) + [ArrayDiffResult.Insert(j-1)]
} else if j == 0 {
return diffFromIndices(table, i - 1, j) + [ArrayDiffResult.Delete(i-1)]
} else if table[i][j] == table[i][j-1] {
return diffFromIndices(table, i, j-1) + [ArrayDiffResult.Insert(j-1)]
} else if table[i][j] == table[i-1][j] {
return diffFromIndices(table, i - 1, j) + [ArrayDiffResult.Delete(i-1)]
} else {
return diffFromIndices(table, i-1, j-1)
}
}
}
public class LCS<T: Equatable> {
/// Returns the longest common subsequence between two arrays.
public static func calculate(x: [T], _ y: [T]) -> [T] {
let table = MemoizedSequenceComparison.buildTable(x, y, x.count, y.count)
return lcsFromIndices(table, x, y, x.count, y.count)
}
/// Walks back through the generated table to generate the LCS.
private static func lcsFromIndices(table: [[Int]], _ x: [T], _ y: [T], _ i: Int, _ j: Int) -> [T] {
if i == 0 && j == 0 {
return []
} else if i == 0 {
return lcsFromIndices(table, x, y, i, j - 1)
} else if j == 0 {
return lcsFromIndices(table, x, y, i - 1, j)
} else if x[i-1] == y[j-1] {
return lcsFromIndices(table, x, y, i - 1, j - 1) + [x[i - 1]]
} else if table[i-1][j] > table[i][j-1] {
return lcsFromIndices(table, x, y, i - 1, j)
} else {
return lcsFromIndices(table, x, y, i, j - 1)
}
}
}
internal struct MemoizedSequenceComparison<T: Equatable> {
static func buildTable(x: [T], _ y: [T], _ n: Int, _ m: Int) -> [[Int]] {
var table = Array(count: n + 1, repeatedValue: Array(count: m + 1, repeatedValue: 0))
for i in 0...n {
for j in 0...m {
if (i == 0 || j == 0) {
table[i][j] = 0
}
else if x[i-1] == y[j-1] {
table[i][j] = table[i-1][j-1] + 1
} else {
table[i][j] = max(table[i-1][j], table[i][j-1])
}
}
}
return table
}
}
| mit | f77ac9768d1a821de9dfb2eeebcbcac6 | 32.285714 | 142 | 0.515558 | 3.426471 | false | false | false | false |
psitaraman/Utilities | CommonUtilities/CommonUtilities/UIApplication+Utilites.swift | 1 | 2401 | /*
MIT License
Copyright (c) 2017 Praveen Sitaraman
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.
*/
//
// UIApplication+Utilites.swift
// CommonUtilities
//
// Created by Praveen Sitaraman on 7/25/17.
// Copyright © 2017 Praveen Sitaraman. All rights reserved.
//
import UIKit
extension UIApplication {
static func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
// tab
if let tabController = controller as? UITabBarController, let selectedController = tabController.selectedViewController {
return topViewController(controller: selectedController)
}
// nav
if let navigationController = controller as? UINavigationController, let visibleContoller = navigationController.visibleViewController {
return topViewController(controller: visibleContoller)
}
// modal
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
/// return copy of any reference type - useful for blocking passing of object reference
static func copyObject<T: AnyObject>() -> T {
return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: T.self)) as! T
}
}
| mit | 148f73c28c37644d319ffd4a87ae5a7c | 39.677966 | 144 | 0.734583 | 5.298013 | false | false | false | false |
gribozavr/swift | test/Generics/deduction.swift | 1 | 12743 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Deduction of generic arguments
//===----------------------------------------------------------------------===//
func identity<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> T { return value }
// expected-note@-1 {{'identity2' produces 'Y', not the expected contextual result type 'X'}}
func identity2<T>(_ value: T) -> Int { return 0 }
// expected-note@-1 {{'identity2' produces 'Int', not the expected contextual result type 'X'}}
struct X { }
struct Y { }
func useIdentity(_ x: Int, y: Float, i32: Int32) {
var x2 = identity(x)
var y2 = identity(y)
// Deduction that involves the result type
x2 = identity(17)
var i32_2 : Int32 = identity(17)
// Deduction where the result type and input type can get different results
var xx : X, yy : Y
xx = identity(yy) // expected-error{{cannot assign value of type 'Y' to type 'X'}}
xx = identity2(yy) // expected-error{{no exact matches in call to global function 'identity2'}}
}
// FIXME: Crummy diagnostic!
func twoIdentical<T>(_ x: T, _ y: T) -> T {}
func useTwoIdentical(_ xi: Int, yi: Float) {
var x = xi, y = yi
x = twoIdentical(x, x)
y = twoIdentical(y, y)
x = twoIdentical(x, 1)
x = twoIdentical(1, x)
y = twoIdentical(1.0, y)
y = twoIdentical(y, 1.0)
twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func mySwap<T>(_ x: inout T,
_ y: inout T) {
let tmp = x
x = y
y = tmp
}
func useSwap(_ xi: Int, yi: Float) {
var x = xi, y = yi
mySwap(&x, &x)
mySwap(&y, &y)
mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
// expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}}
mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func takeTuples<T, U>(_: (T, U), _: (U, T)) {
}
func useTuples(_ x: Int, y: Float, z: (Float, Int)) {
takeTuples((x, y), (y, x))
takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type '(Int, Float)' to expected argument type '(Float, Int)'}}
// FIXME: Use 'z', which requires us to fix our tuple-conversion
// representation.
}
func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {}
func passFunction(_ f: (Int) -> Float, x: Int, y: Float) {
acceptFunction(f, x, y)
acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note {{in call to function 'returnTuple'}}
func testReturnTuple(_ x: Int, y: Float) {
returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}}
var _ : (Int, Float) = returnTuple(x)
var _ : (Float, Float) = returnTuple(y)
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
var _ : (Int, Float) = returnTuple(y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) {
confusingArgAndParam(g, f)
confusingArgAndParam(f, g)
}
func acceptUnaryFn<T, U>(_ f: (T) -> U) { }
func acceptUnaryFnSame<T>(_ f: (T) -> T) { }
func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { }
func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { }
func unaryFnIntInt(_: Int) -> Int {}
func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}}
func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}}
// Variable forms of the above functions
var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt
func passOverloadSet() {
// Passing a non-generic function to a generic function
acceptUnaryFn(unaryFnIntInt)
acceptUnaryFnSame(unaryFnIntInt)
// Passing an overloaded function set to a generic function
// FIXME: Yet more terrible diagnostics.
acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}}
acceptUnaryFnSame(unaryFnOvl)
// Passing a variable of function type to a generic function
acceptUnaryFn(unaryFnIntIntVar)
acceptUnaryFnSame(unaryFnIntIntVar)
// Passing a variable of function type to a generic function to an inout parameter
acceptUnaryFnRef(&unaryFnIntIntVar)
acceptUnaryFnSameRef(&unaryFnIntIntVar)
acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
}
func acceptFnFloatFloat(_ f: (Float) -> Float) {}
func acceptFnDoubleDouble(_ f: (Double) -> Double) {}
func passGeneric() {
acceptFnFloatFloat(identity)
acceptFnFloatFloat(identity2)
}
//===----------------------------------------------------------------------===//
// Simple deduction for generic member functions
//===----------------------------------------------------------------------===//
struct SomeType {
func identity<T>(_ x: T) -> T { return x }
func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}}
func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}}
func returnAs<T>() -> T {}
}
func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) {
var st = sti, i = ii, f = fi
i = st.identity(i)
f = st.identity(f)
i = st.identity2(i)
f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}}
i = st.returnAs()
f = st.returnAs()
acceptFnFloatFloat(st.identity)
acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}}
acceptFnDoubleDouble(st.identity2)
}
struct StaticFuncs {
static func chameleon<T>() -> T {}
func chameleon2<T>() -> T {}
}
struct StaticFuncsGeneric<U> {
// FIXME: Nested generics are very broken
// static func chameleon<T>() -> T {}
}
func chameleon<T>() -> T {}
func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) {
var x: Int16
x = StaticFuncs.chameleon()
x = sf.chameleon2()
// FIXME: Nested generics are very broken
// x = sfi.chameleon()
// typealias SFI = StaticFuncsGeneric<Int>
// x = SFI.chameleon()
_ = x
}
//===----------------------------------------------------------------------===//
// Deduction checking for constraints
//===----------------------------------------------------------------------===//
protocol IsBefore {
func isBefore(_ other: Self) -> Bool
}
func min2<T : IsBefore>(_ x: T, _ y: T) -> T { // expected-note {{where 'T' = 'Float'}}
if y.isBefore(x) { return y }
return x
}
extension Int : IsBefore {
func isBefore(_ other: Int) -> Bool { return self < other }
}
func callMin(_ x: Int, y: Int, a: Float, b: Float) {
_ = min2(x, y)
min2(a, b) // expected-error{{global function 'min2' requires that 'Float' conform to 'IsBefore'}}
}
func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {} // expected-note {{where 'R.Element' = 'IndexingIterator<[Double]>.Element' (aka 'Double')}}
func callRangeOfIsBefore(_ ia: [Int], da: [Double]) {
rangeOfIsBefore(ia.makeIterator())
rangeOfIsBefore(da.makeIterator()) // expected-error{{global function 'rangeOfIsBefore' requires that 'IndexingIterator<[Double]>.Element' (aka 'Double') conform to 'IsBefore'}}
}
func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {}
// expected-note@-1 {{where 'A.Element' = 'IndexingIterator<[Int]>.Element' (aka 'Int'), 'B.Element' = 'IndexingIterator<[Double]>.Element' (aka 'Double')}}
func compareIterators() {
var a: [Int] = []
var b: [Double] = []
testEqualIterElementTypes(a.makeIterator(), b.makeIterator())
// expected-error@-1 {{global function 'testEqualIterElementTypes' requires the types 'IndexingIterator<[Int]>.Element' (aka 'Int') and 'IndexingIterator<[Double]>.Element' (aka 'Double') be equivalent}}
}
protocol P_GI {
associatedtype Y
}
class C_GI : P_GI {
typealias Y = Double
}
class GI_Diff {}
func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {}
// expected-note@-1 {{where 'T.Y' = 'C_GI.Y' (aka 'Double')}}
genericInheritsA(C_GI())
// expected-error@-1 {{global function 'genericInheritsA' requires that 'C_GI.Y' (aka 'Double') inherit from 'GI_Diff'}}
//===----------------------------------------------------------------------===//
// Deduction for member operators
//===----------------------------------------------------------------------===//
protocol Addable { // expected-note {{where 'Self' = 'U'}}
static func +(x: Self, y: Self) -> Self
}
func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T {
u + u // expected-error{{protocol 'Addable' requires that 'U' conform to 'Addable'}}
return x+y
}
//===----------------------------------------------------------------------===//
// Deduction for bound generic types
//===----------------------------------------------------------------------===//
struct MyVector<T> { func size() -> Int {} }
func getVectorSize<T>(_ v: MyVector<T>) -> Int { // expected-note {{in call to function 'getVectorSize'}}
return v.size()
}
func ovlVector<T>(_ v: MyVector<T>) -> X {}
func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {}
func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) {
var i : Int
i = getVectorSize(vi)
i = getVectorSize(vf)
getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<T>'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
var x : X, y : Y
x = ovlVector(vi)
x = ovlVector(vf)
var vvi : MyVector<MyVector<Int>>
y = ovlVector(vvi)
var yy = ovlVector(vvi)
yy = y
y = yy
}
// <rdar://problem/15104554>
postfix operator <*>
protocol MetaFunction {
associatedtype Result
static postfix func <*> (_: Self) -> Result?
}
protocol Bool_ {}
struct False : Bool_ {}
struct True : Bool_ {}
postfix func <*> <B>(_: Test<B>) -> Int? { return .none }
postfix func <*> (_: Test<True>) -> String? { return .none }
class Test<C: Bool_> : MetaFunction {
typealias Result = Int
} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}}
// rdar://problem/20577950
class DeducePropertyParams {
let badSet: Set = ["Hello"]
}
// SR-69
struct A {}
func foo() {
for i in min(1,2) { // expected-error{{for-in loop requires 'Int' to conform to 'Sequence'}}
}
let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
let k = min(A(), A()) // expected-error{{global function 'min' requires that 'A' conform to 'Comparable'}}
let oi : Int? = 5
let l = min(3, oi) // expected-error{{global function 'min' requires that 'Int?' conform to 'Comparable'}}
// expected-note@-1{{wrapped type 'Int' satisfies this requirement}}
}
infix operator +&
func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {}
// expected-note@-1 {{where 'R.Element' = 'String', 'S.Element' = 'String.Element' (aka 'Character')}}
func rdar33477726_1() {
var arr: [String] = []
arr +& "hello"
// expected-error@-1 {{operator function '+&' requires the types 'String' and 'String.Element' (aka 'Character') be equivalent}}
}
func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {}
rdar33477726_2("answer", 42)
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String.Element' (aka 'Character')}}
prefix operator +-
prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {}
// expected-note@-1 {{where 'T.Element' = 'String.Element' (aka 'Character')}}
+-"hello"
// expected-error@-1 {{operator function '+-' requires the types 'String.Element' (aka 'Character') and 'Int' be equivalent}}
func test_transitive_subtype_deduction_for_generic_params() {
class A {}
func foo<T: A>(_: [(String, (T) -> Void)]) {}
func bar<U>(_: @escaping (U) -> Void) -> (U) -> Void {
return { _ in }
}
// Here we have:
// - `W subtype of A`
// - `W subtype of U`
//
// Type variable associated with `U` has to be attempted
// first because solver can't infer bindings for `W` transitively
// through `U`.
func baz<W: A>(_ arr: [(String, (W) -> Void)]) {
foo(arr.map { ($0.0, bar($0.1)) }) // Ok
}
func fiz<T>(_ a: T, _ op: (T, T) -> Bool, _ b: T) {}
func biz(_ v: Int32) {
fiz(v, !=, -1) // Ok because -1 literal should be inferred as Int32
}
}
| apache-2.0 | 929f9b9809bb10303e289cf2a0499089 | 33.440541 | 205 | 0.608256 | 3.60379 | false | false | false | false |
VivaReal/Compose | Compose/Classes/Vendor/Dwiff/Dwifft.swift | 1 | 5179 | //
// LCS.swift
// Dwifft
//
// Created by Jack Flintermann on 3/14/15.
// Copyright (c) 2015 jflinter. All rights reserved.
//
struct Diff<T> {
public let results: [DiffStep<T>]
public var insertions: [DiffStep<T>] {
return results.filter({ $0.isInsertion }).sorted { $0.idx < $1.idx }
}
public var deletions: [DiffStep<T>] {
return results.filter({ !$0.isInsertion }).sorted { $0.idx > $1.idx }
}
public func reversed() -> Diff<T> {
let reversedResults = self.results.reversed().map { (result: DiffStep<T>) -> DiffStep<T> in
switch result {
case .insert(let i, let j):
return .delete(i, j)
case .delete(let i, let j):
return .insert(i, j)
}
}
return Diff<T>(results: reversedResults)
}
}
func +<T> (left: Diff<T>, right: DiffStep<T>) -> Diff<T> {
return Diff<T>(results: left.results + [right])
}
/// These get returned from calls to Array.diff(). They represent insertions or deletions that need to happen to transform array a into array b.
enum DiffStep<T> : CustomDebugStringConvertible {
case insert(Int, T)
case delete(Int, T)
var isInsertion: Bool {
switch(self) {
case .insert:
return true
case .delete:
return false
}
}
public var debugDescription: String {
switch(self) {
case .insert(let i, let j):
return "+\(j)@\(i)"
case .delete(let i, let j):
return "-\(j)@\(i)"
}
}
public var idx: Int {
switch(self) {
case .insert(let i, _):
return i
case .delete(let i, _):
return i
}
}
public var value: T {
switch(self) {
case .insert(let j):
return j.1
case .delete(let j):
return j.1
}
}
}
extension Array where Element: Equatable {
/// Returns the sequence of ArrayDiffResults required to transform one array into another.
func diff(_ other: [Element]) -> Diff<Element> {
let table = MemoizedSequenceComparison.buildTable(self, other, self.count, other.count)
return Array.diffFromIndices(table, self, other, self.count, other.count)
}
/// Walks back through the generated table to generate the diff.
fileprivate static func diffFromIndices(_ table: [[Int]], _ x: [Element], _ y: [Element], _ i: Int, _ j: Int) -> Diff<Element> {
if i == 0 && j == 0 {
return Diff<Element>(results: [])
} else if i == 0 {
return diffFromIndices(table, x, y, i, j-1) + DiffStep.insert(j-1, y[j-1])
} else if j == 0 {
return diffFromIndices(table, x, y, i - 1, j) + DiffStep.delete(i-1, x[i-1])
} else if table[i][j] == table[i][j-1] {
return diffFromIndices(table, x, y, i, j-1) + DiffStep.insert(j-1, y[j-1])
} else if table[i][j] == table[i-1][j] {
return diffFromIndices(table, x, y, i - 1, j) + DiffStep.delete(i-1, x[i-1])
} else {
return diffFromIndices(table, x, y, i-1, j-1)
}
}
/// Applies a generated diff to an array. The following should always be true:
/// Given x: [T], y: [T], x.apply(x.diff(y)) == y
func apply(_ diff: Diff<Element>) -> Array<Element> {
var copy = self
for result in diff.deletions {
copy.remove(at: result.idx)
}
for result in diff.insertions {
copy.insert(result.value, at: result.idx)
}
return copy
}
}
extension Array where Element: Equatable {
/// Returns the longest common subsequence between two arrays.
func LCS(_ other: [Element]) -> [Element] {
let table = MemoizedSequenceComparison.buildTable(self, other, self.count, other.count)
return Array.lcsFromIndices(table, self, other, self.count, other.count)
}
/// Walks back through the generated table to generate the LCS.
fileprivate static func lcsFromIndices(_ table: [[Int]], _ x: [Element], _ y: [Element], _ i: Int, _ j: Int) -> [Element] {
if i == 0 || j == 0 {
return []
} else if x[i-1] == y[j-1] {
return lcsFromIndices(table, x, y, i - 1, j - 1) + [x[i - 1]]
} else if table[i-1][j] > table[i][j-1] {
return lcsFromIndices(table, x, y, i - 1, j)
} else {
return lcsFromIndices(table, x, y, i, j - 1)
}
}
}
internal struct MemoizedSequenceComparison<T: Equatable> {
static func buildTable(_ x: [T], _ y: [T], _ n: Int, _ m: Int) -> [[Int]] {
var table = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
for i in 0...n {
for j in 0...m {
if (i == 0 || j == 0) {
table[i][j] = 0
}
else if x[i-1] == y[j-1] {
table[i][j] = table[i-1][j-1] + 1
} else {
table[i][j] = max(table[i-1][j], table[i][j-1])
}
}
}
return table
}
}
| mit | ea94ed2479b8133be659874a70d99300 | 33.072368 | 144 | 0.525005 | 3.50406 | false | false | false | false |
pkkup/Pkkup-iOS | Pkkup/models/PkkupClient.swift | 1 | 6174 | //
// PkkupClient.swift
// Pkkup
//
// Copyright (c) 2014 Pkkup. All rights reserved.
//
import Foundation
let PKKUP_API_BASE_URL = "http://pkkup.com/api"
// Temporary globals
var _GAMES = [PkkupGame]()
var _LOCATIONS = [PkkupLocation]()
var _PLAYERS = [PkkupPlayer]()
var _GROUPS = [PkkupGroup]()
var _CURRENT_PLAYER : PkkupPlayer!
var _SPORTS = [PkkupSport]()
// A class for handling all API calls and networking
class PkkupClient: BDBOAuth1RequestOperationManager {
var cache = [String:AnyObject]()
var loginCompletion: ((user: PkkupPlayer?, error: NSError?) -> ())?
var accessToken: String!
var accessSecret: String!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
class var sharedInstance : PkkupClient {
struct Static {
static let instance = PkkupClient(
baseURL: NSURL(string: PKKUP_API_BASE_URL)!,
consumerKey: nil,
consumerSecret: nil
)
}
return Static.instance
}
override init(baseURL: NSURL, consumerKey: String!, consumerSecret: String!) {
super.init(baseURL: baseURL, consumerKey: consumerKey, consumerSecret: consumerSecret)
}
func login(url: String, path: String, completion: (user: PkkupPlayer?, error: NSError?) -> Void) {
// perform any logout actions before trying to log in
self.logout()
self.loginCompletion = completion
// Fetch request token & redirect to authorization page
// self.fetchRequestTokenWithPath(
// TWITTER_API_OAUTH1_REQUEST_TOKEN_RESOURCE,
// method: "GET",
// callbackURL: NSURL(string:"\(url)://\(path)"),
// scope: nil,
// success: {
// (requestToken: BDBOAuthToken!) -> Void in
// NSLog("Got the request token")
// var authURL = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)")
// UIApplication.sharedApplication().openURL(authURL)
// }, failure: {
// (error: NSError!) -> Void in
// NSLog("Error getting the request token: \(error)")
// self.loginCompletion?(user: nil, error: error)
// }
// )
}
func logout() {
PkkupClient.sharedInstance.requestSerializer.removeAccessToken()
}
func openURL(url: NSURL) {
// called by AppDelegate.application(..., openURL: ...)
// self.fetchAccessTokenWithPath(
// TWITTER_API_OAUTH1_ACCESS_TOKEN_RESOURCE,
// method: "POST",
// requestToken: BDBOAuthToken(queryString: url.query),
// success: {
// (accessToken: BDBOAuthToken!) -> Void in
// NSLog("Got the access token")
// self.requestSerializer.saveAccessToken(accessToken)
// self.verifyCredentials()
// }, failure: {
// (error: NSError!) -> Void in
// NSLog("Failed to receive access token")
// self.loginCompletion?(user: nil, error: error)
// }
// )
}
func makeApiRequest(resource: String, callback: (AnyObject) -> ()) {
var apiUrl = "\(PKKUP_API_BASE_URL)\(resource)"
// temporarily include App key to increase rate limit
apiUrl = "\(apiUrl)?api_key=secret"
let request = NSMutableURLRequest(URL: NSURL(string: apiUrl)!)
NSLog("Hitting API: \(apiUrl)")
var cachedResult: AnyObject? = cache[apiUrl]
if cachedResult != nil {
callback(cachedResult!)
} else {
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: { (response, data, error) in
var errorValue: NSError? = nil
let result: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &errorValue)
if result != nil {
callback(result!)
self.cache[apiUrl] = result!
} else {
HTKNotificationUtils.displayNetworkErrorMessage()
}
})
}
}
class func getSports() {
PkkupClient.sharedInstance.makeApiRequest("/sports/list", callback: {
(result: AnyObject) -> () in
var responseDictionary = result as NSDictionary
var sportDictionaries = responseDictionary["sports"] as [NSDictionary]
var sports = PkkupSport.sportsWithArray(sportDictionaries)
PkkupSport.sports = sports
_SPORTS = sports
println("Got \(sports.count) sports")
})
}
class func getGames() {
PkkupClient.sharedInstance.makeApiRequest("/games/list", callback: {
(result: AnyObject) -> () in
var responseDictionary = result as NSDictionary
var gameDictionaries = responseDictionary["games"] as [NSDictionary]
var games = PkkupGame.gamesWithArray(gameDictionaries)
_GAMES = games
println("Got \(games.count) games")
})
}
class func getLocations() {
PkkupClient.sharedInstance.makeApiRequest("/locations/list", callback: {
(result: AnyObject) -> () in
var responseDictionary = result as NSDictionary
var locationDictionaries = responseDictionary["locations"] as [NSDictionary]
var locations = PkkupLocation.locationsWithArray(locationDictionaries)
_LOCATIONS = locations
println("Got \(locations.count) locations")
})
}
class func getPlayers() {
PkkupClient.sharedInstance.makeApiRequest("/players/list", callback: {
(result: AnyObject) -> () in
var responseDictionary = result as NSDictionary
var playerDictionaries = responseDictionary["players"] as [NSDictionary]
var players = PkkupPlayer.playersWithArray(playerDictionaries)
_PLAYERS = players
println("Got \(players.count) players")
})
}
}
| mit | 1d01e3b3467a41e7a628d5f20a7e7c26 | 36.646341 | 145 | 0.588273 | 4.556458 | false | false | false | false |
BalestraPatrick/Tweetometer | Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Demos/Timelines Demo/CollectionFilteredTimelineViewController.swift | 2 | 848 | //
// CollectionFilteredTimelineViewController.swift
// FabricSampleApp
//
// Created by Alejandro Crosa on 11/18/16.
// Copyright © 2016 Twitter. All rights reserved.
//
import UIKit
class CollectionFilteredTimelineViewController: TWTRTimelineViewController {
convenience init() {
let client = TWTRAPIClient()
let dataSource = TWTRCollectionTimelineDataSource(collectionID: "659110687482839040", apiClient: client)
// filter the search timeline
let filter = TWTRTimelineFilter()
filter.handles = [ "nasa" ]
dataSource.timelineFilter = filter
self.init(dataSource: dataSource)
self.hidesBottomBarWhenPushed = true
}
func tweetView(tweetView: TWTRTweetView!, didSelectTweet tweet: TWTRTweet!) {
print("Selected tweet with ID: \(tweet.tweetID)")
}
}
| mit | 22350d8bab1bfcd7fe535c2d5a548c24 | 27.233333 | 112 | 0.700118 | 4.505319 | false | false | false | false |
harenbrs/swix | swixUseCases/swix-iOSb6/swix/matrix/complex-math.swift | 4 | 3658 | //
// twoD-complex-math.swift
// swix
//
// Created by Scott Sievert on 7/15/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Swift
import Accelerate
func rank(x:matrix)->Double{
var (u, S, v) = svd(x, compute_uv:false)
var m:Double = (x.shape.0 < x.shape.1 ? x.shape.1 : x.shape.0).double
var tol = S.max() * m * DOUBLE_EPSILON
return sum(S > tol)
}
func dot(x: matrix, y: matrix) -> matrix{
var (Mx, Nx) = x.shape
var (My, Ny) = y.shape
assert(Nx == My, "Matrix sizes not compatible for dot product")
var z = zeros((Mx, Ny))
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
Mx.cint, Ny.cint, Nx.cint, 1.0,
!x, Nx.cint,
!y, Ny.cint, 1.0,
!z, Ny.cint)
return z
}
func svd(x: matrix, compute_uv:Bool=true) -> (matrix, ndarray, matrix){
var (m, n) = x.shape
var nS = m < n ? m : n // number singular values
var sigma = zeros(nS)
var vt = zeros((n,n))
var u = zeros((m,m))
var xx = zeros_like(x)
xx.flat = x.flat
xx = xx.T
var c_uv:CInt = compute_uv==true ? 1 : 0
svd_objc(!xx, m.cint, n.cint, !sigma, !vt, !u, c_uv)
// to get the svd result to match Python
var v = transpose(vt)
u = transpose(u)
return (u, sigma, v)
}
func pinv(x:matrix)->matrix{
var (u, s, v) = svd(x)
var m = u.shape.0
var n = v.shape.1
var ma = m < n ? n : m
var cutoff = DOUBLE_EPSILON * ma.double * max(s)
var i = s > cutoff
var ipos = argwhere(i)
s[ipos] = 1 / s[ipos]
var ineg = argwhere(1-i)
s[ineg] = zeros_like(ineg)
var z = zeros((n, m))
z["diag"] = s
var res = v.T.dot(z).dot(u.T)
return res
}
func inv(x: matrix) -> matrix{
assert(x.shape.0 == x.shape.1, "To take an inverse of a matrix, the matrix must be square. If you want the inverse of a rectangular matrix, use psuedoinverse.")
var y = x.copy()
var (M, N) = x.shape
var ipiv:Array<__CLPK_integer> = Array(count:M*M, repeatedValue:0)
var lwork:__CLPK_integer = __CLPK_integer(N*N)
// var work:[CDouble] = [CDouble](count:lwork, repeatedValue:0)
var work = [CDouble](count: Int(lwork), repeatedValue: 0.0)
var info:__CLPK_integer=0
var nc = __CLPK_integer(N)
dgetrf_(&nc, &nc, !y, &nc, &ipiv, &info)
dgetri_(&nc, !y, &nc, &ipiv, &work, &lwork, &info)
return y
}
func solve(A: matrix, b: ndarray) -> ndarray{
var (m, n) = A.shape
assert(b.n == m, "Ax = b, A.rows == b.n. Sizes must match which makes sense mathematically")
assert(n == m, "Matrix must be square -- dictated by OpenCV")
var x = zeros(n)
CVWrapper.solve(!A, b:!b, x:!x, m:m.cint, n:n.cint)
return x
}
func eig(x: matrix)->ndarray{
// matrix, value, vectors
var (m, n) = x.shape
assert(m == n, "Input must be square")
var value_real = zeros(m)
var value_imag = zeros(n)
var vector = zeros((n,n))
var y = x.copy()
var work:[Double] = Array(count:n*n, repeatedValue:0.0)
var lwork = __CLPK_integer(4 * n)
var info = __CLPK_integer(1)
// don't compute right or left eigenvectors
var job = "N"
var ccharOptional = job.cStringUsingEncoding(NSUTF8StringEncoding)?[0] // CChar?
var jobvl = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
var jobvr = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
work[0] = Double(lwork)
var nc = __CLPK_integer(n)
dgeev_(&jobvl, &jobvr, &nc, !x, &nc,
!value_real, !value_imag, !vector, &nc, !vector, &nc,
&work, &lwork, &info)
vector = vector.T
return value_real
}
| mit | 572205501109763e53cff8a09f33ad3a | 27.578125 | 164 | 0.583106 | 2.884858 | false | false | false | false |
FreeLadder/Ladder | Ladder_iOS/FreeSS/Ladder.swift | 1 | 1086 | //
// Ladder.swift
// FreeSS
//
// Created by YogaXiong on 2017/4/3.
// Copyright © 2017年 YogaXiong. All rights reserved.
//
import Foundation
struct Ladder: CustomStringConvertible {
let ip: String
let port: String
let password: String
let encryption: String
let QRCodeURL: String
init(ip: String, port: String, password: String, encryption: String, QRCodeURL: String) {
self.ip = ip
self.port = port
self.password = password
self.encryption = encryption
self.QRCodeURL = QRCodeURL
}
var description: String {
return "ip: \(ip)" + "\n" + "port: \(port)" + "\n" + "password: \(password)" + "\n" + "encryption: \(encryption)" + "\n" + "QRCodeURL: \(QRCodeURL)" + "\n"
}
func toURL() -> URL {
// 服务器:端口:协议:加密方式:混淆方式:base64(密码)?obfsparam= Base64(混淆参数)&remarks=Base64(备注)
let parts = "\(encryption):\(password)@\(ip):\(port)".base64(urlSafe: false)
return URL(string: "ss://\(parts)")!
}
}
| mpl-2.0 | d4f6205038f5158e45d341ce80e8fdb3 | 27.638889 | 163 | 0.584869 | 3.483108 | false | false | false | false |
nathanlea/CS4153MobileAppDev | WIA/MWAI_Lea_Nathan/MWAI_Lea_Nathan/AppDelegate.swift | 1 | 6104 | //
// AppDelegate.swift
// MWAI_Lea_Nathan
//
// Created by Nathan on 11/1/15.
// Copyright © 2015 Okstate. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "CS4153AppDev.MWAI_Lea_Nathan" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MWAI_Lea_Nathan", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 9c6134192e35580da90625de22d7091d | 53.981982 | 291 | 0.719482 | 5.829035 | false | false | false | false |
dvogt23/KartApp-iOS | karteikarten/ShareVC.swift | 1 | 12776 | //
// ShareVC.swift
//
// ShareViewController
// Controller für die Freigabe-Funktionen der Kartensätze
// Anzeigen, Hinzufügen und Löschen von Berechtigungen eines Kartensatzes
//
import UIKit
import Alamofire
import SwiftyJSON
class ShareVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var exitCardset: UIButton!
@IBOutlet weak var errorLabel: UILabel!
var titelString: String? = nil
var refreshCtrl: UIRefreshControl!
let basicCell = "BasicCell"
// eigene Permission für den gewählten Kartensatz
var myPermission: String? = nil
// Dictionary die alle Freigaben zwischenspeichert
var permissions: [(userid: String, username: String, permission: String)] = []
// Anzahl Besitzer eines Kartensatzes
var countOwner: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// NavigationBar anpassen
let titelNavBar: UILabel = UILabel(frame: CGRectMake(0,0,100,32))
titelNavBar.textAlignment = .Center
titelNavBar.text = self.titelString
self.navigationItem.titleView = titelNavBar
// + Button der Navigation hinzufügen
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addFriendAction")
// Leere Zellen in der Tabelle ausblenden
self.tableView.tableFooterView = UIView()
// Prüfen ob eine Internetverbindung besteht
// Bei Erfolg: Berechtigungen laden
// Bei Fehler: Text in dem Fehler-Label anzeigen
if Reachability.isConnectedToNetwork() == true {
self.errorLabel.text = ""
loadFriends(Int(setid!)!)
}else{
self.errorLabel.text = "Es besteht momentan keine Verbindung zum Internet. Bitte versuchen Sie es später erneut."
}
// Pull Methode (runterziehen zum aktualisieren) der Tabelle hinzufügen
self.refreshCtrl = UIRefreshControl()
self.refreshCtrl.attributedTitle = NSAttributedString(string: "Berechtigungen werden aktualisiert")
self.refreshCtrl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshCtrl)
// Tabellen Methoden an den Controller delegieren
tableView.dataSource = self
tableView.delegate = self
tableView.reloadData()
}
// MARK: RefreshControl
// Pull Methode (runterziehen zum aktualisieren)
func refresh(sender:AnyObject){
if Reachability.isConnectedToNetwork() == true {
loadFriends(Int(setid!)!)
self.errorLabel.text = ""
}else{
self.refreshCtrl.endRefreshing()
self.errorLabel.text = "Es besteht momentan keine Verbindung zum Internet. Bitte versuchen Sie es später erneut."
MeldungKeinInternet()
}
}
// MARK: Tabellen Funktionen
// Anzahl der Zellen zurückgeben
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return permissions.count
}
// Zellen Eigenschaften Definition
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(basicCell)!
// Berechtigung nach Besitzer sortieren
permissions.sortInPlace({$0.permission < $1.permission})
if permissions[indexPath.row].permission == "0" {
countOwner++
if permissions[indexPath.row].userid == cuser["userid"] {
cell.detailTextLabel?.text = "📌👤 Besitzer"
cell.userInteractionEnabled = false
if countOwner == 1 {
exitCardset.enabled = false
exitCardset.backgroundColor = UIColor.grayColor()
}
}else{
cell.detailTextLabel?.text = "👤 Besitzer"
cell.userInteractionEnabled = true
exitCardset.enabled = true
exitCardset.backgroundColor = kBlue
}
cell.textLabel?.text = permissions[indexPath.row].username
}else{
cell.textLabel?.text = permissions[indexPath.row].username
if permissions[indexPath.row].userid == cuser["userid"] {
cell.detailTextLabel?.text = "📌👥 Teilnehmer"
cell.userInteractionEnabled = false
}else{
cell.detailTextLabel?.text = "👥 Teilnehmer"
cell.userInteractionEnabled = true
}
}
if self.myPermission == "1" {cell.userInteractionEnabled = false}
return cell
}
// Löschen-Funktion der Zelle hinzufügen
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "löschen") { (action, indexPath) -> Void in
tableView.editing = false
if Reachability.isConnectedToNetwork() == true {
self.deleteFriend(self.permissions[indexPath.row].username)
self.permissions.removeAtIndex(indexPath.row)
self.countOwner = 0
self.tableView.reloadData()
}else{
}
}
deleteAction.backgroundColor = UIColor.redColor()
return [deleteAction]
}
// MARK: ???
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
// Kartensatz verlassen Funktion
// Kartensatz verlassen und in die Kartensatzansicht wechseln
@IBAction func leaveButtonTapped(sender: AnyObject) {
let alert = UIAlertController(title: "Kartensatz verlassen", message: "Wollen Sie wirklich den Kartensatz verlassen?", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ja", style: .Default, handler:{ (UIAlertAction)in
if Reachability.isConnectedToNetwork() == true {
self.leaveCardset()
}else{
MeldungKeinInternet()
}
}))
alert.addAction(UIAlertAction(title: "Nein", style: .Cancel) { (_) in })
self.presentViewController(alert, animated: true, completion: { })
}
// Berechtigung für Kartensatz laden
// Tabelle neuladen und RefreshControl-Animation beenden
func loadFriends(setid: Int){
DLog("HTTP POST: Karten werden geladen")
Session.sharedInstance.ApiManager().request(.GET, apiURL+"/permission?cardsetid=\(setid)")
.responseSwiftyJSON({ (request, response, json, error) in
//println(json)
//println(error)
if (error == nil){
DLog("HTTP POST Response: Berechtigungen erfolgreich geladen")
self.permissions.removeAll(keepCapacity: false)
for index in 0 ..< json["permissions"].count {
let id: String? = json["permissions"][index]["userid"].stringValue
let username: String? = json["permissions"][index]["username"].stringValue
let permission: String? = json["permissions"][index]["permission"].stringValue
self.permissions += [(userid: id!, username: username!, permission: permission!)]
if id == cuser["userid"] {self.myPermission = permission}
}
self.tableView.reloadData()
}else{
DLog("HTTP POST Response: Berechtigung konnte nicht geladen werden")
//DLog(error!.localizedDescription)
}
self.refreshCtrl.endRefreshing()
})
}
// Berechtugung für Kartensatz löschen
func deleteFriend(username: String){
Session.sharedInstance.ApiManager().request(.DELETE, apiURL+"/permission/\(setid!)?username=\(username)")
.responseSwiftyJSON({ (request, response, json, error) in
//println(json)
//println(error)
if (error == nil){
DLog("HTTP POST Response: Benutzer wurde gelöscht")
if json["error"] == true {
Meldung("Fehler", message: json["message"].stringValue, btnTitle: "OK")
}
}else{
DLog("HTTP POST Response: Benutzer konnten nicht gelöscht werden")
//DLog(error!.localizedDescription)
}
self.refreshCtrl.endRefreshing()
})
}
// Kartensatz verlassen
func leaveCardset(){
Session.sharedInstance.ApiManager().request(.DELETE, apiURL+"/permission/\(setid!)?username=" + cuser["username"]!)
.responseSwiftyJSON({ (request, response, json, error) in
//println(json)
//println(error)
if (error == nil){
DLog("HTTP POST Response: Benutzer wurde gelöscht")
if json["error"] == true {
Meldung("Fehler", message: json["message"].stringValue, btnTitle: "OK")
}
self.performSegueWithIdentifier("showCardsetView", sender: self)
}else{
DLog("HTTP POST Response: Benutzer konnten nicht gelöscht werden")
//DLog(error!.localizedDescription)
}
self.refreshCtrl.endRefreshing()
})
}
// Hinzufügen Funktion
func addFriendAction(){
if self.myPermission == "0" {
let alert = UIAlertController(title: "Freigabe", message: "Geben Sie den Benutzernamen ein:", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in
textField.placeholder = "Benutzername"
textField.secureTextEntry = false
})
alert.addAction(UIAlertAction(title: "Abbrechen", style: .Cancel) { (_) in })
alert.addAction(UIAlertAction(title: "👥 Teilnehmer", style: .Default, handler:{ (UIAlertAction)in
let name = alert.textFields![0]
if Reachability.isConnectedToNetwork() == true {
self.addPermission(name.text!, permission: "1")
}else{
}
}))
alert.addAction(UIAlertAction(title: "👤 Besitzer", style: .Default, handler:{ (UIAlertAction)in
let name = alert.textFields![0]
if Reachability.isConnectedToNetwork() == true {
self.addPermission(name.text!, permission: "0")
}else{
}
}))
self.presentViewController(alert, animated: true, completion: { })
}else{
Meldung("Fehler", message: "Sie haben keine Berechtigung!", btnTitle: "OK")
}
}
// Berechtigung online hinzufügen
func addPermission(username: String, permission: String){
Session.sharedInstance.ApiManager().request(.POST, apiURL+"/permission/\(setid!)", parameters: ["username":username, "permission":permission])
.responseSwiftyJSON({ (request, response, json, error) in
//println(json)
//println(error)
if (error == nil){
DLog("HTTP POST Response: Benutzer wurde erfolgreich hinzugefügt")
if json["error"] == true {
Meldung("Fehler", message: json["message"].stringValue, btnTitle: "OK")
}else{
self.permissions += [(userid: "", username: username, permission: permission)]
self.tableView.reloadData()
}
}else{
DLog("HTTP POST Response: Benutzer konnten nicht hinzugefügt werden")
//DLog(error!.localizedDescription)
}
self.refreshCtrl.endRefreshing()
})
}
}
| mit | 430a843016d8435da2d8d178a245f5eb | 42.138983 | 172 | 0.577793 | 4.83327 | false | false | false | false |
StorageKit/StorageKit | Tests/Storages/CoreData/TestDoubles/SpyEntityDescription.swift | 1 | 2055 | //
// SpyEntityDescription.swift
// StorageKit
//
// Copyright (c) 2017 StorageKit (https://github.com/StorageKit)
//
// 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.
//
@testable import StorageKit
final class SpyEntityDescription {
static fileprivate(set) var isInsertNewObjectCalled = false
static fileprivate(set) var insertNewObjectEntityNameArgument: String?
static fileprivate(set) var insertNewObjectContextArgument: StorageWritableContext?
static func clean() {
isInsertNewObjectCalled = false
insertNewObjectEntityNameArgument = nil
insertNewObjectContextArgument = nil
}
}
extension SpyEntityDescription: EntityDescriptionType {
static func insertNewObject(forEntityName entityName: String, into context: StorageWritableContext) -> StorageEntityType {
isInsertNewObjectCalled = true
insertNewObjectEntityNameArgument = entityName
insertNewObjectContextArgument = context
return DummyStorageEntity()
}
}
| mit | 96169c30a90d961e3a224c579ac0cb77 | 41.8125 | 126 | 0.753285 | 4.904535 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Views/Cells/Chat/ChatMessageURLView.swift | 1 | 2252 | //
// ChatMessageURLView.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/25/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
protocol ChatMessageURLViewProtocol: class {
func openURLFromCell(url: String)
}
final class ChatMessageURLView: UIView {
static let defaultHeight = CGFloat(50)
fileprivate static let imageViewDefaultWidth = CGFloat(50)
weak var delegate: ChatMessageURLViewProtocol?
var url: MessageURL! {
didSet {
updateMessageInformation()
}
}
@IBOutlet weak var viewLeftBorder: UIView!
@IBOutlet weak var imageViewURLWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var imageViewURL: UIImageView! {
didSet {
imageViewURL.layer.masksToBounds = true
}
}
@IBOutlet weak var labelURLTitle: UILabel!
@IBOutlet weak var labelURLDescription: UILabel!
private lazy var tapGesture: UITapGestureRecognizer = {
return UITapGestureRecognizer(target: self, action: #selector(viewDidTapped(_:)))
}()
fileprivate func updateMessageInformation() {
let containsGesture = gestureRecognizers?.contains(tapGesture) ?? false
if !containsGesture {
addGestureRecognizer(tapGesture)
}
labelURLTitle.text = url.title
labelURLDescription.text = url.textDescription
if let imageURL = URL(string: url.imageURL ?? "") {
ImageManager.loadImage(with: imageURL, into: imageViewURL) { [weak self] _, error in
let width = error != nil ? 0 : ChatMessageURLView.imageViewDefaultWidth
self?.imageViewURLWidthConstraint.constant = width
self?.layoutSubviews()
}
} else {
imageViewURLWidthConstraint.constant = 0
layoutSubviews()
}
}
@objc func viewDidTapped(_ sender: Any) {
// delegate?.openURLFromCell(url: url)
}
}
// MARK: Themeable
extension ChatMessageURLView {
override func applyTheme() {
super.applyTheme()
guard let theme = theme else { return }
viewLeftBorder.backgroundColor = theme.auxiliaryText
labelURLDescription.textColor = theme.auxiliaryText
}
}
| mit | 85b6fb30548bdd7a44b4361c3eae17c7 | 28.618421 | 96 | 0.657041 | 4.851293 | false | false | false | false |
scottiesan/RoundedLoadingControl | RoundedLoadingControl/RoundedLoading.swift | 1 | 3918 | //
// RoundedLoading.swift
// RoundedLoadingControl
//
// Created by Scott Ho on 12/3/16.
// Copyright © 2016 Scott Ho. All rights reserved.
//
import UIKit
@IBDesignable
class RoundedLoading: UIView {
var percentageLabel = UILabel()
var range:CGFloat = 100
var currentValue:CGFloat = 0 {
didSet{
animate()
}
}
let margin:CGFloat = 0
let bgLayer = CAShapeLayer()
let fgLayer = CAShapeLayer()
@IBInspectable var bgColor:UIColor = UIColor.black {
didSet {
configure()
}
}
@IBInspectable var fgColor:UIColor = UIColor.blue {
didSet {
configure()
}
}
@IBInspectable var lineWidth:CGFloat = 10 {
didSet {
configure()
}
}
private func setup(){
bgLayer.fillColor = nil
bgLayer.strokeEnd = 1
fgLayer.fillColor = nil
fgLayer.strokeEnd = 0
layer.addSublayer(bgLayer)
layer.addSublayer(fgLayer)
percentageLabel.font = UIFont.systemFont(ofSize: 14)
percentageLabel.textColor = UIColor.black
percentageLabel.translatesAutoresizingMaskIntoConstraints = false
percentageLabel.text = "0%"
addSubview(percentageLabel)
let labelCenterX = percentageLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor)
let labelCenterY = percentageLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: margin)
NSLayoutConstraint.activate([labelCenterX, labelCenterY])
}
private func configure(){
let cur = Int(currentValue)
percentageLabel.text = String("\(cur)%")
bgLayer.strokeColor = bgColor.cgColor
fgLayer.strokeColor = fgColor.cgColor
bgLayer.lineWidth = lineWidth
fgLayer.lineWidth = lineWidth
}
private func setupShapeLayer (shapeLayer: CAShapeLayer){
shapeLayer.frame = self.bounds
let startAngle = DegreesToRadians(270.0001)
let endAngle = DegreesToRadians(270)
let center = percentageLabel.center
let radius = self.bounds.width * 0.35
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
shapeLayer.path = path.cgPath
}
func DegreesToRadians (_ value:CGFloat) -> CGFloat {
return value * CGFloat(M_PI) / 180.0
}
func RadiansToDegrees (_ value:CGFloat) -> CGFloat {
return value * 180.0 / CGFloat(M_PI)
}
override func layoutSubviews() {
super.layoutSubviews()
setupShapeLayer(shapeLayer: bgLayer)
setupShapeLayer(shapeLayer: fgLayer)
}
override func awakeFromNib() {
setup()
configure()
}
override func prepareForInterfaceBuilder() {
setup()
configure()
}
fileprivate func animate() {
let cur = Int(currentValue)
percentageLabel.text = String("\(cur)%")
var fromValue = fgLayer.strokeStart
let toValue = currentValue / range
if let presentationLayer = fgLayer.presentation() {
fromValue = presentationLayer.strokeEnd
}
let percentChange = abs(fromValue - toValue)
// 1
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = fromValue
animation.toValue = toValue
// 2
animation.duration = CFTimeInterval(percentChange * 4)
// 3
fgLayer.removeAnimation(forKey: "stroke")
fgLayer.add(animation, forKey: "stroke")
CATransaction.begin()
CATransaction.setDisableActions(true)
fgLayer.strokeEnd = toValue
CATransaction.commit()
}
}
| mit | bb85e11512f88acfa93f82956a91944e | 26.391608 | 127 | 0.60046 | 5.236631 | false | false | false | false |
devedbox/AXAnimationChain | AXAnimationChain/Classes/Swifty/UIView+Effects.swift | 1 | 9043 | //
// UIView+Effects.swift
// AXAnimationChain
//
// Created by devedbox on 2017/1/15.
// Copyright © 2017年 devedbox. 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 UIKit
import AXAnimationChainSwift
/// Constant enum type of effects showing directions.
///
public enum AXAnimationEffectsDirection: Int {
case top, left, bottom, right
}
/// Calculate the settling duration of spring animation parameters: mass/stiffness/damping.
///
/// - Parameters:
/// - mass: mass of the spring animation to be calculated.
/// - stiffness: stiffness of the spring animation to be calculated.
/// - damping: damping of the spring animation to be calculated.
///
/// - Returns: duration of the spring to be settling.
private func settlingDurationForSpring(mass: Double, stiffness: Double, damping: Double) -> Double {
let beta = damping/(2*mass)
let omega0 = sqrt(stiffness/mass)
let flag = -log(0.001)/min(beta, omega0)
let duration = -log(0.0004)/min(beta, omega0)
return (flag + duration) / 2;
}
/// Animation effects extension of `UIView`.
///
public extension UIView {
/// Run a \`tada\` animation effect on the receiver.
///
/// - parameter completion: a completion closure to execute when the animation finished.
///
public func tada(completion: @escaping () -> Void = {}) {
chainAnimator.basic.property("transform.scale").fromValue(1.0).toValue(1.1).duration(0.15).combineBasic().property("transform.rotation").byValue(.pi/21.0).duration(0.1).autoreverses().repeatCount(2).combineBasic().beginTime(0.1).property("transform.rotation").byValue(-.pi/18.0).duration(0.1).autoreverses().repeatCount(2).nextToBasic().property("transform.scale").toValue(1.0).duration(0.15).start(completion: completion)
}
/// Run a \`bonuce\` animation effect on the receiver.
///
/// - Parameters:
/// - from: the from direction of the bonuce animation showing up.
/// - completion: a completion closure to execute when the animation finished.
///
public func bonuce(from direction: AXAnimationEffectsDirection = .top, completion: @escaping () -> Void = {}) {
switch direction {
case .top:
chainAnimator.basic.property("position.y").byValue(50).toValue(self.layer.position.y).duration(0.5).easeOutBounce().start(completion: completion)
case .left:
chainAnimator.basic.property("position.x").byValue(50).toValue(self.layer.position.x).duration(0.5).easeOutBounce().start(completion: completion)
case .bottom:
chainAnimator.basic.property("position.y").fromValue(self.layer.position.y+50).toValue(self.layer.position.y).duration(0.5).easeOutBounce().start(completion: completion)
default:
chainAnimator.basic.property("position.x").fromValue(self.layer.position.x+50).toValue(self.layer.position.x).duration(0.5).easeOutBounce().start(completion: completion)
}
}
/// Run a \`pulse\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func pulse(completion: @escaping () -> Void = {}) {
chainAnimator.basic.property("transform.scale").byValue(0.1).duration(0.5).linear().autoreverses().start(completion: completion)
}
/// Run a \`shake\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func shake(completion: @escaping () -> Void = {}) {
let position = layer.position
chainAnimator.basic.property("position.x").fromValue(position.x-20).toValue(position.x+20).duration(0.1).linear().autoreverses().repeatCount(1.5).nextToBasic().property("position.x").toValue(position.x).duration(0.1).start(completion: completion)
}
/// Run a \`swing\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func swing(completion: @escaping () -> Void = {}) {
chainAnimator.basic.property("transform.rotation").byValue(.pi/21.0).duration(0.1).autoreverses().repeatCount(2).combineBasic().beginTime(0.1).property("transform.rotation").byValue(-.pi/18.0).duration(0.1).autoreverses().repeatCount(2).nextToBasic().property("transform.scale").toValue(1.0).duration(0.15).start(completion: completion)
}
/// Run a \`snap\` animation effect on the receiver.
///
/// - Parameter from: the from direction of the bonuce animation showing up.
///
public func snap(from direction: AXAnimationEffectsDirection = .left) {
layer.anchorToRight()
chainAnimator.spring.property("position.x").byValue(150).toValue(self.layer.position.x)/*.mass(1).stiffness(100).damping(13)*/.combineSpring().property("transform.scale.x").byValue(-0.5).combineSpring().beginTime(0.5).property("transform.scale.x").byValue(0.5).mass(1).stiffness(100).damping(13).start()
}
/// Run a \`expand\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func expand(completion:@escaping () -> Void = {}) {
chainAnimator.basic.property("transform.scale").fromValue(0.0).toValue(1.0).duration(0.5).start(completion: completion)
}
/// Run a \`compress\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func compress(completion: @escaping () -> Void = {}) {
chainAnimator.basic.property("transform.scale").fromValue(1.0).toValue(0.0).duration(0.5).start(completion: completion)
}
/// Run a \`hinge\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func hinge(completion: @escaping () -> Void = {}) {
layer.anchorToLeftTop()
chainAnimator.spring.property("transform.rotation").fromValue(0).toValue(acos(Double(bounds.height)/Double(pow(pow(bounds.width, 2.0)+pow(bounds.height, 2.0), 0.5)))).mass(2).stiffness(100).damping(10).combineBasic().beginTime(1.0).property("position.y").byValue(UIScreen.main.bounds.height).duration(0.5).easeInCubic().start(completion: completion)
}
/// Run a \`drop\` animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func drop(completion: @escaping () -> Void = {}) {
chainAnimator.basic.anchorToRightTop().property("transform.rotation").toValue(-Double.pi/18*2).duration(1.0).combineBasic().property("position.y").fromValue(layer.position.y).toValue(UIScreen.main.bounds.height+layer.position.y).duration(0.5).easeInCubic().start(completion: completion)
}
/// Run a morph animation effect on the receiver.
///
/// - Parameter completion: a completion closure to execute when the animation finished.
///
public func morph(completion: @escaping () -> Void = {}) {
let duration = 0.25;
let minscale = 0.8;
let maxscale = 1.2;
chainAnimator.basic.property("transform.scale.y").duration(duration).toValue(minscale).linear().combineBasic().property("transform.scale.x").duration(duration).toValue(maxscale).linear().nextToBasic().property("transform.scale.y").duration(duration).toValue(maxscale).linear().combineBasic().property("transform.scale.x").duration(duration).toValue(minscale).linear().nextToBasic().property("transform.scale.y").duration(duration).toValue(minscale).linear().combineBasic().property("transform.scale.x").duration(duration).toValue(maxscale).linear().nextToBasic().property("transform.scale.y").duration(duration).toValue(1.0).linear().combineBasic().property("transform.scale.x").duration(duration).toValue(1.0).linear().start(completion: completion)
}
}
| mit | bac3ed4db5b46709050314103f56380a | 60.496599 | 757 | 0.700221 | 3.987649 | false | false | false | false |
SquidKit/SquidKit | SquidKit/UIApplication+Update.swift | 1 | 6441 | //
// UIApplication+Update.swift
// SquidKit
//
// Created by Mike Leavy on 8/24/18.
// Copyright © 2018-2019 Squid Store, LLC. All rights reserved.
//
import UIKit
private func parseVersion(_ lhs: AppVersion, rhs: AppVersion) -> Zip2Sequence<[Int], [Int]> {
let lhs = lhs.versionString.split(separator: ".").map { (String($0) as NSString).integerValue }
let rhs = rhs.versionString.split(separator: ".").map { (String($0) as NSString).integerValue }
let count = max(lhs.count, rhs.count)
return zip(
lhs + Array(repeating: 0, count: count - lhs.count),
rhs + Array(repeating: 0, count: count - rhs.count))
}
public func == (lhs: AppVersion, rhs: AppVersion) -> Bool {
var result: Bool = true
for (l, r) in parseVersion(lhs, rhs: rhs) {
if l != r {
result = false
}
}
return result
}
public func < (lhs: AppVersion, rhs: AppVersion) -> Bool {
for (l, r) in parseVersion(lhs, rhs: rhs) {
if l < r {
return true
}
else if l > r {
return false
}
}
return false
}
public struct AppVersion: Comparable {
public static var marketingVersion: AppVersion? {
guard let shortVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else {
return nil
}
return AppVersion(shortVersion)
}
public static var version: AppVersion? {
guard let bundleVersion = Bundle.main.infoDictionary?[kCFBundleVersionKey as String] as? String else {
return nil
}
return AppVersion(bundleVersion)
}
fileprivate(set) public var versionString: String
public init(_ versionString: String) {
self.versionString = versionString
}
}
extension AppVersion: CustomStringConvertible {
public var description: String {
return self.versionString
}
}
public typealias AppUpdateInfoCompletion = (UIApplication.StoreVersion, URL?, Error?) -> Void
extension UIApplication {
// Enumeration constants for app store version status as compaered to version of currently running app.
// String parameters are the app store version short string
public enum StoreVersion: CustomStringConvertible {
// version on store is newer
case newer(String)
// version on store is older
case older(String)
// app version and store version are identical
case identical(String)
// store version is unknown or could not be determined
case unknown
public var description: String {
switch self {
case .newer(let value):
return "newer (\(value))"
case .older(let value):
return "older (\(value))"
case .identical(let value):
return "identical (\(value))"
case .unknown:
return "unknown"
}
}
}
private struct AppStoreLookupResult: Decodable {
var results: [AppStoreLookupInfo]
}
private struct AppStoreLookupInfo: Decodable {
var version: String
var trackViewUrl: String?
}
public enum AppUpdateVersionError: Error {
case invalidBundleInfo
case invalidResponse
}
private func getAppInfo(completion: @escaping (AppStoreLookupInfo?, Error?) -> Void) -> URLSessionDataTask? {
guard let identifier = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String,
let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(identifier)") else {
DispatchQueue.main.async {
completion(nil, AppUpdateVersionError.invalidBundleInfo)
}
return nil
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
if let error = error {throw error}
guard let data = data else {throw AppUpdateVersionError.invalidResponse}
let result = try JSONDecoder().decode(AppStoreLookupResult.self, from: data)
guard let info = result.results.first else {throw AppUpdateVersionError.invalidResponse}
completion(info, nil)
}
catch {
completion(nil, error)
}
}
task.resume()
return task
}
public func checkAppStoreVersion(completion: @escaping AppUpdateInfoCompletion) {
guard let currentVersion = AppVersion.marketingVersion else {
completion(.unknown, nil, nil)
return
}
let _ = getAppInfo { [weak self] (info, error) in
guard error == nil else {
self?.handleCompletion(version: .unknown, url: nil, error: error, completion: completion)
return
}
guard let version = info?.version else {
self?.handleCompletion(version: .unknown, url: nil, error: nil, completion: completion)
return
}
var storeURL: URL?
if let trackURL = info?.trackViewUrl {
var components = URLComponents(string: trackURL)
// set the "load store" and "media type" parameters
let loadStoreItem = URLQueryItem(name: "ls", value: "1")
let mediaTypeItem = URLQueryItem(name: "mt", value: "8")
components?.queryItems = [loadStoreItem, mediaTypeItem]
storeURL = components?.url
}
let appStoreVersion = AppVersion(version)
var status = StoreVersion.unknown
if appStoreVersion == currentVersion {
status = .identical(version)
}
else if appStoreVersion > currentVersion {
status = .newer(version)
}
else if appStoreVersion < currentVersion {
status = .older(version)
}
self?.handleCompletion(version: status, url: storeURL, error: error, completion: completion)
}
}
private func handleCompletion(version: StoreVersion, url: URL?, error: Error?, completion: @escaping AppUpdateInfoCompletion) {
DispatchQueue.main.async {
completion(version, url, error)
}
}
}
| mit | 3a6a9d4b90ee97e2d11f448fcfdbf31f | 33.074074 | 131 | 0.584627 | 4.972973 | false | false | false | false |
appanalytic/lib-swift | AppAnalyticsSwift/Classes/AppAnalyticsSwift.swift | 1 | 11530 | //
// AppAnalytic.swift
// Pods
//
// Created by Vahid Sayad on 2016-06-19.
//
//
import Foundation
import UIKit
public extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 where value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8":return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: AppAnalyticsSwift Class
// //////////////////////////////////////////////////////////////////////////////////////////////////
public class AppAnalyticsSwift{
private let _accessKey: String
private var _APIURL = "http://appanalytics.ir/api/v1/iosservice/initialize/"
private var _APIURL_DeviceInfo = "http://appanalytics.ir/api/v1/iosservice/setdeviceinfo/"
private var _APIURL_AddEvent = "http://appanalytics.ir/api/v1/iosservice/addevent/"
private let _UUID: String
private var _deviceModelName: String
private var _iOSVersion: String
private var _orientation: String
private var _batteryLevel: String
private var _multitaskingSupported: String
// //////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: submitCampain Function
// //////////////////////////////////////////////////////////////////////////////////////////////////
public func submitCampaign(){
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey("firstTimeAppAnalytics") {
print("AppAnalytic Info (Submit Campaign): Already initialized")
} else {
let url = NSURL(string: self._APIURL + self._UUID)
let request = NSMutableURLRequest(URL: url!)
request.setValue(self._accessKey, forHTTPHeaderField: "Access-Key")
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
if let data = data {
do {
let jsonDic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
let status = jsonDic["status"] as? String;
if status == "ok" {
defaults.setBool(true, forKey: "firstTimeAppAnalytics")
print("AppAnalytic Info (Submit Campaign): [", String(data: data, encoding: NSUTF8StringEncoding)!,"]")
self.sendDeviceInfo(self.getDeviceInfo())
}
} catch {
print("AppAnalytic Error (Submit Campaign): [Error in deserialize AppAnalytics.ir JSON result]")
defaults.setBool(false, forKey: "firstTimeAppAnalytics")
}
}
if let error = error {
print("AppAnalytic Error (Submit Campaign): [\(error.localizedDescription)")
defaults.setBool(false, forKey: "firstTimeAppAnalytics")
}
}.resume()
}
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: AddEvent()
// //////////////////////////////////////////////////////////////////////////////////////////////////
public func addEvent(eventName eventName: String!, eventValue: String?){
var tmpURL = self._APIURL_AddEvent + self._UUID + "/"
if eventName.characters.count > 0 {
tmpURL += eventName + "/"
} else {
return
}
if eventValue != nil && eventValue?.characters.count > 0 {
tmpURL += eventValue!
}
print("TMPURL: \(tmpURL)")
let url = NSURL(string: tmpURL)
let request = NSMutableURLRequest(URL: url!)
request.setValue(self._accessKey, forHTTPHeaderField: "Access-Key")
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
if let data = data {
print("AppAnalytic Info (AddEvent): [", String(data: data, encoding: NSUTF8StringEncoding)!,"]")
self.sendDeviceInfo(self.getDeviceInfo())
}
if let error = error {
print("AppAnalytic Error (AddEvent): [\(error.localizedDescription)]")
}
}.resume()
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: SendDeviceInfo()
// //////////////////////////////////////////////////////////////////////////////////////////////////
private func sendDeviceInfo(jsonData: NSData){
let defaults = NSUserDefaults.standardUserDefaults()
let url = NSURL(string: self._APIURL_DeviceInfo + self._UUID)
let request = NSMutableURLRequest(URL: url!)
request.setValue(self._accessKey, forHTTPHeaderField: "Access-Key")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = jsonData
NSURLSession.sharedSession().dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) in
if let data = data {
do {
let jsonDic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
let status = jsonDic["status"] as? String;
if status == "ok" {
defaults.setBool(true, forKey: "firstTimeAppAnalytics")
print("AppAnalytic Info (Send Device Info): [", String(data: data, encoding: NSUTF8StringEncoding)!,"]")
}
} catch {
print("AppAnalytic Error (Send Device Info): [Error in deserialize AppAnalytics.ir JSON result]")
defaults.setBool(false, forKey: "firstTimeAppAnalytics")
}
}
if let error = error {
print("AppAnalytic Error (Send Device Info): [\(error.localizedDescription)]")
defaults.setBool(false, forKey: "firstTimeAppAnalytics")
}
}.resume()
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// Mark: GetDeviceInfo()
// //////////////////////////////////////////////////////////////////////////////////////////////////
private func getDeviceInfo() -> NSData {
var json = NSData()
let info = NSMutableDictionary()
if self._deviceModelName != "Error" {
info["DeviceModel"] = self._deviceModelName
}
if self._iOSVersion != "Error" {
info["iOSVersion"] = self._iOSVersion
}
if self._orientation != "Error" {
info["Orientation"] = self._orientation
}
if self._batteryLevel != "Error" {
info["BatteryLevel"] = self._batteryLevel
}
if self._multitaskingSupported != "Error" {
info["MultiTaskingSupported"] = self._multitaskingSupported
}
do {
json = try NSJSONSerialization.dataWithJSONObject(info, options: NSJSONWritingOptions.PrettyPrinted)
} catch let error as NSError {
print("AppAnalytic Error: [\(error.localizedDescription)]")
}
return json
}
// //////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Init
// //////////////////////////////////////////////////////////////////////////////////////////////////
public init(accessKey key: String){
self._accessKey = key
if let id = UIDevice.currentDevice().identifierForVendor {
self._UUID = id.UUIDString
} else {
self._UUID = "error"
}
//Device model name
self._deviceModelName = UIDevice.currentDevice().modelName
// iOS Version
self._iOSVersion = UIDevice.currentDevice().systemVersion
// Device Oriantation
let orientation = UIDevice.currentDevice().orientation
switch orientation {
case .LandscapeLeft:
self._orientation = "LandscapeLeft"
case .LandscapeRight:
self._orientation = "LandscapeRight"
case .Portrait:
self._orientation = "Portrait"
case .PortraitUpsideDown:
self._orientation = "PortraitUpsideDown"
default:
self._orientation = "Error"
}
// Battery Level
switch UIDevice.currentDevice().batteryLevel {
case -1.0:
self._batteryLevel = "Error"
default:
self._batteryLevel = String("\(UIDevice.currentDevice().batteryLevel )")
}
//Multi tasking supported:
if UIDevice.currentDevice().multitaskingSupported {
self._multitaskingSupported = "true"
} else {
self._multitaskingSupported = "false"
}
}
} | mit | a04181706c29a4b856fe60e86bc4bcd1 | 44.577075 | 135 | 0.483088 | 5.485252 | false | false | false | false |
pnhechim/Fiestapp-iOS | Fiestapp/Fiestapp/Common/Extensions/UIImageViewExtension.swift | 1 | 1049 | //
// UIImageViewExtension.swift
// Fiestapp
//
// Created by Nicolás Hechim on 11/6/17.
// Copyright © 2017 Mint. All rights reserved.
//
import UIKit
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFill) {
contentMode = mode
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFill) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
| mit | de1f7cba31f7de74151a0b90b4c78125 | 33.9 | 102 | 0.603629 | 4.632743 | false | false | false | false |
coreymason/LAHacks2017 | ios/DreamWell/DreamWell/StatisticsViewController.swift | 1 | 6330 | //
// StatisticsViewController.swift
// DreamWell
//
// Created by Rohin Bhushan on 4/1/17.
// Copyright © 2017 rohin. All rights reserved.
//
import UIKit
import Charts
class StatisticsViewController: UIViewController, ServicesDelegate {
@IBOutlet weak var chartView: LineChartView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var transcriptTextView: UITextView!
@IBOutlet weak var dateLabel: UILabel!
var positivity : Int?
var temp : Int?
var humidity : Int?
var sleepRating : Int?
var lightAvg : Int?
var keywords : [String]?
var currentDate : Date = Date() {
didSet {
let format = DateFormatter()
format.dateStyle = .medium
format.timeStyle = .none
dateLabel.text = format.string(from: currentDate)
}
}
var axisLabel : UILabel?
var currentOffset = 0
override func viewDidLoad() {
super.viewDidLoad()
Services.delegate = self
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = UIColor.clear
tableView.separatorStyle = .none
self.tableView.contentInset = UIEdgeInsetsMake(-36, 0, 0, 0);
// configure chart
chartView.isUserInteractionEnabled = false
let d = Description()
d.enabled = false
chartView.chartDescription = d
chartView.drawGridBackgroundEnabled = true
chartView.drawBordersEnabled = true
chartView.legend.enabled = false
chartView.leftAxis.enabled = true
chartView.leftAxis.drawLabelsEnabled = false
chartView.rightAxis.enabled = false
chartView.xAxis.enabled = true
chartView.xAxis.avoidFirstLastClippingEnabled = true
chartView.gridBackgroundColor = UIColor.white
chartView.borderColor = veryLightGray
chartView.leftAxis.drawGridLinesEnabled = false
chartView.leftAxis.axisLineColor = veryLightGray
chartView.leftAxis.labelTextColor = UIColor.lightGray
chartView.xAxis.gridColor = veryLightGray
chartView.xAxis.axisLineColor = veryLightGray
chartView.xAxis.labelPosition = .bottom
chartView.xAxis.labelTextColor = UIColor.lightGray
chartView.noDataText = "No data yet"
Services.delegate = self
Services.getDailyStat()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Services.delegate = self
Services.getSuggestions()
}
@IBAction func previous(_ sender: Any) {
let calendar = Calendar.current
currentDate = calendar.date(byAdding: .day, value: -1, to: currentDate)!
currentOffset -= 1
Services.getDailyStat(dayOffset: currentOffset)
}
@IBAction func next(_ sender: Any) {
let calendar = Calendar.current
currentDate = calendar.date(byAdding: .day, value: 1, to: currentDate)!
currentOffset += 1
Services.getDailyStat(dayOffset: currentOffset)
}
func addLeftAxisLabel(text: String) {
axisLabel?.removeFromSuperview()
let font = UIFont(name: "Avenir Next", size: 15.0)!
let labelSize = (text as NSString).size(attributes: [NSFontAttributeName: font])
axisLabel = UILabel()
axisLabel?.text = text
axisLabel?.font = font
axisLabel?.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 2)
axisLabel?.frame = CGRect(x: chartView.frame.origin.x - 25, y: 100, width: labelSize.height, height: labelSize.width)
axisLabel?.center.y = chartView.center.y
self.view.addSubview(axisLabel!)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
transcriptTextView.setContentOffset(CGPoint.zero, animated: false)
}
func dailyStatsReceived(json: [String : Any]) {
print(json)
positivity = Int(((json["sentiment"] as? Double) ?? 0.0) * 100)
transcriptTextView.text = " Transcript: " + (json["dreamContent"] as! String)
if let roomData = json["roomData"] as? [String : Any] {
humidity = roomData["humidAvg"] as? Int
lightAvg = roomData["lightAvg"] as? Int
let yVals = roomData["audioValues"] as! NSArray as! [Double]
temp = roomData["tempAvg"] as? Int
keywords = json["keywords"] as? NSArray as? [String]
sleepRating = json["quality"] as? Int
updateChart(yVals: yVals)
}
tableView.reloadData()
}
func updateChart(yVals: [Double]) {
var entries = [ChartDataEntry]()
for (index, val) in yVals.enumerated() {
let entry = ChartDataEntry(x: Double(index + 2) / 2.0, y: val)
entries.append(entry)
}
let dataSet = LineChartDataSet(values: entries, label: nil)
dataSet.colors = [greenColor]
dataSet.mode = .cubicBezier
dataSet.drawFilledEnabled = true
dataSet.drawValuesEnabled = false
dataSet.drawCirclesEnabled = false
dataSet.fillColor = greenColor
dataSet.fillAlpha = 0.4
let dataSets = [dataSet]
let data = LineChartData(dataSets: dataSets)
chartView.data = data
chartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: { (val, base) -> String in
return "\(Int(val)) am"
})
chartView.animate(yAxisDuration: 1.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension StatisticsViewController : UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 25.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
switch indexPath.row {
case 0:
(cell.viewWithTag(0) as! UILabel).text = "Dream Positivity"
(cell.viewWithTag(1) as! UILabel).text = "\(positivity ?? 96)%"
case 1:
(cell.viewWithTag(0) as! UILabel).text = "Temperature"
(cell.viewWithTag(1) as! UILabel).text = "\(temp ?? 69)º"
case 2:
(cell.viewWithTag(0) as! UILabel).text = "Humidity"
(cell.viewWithTag(1) as! UILabel).text = "\(humidity ?? 0)%"
case 3:
(cell.viewWithTag(0) as! UILabel).text = "Sleep rating"
(cell.viewWithTag(1) as! UILabel).text = "\(sleepRating ?? 7)/10"
case 4:
(cell.viewWithTag(0) as! UILabel).text = "Light"
(cell.viewWithTag(1) as! UILabel).text = "\(lightAvg ?? 0)%"
case 5:
(cell.viewWithTag(0) as! UILabel).text = "Keywords"
(cell.viewWithTag(1) as! UILabel).text = (keywords ?? ["none found"]).joined(separator: ", ")
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
}
| mit | 55ecb524b513e9d143c4c512ec6b68c5 | 30.019608 | 119 | 0.71476 | 3.753262 | false | false | false | false |
barbrobmich/linkbase | LinkBase/LinkBase/ProfileSetupViewController.swift | 1 | 8593 | //
// ProfileSetupViewController.swift
// LinkBase
//
// Created by Barbara Ristau on 4/1/17.
// Copyright © 2017 barbrobmich. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class ProfileSetupViewController: UIViewController {
@IBOutlet weak var profileImageView: PFImageView!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var weirdFactTextView: UITextView!
@IBOutlet weak var saveButton: UIButton!
var currentUser: User!
var firstName: String!
var lastName: String!
var weirdFact: String!
var image: UIImage!
var changedProfileImage: Bool?
var onPhotoTap: UITapGestureRecognizer!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.isHidden = false
currentUser = User.current()
print("Current user: \(currentUser.username!)")
changedProfileImage = false
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.startUpdatingLocation()
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.requestWhenInUseAuthorization()
firstName = currentUser.object(forKey: "firstname") as? String
lastName = currentUser.object(forKey: "lastname") as? String
weirdFact = currentUser.object(forKey: "weird_fact") as? String
firstNameTextField.text = firstName
lastNameTextField.text = lastName
emailTextField.text = currentUser.email!
getCurrentUserImage()
onPhotoTap = UITapGestureRecognizer(target: self, action: #selector(self.getPhoto(_:)))
profileImageView.addGestureRecognizer(onPhotoTap)
profileImageView.isUserInteractionEnabled = true
}
// MARK: - PROFILE IMAGE RELATED METHODS
func getCurrentUserImage() {
let myImage = PFImageView()
if currentUser["profile_image"] != nil {
// weirdFact = currentUser.object(forKey: "weird_fact") as? String
// myImage.file = currentUser["profile_image"] as? PFFile
myImage.file = currentUser.object(forKey: "profile_image") as? PFFile
myImage.loadInBackground()
} else {
myImage.image = UIImage(named: "profilePlaceholder")!
}
profileImageView.image = myImage.image
profileImageView.clipsToBounds = true
profileImageView.layer.cornerRadius = 15
}
func getPhoto(_ sender: UITapGestureRecognizer){
print("Getting the photo")
pickPhoto()
}
func show(image: UIImage) {
profileImageView.image = image
profileImageView.frame = CGRect(x: 70, y: 50, width: 64, height: 64)
// adjust x and y coordinates, can these be set in autolayout
}
func postProfileImageToParse() {
User.saveProfileImage(image: profileImageView.image) { (success: Bool, error: Error?) -> Void in
if success {
print("Successful Post to Parse")
}
else {
print("Can't post to parse")
}
}
}
@IBAction func onSave(_ sender: UIButton) {
print("tapped on Save")
// need to change this to update / just regular save
// postProfileImageToParse()
//
// User.updateProfileData(fname: firstNameTextField.text!, lname: lastNameTextField.text!, email: emailTextField.text!, weirdFact: weirdFactTextView.text) { (success: Bool, error: Error?) -> Void in
//
// if success {
// print("Successful Post to Parse")
// // segue to next section
// }
// else {
// print("Can't post to parse")
// }
// }
}
@IBAction func onLogout(_ sender: UIButton) {
print("Logging Out")
User.logOut()
NotificationCenter.default.post(name: NSNotification.Name(rawValue: User.userDidLogout), object: nil)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "AddAffiliations" {
print("Going to add Affiliations")
let destinationNavigationController = segue.destination as! UINavigationController
let targetController = destinationNavigationController.topViewController as! AddAffiliationsViewController
targetController.navigationItem.title = "Add Affiliations"
}
}
}
extension ProfileSetupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func takePhotoWithCamera() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
image = info[UIImagePickerControllerEditedImage] as? UIImage
print("did pick the image")
if let theImage = image{
print("Going to show the image")
changedProfileImage = true
show(image: theImage)
}
//tableView.reloadData()
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func choosePhotoFromLibrary() {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}
func pickPhoto() {
if true || UIImagePickerController.isSourceTypeAvailable(.camera) {
showPhotoMenu()
}
else {
choosePhotoFromLibrary()
}
}
func showPhotoMenu() {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)
let takePhotoAction = UIAlertAction(title: "Take Photo", style: .default, handler: {_ in self.takePhotoWithCamera() })
alertController.addAction(takePhotoAction)
let chooseFromLibraryAction = UIAlertAction(title: "Choose From Library", style: .default, handler: {_ in self.choosePhotoFromLibrary() })
alertController.addAction(chooseFromLibraryAction)
present(alertController, animated: true, completion: nil)
}
}
// MARK: - Get current location
extension ProfileSetupViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Updating with current location")
// only create an Address if a User doesn't have an address
if !self.currentUser.hasAddress{
// makes an address based on current location
let addr = Address(lat: (locations.last?.coordinate.latitude)!, long: (locations.last?.coordinate.longitude)!)
self.locationManager?.stopUpdatingLocation()
//constructs the address from the GPS location
addr.setLocationfromSelf()
//updates to Parse
addr.postAddress(user: self.currentUser) { (success: Bool, error: Error?) in
if success{
print("address sent to parse")
}else{
print("dang no address sent")
}
}
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error trying to get gps: \(error.localizedDescription)")
}
}
| mit | 9d5576e81e2d6fb608d83ea003e5cb8d | 32.694118 | 205 | 0.624884 | 5.521851 | false | false | false | false |
neotron/SwiftBot-Discord | DiscordAPI/Source/API/WebSockets/WebsocketAPIManager.swift | 1 | 6126 | //
// Created by David Hedbor on 2/12/16.
// Copyright (c) 2016 NeoTron. All rights reserved.
//
// Handles all communication over the Websocket API
import Foundation
import Starscream
import ObjectMapper
import Dispatch
public protocol WebsocketAPIManagerDelegate : class {
func websocketAuthenticationError()
func websocketEndpointError()
func websocketMessageReceived(_ message: MessageModel, event: MessageEventType)
}
open class WebsocketAPIManager: NSObject, WebSocketDelegate {
weak var delegate: WebsocketAPIManagerDelegate?
fileprivate var socket: WebSocket?
fileprivate var timer: Timer?
fileprivate var sequence: Int?
open func fetchEndpointAndConnect() {
// This will fetch the websocket URL
if Registry.instance.websocketEndpoint == nil {
let request = GatewayUrlRequest()
request.execute({
(success: Bool) in
if (success) {
self.connectWebSocket()
} else {
LOG_ERROR("Websocket gateway request failed, no endpoint available.")
self.delegate?.websocketAuthenticationError()
}
});
} else {
connectWebSocket()
}
}
fileprivate func connectWebSocket()
{
guard let urlString = Registry.instance.websocketEndpoint, let url = URL(string: urlString) else {
LOG_ERROR("Failed to create websocket endpoint URL")
delegate?.websocketEndpointError()
return
}
socket = WebSocket(url: url)
socket!.delegate = self
socket!.connect()
}
func handleMessage(_ text: String) {
if let message = Mapper<WebsocketMessageModel>().map(JSONString: text), let type = message.type, let data = message.data {
self.sequence = message.sequence // for heart beat
switch (type) {
case "READY":
processReady(data)
case "MESSAGE_CREATE":
processMessage(data, event: .Create)
case "MESSAGE_UPDATE":
processMessage(data, event: .Update)
case "TYPING_START", "PRESENCE_UPDATE":
// We don't care about these at all
break
default:
LOG_INFO("Unhandled message received: \(type)")
}
}
}
func processMessage(_ dict: [String:AnyObject], event: MessageEventType) {
if let message = Mapper<MessageModel>().map(JSON: dict) {
if let authorId = message.author?.id, let myId = Registry.instance.user?.id {
if authorId == myId {
LOG_DEBUG("Ignoring message from myself.")
return
}
}
LOG_DEBUG("Decoded \(event) message: \(message)")
delegate?.websocketMessageReceived(message, event: event)
} else {
LOG_ERROR("Failed to decode message \(event) from dict \(dict)")
}
}
func processReady(_ dict: [String:AnyObject]) {
if let ready = Mapper<WebsocketReadyMessageModel>().map(JSON: dict) {
if let hbi = ready.heartbeatInterval {
LOG_INFO("Ready response received. Enabling heartbeat.")
enableKeepAlive(Double(hbi) / 1000.0)
} else {
LOG_ERROR("Ready response received, heartbeat interval missing!.")
}
if let botuser = ready.user {
Registry.instance.user = botuser // save user since we need user id later.
}
} else {
LOG_ERROR("Ready response received but could not be parsed: \(dict)")
}
}
func cancelKeepAlive() {
if let timer = self.timer {
timer.invalidate()
self.timer = nil
}
}
func enableKeepAlive(_ interval: Double) {
cancelKeepAlive()
LOG_DEBUG("Starting heartbeat timer with an interval of \(interval).");
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(sendHeartbeat), userInfo: nil, repeats: true)
}
func sendHeartbeat() {
guard let sequence = self.sequence else {
LOG_ERROR("Missing sequence for heartbeat.")
return
}
if let socket = self.socket, let heartbeat = Mapper().toJSONString(WebsocketHeartbeatModel(sequence: sequence)) {
socket.write(string: heartbeat)
LOG_DEBUG("Sent heartbeat \(heartbeat)");
}
}
// Websocket API callbacks below.
open func websocketDidConnect(socket: WebSocket) {
LOG_INFO("Websocket connected")
if let helloMessage = Mapper().toJSONString(WebsocketHelloMessageModel()) {
socket.write(string: helloMessage);
}
}
open func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
cancelKeepAlive()
if let err = error {
LOG_ERROR("Websocket disconnected with error: \(err) - attempting reconnect")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(5*NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) {
self.socket = nil
self.connectWebSocket()
}
} else {
LOG_INFO("Websocket disconnected")
}
}
open func websocketDidReceiveMessage(socket: WebSocket, text: String) {
LOG_DEBUG("Websocket text message received.")
handleMessage(text)
}
open func websocketDidReceiveData(socket: WebSocket, data: Data) {
do {
let inflatedData = try data.gunzipped()
if let text = String(data: inflatedData, encoding: String.Encoding.utf8) {
LOG_DEBUG("Websocket binary message received (\(data.count) -> \(inflatedData.count))")
handleMessage(text)
} else {
LOG_ERROR("Failed to decode binary message.")
}
} catch {
LOG_ERROR("Failed to gunzip binary data packet.")
return
}
}
}
| gpl-3.0 | 9e959e844b178fc84cf3019545805894 | 34.206897 | 140 | 0.584394 | 5.041975 | false | false | false | false |
devpunk/velvet_room | Pods/XmlHero/Source/XmlBuilder.swift | 1 | 930 | import Foundation
final class XmlBuilder
{
private weak var xml:Xml?
init(
xml:Xml,
object:Any)
{
self.xml = xml
guard
let string:String = deserialize(object:object)
else
{
failed()
return
}
deserialized(string:string)
}
//MARK: private
private func failed()
{
let error:XmlError = XmlError.failedDeserializing()
xml?.buildingError(error:error)
}
private func addHeader(string:String) -> String
{
var headered:String = XmlBuilder.factoryHeader()
headered.append(string)
return headered
}
private func deserialized(string:String)
{
let headered:String = addHeader(string:string)
xml?.buildingFinished(string:headered)
}
}
| mit | 8b9a389845b43d59d8d7ba0245a21ed5 | 17.979592 | 59 | 0.519355 | 4.894737 | false | false | false | false |
sadawi/PrimarySource | Pod/iOS/FieldCell.swift | 1 | 4816 | //
// FieldCell.swift
// Pods
//
// Created by Sam Williams on 11/30/15.
//
//
import UIKit
enum ControlAlignment {
case right
}
public enum FieldLabelPosition {
case top
case left
}
public enum FieldState {
case normal
case error([String])
case editing
}
open class FieldCell<Value: Equatable>: TitleDetailsCell {
var errorLabel:UILabel?
var errorIcon:UIImageView?
open var value:Value? {
didSet {
if oldValue != self.value {
self.valueChanged(from: oldValue, to: self.value)
}
self.update()
}
}
open var isReadonly:Bool = false
open var placeholderText:String? {
didSet {
self.update()
}
}
open var isBlank:Bool {
get { return self.value == nil }
}
open var state:FieldState = .normal {
didSet {
self.update()
self.stylize()
}
}
open dynamic var errorTextColor:UIColor? = UIColor.red
lazy var accessoryToolbar:UIToolbar = {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: 36))
self.configureAccessoryToolbar(toolbar)
return toolbar
}()
func configureAccessoryToolbar(_ toolbar:UIToolbar) {
var items:[UIBarButtonItem] = []
if self.toolbarShowsCancelButton {
items.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FieldCell.cancel)))
}
if self.toolbarShowsClearButton {
items.append(UIBarButtonItem(title: "Clear", style: .plain, target: self, action: #selector(FieldCell.clear)))
}
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
items.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FieldCell.commit)))
toolbar.items = items
}
var toolbarShowsCancelButton = false
var toolbarShowsClearButton = false
open func commit() {
}
open func cancel() {
}
open func clear() {
self.cancel()
self.update()
}
open var onChange:((Value?, Value?) -> Void)?
override open func buildView() {
super.buildView()
let errorLabel = UILabel(frame: self.detailContent!.bounds)
errorLabel.numberOfLines = 0
errorLabel.translatesAutoresizingMaskIntoConstraints = false
self.detailContent?.addSubview(errorLabel)
self.errorLabel = errorLabel
}
private var detailConstraints:[NSLayoutConstraint] = []
override func setupConstraints() {
super.setupConstraints()
guard let errorLabel = self.errorLabel, let detailContent = self.detailContent else { return }
detailContent.removeConstraints(self.detailConstraints)
self.detailConstraints.removeAll()
let views = ["error":errorLabel]
let metrics = [
"left": self.defaultContentInsets.left,
"right": self.defaultContentInsets.right,
"top": self.defaultContentInsets.top,
"bottom": self.defaultContentInsets.bottom,
"icon": 20
]
self.detailConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[error]-right-|", options: .alignAllTop, metrics: metrics, views: views)
self.detailConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[error]|", options: .alignAllTop, metrics: metrics, views: views)
detailContent.addConstraints(self.detailConstraints)
}
override open func update() {
super.update()
switch self.state {
case .error(let messages):
self.errorIcon?.image = UIImage(named: "error-32", in: Bundle(for: FieldCell.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
self.errorLabel?.text = messages.joined(separator: "\n")
default:
self.errorIcon?.image = nil
self.errorLabel?.text = nil
}
}
override open func stylize() {
super.stylize()
self.errorLabel?.textColor = self.errorTextColor
self.errorIcon?.tintColor = self.errorTextColor
self.errorLabel?.font = self.valueFont
}
open func valueChanged(from oldValue: Value?, to newValue: Value?) {
if let onChange = self.onChange {
onChange(oldValue, newValue)
}
}
open override func prepareForReuse() {
super.prepareForReuse()
self.onChange = nil
self.accessoryType = .none
self.placeholderText = nil
}
}
| mit | 2f18b198a349baf0edf286b44c803a91 | 28.187879 | 165 | 0.605689 | 4.820821 | false | false | false | false |
CooperCorona/Voronoi | Sources/Voronoi/VoronoiCell.swift | 1 | 9524 | //
// VoronoiCell.swift
// Voronoi2
//
// Created by Cooper Knaak on 5/29/16.
// Copyright © 2016 Cooper Knaak. All rights reserved.
//
import Foundation
import CoronaMath
internal func ~=(lhs:Double, rhs:Double) -> Bool {
let epsilon = 0.00001
return abs(lhs - rhs) < epsilon
}
/**
Combines a voronoi point and the edges / vertices around it.
*/
open class VoronoiCell {
///The original voronoi point.
public let voronoiPoint:Point
///The boundaries of the VoronoiDiagram.
public let boundaries:Size
///The vertices that form the edges of this cell.
fileprivate var vertices:[Point]? = nil
///The actual edges that form the boundaries of this cell.
internal var cellEdges:[VoronoiEdge] = []
///The neighboring cells adjacent to this cell.
///They must be weak references because otherwise, we have retain cycles.
///In a tiled diagram, this includes neighbors of symmetric cells (said
///symmetric cells do not have their own neighbors).
internal var weakNeighbors:Set<WeakReference<VoronoiCell>> = []
open var neighbors:[VoronoiCell] { return self.weakNeighbors.compactMap() { $0.object } }
///In a tiled diagram, cells outside the diagram are created. These are called the *symmetric* cells.
///In the interest of abstraction, these cells should not be considered on their own. Instead,
///they pass neighbors to their parent, so a cell can have a neighbor somewhere on the opposite
///side of the diagram because a symmetric child lies adjacent to it.
public internal(set) weak var symmetricParent:VoronoiCell? = nil
public internal(set) var symmetricChildren:[VoronoiCell] = []
///In a tiled diagram, cells outside the diagram lying on the same axis as the original cells
///are created. These are called the *symmetric* cells. They are used to simulate laying a
///voronoi diagram side by side. These cells are not considered "real" by the result of the diagram.
public var isSymmetricCell:Bool { return self.symmetricParent != nil }
///The set of the voronoi diagram's boundaries that this
///cell touches. Initialized by makeVertexLoop.
private var _boundaryEdges:Set<Direction2D> = []
open private(set) lazy var boundaryEdges:Set<Direction2D> = {
//We can't initialize boundaryEdges until makeVertexLoop
//is called, but we can't use normal lazy loading because
//makeVertexLoop initializes it directly. Thus, we have
//a private variable that makeVertexLoop initializes.
//Then, this public variable just sets itself to the
//value of the private variable, first making sure
//the private variable is initialized.
let _ = self.makeVertexLoop()
return self._boundaryEdges
}()
///Initializes a VoronoiCell with a voronoi point and the boundaries of a VoronoiDiagram.
public init(point:Point, boundaries:Size) {
self.voronoiPoint = point
self.boundaries = boundaries
}
///Calculates the vertices in the correct order so they can be
///combined to form the edges of this cell.
open func makeVertexLoop() -> [Point] {
if let vertices = self.vertices {
return vertices
}
let vertices = self.windVertices()
self.vertices = vertices
return vertices
}
fileprivate func insertBoundaryEdge(for intersection:Point) {
if intersection.x ~= 0.0 {
self._boundaryEdges.insert(.Left)
}
if intersection.x ~= self.boundaries.width {
self._boundaryEdges.insert(.Right)
}
if intersection.y ~= 0.0 {
self._boundaryEdges.insert(.Down)
}
if intersection.y ~= self.boundaries.height {
self._boundaryEdges.insert(.Up)
}
}
/**
Generates all the vertices associated with this cell,
and then sorts them according to their angle from the
voronoi point.
*/
fileprivate func windVertices() -> [Point] {
let frame = Rect(origin: Point.zero, size: self.boundaries)
var corners = [
Point(x: 0.0, y: 0.0),
Point(x: self.boundaries.width, y: 0.0),
Point(x: self.boundaries.width, y: self.boundaries.height),
Point(x: 0.0, y: self.boundaries.height),
]
var vertices:[Point] = []
for cellEdge in self.cellEdges {
let line = VoronoiLine(start: cellEdge.startPoint, end: cellEdge.endPoint, voronoi: self.voronoiPoint)
corners = corners.filter() { line.pointLiesAbove($0) == line.voronoiPointLiesAbove }
let intersections = cellEdge.intersectionWith(self.boundaries)
vertices += intersections
if frame.contains(point: cellEdge.startPoint) {
vertices.append(cellEdge.startPoint)
}
if frame.contains(point: cellEdge.endPoint) {
vertices.append(cellEdge.endPoint)
}
}
vertices += corners
//The sorting approach only works if the voronoi point is inside
//all the vertices, which isn't true if the voronoi point is
//outside the bounds of the diagram. In that case, we need
//to calculate a point inside all the vertices (in this case,
//the geometric center). The algorithm proceeds the same,
//it just doesn't require the potentially expensive operation.
if frame.contains(point: self.voronoiPoint) {
vertices = vertices.sorted() { self.voronoiPoint.angle(to: $0) < self.voronoiPoint.angle(to: $1) }
} else {
let center = vertices.reduce(Point.zero) { $0 + $1 } / Double(vertices.count)
vertices = vertices.sorted() { center.angle(to: $0) < center.angle(to: $1) }
}
vertices = self.removeDuplicates(vertices)
self._boundaryEdges = self.calculateBoundaryEdges(vertices: vertices)
return vertices
}
/**
Removes adjacent duplicate vertices. The way the algorithm works, duplicate
vertices should always be adjacent to each other. This is most apparent when
the voronoi points lie on a circle; then, many circle events will occur at the
center of said circle, causing many duplicate points right next to each other.
- parameter vertices: An array of points.
- returns: The array of points with duplicate (and adjacent) vertices removed.
*/
fileprivate func removeDuplicates(_ vertices:[Point]) -> [Point] {
var i = 0
var filteredVertices = vertices
while i < filteredVertices.count - 1 {
if filteredVertices[i] ~= filteredVertices[i + 1] {
filteredVertices.remove(at: i + 1)
} else {
i += 1
}
}
return filteredVertices
}
/**
Determines which edges of the voronoi diagram this cell touches.
- parameter vertices: The vertices of this cell.
- returns: A set of directions corresponding to which edges of the boundaries this cell touches.
*/
fileprivate func calculateBoundaryEdges(vertices:[Point]) -> Set<Direction2D> {
var edges:Set<Direction2D> = []
for vertex in vertices {
if vertex.x ~= 0.0 {
edges.insert(.Left)
}
if vertex.x ~= self.boundaries.width {
edges.insert(.Right)
}
if vertex.y ~= 0.0 {
edges.insert(.Down)
}
if vertex.y ~= self.boundaries.height {
edges.insert(.Up)
}
}
return edges
}
/**
Adds a VoronoiCell as a neighbor to this cell.
- parameter neighbor: The cell adjacent to this cell to mark as a neighbor.
*/
internal func add(neighbor:VoronoiCell) {
self.symmetricParent?.add(neighbor: neighbor)
self.weakNeighbors.insert(WeakReference(object: neighbor.symmetricParent ?? neighbor))
}
internal func addSymmetricChild(x:Double, y:Double) -> VoronoiCell {
let symmetricCell = VoronoiCell(point: self.voronoiPoint + Point(x: x, y: y), boundaries: self.boundaries)
symmetricCell.symmetricParent = self
self.symmetricChildren.append(symmetricCell)
return symmetricCell
}
}
extension VoronoiCell {
public func contains(point:Point) -> Bool {
//Ideally, the user has already called makeVertexLoop.
//If not, we incur the expensive calculations (but
//guarantee that the vertices exist).
let vertices = self.makeVertexLoop()
for (i, vertex) in vertices.enumerated().dropLast() {
let line = VoronoiLine(start: vertex, end: vertices[i + 1], voronoi: self.voronoiPoint)
if line.pointLiesAbove(point) != line.voronoiPointLiesAbove {
return false
}
}
if let last = vertices.last, let first = vertices.first {
let lastLine = VoronoiLine(start: last, end: first, voronoi: self.voronoiPoint)
if lastLine.pointLiesAbove(point) != lastLine.voronoiPointLiesAbove {
return false
}
}
return true
}
}
extension VoronoiCell: Hashable {
public func hash(into hasher:inout Hasher) {
hasher.combine(Unmanaged.passUnretained(self).toOpaque())
}
}
public func ==(lhs:VoronoiCell, rhs:VoronoiCell) -> Bool {
return lhs === rhs
}
| mit | 2ea9f1c88fe1644a994a66c7233148a4 | 39.351695 | 114 | 0.637614 | 4.239982 | false | false | false | false |
easytargetmixel/micopi_ios | micopi/Engine/Color/ARGBColorPalette.swift | 1 | 2124 | import CoreGraphics.CGColor
class ARGBColorPalette: NSObject {
static let defaultPalette = [
ARGBColor(hex: 0xFF000000),
ARGBColor(hex: 0xFF333333),
ARGBColor(hex: 0xFF101010),
ARGBColor(hex: 0xFF292929),
ARGBColor(hex: 0xFF404040),
ARGBColor(hex: 0xFFE8DDCB),
ARGBColor(hex: 0xFFCDB380),
ARGBColor(hex: 0xFF036564),
ARGBColor(hex: 0xFF033649),
ARGBColor(hex: 0xFF031634),
ARGBColor(hex: 0xFF351330),
ARGBColor(hex: 0xFF424254),
ARGBColor(hex: 0xFF64908A),
ARGBColor(hex: 0xFFE8CAA4),
ARGBColor(hex: 0xFFCC2A41),
ARGBColor(hex: 0xFFA8A7A7),
ARGBColor(hex: 0xFFCC527A),
ARGBColor(hex: 0xFFE8175D),
ARGBColor(hex: 0xFF474747),
ARGBColor(hex: 0xFF363636),
ARGBColor(hex: 0xFF904C76),
ARGBColor(hex: 0xFFDE2D89),
ARGBColor(hex: 0xFFEA4F72),
ARGBColor(hex: 0xFFF4B182),
ARGBColor(hex: 0xFFA55B4D)
]
var colors = ARGBColorPalette.defaultPalette
override init() {}
init(colors: [ARGBColor]) {
self.colors = colors
}
func setColorsRandomly(randomColorGenerator: RandomColorGenerator) {
colors = [
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
randomColorGenerator.nextARGBColor(),
]
}
func color(
randomNumberGenerator: RandomNumberGenerator = RandomNumberGenerator()
) -> ARGBColor {
return color(randomNumber: randomNumberGenerator.int)
}
func color(randomNumber: Int) -> ARGBColor {
let randomIndex = abs(randomNumber % colors.count)
return colors[randomIndex]
}
}
| gpl-3.0 | e4232c685224bd6c483ac05063a2c05b | 31.181818 | 78 | 0.62806 | 4.100386 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/EclipseCenter/Countdown/CountDownCell.swift | 1 | 1802 | //
// CountDownCell.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 7/25/17.
//
// Copyright © 2017 Arlindo Goncalves.
// 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/].
//
// For Contact email: [email protected]
import Eureka
final class CountDownCell: Cell<Date>, CellType {
let countdownView = CountdownView.loadFromNib()!
var date: Date?
override func setup() {
selectionStyle = .none
countdownView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(countdownView)
countdownView.anchor(
contentView.topAnchor,
left: contentView.leftAnchor,
bottom: contentView.bottomAnchor,
right: contentView.rightAnchor
)
}
override func update() {
super.update()
if let date = date {
countdownView.startCountdown(date)
}
}
}
final class CountDownRow: Row<CountDownCell>, RowType {
required init(tag: String?) {
super.init(tag: tag)
cellProvider = CellProvider<CountDownCell>()
}
func set(date : Date) {
cell.date = date
updateCell()
}
}
| gpl-3.0 | 89def0376e046242cc59c6c05bb599e8 | 29.016667 | 73 | 0.668517 | 4.457921 | false | false | false | false |
iOSTestApps/arex-7 | ArexKit/Models/Pistachio/MessagePackValueTransformers.swift | 1 | 10898 | import Foundation
import MessagePack
import Monocle
import Pistachio
import Result
import ValueTransformer
public enum MessagePackValueTransformersError: ErrorType {
case InvalidType(String)
case IncorrectExtendedType
case ExpectedStringKey
}
public struct MessagePackValueTransformers {
public static let bool: ReversibleValueTransformer<Bool, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Bool(value))
}, reverseTransformClosure: { value in
if let value = value.boolValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Bool"))
}
})
public static func int<S: SignedIntegerType>() -> ReversibleValueTransformer<S, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .success(.Int(numericCast(value)))
}, reverseTransformClosure: { value in
if let value = value.integerValue {
return .success(numericCast(value))
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Int"))
}
})
}
public static func uint<U: UnsignedIntegerType>() -> ReversibleValueTransformer<U, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .success(.UInt(numericCast(value)))
}, reverseTransformClosure: { value in
if let value = value.unsignedIntegerValue {
return .success(numericCast(value))
} else {
return .failure(MessagePackValueTransformersError.InvalidType("UInt"))
}
})
}
public static let float: ReversibleValueTransformer<Float32, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Float(value))
}, reverseTransformClosure: { value in
if let value = value.floatValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Float"))
}
})
public static let double: ReversibleValueTransformer<Float64, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Double(value))
}, reverseTransformClosure: { value in
if let value = value.doubleValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Double"))
}
})
public static let string: ReversibleValueTransformer<String, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.String(value))
}, reverseTransformClosure: { value in
if let value = value.stringValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("String"))
}
})
public static let binary: ReversibleValueTransformer<Data, MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Binary(value))
}, reverseTransformClosure: { value in
if let value = value.dataValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Binary"))
}
})
public static let array: ReversibleValueTransformer<[MessagePackValue], MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Array(value))
}, reverseTransformClosure: { value in
if let value = value.arrayValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Array"))
}
})
public static let map: ReversibleValueTransformer<[MessagePackValue : MessagePackValue], MessagePackValue, ErrorType> = ReversibleValueTransformer(transformClosure: { value in
return .success(.Map(value))
}, reverseTransformClosure: { value in
if let value = value.dictionaryValue {
return .success(value)
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Map"))
}
})
public static func extended(type: Int8) -> ReversibleValueTransformer<Data, MessagePackValue, ErrorType> {
return ReversibleValueTransformer(transformClosure: { value in
return .success(.Extended(type, value))
}, reverseTransformClosure: { value in
if let (decodedType, data) = value.extendedValue {
if decodedType == type {
return .success(data)
} else {
return .failure(MessagePackValueTransformersError.IncorrectExtendedType)
}
} else {
return .failure(MessagePackValueTransformersError.InvalidType("Extended"))
}
})
}
}
public func messagePackBool<A>(lens: Lens<A, Bool>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.bool)
}
public func messagePackBool<A>(lens: Lens<A, Bool?>, defaultTransformedValue: MessagePackValue = .Bool(false)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.bool, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackInt<A, S: SignedIntegerType>(lens: Lens<A, S>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.int())
}
public func messagePackInt<A, S: SignedIntegerType>(lens: Lens<A, S?>, defaultTransformedValue: MessagePackValue = .Int(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.int(), defaultTransformedValue: defaultTransformedValue))
}
public func messagePackUInt<A, U: UnsignedIntegerType>(lens: Lens<A, U>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.uint())
}
public func messagePackUInt<A, U: UnsignedIntegerType>(lens: Lens<A, U?>, defaultTransformedValue: MessagePackValue = .UInt(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.uint(), defaultTransformedValue: defaultTransformedValue))
}
public func messagePackFloat<A>(lens: Lens<A, Float32>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.float)
}
public func messagePackFloat<A>(lens: Lens<A, Float32?>, defaultTransformedValue: MessagePackValue = .Float(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.float, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackDouble<A>(lens: Lens<A, Float64>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.double)
}
public func messagePackDouble<A>(lens: Lens<A, Float64?>, defaultTransformedValue: MessagePackValue = .Double(0)) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.double, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackString<A>(lens: Lens<A, String>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.string)
}
public func messagePackString<A>(lens: Lens<A, String?>, defaultTransformedValue: MessagePackValue = .String("")) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.string, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackBinary<A>(lens: Lens<A, Data>) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, MessagePackValueTransformers.binary)
}
public func messagePackBinary<A>(lens: Lens<A, Data?>, defaultTransformedValue: MessagePackValue = .Binary([])) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return map(lens, lift(MessagePackValueTransformers.binary, defaultTransformedValue: defaultTransformedValue))
}
public func messagePackArray<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, [T.ValueType]>) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(adapter) >>> MessagePackValueTransformers.array)
}
}
public func messagePackArray<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, [T.ValueType]?>, defaultTransformedValue: MessagePackValue = .Nil) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(lift(adapter) >>> MessagePackValueTransformers.array, defaultTransformedValue: defaultTransformedValue))
}
}
public func messagePackMap<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType>) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, adapter)
}
}
public func messagePackMap<A, T: AdapterType where T.TransformedValueType == MessagePackValue, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType?>, defaultTransformedValue: MessagePackValue = .Nil) -> (adapter: T) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter in
return map(lens, lift(adapter, defaultTransformedValue: defaultTransformedValue))
}
}
public func messagePackExtended<A, T: AdapterType where T.TransformedValueType == Data, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType>) -> (adapter: T, type: Int8) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter, type in
return map(map(lens, adapter), MessagePackValueTransformers.extended(type))
}
}
public func messagePackExtended<A, T: AdapterType where T.TransformedValueType == Data, T.ErrorType == ErrorType>(lens: Lens<A, T.ValueType?>, defaultTransformedValue: Data = Data()) -> (adapter: T, type: Int8) -> Lens<Result<A, ErrorType>, Result<MessagePackValue, ErrorType>> {
return { adapter, type in
return map(map(lens, lift(adapter, defaultTransformedValue: defaultTransformedValue)), MessagePackValueTransformers.extended(type))
}
}
| mit | 10034a9c93ddfbbb8c0193dd0468b1ea | 49.453704 | 288 | 0.711415 | 4.679261 | false | false | false | false |
athiercelin/ATSketchKit | ATSketchKit/ATColorPicker.swift | 1 | 4941 | //
// ATColorPicker.swift
// ATSketchKit
//
// Created by Arnaud Thiercelin on 1/17/16.
// Copyright © 2016 Arnaud Thiercelin. 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 UIKit
/** This class provides a basic view to pick a new color using a color map */
@IBDesignable public class ATColorPicker: UIView {
public var delegate: ATColorPickerDelegate?
@IBInspectable public var cornerRadius: Float = 6.0
public enum ColorSpace {
case hsv
case custom
}
public var colorSpace = ColorSpace.hsv
public override init(frame: CGRect) {
super.init(frame: frame)
self.configure()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configure()
}
func configure() {
self.layer.cornerRadius = CGFloat(self.cornerRadius)
self.layer.masksToBounds = true
}
// MARK: - Drawing
public override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
for x in 0..<Int(rect.size.width) {
for y in 0..<Int(rect.size.height) {
let point = CGPoint(x: CGFloat(x), y: CGFloat(y))
let color = colorAtPoint(point, inRect: rect)
color.setFill()
let rect = CGRect(x: CGFloat(x), y: CGFloat(y), width: 1.0, height: 1.0)
context.fill(rect)
}
}
}
// MARK: - Event handling
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// kickstart the flow.
}
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = touches.first!.location(in: self)
let color = self.colorAtPoint(point, inRect: self.bounds)
NSLog("Color At Point[\(point.x),\(point.y)]: \(color)")
if self.delegate != nil {
self.delegate!.colorPicker(self, didChangeToSelectedColor: color)
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
let point = touches.first!.location(in: self)
let color = self.colorAtPoint(point, inRect: self.bounds)
if self.delegate != nil {
self.delegate!.colorPicker(self, didEndSelectionWithColor: color)
}
}
// MARK: - Convenience color methods
func colorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor {
var color = UIColor.white
switch colorSpace {
case .hsv:
color = self.hsvColorAtPoint(point, inRect: rect)
default:
color = self.customColorAtPoint(point, inRect: rect)
}
return color
}
func customColorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor {
let x = point.x
let y = point.y
let redValue = (y/rect.size.height + (rect.size.width - x)/rect.size.width) / 2
let greenValue = ((rect.size.height - y)/rect.size.height + (rect.size.width - x)/rect.size.width) / 2
let blueValue = (y/rect.size.height + x/rect.size.width) / 2
let color = UIColor(red: redValue, green: greenValue, blue: blueValue, alpha: 1.0)
return color
}
func hsvColorAtPoint(_ point: CGPoint, inRect rect: CGRect) -> UIColor {
return UIColor(hue: point.x/rect.size.width, saturation: point.y/rect.size.height, brightness: 1.0, alpha: 1.0)
}
public override var description: String {
get {
return self.debugDescription
}
}
public override var debugDescription: String {
get {
return "ATColorPicker \n" +
"ColorSpace: \(self.colorSpace)\n"
}
}
}
| mit | 00f3e49b65be65d8d98882342d0026ec | 34.797101 | 119 | 0.622065 | 4.352423 | false | false | false | false |
richy486/EndlessPageView | EndlessPageView/CGHelpers.swift | 1 | 3717 | //
// CGHelpers.swift
//
// Created by Richard Adem on 6/21/16.
// Copyright © 2016 Richard Adem. All rights reserved.
//
import Foundation
// CGFloat
func round(_ value: CGFloat, tollerence:CGFloat)-> CGFloat {
if fabs(value).truncatingRemainder(dividingBy: 1.0) < tollerence || fabs(value).truncatingRemainder(dividingBy: 1.0) > 1.0 - tollerence {
return round(value)
}
return value
}
extension CGFloat {
public static var pi: CGFloat {
get {
return CGFloat(M_PI)
}
}
public static var pi2: CGFloat {
get {
return CGFloat(M_PI/2)
}
}
}
// CGPoint
func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
func * (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x * right.x, y: left.y * right.y)
}
func / (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x / right.x, y: left.y / right.y)
}
func % (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x.truncatingRemainder(dividingBy: right.x), y: left.y.truncatingRemainder(dividingBy: right.y))
}
func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
func -= (left: inout CGPoint, right: CGPoint) {
left = left - right
}
func *= (left: inout CGPoint, right: CGPoint) {
left = left * right
}
func /= (left: inout CGPoint, right: CGPoint) {
left = left / right
}
func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x * right, y: left.y * right)
}
func / (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x / right, y: left.y / right)
}
func + (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x + right, y: left.y + right)
}
func - (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: left.x - right, y: left.y - right)
}
func floor(_ point:CGPoint) -> CGPoint {
return CGPoint(x: floor(point.x), y: floor(point.y))
}
func round(_ value: CGPoint, tollerence:CGFloat)-> CGPoint {
return CGPoint(x: round(value.x, tollerence: tollerence)
, y: round(value.y, tollerence: tollerence))
}
// CGSize
func + (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width + right.width, height: left.height + right.height)
}
func - (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width - right.width, height: left.height - right.height)
}
func * (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width * right.width, height: left.height * right.height)
}
func / (left: CGSize, right: CGSize) -> CGSize {
return CGSize(width: left.width / right.width, height: left.height / right.height)
}
func / (left: CGSize, right: CGFloat) -> CGSize {
return CGSize(width: left.width / right, height: left.height / right)
}
// CGSize v CGPoint
func sizeToPoint(_ size: CGSize) -> CGPoint {
return CGPoint(x: size.width, y: size.height)
}
func * (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x * right.width, y: left.y * right.height)
}
func / (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x / right.width, y: left.y / right.height)
}
func + (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x + right.width, y: left.y + right.height)
}
func - (left: CGPoint, right: CGSize) -> CGPoint {
return CGPoint(x: left.x - right.width, y: left.y - right.height)
}
| mit | 525bda5a3a112323c66ebad19da1df15 | 24.627586 | 141 | 0.621636 | 3.276896 | false | false | false | false |
milseman/swift | test/ClangImporter/objc_redeclared_properties.swift | 26 | 1771 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules -D ONE_MODULE %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules -D SUB_MODULE %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -I %S/Inputs/custom-modules -D TWO_MODULES %s -verify
// REQUIRES: objc_interop
#if ONE_MODULE
import RedeclaredProperties
#elseif SUB_MODULE
import RedeclaredPropertiesSub
import RedeclaredPropertiesSub.Private
#elseif TWO_MODULES
import RedeclaredPropertiesSplit
import RedeclaredPropertiesSplit2
#endif
func test(obj: RPFoo) {
if let _ = obj.nonnullToNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
obj.nonnullToNullable = obj // expected-error {{cannot assign to property: 'nonnullToNullable' is a get-only property}}
if let _ = obj.nullableToNonnull {} // okay
obj.nullableToNonnull = obj // expected-error {{cannot assign to property: 'nullableToNonnull' is a get-only property}}
let _: RPFoo = obj.typeChangeMoreSpecific // expected-error {{cannot convert value of type 'Any' to specified type 'RPFoo'}}
obj.typeChangeMoreSpecific = obj // expected-error {{cannot assign to property: 'typeChangeMoreSpecific' is a get-only property}}
let _: RPFoo = obj.typeChangeMoreGeneral
obj.typeChangeMoreGeneral = obj // expected-error {{cannot assign to property: 'typeChangeMoreGeneral' is a get-only property}}
if let _ = obj.accessorRedeclaredAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
if let _ = obj.accessorDeclaredFirstAsNullable {} // expected-error {{initializer for conditional binding must have Optional type}}
}
| apache-2.0 | 38a21b5799a75fcb902b39b6e23f6c37 | 54.34375 | 133 | 0.763411 | 3.841649 | false | false | false | false |
codingforentrepreneurs/30-Days-of-Swift | Lecture_Source/30 - Simple/Simple/LocationCollectionViewCell.swift | 1 | 923 | //
// LocationCollectionViewCell.swift
// Simple
//
// Created by Justin Mitchel on 12/18/14.
// Copyright (c) 2014 Coding for Entrepreneurs. All rights reserved.
//
import UIKit
class LocationCollectionViewCell: UICollectionViewCell {
var textView:UITextView!
required init(coder aDecoder:NSCoder) {
super.init(coder: aDecoder)
}
override init(frame:CGRect) {
super.init(frame:frame)
let tvFrame = CGRectMake(10, 0, frame.size.width - 20, frame.size.height)
textView = UITextView(frame: tvFrame)
textView.font = UIFont.systemFontOfSize(20.0)
textView.backgroundColor = UIColor(white: 1.0, alpha: 0.3)
textView.textAlignment = .Left
textView.scrollEnabled = false
textView.userInteractionEnabled = false
textView.editable = false
contentView.addSubview(textView)
}
}
| apache-2.0 | 94beb22a6e1caa3f2d02ddbec4d2e2d4 | 26.147059 | 81 | 0.650054 | 4.333333 | false | false | false | false |
blg-andreasbraun/ProcedureKit | Sources/Cloud/CKFetchRecordZoneChangesOperation.swift | 2 | 8409 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import CloudKit
/// A generic protocol which exposes the properties used by Apple's CKFetchRecordZoneChangesOperation.
public protocol CKFetchRecordZoneChangesOperationProtocol: CKDatabaseOperationProtocol, CKFetchAllChanges {
/// The type of the CloudKit FetchRecordZoneChangesOptions
associatedtype FetchRecordZoneChangesOptions
/// - returns: the record zone IDs which will fetch changes
var recordZoneIDs: [RecordZoneID] { get set }
/// - returns: the per-record-zone options
var optionsByRecordZoneID: [RecordZoneID : FetchRecordZoneChangesOptions]? { get set }
/// - returns: a block for when a record is changed
var recordChangedBlock: ((Record) -> Void)? { get set }
/// - returns: a block for when a recordID is deleted (receives the recordID and the recordType)
var recordWithIDWasDeletedBlock: ((RecordID, String) -> Void)? { get set }
/// - returns: a block for when a recordZone changeToken update is sent
var recordZoneChangeTokensUpdatedBlock: ((RecordZoneID, ServerChangeToken?, Data?) -> Void)? { get set }
/// - returns: a block for when a recordZone fetch is complete
var recordZoneFetchCompletionBlock: ((RecordZoneID, ServerChangeToken?, Data?, Bool, Error?) -> Void)? { get set }
/// - returns: the completion for fetching records (i.e. for the entire operation)
var fetchRecordZoneChangesCompletionBlock: ((Error?) -> Void)? { get set }
}
@available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *)
extension CKFetchRecordZoneChangesOperation: CKFetchRecordZoneChangesOperationProtocol, AssociatedErrorProtocol {
// The associated error type
public typealias AssociatedError = PKCKError
/// The type of the CloudKit FetchRecordZoneChangesOptions
public typealias FetchRecordZoneChangesOptions = CKFetchRecordZoneChangesOptions
}
extension CKProcedure where T: CKFetchRecordZoneChangesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError {
/// - returns: the record zone IDs which will fetch changes
public var recordZoneIDs: [T.RecordZoneID] {
get { return operation.recordZoneIDs }
set { operation.recordZoneIDs = newValue }
}
/// - returns: the per-record-zone options
public var optionsByRecordZoneID: [T.RecordZoneID : T.FetchRecordZoneChangesOptions]? {
get { return operation.optionsByRecordZoneID }
set { operation.optionsByRecordZoneID = newValue }
}
/// - returns: a block for when a record is changed
public var recordChangedBlock: CloudKitProcedure<T>.FetchRecordZoneChangesRecordChangedBlock? {
get { return operation.recordChangedBlock }
set { operation.recordChangedBlock = newValue }
}
/// - returns: a block for when a recordID is deleted (receives the recordID and the recordType)
public var recordWithIDWasDeletedBlock: CloudKitProcedure<T>.FetchRecordZoneChangesRecordWithIDWasDeletedBlock? {
get { return operation.recordWithIDWasDeletedBlock }
set { operation.recordWithIDWasDeletedBlock = newValue }
}
/// - returns: a block for when a recordZone changeToken update is sent
public var recordZoneChangeTokensUpdatedBlock: CloudKitProcedure<T>.FetchRecordZoneChangesRecordZoneChangeTokensUpdatedBlock? {
get { return operation.recordZoneChangeTokensUpdatedBlock }
set { operation.recordZoneChangeTokensUpdatedBlock = newValue }
}
/// - returns: a block to execute when the fetch for a zone has completed
public var recordZoneFetchCompletionBlock: CloudKitProcedure<T>.FetchRecordZoneChangesCompletionRecordZoneFetchCompletionBlock? {
get { return operation.recordZoneFetchCompletionBlock }
set { operation.recordZoneFetchCompletionBlock = newValue }
}
/// - returns: the completion for fetching records (i.e. for the entire operation)
func setFetchRecordZoneChangesCompletionBlock(_ block: @escaping CloudKitProcedure<T>.FetchRecordZoneChangesCompletionBlock) {
operation.fetchRecordZoneChangesCompletionBlock = { [weak self] error in
if let strongSelf = self, let error = error {
strongSelf.append(fatalError: PKCKError(underlyingError: error))
}
else {
block()
}
}
}
}
extension CloudKitProcedure where T: CKFetchRecordZoneChangesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError {
/// A typealias for the block types used by CloudKitOperation<CKFetchRecordZoneChangesOperationType>
public typealias FetchRecordZoneChangesRecordChangedBlock = (T.Record) -> Void
/// A typealias for the block types used by CloudKitOperation<CKFetchRecordZoneChangesOperationType>
public typealias FetchRecordZoneChangesRecordWithIDWasDeletedBlock = (T.RecordID, String) -> Void
/// A typealias for the block types used by CloudKitOperation<CKFetchRecordZoneChangesOperationType>
public typealias FetchRecordZoneChangesRecordZoneChangeTokensUpdatedBlock = (T.RecordZoneID, T.ServerChangeToken?, Data?) -> Void
/// A typealias for the block types used by CloudKitOperation<CKFetchRecordZoneChangesOperationType>
public typealias FetchRecordZoneChangesCompletionRecordZoneFetchCompletionBlock = (T.RecordZoneID, T.ServerChangeToken?, Data?, Bool, Error?) -> Void
/// A typealias for the block types used by CloudKitOperation<CKFetchRecordZoneChangesOperationType>
public typealias FetchRecordZoneChangesCompletionBlock = () -> Void
/// - returns: the record zone IDs which will fetch changes
public var recordZoneIDs: [T.RecordZoneID] {
get { return current.recordZoneIDs }
set {
current.recordZoneIDs = newValue
appendConfigureBlock { $0.recordZoneIDs = newValue }
}
}
/// - returns: the per-record-zone options
public var optionsByRecordZoneID: [T.RecordZoneID : T.FetchRecordZoneChangesOptions]? {
get { return current.optionsByRecordZoneID }
set {
current.optionsByRecordZoneID = newValue
appendConfigureBlock { $0.optionsByRecordZoneID = newValue }
}
}
/// - returns: a block for when a record is changed
public var recordChangedBlock: FetchRecordZoneChangesRecordChangedBlock? {
get { return current.recordChangedBlock }
set {
current.recordChangedBlock = newValue
appendConfigureBlock { $0.recordChangedBlock = newValue }
}
}
/// - returns: a block for when a recordID is deleted (receives the recordID and the recordType)
public var recordWithIDWasDeletedBlock: FetchRecordZoneChangesRecordWithIDWasDeletedBlock? {
get { return current.recordWithIDWasDeletedBlock }
set {
current.recordWithIDWasDeletedBlock = newValue
appendConfigureBlock { $0.recordWithIDWasDeletedBlock = newValue }
}
}
/// - returns: a block for when a recordZone changeToken update is sent
public var recordZoneChangeTokensUpdatedBlock: FetchRecordZoneChangesRecordZoneChangeTokensUpdatedBlock? {
get { return current.recordZoneChangeTokensUpdatedBlock }
set {
current.recordZoneChangeTokensUpdatedBlock = newValue
appendConfigureBlock { $0.recordZoneChangeTokensUpdatedBlock = newValue }
}
}
/// - returns: a block to execute when the fetch for a zone has completed
public var recordZoneFetchCompletionBlock: FetchRecordZoneChangesCompletionRecordZoneFetchCompletionBlock? {
get { return current.recordZoneFetchCompletionBlock }
set {
current.recordZoneFetchCompletionBlock = newValue
appendConfigureBlock { $0.recordZoneFetchCompletionBlock = newValue }
}
}
/**
Before adding the CloudKitOperation instance to a queue, set a completion block
to collect the results in the successful case. Setting this completion block also
ensures that error handling gets triggered.
- parameter block: a FetchRecordZoneChangesCompletionBlock block
*/
public func setFetchRecordZoneChangesCompletionBlock(block: @escaping FetchRecordZoneChangesCompletionBlock) {
appendConfigureBlock { $0.setFetchRecordZoneChangesCompletionBlock(block) }
}
}
| mit | e4c57c219cd5b5e5f1745fd3844a09fe | 45.972067 | 153 | 0.733825 | 5.590426 | false | false | false | false |
enums/Pjango | Source/Pjango/DB/PCDataBase.swift | 1 | 6769 | //
// PCDataBase.swift
// Pjango
//
// Created by 郑宇琦 on 2017/6/17.
// Copyright © 2017年 郑宇琦. All rights reserved.
//
import Foundation
public enum PCDataBaseState {
case empty
case inited
case setuped
case connected
case disconnected
}
open class PCDataBase {
open var schema: String? {
return nil
}
public let config: PCDataBaseConfig
open var state: PCDataBaseState
public let _pjango_core_database_lock = NSLock.init()
public init(config: PCDataBaseConfig) {
self.config = config
self.state = .inited
}
public static var empty: PCDataBase {
let database = PCDataBase.init(config: PCDataBaseConfig.init())
database.state = .empty
return database
}
open func setup() {
_pjango_core_database_lock.lock()
defer {
_pjango_core_database_lock.unlock()
}
guard state != .empty else {
return
}
doSetup()
self.state = .setuped
}
open func doSetup() { }
open func connect() {
_pjango_core_database_lock.lock()
defer {
_pjango_core_database_lock.unlock()
}
guard state == .setuped || state == .disconnected else {
return
}
doConnect()
self.state = .connected
}
open func doConnect() { }
@discardableResult
open func query(_ sql: PCSqlStatement) -> [PCDataBaseRecord]? {
_pjango_core_database_lock.lock()
defer {
_pjango_core_database_lock.unlock()
}
guard state == .connected else {
return nil
}
_pjango_core_log.debug("Query: \(sql)")
return doQuery(sql)
}
open func doQuery(_ sql: PCSqlStatement) -> [PCDataBaseRecord]? { return nil }
open func isSchemaExist(_ schema: String) -> Bool {
guard let ret = query(PCSqlUtility.selectSchema(schema)) else {
return false
}
if ret.count >= 1 {
return true
} else {
return false
}
}
open func isTableExist(_ table: String) -> Bool {
return query(PCSqlUtility.selectTable(schema, table, ext: "LIMIT 1")) != nil ? true : false
}
open func createSchema() {
guard let schema = schema else {
_pjango_core_log.error("Failed on creating schema. Schema value is nil.")
return
}
guard query(PCSqlUtility.createSchema(schema)) != nil else {
_pjango_core_log.error("Failed on creating schema `\(schema)`")
return
}
_pjango_core_log.info("Success on creating schema `\(schema)`")
}
open func dropSchema() {
guard let schema = schema else {
_pjango_core_log.error("Failed on droping schema. Schema value is nil.")
return
}
guard query(PCSqlUtility.dropSchema(schema)) != nil else {
_pjango_core_log.error("Failed on droping schema `\(schema)`")
return
}
_pjango_core_log.info("Sucess on droping schema `\(schema)`")
}
open func createTable(model: PCMetaModel) {
guard query(PCSqlUtility.createTable(schema, model.tableName, model._pjango_core_model_fields)) != nil else {
_pjango_core_log.error("Failed on creating table \(PCSqlUtility.schemaAndTableToStr(schema, model.tableName))")
return
}
_pjango_core_log.info("Success on creating table \(PCSqlUtility.schemaAndTableToStr(schema, model.tableName))")
}
open func dropTable(model: PCMetaModel) {
dropTable(model.tableName)
}
open func dropTable(_ table: String) {
guard query(PCSqlUtility.dropTable(schema, table)) != nil else {
_pjango_core_log.error("Failed on droping table \(PCSqlUtility.schemaAndTableToStr(schema, table))")
return
}
_pjango_core_log.info("Success on droping table \(PCSqlUtility.schemaAndTableToStr(schema, table))")
}
open func selectTable(model: PCMetaModel, ext: String? = nil) -> [PCDataBaseRecord]? {
return selectTable(table: model.tableName, ext: ext)
}
open func selectTable(table: String, ext: String? = nil) -> [PCDataBaseRecord]? {
return query(PCSqlUtility.selectTable(schema, table, ext: ext))
}
@discardableResult
open func insertModel(_ model: PCModel) -> Bool {
let record = model._pjango_core_model_fields.compactMap { (field) -> String? in
switch field.type {
case .string: return field.strValue
case .int: return "\(field.intValue)"
case .text: return field.strValue
case .unknow: return nil
}
}
guard record.count == model._pjango_core_model_fields.count else {
return false
}
guard query(PCSqlUtility.insertRecord(schema, model.tableName, record)) != nil else {
_pjango_core_log.error("Failed on insert model \(PCSqlUtility.schemaAndTableToStr(schema, model.tableName))")
return false
}
return true
}
@discardableResult
open func updateModel(_ model: PCModel) -> Bool {
guard let id = model._pjango_core_model_id else {
return false
}
let updateStr = model._pjango_core_model_fields_key.compactMap { (key) -> String? in
guard let type = model._pjango_core_model_fields_type[key], let value = model._pjango_core_model_get_filed_data(key: key) else {
return nil
}
switch type {
case .string:
guard let strValue = value as? String else {
return nil
}
return strValue
case .int:
guard let intValue = value as? Int else {
return nil
}
return "\(intValue)"
case .text:
guard let textValue = value as? String else {
return nil
}
return textValue
case .unknow: return nil
}
}
guard updateStr.count == model._pjango_core_model_fields_key.count else {
return false
}
guard query(PCSqlUtility.updateRecord(schema, model.tableName, id: id, fields: model._pjango_core_model_fields_key, record: updateStr)) != nil else {
_pjango_core_log.error("Failed on update model \(PCSqlUtility.schemaAndTableToStr(schema, model.tableName))")
return false
}
return true
}
}
| apache-2.0 | b234ce3a3552aecf698338a9befe4a26 | 31.161905 | 157 | 0.568404 | 4.156308 | false | false | false | false |
xiaoyouPrince/DYLive | DYLive/DYLive/Classes/Main/ViewModel/BaseViewModel.swift | 1 | 1559 | //
// BaseViewModel.swift
// DYLive
//
// Created by 渠晓友 on 2017/5/3.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
// 首页 和 娱乐页面的VM的代码抽取
import UIKit
class BaseViewModel {
/// 主播组
lazy var anchorGroups : [AnchorGroup] = [AnchorGroup]()
}
extension BaseViewModel{
func loadAnchorData(isGroupData: Bool , URLString : String , parameters : [String : Any]? = nil, finishCallback: @escaping () -> ()) {
NetworkTools.requestData(type: .GET, URLString: URLString , parameters: parameters ) { (result) in
// 转字典,校验
guard let resultDict = result as? [String : Any] else {return}
// 转成数组
guard let dataArray = resultDict["data"] as? [[String : Any]] else {return}
if isGroupData {
// 字典转模型
for dict in dataArray{
self.anchorGroups.append(AnchorGroup.init(dict : dict))
}
}else{
// 趣玩页面数据结构不同,直接方法的anchorModel
let group = AnchorGroup()
for dict in dataArray {
group.anchors.append(AnchorModel(dict: dict))
}
self.anchorGroups.append(group)
}
// callBack
finishCallback()
}
}
}
| mit | 9e1f71d05fe94bb4192a1dc570f5628a | 25.509091 | 138 | 0.484225 | 4.925676 | false | false | false | false |
tokorom/swift-build-report | Tests/SwiftBuildReportTests/DefaultFormatterTests.swift | 1 | 6693 | //
// DefaultFormatterTests.swift
//
// Created by ToKoRo on 2016-12-09.
//
import XCTest
@testable import SwiftBuildReport
class DefaultFormatterTests: XCTestCase {
let subject = DefaultFormatter()
func testNormalLine() {
let line = "foo bar"
let expected: FormattedLine.Kind = .normal
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testCompileStart() {
let line = "Compile Swift Module 'SwiftBuildReport' (7 sources)"
let expected: FormattedLine.Kind = .compileStart
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testCompileError() {
let line = "/Users/tokorom/develop/github/swift-build-report/Sources/SwiftBuildReport/main.swift:31:1: error: foo bar"
let expected: FormattedLine.Kind = .compileError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testCompileWarning() {
let line = "/Users/hoge/develop/Hoge.swift:28:9: warning: expression following 'return' is treated as an argument of the 'return'"
let expected: FormattedLine.Kind = .compileWarning
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testCompileNote() {
let line = "Foundation/Hoge.swift:28:9: note: indent the expression to silence this warning"
let expected: FormattedLine.Kind = .compileNote
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testLinking() {
let line = "Linking ./.build/debug/SwiftBuildReport"
let expected: FormattedLine.Kind = .linking
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testBuildErrorSummary() {
let line = "<unknown>:0: error: build had 1 command failures"
let expected: FormattedLine.Kind = .buildSummaryWithError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestSuiteStarted() {
let line = "Test Suite 'DefaultFormatterTests' started at 2016-12-09 11:09:14.488"
let expected: FormattedLine.Kind = .testSuiteStarted
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestSuitePassed() {
let line = "Test Suite 'DefaultFormatterTests' passed at 2016-12-10 14:31:04.973."
let expected: FormattedLine.Kind = .testSuitePassed
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestSuiteFailed() {
let line = "Test Suite 'DefaultFormatterTests' failed at 2016-12-10 14:34:46.050."
let expected: FormattedLine.Kind = .testSuiteFailed
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestCaseStarted() {
let line = "Test Case '-[SwiftBuildReportTests.AnsiColorTests testGreen]' started."
let expected: FormattedLine.Kind = .testCaseStarted
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestCasePassed() {
let line = "Test Case '-[SwiftBuildReportTests.DefaultFormatterTests testErrorPoint]' passed (0.000 seconds)."
let expected: FormattedLine.Kind = .testCasePassed
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestCaseFailed() {
let line = "Test Case '-[SwiftBuildReportTests.DefaultFormatterTests testTestCasePassed]' failed (0.002 seconds)."
let expected: FormattedLine.Kind = .testCaseFailed
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestError() {
let line = "/Users/tokorom/develop/github/swift-build-report/Tests/SwiftBuildReportTests/DefaultFormatterTests.swift"
+ ":45: error: -[SwiftBuildReportTests.DefaultFormatterTests testBuildErrorSummary] : "
+ "XCTAssertEqual failed: (\"normal\") is not equal to (\"buildSummaryWithError\") -"
let expected: FormattedLine.Kind = .testError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestErrorWithRuntimeError() {
let line = "/Users/tokorom/develop/github/swift-build-report/Sources/SwiftBuildReport/DefaultReporter.swift:70: erro"
+ "r: -[SwiftBuildReportTests.DefaultReporterTests testBuildSummaryWithError] : failed: caught \"NSInvalidAr"
+ "gumentException\", \"*** -[NSFileManager fileSystemRepresentationWithPath:]: nil or empty path argument\""
let expected: FormattedLine.Kind = .testError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestErrorWithAssertNotNil() {
let line = "/Users/tokorom/develop/github/swift-build-report/Tests/SwiftBuildReportTests/DefaultReporterTests.swift:64: "
+ "error: -[SwiftBuildReportTests.DefaultReporterTests testBuildSummaryWithError] : XCTAssertNotNil failed -"
let expected: FormattedLine.Kind = .testError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testErrorPoint() {
let line = " ^ "
let expected: FormattedLine.Kind = .errorPoint
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testErrorPointLong() {
let line = " ^~~~~~ "
let expected: FormattedLine.Kind = .errorPoint
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestErrorWithLongMessage() {
let line = "/Users/tokorom/develop/github/swift-build-report/Tests/SwiftBuildReportTests/DefaultFormatterTests.swift:80"
+ ": error: -[SwiftBuildReportTests.DefaultFormatterTests testTestSummary] : XCTAssertEqual failed: (\" Exec"
+ "uted 10 tests, with 2 failuers (0 unexpected) in 0.008 (0.009) seconds\") is not equal to (\" Executed 10 tests"
+ ", with 2 failuers (0 unexpected) in 0.008 (0.009) seconds\") -"
let expected: FormattedLine.Kind = .testError
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
func testTestSummary() {
let line = " Executed 10 tests, with 1 failure (0 unexpected) in 0.008 (0.009) seconds"
let expected: FormattedLine.Kind = .testSummary
let kind = subject.parse(line: line).kind
XCTAssertEqual(kind, expected)
}
}
| mit | f3badc7fe481a513eb892318b29fb740 | 40.83125 | 138 | 0.666816 | 4.28215 | false | true | false | false |
n-yuasa/CustomTransitionSample | CustomTransitionSample/ViewController.swift | 1 | 1219 | //
// ViewController.swift
// CustomTransitionSample
//
//
import UIKit
class ViewController: UIViewController, UIViewControllerTransitioningDelegate {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func buttonClick(sender: AnyObject) {
let modalVC = storyboard?.instantiateViewControllerWithIdentifier("ModalView") as! ModalViewController
modalVC.transitioningDelegate = self
modalVC.modalPresentationStyle = .OverCurrentContext
presentViewController(modalVC, animated: true, completion: nil)
}
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let transition = ScaleTransitioning(presenting: true)
return transition
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let transition = ScaleTransitioning(presenting: false)
return transition
}
}
| mit | 5a0a741cf31edf782c74752e11b31bac | 31.945946 | 217 | 0.743232 | 6.848315 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/call/CallService.swift | 1 | 78933 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import PromiseKit
import SignalRingRTC
import WebRTC
import SignalServiceKit
import SignalMessaging
/**
* `CallService` is a global singleton that manages the state of RingRTC-backed Signal
* Calls (as opposed to legacy "RedPhone Calls" and "WebRTC Calls").
*
* It serves as a connection between the `CallUIAdapter` and the `CallConnection`
* provided by RingRTC.
*
* ## Signaling
*
* Signaling refers to the setup and tear down of the connection. Before the connection
* is established, this must happen out of band (using the Signal Service), but once the
* connection is established it's possible to publish updates (like hangup) via the
* established channel.
*
* Signaling state is synchronized on the main thread and only mutated in the handleXXX
* family of methods.
*
* Following is a high level process of the exchange of messages that takes place during
* call signaling.
*
* ### Key
*
* --[SOMETHING]--> represents a message from the caller to the callee
* <--[SOMETHING]-- represents a message from the callee to the caller
* SS: Message sent via Signal Service
* DC: Message sent via RingRTC (using a WebRTC Data Channel)
*
* ### Message Exchange / State Flow Overview
*
* | Caller | Callee |
* +------------------------+----------------------------------------+
* Start outgoing call: `handleOutgoingCall`...
* --[SS.CallOffer]-->
* ...and start generating ICE updates.
*
* As ICE candidates are generated, `handleLocalAddedIceCandidate`
* is called and we *store* the ICE updates for later.
*
* Received call offer: `handleReceivedOffer`
* Send call answer
* <--[SS.CallAnswer]--
* ... and start generating ICE updates.
*
* As ICE candidates are generated, `handleLocalAddedIceCandidate`
* is called which immediately sends the ICE updates to the Caller.
* <--[SS.ICEUpdate]-- (sent multiple times)
*
* Received CallAnswer: `handleReceivedAnswer`
* So send any stored ice updates (and send future ones immediately)
* --[SS.ICEUpdates]-->
*
* Once compatible ICE updates have been exchanged both parties: `handleRinging`:
*
* Show remote ringing UI...
* Show incoming call UI...
*
* If callee answers Call send `connected` message by invoking
* the `accept` CallConnection API.
*
* <--[DC.ConnectedMesage]--
* Received connected message via remoteConnected call event...
* Show Call is connected.
*
* Hang up (this could equally be sent by the Callee)
* --[DC.Hangup]--> (via CallConnection API)
* --[SS.Hangup]-->
*/
public enum CallError: Error {
case providerReset
case assertionError(description: String)
case disconnected
case externalError(underlyingError: Error)
case timeout(description: String)
case obsoleteCall(description: String)
case fatalError(description: String)
case messageSendFailure(underlyingError: Error)
}
// All Observer methods will be invoked from the main thread.
protocol CallServiceObserver: class {
/**
* Fired whenever the call changes.
*/
func didUpdateCall(call: SignalCall?)
/**
* Fired whenever the local or remote video track become active or inactive.
*/
func didUpdateVideoTracks(call: SignalCall?,
localCaptureSession: AVCaptureSession?,
remoteVideoTrack: RTCVideoTrack?)
}
protocol SignalCallDataDelegate: class {
func outgoingIceUpdateDidFail(call: SignalCall, error: Error)
}
// Gather all per-call state in one place.
private class SignalCallData: NSObject {
fileprivate weak var delegate: SignalCallDataDelegate?
public let call: SignalCall
public var backgroundTask: OWSBackgroundTask?
// Used to ensure any received ICE messages wait until the callConnection is set up.
let callConnectionPromise: Promise<Void>
let callConnectionResolver: Resolver<Void>
// Used to ensure CallOffer was sent before sending any ICE updates.
let readyToSendIceUpdatesPromise: Promise<Void>
let readyToSendIceUpdatesResolver: Resolver<Void>
weak var localCaptureSession: AVCaptureSession? {
didSet {
AssertIsOnMainThread()
Logger.info("")
}
}
weak var remoteVideoTrack: RTCVideoTrack? {
didSet {
AssertIsOnMainThread()
Logger.info("")
}
}
var isRemoteVideoEnabled = false {
didSet {
AssertIsOnMainThread()
Logger.info("\(isRemoteVideoEnabled)")
}
}
var callConnectionFactory: CallConnectionFactory? {
didSet {
AssertIsOnMainThread()
Logger.debug(".callConnectionFactory setter: \(oldValue != nil) -> \(callConnectionFactory != nil) \(String(describing: callConnectionFactory))")
}
}
var callConnection: CallConnection? {
didSet {
AssertIsOnMainThread()
Logger.debug(".callConnection setter: \(oldValue != nil) -> \(callConnection != nil) \(String(describing: callConnection))")
}
}
var shouldSendHangup = false {
didSet {
AssertIsOnMainThread()
Logger.info("")
}
}
required init(call: SignalCall, delegate: SignalCallDataDelegate) {
self.call = call
self.delegate = delegate
let (callConnectionPromise, callConnectionResolver) = Promise<Void>.pending()
self.callConnectionPromise = callConnectionPromise
self.callConnectionResolver = callConnectionResolver
let (readyToSendIceUpdatesPromise, readyToSendIceUpdatesResolver) = Promise<Void>.pending()
self.readyToSendIceUpdatesPromise = readyToSendIceUpdatesPromise
self.readyToSendIceUpdatesResolver = readyToSendIceUpdatesResolver
self.callConnectionFactory = CallConnectionFactory()
super.init()
}
deinit {
Logger.debug("[SignalCallData] deinit")
}
// MARK: -
public func terminate() {
AssertIsOnMainThread()
Logger.debug("")
self.call.removeAllObservers()
// In case we're still waiting on the callConnection setup somewhere, we need to reject it to avoid a memory leak.
// There is no harm in rejecting a previously fulfilled promise.
self.callConnectionResolver.reject(CallError.obsoleteCall(description: "Terminating call"))
// In case we're still waiting on this promise somewhere, we need to reject it to avoid a memory leak.
// There is no harm in rejecting a previously fulfilled promise.
self.readyToSendIceUpdatesResolver.reject(CallError.obsoleteCall(description: "Terminating call"))
DispatchQueue.global().async {
if let callConnection = self.callConnection {
Logger.debug("Calling callConnection.close()")
callConnection.close()
}
if let callConnectionFactory = self.callConnectionFactory {
Logger.debug("Calling callConnectionFactory.close()")
callConnectionFactory.close()
}
self.outgoingIceUpdateQueue.removeAll()
Logger.debug("done")
}
}
// MARK: - Dependencies
private var messageSender: MessageSender {
return SSKEnvironment.shared.messageSender
}
// MARK: - Outgoing ICE updates.
// Setting up a call involves sending many (currently 20+) ICE updates.
// We send messages serially in order to preserve outgoing message order.
// There are so many ICE updates per call that the cost of sending all of
// those messages becomes significant. So we batch outgoing ICE updates,
// making sure that we only have one outgoing ICE update message at a time.
//
// This variable should only be accessed on the main thread.
private var outgoingIceUpdateQueue = [SSKProtoCallMessageIceUpdate]()
private var outgoingIceUpdatesInFlight = false
func sendOrEnqueue(outgoingIceUpdate iceUpdateProto: SSKProtoCallMessageIceUpdate) {
AssertIsOnMainThread()
outgoingIceUpdateQueue.append(iceUpdateProto)
tryToSendIceUpdates()
}
private func tryToSendIceUpdates() {
AssertIsOnMainThread()
guard !outgoingIceUpdatesInFlight else {
Logger.verbose("Enqueued outgoing ice update")
return
}
let iceUpdateProtos = outgoingIceUpdateQueue
guard iceUpdateProtos.count > 0 else {
// Nothing in the queue.
return
}
outgoingIceUpdateQueue.removeAll()
outgoingIceUpdatesInFlight = true
/**
* Sent by both parties out of band of the RTC calling channels, as part of setting up those channels. The messages
* include network accessibility information from the perspective of each client. Once compatible ICEUpdates have been
* exchanged, the clients can connect.
*/
let callMessage = OWSOutgoingCallMessage(thread: call.thread, iceUpdateMessages: iceUpdateProtos)
let sendPromise = self.messageSender.sendMessage(.promise, callMessage.asPreparer)
.done { [weak self] in
AssertIsOnMainThread()
guard let strongSelf = self else {
return
}
strongSelf.outgoingIceUpdatesInFlight = false
strongSelf.tryToSendIceUpdates()
}.catch { [weak self] (error) in
AssertIsOnMainThread()
guard let strongSelf = self else {
return
}
strongSelf.outgoingIceUpdatesInFlight = false
strongSelf.delegate?.outgoingIceUpdateDidFail(call: strongSelf.call, error: error)
}
sendPromise.retainUntilComplete()
}
}
// MARK: - CallService
// This class' state should only be accessed on the main queue.
@objc public class CallService: NSObject, CallObserver, CallConnectionDelegate, SignalCallDataDelegate {
// MARK: - Properties
var observers = [Weak<CallServiceObserver>]()
// Exposed by environment.m
@objc public var callUIAdapter: CallUIAdapter!
// MARK: Class
static let fallbackIceServer = RTCIceServer(urlStrings: ["stun:stun1.l.google.com:19302"])
// MARK: Ivars
fileprivate var deferredHangupList: [UInt64: SignalCallData] = [:]
private var _callData: SignalCallData?
fileprivate var callData: SignalCallData? {
set {
AssertIsOnMainThread()
let oldValue = _callData
_callData = newValue
oldValue?.delegate = nil
oldValue?.call.removeObserver(self)
newValue?.call.addObserverAndSyncState(observer: self)
updateIsVideoEnabled()
// Prevent device from sleeping while we have an active call.
if oldValue != newValue {
if let oldValue = oldValue {
DeviceSleepManager.sharedInstance.removeBlock(blockObject: oldValue)
}
if let newValue = newValue {
DeviceSleepManager.sharedInstance.addBlock(blockObject: newValue)
self.startCallTimer()
} else {
stopAnyCallTimer()
}
}
Logger.debug(".callData setter: \(oldValue?.call.identifiersForLogs as Optional) -> \(newValue?.call.identifiersForLogs as Optional)")
for observer in observers {
observer.value?.didUpdateCall(call: newValue?.call)
}
}
get {
AssertIsOnMainThread()
return _callData
}
}
// NOTE: This accessor should only be used outside this class.
// Within this class use callData to ensure coherency.
@objc
var currentCall: SignalCall? {
get {
AssertIsOnMainThread()
return callData?.call
}
}
@objc public override init() {
super.init()
SwiftSingletons.register(self)
NotificationCenter.default.addObserver(self,
selector: #selector(didEnterBackground),
name: NSNotification.Name.OWSApplicationDidEnterBackground,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didBecomeActive),
name: NSNotification.Name.OWSApplicationDidBecomeActive,
object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Dependencies
private var contactsManager: OWSContactsManager {
return Environment.shared.contactsManager
}
private var messageSender: MessageSender {
return SSKEnvironment.shared.messageSender
}
private var accountManager: AccountManager {
return AppEnvironment.shared.accountManager
}
private var notificationPresenter: NotificationPresenter {
return AppEnvironment.shared.notificationPresenter
}
var databaseStorage: SDSDatabaseStorage {
return SDSDatabaseStorage.shared
}
// MARK: - Notifications
@objc func didEnterBackground() {
AssertIsOnMainThread()
self.updateIsVideoEnabled()
}
@objc func didBecomeActive() {
AssertIsOnMainThread()
self.updateIsVideoEnabled()
}
/**
* Choose whether to use CallKit or a Notification backed interface for calling.
*/
@objc public func createCallUIAdapter() {
AssertIsOnMainThread()
if self.callData != nil {
Logger.warn("ending current call in. Did user toggle callkit preference while in a call?")
self.terminate(callData: self.callData)
}
self.callUIAdapter = CallUIAdapter(callService: self, contactsManager: self.contactsManager, notificationPresenter: self.notificationPresenter)
}
// MARK: - Service Actions
/**
* Initiate an outgoing call.
*/
func handleOutgoingCall(_ call: SignalCall) -> Promise<Void> {
AssertIsOnMainThread()
Logger.info("")
let callId = call.signalingId
BenchEventStart(title: "Outgoing Call Connection", eventId: "call-\(callId)")
guard self.callData == nil else {
let errorDescription = "call was unexpectedly already set."
Logger.error(errorDescription)
call.state = .localFailure
return Promise(error: CallError.assertionError(description: errorDescription))
}
let callData = SignalCallData(call: call, delegate: self)
self.callData = callData
// MJK TODO remove this timestamp param
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), callType: .outgoingIncomplete, in: call.thread)
databaseStorage.write { transaction in
callRecord.anyInsert(transaction: transaction)
}
call.callRecord = callRecord
let promise = getIceServers().done { iceServers in
guard !call.isTerminated else {
Logger.debug("terminated call")
return
}
guard self.callData === callData else {
throw CallError.obsoleteCall(description: "obsolete call")
}
guard callData.callConnection == nil else {
let errorDescription = "callConnection was unexpectedly already set."
Logger.error(errorDescription)
throw CallError.assertionError(description: errorDescription)
}
Logger.debug("got ice servers: \(iceServers) for call: \(call.identifiersForLogs)")
let useTurnOnly = Environment.shared.preferences.doCallsHideIPAddress()
// Create a CallConnection to handle the call media.
let callConnection = try callData.callConnectionFactory?.createCallConnection(delegate: self, iceServers: iceServers, callId: callId, isOutgoing: true, hideIp: useTurnOnly)
Logger.debug("setting callConnection for call: \(call.identifiersForLogs)")
callData.callConnection = callConnection
callData.callConnectionResolver.fulfill(())
try callConnection?.sendOffer()
}
promise.catch { error in
Logger.error("outgoing call \(call.identifiersForLogs) failed with error: \(error)")
guard self.callData === callData else {
Logger.debug("ignoring error for obsolete call")
return
}
self.handleFailedCall(failedCall: call, error: error)
}.retainUntilComplete()
return promise
}
func readyToSendIceUpdates(call: SignalCall) {
AssertIsOnMainThread()
Logger.debug("")
guard let callData = self.callData else {
self.handleFailedCall(failedCall: call, error: CallError.obsoleteCall(description: "obsolete call"))
return
}
guard callData.call === call else {
Logger.warn("ignoring \(#function) for call other than current call")
return
}
callData.readyToSendIceUpdatesResolver.fulfill(())
}
/**
* Called by the call initiator after receiving a CallAnswer from the callee.
*/
public func handleReceivedAnswer(thread: TSContactThread, callId: UInt64, sessionDescription: String) {
AssertIsOnMainThread()
Logger.info("for call: \(callId) thread: \(thread.contactAddress)")
guard let callData = self.callData else {
Logger.warn("ignoring obsolete call: \(callId)")
return
}
let call = callData.call
guard call.signalingId == callId else {
Logger.warn("ignoring mismatched call: \(callId) currentCall: \(call.signalingId)")
return
}
guard let callConnection = callData.callConnection else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "callConnection was unexpectedly nil"))
return
}
do {
try callConnection.receivedAnswer(sdp: sessionDescription)
} catch {
Logger.debug("receivedAnswer failed with \(error)")
self.handleFailedCall(failedCall: call, error: error)
}
}
/**
* User didn't answer incoming call
*/
public func handleMissedCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("")
if call.callRecord == nil {
// MJK TODO remove this timestamp param
call.callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
callType: .incomingMissed,
in: call.thread)
}
guard let callRecord = call.callRecord else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "callRecord was unexpectedly nil"))
return
}
switch callRecord.callType {
case .incomingMissed:
databaseStorage.write { transaction in
callRecord.anyUpsert(transaction: transaction)
}
callUIAdapter.reportMissedCall(call)
case .incomingIncomplete, .incoming:
callRecord.updateCallType(.incomingMissed)
callUIAdapter.reportMissedCall(call)
case .outgoingIncomplete:
callRecord.updateCallType(.outgoingMissed)
case .incomingMissedBecauseOfChangedIdentity, .incomingDeclined, .outgoingMissed, .outgoing:
owsFailDebug("unexpected RPRecentCallType: \(callRecord.callType)")
databaseStorage.write { transaction in
callRecord.anyUpsert(transaction: transaction)
}
default:
databaseStorage.write { transaction in
callRecord.anyUpsert(transaction: transaction)
}
owsFailDebug("unknown RPRecentCallType: \(callRecord.callType)")
}
}
/**
* Received a call while already in another call.
*/
private func handleLocalBusyCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("for call: \(call.identifiersForLogs) thread: \(call.thread.contactAddress)")
do {
let busyBuilder = SSKProtoCallMessageBusy.builder(id: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, busyMessage: try busyBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
sendPromise.retainUntilComplete()
handleMissedCall(call)
} catch {
owsFailDebug("Couldn't build proto")
}
}
/**
* The callee was already in another call.
*/
public func handleRemoteBusy(thread: TSContactThread, callId: UInt64) {
AssertIsOnMainThread()
Logger.info("for thread: \(thread.contactAddress)")
guard let callData = self.callData else {
Logger.warn("ignoring obsolete call: \(callId)")
return
}
let call = callData.call
guard call.signalingId == callId else {
Logger.warn("ignoring mismatched call: \(callId) currentCall: \(call.signalingId)")
return
}
guard thread.contactAddress == call.remoteAddress else {
Logger.warn("ignoring obsolete call")
return
}
call.state = .remoteBusy
assert(call.callRecord != nil)
call.callRecord?.updateCallType(.outgoingMissed)
callUIAdapter.remoteBusy(call)
terminate(callData: self.callData)
}
/**
* Received an incoming call offer. We still have to complete setting up the Signaling channel before we notify
* the user of an incoming call.
*/
public func handleReceivedOffer(thread: TSContactThread, callId: UInt64, sessionDescription callerSessionDescription: String) {
AssertIsOnMainThread()
Logger.info("")
BenchEventStart(title: "Incoming Call Connection", eventId: "call-\(callId)")
let newCall = SignalCall.incomingCall(localId: UUID(), remoteAddress: thread.contactAddress, signalingId: callId)
Logger.info("receivedCallOffer: \(newCall.identifiersForLogs)")
let untrustedIdentity = OWSIdentityManager.shared().untrustedIdentityForSending(to: thread.contactAddress)
guard untrustedIdentity == nil else {
Logger.warn("missed a call due to untrusted identity: \(newCall.identifiersForLogs)")
let callerName = self.contactsManager.displayName(for: thread.contactAddress)
switch untrustedIdentity!.verificationState {
case .verified:
owsFailDebug("shouldn't have missed a call due to untrusted identity if the identity is verified")
self.notificationPresenter.presentMissedCall(newCall, callerName: callerName)
case .default:
self.notificationPresenter.presentMissedCallBecauseOfNewIdentity(call: newCall, callerName: callerName)
case .noLongerVerified:
self.notificationPresenter.presentMissedCallBecauseOfNoLongerVerifiedIdentity(call: newCall, callerName: callerName)
}
// MJK TODO remove this timestamp param
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
callType: .incomingMissedBecauseOfChangedIdentity,
in: thread)
assert(newCall.callRecord == nil)
newCall.callRecord = callRecord
databaseStorage.write { transaction in
callRecord.anyInsert(transaction: transaction)
}
terminate(callData: nil)
return
}
if let existingCallData = self.callData {
let existingCall = existingCallData.call
// TODO on iOS10+ we can use CallKit to swap calls rather than just returning busy immediately.
Logger.info("receivedCallOffer: \(newCall.identifiersForLogs) but we're already in call: \(existingCall.identifiersForLogs)")
handleLocalBusyCall(newCall)
if existingCall.remoteAddress == newCall.remoteAddress {
Logger.info("handling call from current call user as remote busy.: \(newCall.identifiersForLogs) but we're already in call: \(existingCall.identifiersForLogs)")
// If we're receiving a new call offer from the user we already think we have a call with,
// terminate our current call to get back to a known good state. If they call back, we'll
// be ready.
//
// TODO: Auto-accept this incoming call if our current call was either a) outgoing or
// b) never connected. There will be a bit of complexity around making sure that two
// parties that call each other at the same time end up connected.
switch existingCall.state {
case .idle, .dialing, .remoteRinging:
// If both users are trying to call each other at the same time,
// both should see busy.
handleRemoteBusy(thread: existingCall.thread, callId: existingCall.signalingId)
case .answering, .localRinging, .connected, .localFailure, .localHangup, .remoteHangup, .remoteBusy, .reconnecting:
// If one user calls another while the other has a "vestigial" call with
// that same user, fail the old call.
terminate(callData: nil)
}
}
return
}
Logger.info("starting new call: \(newCall.identifiersForLogs)")
let callData = SignalCallData(call: newCall, delegate: self)
self.callData = callData
callData.shouldSendHangup = true
Logger.debug("Enable backgroundTask")
let backgroundTask: OWSBackgroundTask? = OWSBackgroundTask(label: "\(#function)", completionBlock: { status in
AssertIsOnMainThread()
guard status == .expired else {
return
}
let timeout = CallError.timeout(description: "background task time ran out before call connected.")
guard self.callData?.call === newCall else {
Logger.warn("ignoring obsolete call")
return
}
self.handleFailedCall(failedCall: newCall, error: timeout)
})
callData.backgroundTask = backgroundTask
getIceServers().done { iceServers in
// FIXME for first time call recipients I think we'll see mic/camera permission requests here,
// even though, from the users perspective, no incoming call is yet visible.
Logger.debug("got ice servers: \(iceServers) for call: \(newCall.identifiersForLogs)")
guard let currentCallData = self.callData, currentCallData.call === newCall else {
throw CallError.obsoleteCall(description: "getIceServers() response for obsolete call")
}
assert(currentCallData.callConnection == nil, "Unexpected CallConnection instance")
// For contacts not stored in our system contacts, we assume they are an unknown caller, and we force
// a TURN connection, so as not to reveal any connectivity information (IP/port) to the caller.
let isUnknownCaller = !self.contactsManager.hasSignalAccount(for: thread.contactAddress)
let useTurnOnly = isUnknownCaller || Environment.shared.preferences.doCallsHideIPAddress()
// Create a CallConnection to handle the call media.
let callConnection = try currentCallData.callConnectionFactory?.createCallConnection(delegate: self, iceServers: iceServers, callId: callId, isOutgoing: false, hideIp: useTurnOnly)
Logger.debug("setting callConnection for call: \(newCall.identifiersForLogs)")
callData.callConnection = callConnection
callData.callConnectionResolver.fulfill(())
try callConnection?.receivedOffer(sdp: callerSessionDescription)
}.recover { error in
Logger.error("incoming call \(newCall.identifiersForLogs) failed with error: \(error)")
guard self.callData?.call === newCall else {
Logger.debug("ignoring error for obsolete call")
return
}
self.handleFailedCall(failedCall: newCall, error: error)
}.retainUntilComplete()
}
/**
* Remote client (could be caller or callee) sent us a connectivity update
*/
public func handleRemoteAddedIceCandidate(thread: TSContactThread, callId: UInt64, sdp: String, lineIndex: Int32, mid: String) {
AssertIsOnMainThread()
Logger.debug("for callId: \(callId)")
guard let callData = self.callData,
callData.call.signalingId == callId else {
Logger.warn("ignoring ICE candidate for obsolete call: \(callId)")
return
}
callData.callConnectionPromise.done {
AssertIsOnMainThread()
Logger.debug("handling callId: \(callId)")
guard callData === self.callData else {
Logger.warn("ignoring ICE candidate for obsolete call: \(callId)")
return
}
let call = callData.call
guard thread.contactAddress == call.thread.contactAddress else {
Logger.warn("ignoring remote ice update for thread: \(String(describing: thread.uniqueId)) due to thread mismatch. Call already ended?")
return
}
guard let callConnection = callData.callConnection else {
Logger.warn("ignoring remote ice update for thread: \(String(describing: thread.uniqueId)) since there is no current callConnection. Call already ended?")
return
}
try callConnection.receivedIceCandidate(sdp: sdp, lineIndex: lineIndex, sdpMid: mid)
}.catch { error in
Logger.error("handleRemoteAddedIceCandidate failed with error: \(error)")
// @note We will move on and try to connect the call.
}.retainUntilComplete()
}
/**
* Local client (could be caller or callee) generated some connectivity information that we should send to the
* remote client.
*/
private func handleLocalAddedIceCandidate(_ iceCandidate: RTCIceCandidate, callData: SignalCallData) {
AssertIsOnMainThread()
guard self.callData === callData else {
Logger.warn("Receive local ICE candidate for obsolete call.")
return
}
// Wait until we've sent the CallOffer before sending any ice updates for the call to ensure
// intuitive message ordering for other clients.
callData.readyToSendIceUpdatesPromise.done {
guard callData === self.callData else {
self.handleFailedCurrentCall(error: .obsoleteCall(description: "current call changed since we became ready to send ice updates"))
return
}
let call = callData.call
guard call.state != .idle else {
// This will only be called for the current callConnection, so
// fail the current call.
self.handleFailedCurrentCall(error: CallError.assertionError(description: "ignoring local ice candidate, since call is now idle."))
return
}
guard let sdpMid = iceCandidate.sdpMid else {
owsFailDebug("Missing sdpMid")
throw CallError.fatalError(description: "Missing sdpMid")
}
guard iceCandidate.sdpMLineIndex < UINT32_MAX else {
owsFailDebug("Invalid sdpMLineIndex")
throw CallError.fatalError(description: "Invalid sdpMLineIndex")
}
Logger.info("sending ICE Candidate \(call.identifiersForLogs).")
let iceUpdateProto: SSKProtoCallMessageIceUpdate
do {
let iceUpdateBuilder = SSKProtoCallMessageIceUpdate.builder(id: call.signalingId,
sdpMid: sdpMid,
sdpMlineIndex: UInt32(iceCandidate.sdpMLineIndex),
sdp: iceCandidate.sdp)
iceUpdateProto = try iceUpdateBuilder.build()
} catch {
owsFailDebug("Couldn't build proto")
throw CallError.fatalError(description: "Couldn't build proto")
}
/**
* Sent by both parties out of band of the RTC calling channels, as part of setting up those channels. The messages
* include network accessibility information from the perspective of each client. Once compatible ICEUpdates have been
* exchanged, the clients can connect.
*/
callData.sendOrEnqueue(outgoingIceUpdate: iceUpdateProto)
}.catch { error in
Logger.error("waitUntilReadyToSendIceUpdates failed with error: \(error)")
}.retainUntilComplete()
}
/**
* The clients can now communicate via WebRTC, so we can let the UI know.
*
* Called by both caller and callee. Compatible ICE messages have been exchanged between the local and remote
* client.
*/
private func handleRinging() {
AssertIsOnMainThread()
guard let callData = self.callData else {
// This will only be called for the current callConnection, so
// fail the current call.
handleFailedCurrentCall(error: CallError.assertionError(description: "ignoring \(#function) since there is no current call."))
return
}
let call = callData.call
let callId = call.signalingId
Logger.info("\(call.identifiersForLogs)")
switch call.state {
case .dialing:
if call.state != .remoteRinging {
BenchEventComplete(eventId: "call-\(callId)")
}
call.state = .remoteRinging
case .answering:
if call.state != .localRinging {
BenchEventComplete(eventId: "call-\(callId)")
}
call.state = .localRinging
self.callUIAdapter.reportIncomingCall(call, thread: call.thread)
case .remoteRinging:
Logger.info("call already ringing. Ignoring \(#function): \(call.identifiersForLogs).")
case .connected:
Logger.info("Call reconnected \(#function): \(call.identifiersForLogs).")
case .reconnecting:
call.state = .connected
case .idle, .localRinging, .localFailure, .localHangup, .remoteHangup, .remoteBusy:
owsFailDebug("unexpected call state: \(call.state): \(call.identifiersForLogs).")
}
}
private func handleReconnecting() {
AssertIsOnMainThread()
guard let callData = self.callData else {
// This will only be called for the current callConnection, so
// fail the current call.
handleFailedCurrentCall(error: CallError.assertionError(description: "ignoring \(#function) since there is no current call."))
return
}
let call = callData.call
Logger.info("\(call.identifiersForLogs).")
switch call.state {
case .remoteRinging, .localRinging:
Logger.debug("disconnect while ringing... we'll keep ringing")
case .connected:
call.state = .reconnecting
default:
owsFailDebug("unexpected call state: \(call.state): \(call.identifiersForLogs).")
}
}
/**
* The remote client (caller or callee) ended the call.
*/
public func handleRemoteHangup(thread: TSContactThread, callId: UInt64) {
AssertIsOnMainThread()
Logger.info("")
guard let callData = self.callData else {
// This may happen if we hang up slightly before they hang up.
handleFailedCurrentCall(error: .obsoleteCall(description:"call was unexpectedly nil"))
return
}
let call = callData.call
guard call.signalingId == callId else {
Logger.warn("ignoring mismatched call: \(callId) currentCall: \(call.signalingId)")
return
}
guard thread.contactAddress == call.thread.contactAddress else {
// This can safely be ignored.
// We don't want to fail the current call because an old call was slow to send us the hangup message.
Logger.warn("ignoring hangup for thread: \(thread.contactAddress) which is not the current call: \(call.identifiersForLogs)")
return
}
Logger.info("\(call.identifiersForLogs).")
switch call.state {
case .idle, .dialing, .answering, .localRinging, .localFailure, .remoteBusy, .remoteRinging:
handleMissedCall(call)
case .connected, .reconnecting, .localHangup, .remoteHangup:
Logger.info("call is finished.")
}
call.state = .remoteHangup
// Notify UI
callUIAdapter.remoteDidHangupCall(call)
// self.call is nil'd in `terminateCall`, so it's important we update it's state *before* calling `terminateCall`
terminate(callData: self.callData)
}
/**
* User chose to answer call referred to by call `localId`. Used by the Callee only.
*
* Used by notification actions which can't serialize a call object.
*/
@objc public func handleAnswerCall(localId: UUID) {
AssertIsOnMainThread()
guard let callData = self.callData else {
// This should never happen; return to a known good state.
owsFailDebug("call was unexpectedly nil")
handleFailedCurrentCall(error: CallError.assertionError(description: "call was unexpectedly nil"))
return
}
let call = callData.call
guard call.localId == localId else {
// This should never happen; return to a known good state.
owsFailDebug("callLocalId: \(localId) doesn't match current calls: \(call.localId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "callLocalId: \(localId) doesn't match current calls: \(call.localId)"))
return
}
self.handleAnswerCall(call)
}
/**
* User chose to answer call referred to by call `localId`. Used by the Callee only.
*/
public func handleAnswerCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("")
guard let callData = self.callData else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "callData unexpectedly nil"))
return
}
guard call == callData.call else {
// This could conceivably happen if the other party of an old call was slow to send us their answer
// and we've subsequently engaged in another call. Don't kill the current call, but just ignore it.
Logger.warn("ignoring \(#function) for call other than current call")
return
}
guard let callConnection = callData.callConnection else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "missing callConnection"))
return
}
Logger.info("\(call.identifiersForLogs).")
// MJK TODO remove this timestamp param
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(), callType: .incomingIncomplete, in: call.thread)
databaseStorage.write { transaction in
callRecord.anyInsert(transaction: transaction)
}
call.callRecord = callRecord
do {
try callConnection.accept()
} catch {
self.handleFailedCall(failedCall: call, error: error)
return
}
handleConnectedCall(callData)
}
/**
* For outgoing call, when the callee has chosen to accept the call.
* For incoming call, when the local user has chosen to accept the call.
*/
private func handleConnectedCall(_ callData: SignalCallData) {
AssertIsOnMainThread()
Logger.info("")
guard callData === self.callData else {
Logger.debug("Ignoring connected for obsolete call.")
return
}
let call = callData.call
guard let callConnection = callData.callConnection else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "callConnection unexpectedly nil"))
return
}
Logger.info("handleConnectedCall: \(callData.call.identifiersForLogs).")
// End the background task.
callData.backgroundTask = nil
callData.call.state = .connected
// We don't risk transmitting any media until the remote client has admitted to being connected.
ensureAudioState(call: callData.call, callConnection: callConnection)
do {
try callConnection.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack())
} catch {
owsFailDebug("callConnection.setLocalVideoEnabled failed \(error)")
}
}
/**
* Local user chose to end the call.
*
* Can be used for Incoming and Outgoing calls.
*/
func handleLocalHungupCall(_ call: SignalCall) {
AssertIsOnMainThread()
Logger.info("")
guard let callData = self.callData else {
owsFailDebug("no valid callData found, nothing to hangup")
return
}
guard callData.call === call else {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "ignoring \(#function) for call other than current call"))
return
}
Logger.info("\(call.identifiersForLogs)")
if let callRecord = call.callRecord {
if callRecord.callType == .outgoingIncomplete {
callRecord.updateCallType(.outgoingMissed)
}
} else if call.state == .localRinging {
// MJK TODO remove this timestamp param
let callRecord = TSCall(timestamp: NSDate.ows_millisecondTimeStamp(),
callType: .incomingDeclined,
in: call.thread)
databaseStorage.write { transaction in
callRecord.anyInsert(transaction: transaction)
}
call.callRecord = callRecord
} else {
owsFailDebug("missing call record")
}
let originalState = call.state
call.state = .localHangup
if let callConnection = callData.callConnection {
// Stop audio capture ASAP
ensureAudioState(call: call, callConnection: callConnection)
switch originalState {
case .dialing, .remoteRinging, .localRinging, .connected, .reconnecting:
// Only in these states would we expect the CallConnection to
// be negotiated and need to do a formal hangup (again).
Logger.debug("hanging up via CallConnection")
do {
// Hangup a call, should send 'hangup' message via data channel. Will
// also call shouldSendHangup which will send a 'hangup' message via
// signaling and actually terminate the call.
// Add the call to the deferredHangupList
deferredHangupList[call.signalingId] = callData
self.callData = nil
Logger.debug("deferredHangupList.count: \(deferredHangupList.count)")
try callConnection.hangup()
} catch {
// In case of error, clear the item from the list.
deferredHangupList.removeValue(forKey: call.signalingId)
owsFailDebug("\(error)")
terminate(callData: callData)
}
default:
Logger.debug("")
terminate(callData: callData)
}
} else {
Logger.info("ending call before callConnection created (device offline or quick hangup)")
guard callData.shouldSendHangup else {
terminate(callData: callData)
return
}
do {
let hangupBuilder = SSKProtoCallMessageHangup.builder(id: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, hangupMessage: try hangupBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
.done {
Logger.debug("sent hangup call message to \(call.thread.contactAddress)")
}.ensure {
self.terminate(callData: callData)
}.catch { error in
owsFailDebug("failed to send hangup call message to \(call.thread.contactAddress) with error: \(error)")
}
sendPromise.retainUntilComplete()
} catch {
owsFailDebug("couldn't build hangup proto")
terminate(callData: callData)
}
}
}
/**
* Local user toggled to mute audio.
*
* Can be used for Incoming and Outgoing calls.
*/
func setIsMuted(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
guard let callData = self.callData else {
// This can happen after a call has ended. Reproducible on iOS11, when the other party ends the call.
Logger.info("ignoring mute request for obsolete call")
return
}
let call = callData.call
call.isMuted = isMuted
guard let callConnection = callData.callConnection else {
// The callConnection might not be created yet.
return
}
ensureAudioState(call: call, callConnection: callConnection)
}
/**
* Local user toggled to hold call. Currently only possible via CallKit screen,
* e.g. when another Call comes in.
*/
func setIsOnHold(call: SignalCall, isOnHold: Bool) {
AssertIsOnMainThread()
guard let callData = self.callData, call == callData.call else {
Logger.info("ignoring hold request for obsolete call")
return
}
call.isOnHold = isOnHold
guard let callConnection = callData.callConnection else {
// The callConnection might not be created yet.
return
}
ensureAudioState(call: call, callConnection: callConnection)
}
func ensureAudioState(call: SignalCall, callConnection: CallConnection) {
guard call.state == .connected else {
do {
try callConnection.setLocalAudioEnabled(enabled: false)
} catch {
owsFailDebug("callConnection.setLocalAudioEnabled failed")
}
return
}
guard !call.isMuted else {
do {
try callConnection.setLocalAudioEnabled(enabled: false)
} catch {
owsFailDebug("callConnection.setLocalAudioEnabled failed")
}
return
}
guard !call.isOnHold else {
do {
try callConnection.setLocalAudioEnabled(enabled: false)
} catch {
owsFailDebug("callConnection.setLocalAudioEnabled failed")
}
return
}
do {
try callConnection.setLocalAudioEnabled(enabled: true)
} catch {
owsFailDebug("callConnection.setLocalAudioEnabled failed")
}
}
/**
* Local user toggled video.
*
* Can be used for Incoming and Outgoing calls.
*/
func setHasLocalVideo(hasLocalVideo: Bool) {
AssertIsOnMainThread()
guard let frontmostViewController = UIApplication.shared.frontmostViewController else {
owsFailDebug("could not identify frontmostViewController")
return
}
guard let callData = self.callData else {
owsFailDebug("Missing callData")
return
}
frontmostViewController.ows_askForCameraPermissions { granted in
guard self.callData === callData else {
owsFailDebug("Ignoring camera permissions for obsolete call.")
return
}
if granted {
// Success callback; camera permissions are granted.
self.setHasLocalVideoWithCameraPermissions(hasLocalVideo: hasLocalVideo)
} else {
// Failed callback; camera permissions are _NOT_ granted.
// We don't need to worry about the user granting or remoting this permission
// during a call while the app is in the background, because changing this
// permission kills the app.
OWSAlerts.showAlert(title: NSLocalizedString("MISSING_CAMERA_PERMISSION_TITLE", comment: "Alert title when camera is not authorized"),
message: NSLocalizedString("MISSING_CAMERA_PERMISSION_MESSAGE", comment: "Alert body when camera is not authorized"))
}
}
}
private func setHasLocalVideoWithCameraPermissions(hasLocalVideo: Bool) {
AssertIsOnMainThread()
guard let callData = self.callData else {
// This can happen if you toggle local video right after
// the other user ends the call.
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
call.hasLocalVideo = hasLocalVideo
guard let callConnection = callData.callConnection else {
// The callConnection might not be created yet.
return
}
if call.state == .connected {
do {
try callConnection.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack())
} catch {
owsFailDebug("callConnection.setLocalVideoEnabled failed \(error)")
}
}
}
@objc
func handleCallKitStartVideo() {
AssertIsOnMainThread()
self.setHasLocalVideo(hasLocalVideo: true)
}
func setCameraSource(call: SignalCall, isUsingFrontCamera: Bool) {
AssertIsOnMainThread()
guard let callData = self.callData,
let callConnection = callData.callConnection else {
return
}
do {
try callConnection.setCameraSource(isUsingFrontCamera: isUsingFrontCamera)
} catch {
owsFailDebug("callConnection.setCameraSource failed")
}
}
// MARK: - CallConnectionDelegate
public func callConnection(_ callConnectionParam: CallConnection, onCallEvent event: CallEvent, callId: UInt64) {
AssertIsOnMainThread()
guard let callData = self.callData,
callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("received call event for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "received call event for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
switch event {
case .ringing:
Logger.debug("Got ringing.")
// The underlying connection is established, notify the user.
handleRinging()
case .remoteConnected:
Logger.debug("Got remoteConnected, the peer (callee) accepted the call: \(call.identifiersForLogs)")
callUIAdapter.recipientAcceptedCall(call)
handleConnectedCall(callData)
case .remoteVideoEnable:
Logger.debug("remote participant sent VideoStreamingStatus via data channel: \(call.identifiersForLogs).")
callData.isRemoteVideoEnabled = true
fireDidUpdateVideoTracks()
case .remoteVideoDisable:
Logger.debug("remote participant sent VideoStreamingStatus via data channel: \(call.identifiersForLogs).")
callData.isRemoteVideoEnabled = false
fireDidUpdateVideoTracks()
case .remoteHangup:
Logger.debug("Got remoteHangup: \(call.identifiersForLogs)")
handleRemoteHangup(thread: call.thread, callId: callId)
case .connectionFailed:
Logger.debug("Got connectionFailed.")
// Return to a known good state.
self.handleFailedCurrentCall(error: CallError.disconnected)
case .callTimeout:
Logger.debug("Got callTimeout.")
let description: String
if call.direction == .outgoing {
description = "timeout for outgoing call"
} else {
description = "timeout for incoming call"
}
handleFailedCall(failedCall: call, error: CallError.timeout(description: description))
case .callReconnecting:
Logger.debug("Got callReconnecting.")
self.handleReconnecting()
}
}
public func callConnection(_ callConnectionParam: CallConnection, onCallError error: String, callId: UInt64) {
AssertIsOnMainThread()
Logger.debug("Got an error from RingRTC: \(error)")
guard let callData = self.callData,
callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("received call error for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "received call error for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
// We will try to send a hangup over signaling to let the
// remote peer know we are ending the call.
do {
let hangupBuilder = SSKProtoCallMessageHangup.builder(id: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, hangupMessage: try hangupBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
.done {
Logger.debug("sent hangup call message to \(call.thread.contactAddress)")
guard self.callData === callData else {
Logger.debug("Ignoring hangup send success for obsolete call.")
return
}
// We fail the call rather than terminate it.
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: error))
}.catch { error in
Logger.error("failed to send hangup call message to \(call.thread.contactAddress) with error: \(error)")
guard self.callData === callData else {
Logger.debug("Ignoring hangup send failure for obsolete call.")
return
}
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: "failed to send hangup call message"))
}
sendPromise.retainUntilComplete()
} catch {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "couldn't build hangup proto"))
}
}
public func callConnection(_ callConnectionParam: CallConnection, onAddRemoteVideoTrack track: RTCVideoTrack, callId: UInt64) {
AssertIsOnMainThread()
guard let callData = self.callData,
callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("received remote video track for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "received remote video track for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
callData.remoteVideoTrack = track
fireDidUpdateVideoTracks()
}
public func callConnection(_ callConnectionParam: CallConnection, onUpdateLocalVideoSession session: AVCaptureSession?, callId: UInt64) {
AssertIsOnMainThread()
guard let callData = self.callData,
callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("received local video session for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "received local video session for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
callData.localCaptureSession = session
fireDidUpdateVideoTracks()
}
public func callConnection(_ callConnectionParam: CallConnection, shouldSendOffer sdp: String, callId: UInt64) {
AssertIsOnMainThread()
Logger.debug("Got onSendOffer")
guard let callData = self.callData,
callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard !call.isTerminated else {
Logger.debug("terminated call")
return
}
guard callId == call.signalingId else {
owsFailDebug("should send offer for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "should send offer for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
callData.shouldSendHangup = true
do {
let offerBuilder = SSKProtoCallMessageOffer.builder(id: call.signalingId, sessionDescription: sdp)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, offerMessage: try offerBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
.done {
Logger.debug("sent offer call message to \(call.thread.contactAddress)")
guard self.callData === callData else {
Logger.debug("Ignoring call offer send success for obsolete call.")
return
}
guard !call.isTerminated else {
Logger.debug("terminated call")
return
}
// Ultimately, RingRTC will start sending Ice Candidates at the proper
// time, so we open the gate here right after sending the offer.
self.readyToSendIceUpdates(call: call)
}.catch { error in
Logger.error("failed to send offer call message to \(call.thread.contactAddress) with error: \(error)")
guard self.callData === callData else {
Logger.debug("Ignoring call offer send failure for obsolete call.")
return
}
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: "failed to send offer call message"))
}
sendPromise.retainUntilComplete()
} catch {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "couldn't build offer proto"))
}
}
public func callConnection(_ callConnectionParam: CallConnection, shouldSendAnswer sdp: String, callId: UInt64) {
AssertIsOnMainThread()
Logger.debug("Got onSendAnswer")
guard let callData = self.callData, callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("should send answer for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "should send answer for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
do {
let answerBuilder = SSKProtoCallMessageAnswer.builder(id: call.signalingId, sessionDescription: sdp)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, answerMessage: try answerBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
.done {
Logger.debug("sent answer call message to \(call.thread.contactAddress)")
guard self.callData === callData else {
Logger.debug("Ignoring call answer send success for obsolete call.")
return
}
guard !call.isTerminated else {
Logger.debug("terminated call")
return
}
// Ultimately, RingRTC will start sending Ice Candidates at the proper
// time, so we open the gate here right after sending the answer.
self.readyToSendIceUpdates(call: call)
}.catch { error in
Logger.error("failed to send answer call message to \(call.thread.contactAddress) with error: \(error)")
guard self.callData === callData else {
Logger.debug("Ignoring call answer send failure for obsolete call.")
return
}
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: "failed to send answer call message"))
}
sendPromise.retainUntilComplete()
} catch {
handleFailedCall(failedCall: call, error: CallError.assertionError(description: "couldn't build answer proto"))
}
}
public func callConnection(_ callConnectionParam: CallConnection, shouldSendIceCandidates candidates: [RTCIceCandidate], callId: UInt64) {
AssertIsOnMainThread()
guard let callData = self.callData, callConnectionParam == callData.callConnection else {
Logger.debug("Ignoring event from obsolete call.")
return
}
let call = callData.call
guard callId == call.signalingId else {
owsFailDebug("should send ice candidate for call with id: \(callId) but current call has id: \(call.signalingId)")
handleFailedCurrentCall(error: CallError.assertionError(description: "should send ice candidate for call with id: \(callId) but current call has id: \(call.signalingId)"))
return
}
// We keep the Ice Candidate queue here in the app so that
// it can batch candidates together as fast as it takes to
// actually send the messages.
for iceCandidate in candidates {
self.handleLocalAddedIceCandidate(iceCandidate, callData: callData)
}
}
public func callConnection(_ callConnectionParam: CallConnection, shouldSendHangup callId: UInt64) {
AssertIsOnMainThread()
Logger.debug("Got onSendHangup")
guard let callData = deferredHangupList.removeValue(forKey: callId) else {
owsFailDebug("obsolete call: \(callId)")
return
}
Logger.debug("deferredHangupList.count: \(deferredHangupList.count)")
guard callConnectionParam == callData.callConnection else {
Logger.debug("obsolete client: \(callId)")
return
}
let call = callData.call
do {
let hangupBuilder = SSKProtoCallMessageHangup.builder(id: call.signalingId)
let callMessage = OWSOutgoingCallMessage(thread: call.thread, hangupMessage: try hangupBuilder.build())
let sendPromise = messageSender.sendMessage(.promise, callMessage.asPreparer)
.done {
Logger.debug("sent hangup call message to \(call.thread.contactAddress)")
}.ensure {
self.terminate(callData: callData)
}.catch { error in
owsFailDebug("failed to send hangup call message to \(call.thread.contactAddress) with error: \(error)")
}
sendPromise.retainUntilComplete()
} catch {
owsFailDebug("couldn't build hangup proto")
terminate(callData: callData)
}
}
// MARK: -
/**
* RTCIceServers are used when attempting to establish an optimal connection to the other party. SignalService supplies
* a list of servers, plus we have fallback servers hardcoded in the app.
*/
private func getIceServers() -> Promise<[RTCIceServer]> {
return self.accountManager.getTurnServerInfo()
.map(on: DispatchQueue.global()) { turnServerInfo -> [RTCIceServer] in
Logger.debug("got turn server urls: \(turnServerInfo.urls)")
return turnServerInfo.urls.map { url in
if url.hasPrefix("turn") {
// Only "turn:" servers require authentication. Don't include the credentials to other ICE servers
// as 1.) they aren't used, and 2.) the non-turn servers might not be under our control.
// e.g. we use a public fallback STUN server.
return RTCIceServer(urlStrings: [url], username: turnServerInfo.username, credential: turnServerInfo.password)
} else {
return RTCIceServer(urlStrings: [url])
}
} + [CallService.fallbackIceServer]
}.recover(on: DispatchQueue.global()) { (error: Error) -> Guarantee<[RTCIceServer]> in
Logger.error("fetching ICE servers failed with error: \(error)")
Logger.warn("using fallback ICE Servers")
return Guarantee.value([CallService.fallbackIceServer])
}
}
// This method should be called when either: a) we know or assume that
// the error is related to the current call. b) the error is so serious
// that we want to terminate the current call (if any) in order to
// return to a known good state.
public func handleFailedCurrentCall(error: CallError) {
Logger.debug("")
// Return to a known good state by ending the current call, if any.
handleFailedCall(failedCall: self.callData?.call, error: error)
}
// This method should be called when a fatal error occurred for a call.
//
// * If we know which call it was, we should update that call's state
// to reflect the error.
// * IFF that call is the current call, we want to terminate it.
public func handleFailedCall(failedCall: SignalCall?, error: Error) {
AssertIsOnMainThread()
let callError: CallError = {
switch error {
case let callError as CallError:
return callError
default:
return CallError.externalError(underlyingError: error)
}
}()
if case CallError.assertionError(description: let description) = error {
owsFailDebug(description)
}
if let failedCall = failedCall {
switch failedCall.state {
case .answering, .localRinging:
assert(failedCall.callRecord == nil)
// call failed before any call record could be created, make one now.
handleMissedCall(failedCall)
default:
assert(failedCall.callRecord != nil)
}
// It's essential to set call.state before terminateCall, because terminateCall nils self.call
failedCall.error = callError
failedCall.state = .localFailure
self.callUIAdapter.failCall(failedCall, error: callError)
// Only terminate the current call if the error pertains to the current call.
guard failedCall === self.callData?.call else {
Logger.debug("ignoring obsolete call: \(failedCall.identifiersForLogs).")
return
}
Logger.error("call: \(failedCall.identifiersForLogs) failed with error: \(error)")
} else {
Logger.error("unknown call failed with error: \(error)")
}
// Only terminate the call if it is the current call.
terminate(callData: self.callData)
}
/**
* Clean up any existing call state and get ready to receive a new call.
*/
private func terminate(callData: SignalCallData?) {
AssertIsOnMainThread()
Logger.debug("")
callData?.terminate()
callUIAdapter.didTerminateCall(callData?.call)
if self.callData === callData {
// Terminating the current call.
fireDidUpdateVideoTracks()
// nil self.callData when terminating the current call.
self.callData = nil
}
// Apparently WebRTC will sometimes disable device orientation notifications.
// After every call ends, we need to ensure they are enabled.
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
// MARK: - CallObserver
internal func stateDidChange(call: SignalCall, state: CallState) {
AssertIsOnMainThread()
Logger.info("\(state)")
updateIsVideoEnabled()
}
internal func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool) {
AssertIsOnMainThread()
Logger.info("\(hasLocalVideo)")
self.updateIsVideoEnabled()
}
internal func muteDidChange(call: SignalCall, isMuted: Bool) {
AssertIsOnMainThread()
// Do nothing
}
internal func holdDidChange(call: SignalCall, isOnHold: Bool) {
AssertIsOnMainThread()
// Do nothing
}
internal func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?) {
AssertIsOnMainThread()
// Do nothing
}
// MARK: - Video
private func shouldHaveLocalVideoTrack() -> Bool {
AssertIsOnMainThread()
guard let callData = self.callData else {
return false
}
let call = callData.call
// The iOS simulator doesn't provide any sort of camera capture
// support or emulation (http://goo.gl/rHAnC1) so don't bother
// trying to open a local stream.
return (!Platform.isSimulator &&
UIApplication.shared.applicationState != .background &&
call.state == .connected &&
call.hasLocalVideo)
}
//TODO only fire this when it's changed? as of right now it gets called whenever you e.g. lock the phone while it's incoming ringing.
private func updateIsVideoEnabled() {
AssertIsOnMainThread()
guard let callData = self.callData else {
return
}
guard let callConnection = callData.callConnection else {
return
}
let shouldHaveLocalVideoTrack = self.shouldHaveLocalVideoTrack()
Logger.info("shouldHaveLocalVideoTrack: \(shouldHaveLocalVideoTrack)")
do {
try callConnection.setLocalVideoEnabled(enabled: shouldHaveLocalVideoTrack)
if callData.call.state == .connected {
try callConnection.sendLocalVideoStatus(enabled: shouldHaveLocalVideoTrack)
}
} catch {
owsFailDebug("error: \(error)")
}
}
// MARK: - Observers
// The observer-related methods should be invoked on the main thread.
func addObserverAndSyncState(observer: CallServiceObserver) {
AssertIsOnMainThread()
observers.append(Weak(value: observer))
// Synchronize observer with current call state
fireDidUpdateVideoTracks(forObserver: observer)
}
// The observer-related methods should be invoked on the main thread.
func removeObserver(_ observer: CallServiceObserver) {
AssertIsOnMainThread()
while let index = observers.firstIndex(where: { $0.value === observer }) {
observers.remove(at: index)
}
}
// The observer-related methods should be invoked on the main thread.
func removeAllObservers() {
AssertIsOnMainThread()
observers = []
}
private func fireDidUpdateVideoTracks() {
AssertIsOnMainThread()
for weakObserver in observers {
if let observer = weakObserver.value {
fireDidUpdateVideoTracks(forObserver: observer)
}
}
}
private func fireDidUpdateVideoTracks(forObserver observer: CallServiceObserver) {
AssertIsOnMainThread()
let isRemoteVideoEnabled = callData?.isRemoteVideoEnabled ?? false
let remoteVideoTrack = isRemoteVideoEnabled ? callData?.remoteVideoTrack : nil
observer.didUpdateVideoTracks(call: callData?.call,
localCaptureSession: callData?.localCaptureSession,
remoteVideoTrack: remoteVideoTrack)
}
// MARK: CallViewController Timer
var activeCallTimer: Timer?
func startCallTimer() {
AssertIsOnMainThread()
stopAnyCallTimer()
assert(self.activeCallTimer == nil)
guard let callData = self.callData else {
owsFailDebug("Missing callData.")
return
}
self.activeCallTimer = WeakTimer.scheduledTimer(timeInterval: 1, target: self, userInfo: nil, repeats: true) { timer in
guard callData === self.callData else {
owsFailDebug("call has since ended. Timer should have been invalidated.")
timer.invalidate()
return
}
let call = callData.call
self.ensureCallScreenPresented(call: call)
}
}
func ensureCallScreenPresented(call: SignalCall) {
guard self.callData?.call === call else {
owsFailDebug("obsolete call: \(call.identifiersForLogs)")
return
}
guard let connectedDate = call.connectedDate else {
// Ignore; call hasn't connected yet.
return
}
let kMaxViewPresentationDelay: Double = 5
guard fabs(connectedDate.timeIntervalSinceNow) > kMaxViewPresentationDelay else {
// Ignore; call connected recently.
return
}
guard !call.isTerminated else {
// There's a brief window between when the callViewController is removed
// and when this timer is terminated.
//
// We don't want to fail a call that's already terminated.
Logger.debug("ignoring screen protection check for already terminated call.")
return
}
if !OWSWindowManager.shared().hasCall() {
owsFailDebug("Call terminated due to missing call view.")
self.handleFailedCall(failedCall: call, error: CallError.assertionError(description: "Call view didn't present after \(kMaxViewPresentationDelay) seconds"))
return
}
}
func stopAnyCallTimer() {
AssertIsOnMainThread()
self.activeCallTimer?.invalidate()
self.activeCallTimer = nil
}
// MARK: - SignalCallDataDelegate
func outgoingIceUpdateDidFail(call: SignalCall, error: Error) {
AssertIsOnMainThread()
guard self.callData?.call === call else {
Logger.warn("obsolete call")
return
}
handleFailedCall(failedCall: call, error: CallError.messageSendFailure(underlyingError: error))
}
}
extension RPRecentCallType: CustomStringConvertible {
public var description: String {
switch self {
case .incoming:
return ".incoming"
case .outgoing:
return ".outgoing"
case .incomingMissed:
return ".incomingMissed"
case .outgoingIncomplete:
return ".outgoingIncomplete"
case .incomingIncomplete:
return ".incomingIncomplete"
case .incomingMissedBecauseOfChangedIdentity:
return ".incomingMissedBecauseOfChangedIdentity"
case .incomingDeclined:
return ".incomingDeclined"
case .outgoingMissed:
return ".outgoingMissed"
default:
owsFailDebug("unexpected RPRecentCallType: \(self)")
return "RPRecentCallTypeUnknown"
}
}
}
| gpl-3.0 | 8c8c7ca0e77d5513ba9509b5cb3986c8 | 37.00337 | 192 | 0.61537 | 5.528682 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/Scenes/Analyze/Option/OptionModelController.swift | 1 | 1288 | //
// OptionModelController.swift
// Mah Income
//
// Created by Van Luu on 5/8/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import UIKit
import RealmSwift
class OptionModelController {
weak var viewController: AnalyzeOptionProtocol!
fileprivate lazy var categoryWorker: CategoryWorker? = {
return CategoryWorker()
}()
fileprivate lazy var paymentWorker: PaymentWorker? = {
return PaymentWorker()
}()
func fetchAllCategory() {
guard let worker = categoryWorker else {
// (viewController).presentError(des: MahError.cannotInit.textMsg)
return
}
viewController.reloadData(listCategories: worker.getAllCategory())
}
func getPayment(of category: CategoryModel) -> LinkingObjects<PaymentModel> {
return category.owners
}
func dateFrom(kind: Calendar.Component, value: Int) -> Date? {
let calendar = Calendar.current
return calendar.date(byAdding: kind, value: value, to: Date(), wrappingComponents: false)
}
func getPaymentsFrom(date: Date) -> Results<PaymentModel>? {
guard let worker = paymentWorker else {
// (viewController).presentError(des: MahError.cannotInit.textMsg)
return nil
}
return worker.getAllPaymentsFrom(date: date)
}
}
| mit | bdcef8aa5712c3ffc59529482572ece4 | 23.283019 | 93 | 0.6892 | 4.29 | false | false | false | false |
DDSSwiftTech/SwiftGtk | Sources/SignalBox.swift | 2 | 2558 | //
// Copyright © 2016 Tomas Linhart. All rights reserved.
//
protocol SignalBox {
associatedtype CallbackType
var callback: CallbackType { get }
init(callback: CallbackType)
}
typealias SignalCallbackZero = () -> Void
typealias SignalCallbackOne = (UnsafeMutableRawPointer) -> Void
typealias SignalCallbackTwo = (UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void
typealias SignalCallbackThree = (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void
typealias SignalCallbackFour = (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void
typealias SignalCallbackFive = (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void
typealias SignalCallbackSix = (UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer, UnsafeMutableRawPointer) -> Void
/// Provides a box that captures a callback for a signal so it makes easier to add signals.
class SignalBoxZero: SignalBox {
typealias CallbackType = SignalCallbackZero
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxOne: SignalBox {
typealias CallbackType = SignalCallbackOne
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxTwo: SignalBox {
typealias CallbackType = SignalCallbackTwo
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxThree: SignalBox {
typealias CallbackType = SignalCallbackThree
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxFour: SignalBox {
typealias CallbackType = SignalCallbackFour
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxFive: SignalBox {
typealias CallbackType = SignalCallbackFive
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
class SignalBoxSix: SignalBox {
typealias CallbackType = SignalCallbackSix
let callback: CallbackType
required init(callback: @escaping CallbackType) {
self.callback = callback
}
}
| mit | a7d1b24391c23b2643064e68e95b4186 | 27.411111 | 188 | 0.759484 | 5.316008 | false | false | false | false |
asm-products/landline-ios | landline/landline/ChatListViewController.swift | 1 | 1964 | //
// ChatListViewController.swift
// landline
//
// Created by Jason Lagaac on 28/02/2015.
// Copyright (c) 2015 landline. All rights reserved.
//
import UIKit
class ChatListViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
var selectedChatName : String = ""
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func showMenu() {
NSNotificationCenter.defaultCenter().postNotificationName("showMenu", object: nil)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell : ChatListTableCell = tableView.dequeueReusableCellWithIdentifier("ChatListTableCell") as ChatListTableCell
switch (indexPath.row) {
case 0:
cell.chatNameLbl?.text = "Landline"
case 1:
cell.chatNameLbl?.text = "Assembly"
case 2:
cell.chatNameLbl?.text = "The Super Friends"
default:
break
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell : ChatListTableCell = tableView.cellForRowAtIndexPath(indexPath) as ChatListTableCell
selectedChatName = cell.chatNameLbl!.text!
performSegueWithIdentifier("ChatViewController", sender: nil);
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ChatViewController" {
var vc = segue.destinationViewController as ChatViewController
vc.navigationItem.title = selectedChatName
}
}
}
| agpl-3.0 | 50780701638e738e6141de6317c4e652 | 29.215385 | 124 | 0.64053 | 5.563739 | false | false | false | false |
gowansg/firefox-ios | Account/HawkHelper.swift | 23 | 5366 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
public class HawkHelper {
private let NonceLengthInBytes: UInt = 8
let id: String
let key: NSData
public init(id: String, key: NSData) {
self.id = id
self.key = key
}
// Produce a HAWK value suitable for an "Authorization: value" header, timestamped now.
public func getAuthorizationValueFor(request: NSURLRequest) -> String {
let timestampInSeconds: Int64 = Int64(NSDate().timeIntervalSince1970)
return getAuthorizationValueFor(request, at: timestampInSeconds)
}
// Produce a HAWK value suitable for an "Authorization: value" header.
func getAuthorizationValueFor(request: NSURLRequest, at timestampInSeconds: Int64) -> String {
let nonce = NSData.randomOfLength(NonceLengthInBytes)!.base64EncodedString
let extra = ""
return getAuthorizationValueFor(request, at: timestampInSeconds, nonce: nonce, extra: extra)
}
func getAuthorizationValueFor(request: NSURLRequest, at timestampInSeconds: Int64, nonce: String, extra: String) -> String {
let timestampString = String(timestampInSeconds)
let hashString = HawkHelper.getPayloadHashFor(request)
let requestString = HawkHelper.getRequestStringFor(request, timestampString: timestampString, nonce: nonce, hash: hashString, extra: extra)
let macString = HawkHelper.getSignatureFor(requestString.utf8EncodedData!, key: self.key)
let s = NSMutableString(string: "Hawk ")
func append(key: String, value: String) -> Void {
s.appendString(key)
s.appendString("=\"")
s.appendString(value)
s.appendString("\", ")
}
append("id", id)
append("ts", timestampString)
append("nonce", nonce)
if !hashString.isEmpty {
append("hash", hashString)
}
if !extra.isEmpty {
append("ext", HawkHelper.escapeExtraHeaderAttribute(extra))
}
append("mac", macString)
// Drop the trailing "\",".
return s.substringToIndex(s.length - 2)
}
class func getSignatureFor(input: NSData, key: NSData) -> String {
return input.hmacSha256WithKey(key).base64EncodedString
}
class func getRequestStringFor(request: NSURLRequest, timestampString: String, nonce: String, hash: String, extra: String) -> String {
let s = NSMutableString(string: "hawk.1.header\n")
func append(line: String) -> Void {
s.appendString(line)
s.appendString("\n")
}
append(timestampString)
append(nonce)
append(request.HTTPMethod?.uppercaseString ?? "GET")
let url = request.URL!
s.appendString(url.path!)
if let query = url.query {
s.appendString("?")
s.appendString(query)
}
if let fragment = url.fragment {
s.appendString("#")
s.appendString(fragment)
}
s.appendString("\n")
append(url.host!)
if let port = url.port {
append(port.stringValue)
} else {
if url.scheme?.lowercaseString == "https" {
append("443")
} else {
append("80")
}
}
append(hash)
if !extra.isEmpty {
append(HawkHelper.escapeExtraString(extra))
} else {
append("")
}
return s as String
}
class func getPayloadHashFor(request: NSURLRequest) -> String {
if let body = request.HTTPBody {
let d = NSMutableData()
func append(s: String) {
let data = s.utf8EncodedData!
d.appendBytes(data.bytes, length: data.length)
}
append("hawk.1.payload\n")
append(getBaseContentTypeFor(request.valueForHTTPHeaderField("Content-Type")))
append("\n") // Trailing newline is specified by Hawk.
d.appendBytes(body.bytes, length: body.length)
append("\n") // Trailing newline is specified by Hawk.
return d.sha256.base64EncodedString
} else {
return ""
}
}
class func getBaseContentTypeFor(contentType: String?) -> String {
if let contentType = contentType {
if let index = find(contentType, ";") {
return contentType.substringToIndex(index).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
} else {
return contentType.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
}
} else {
return "text/plain"
}
}
class func escapeExtraHeaderAttribute(extra: String) -> String {
return extra.stringByReplacingOccurrencesOfString("\\", withString: "\\\\").stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
}
class func escapeExtraString(extra: String) -> String {
return extra.stringByReplacingOccurrencesOfString("\\", withString: "\\\\").stringByReplacingOccurrencesOfString("\n", withString: "\\n")
}
}
| mpl-2.0 | b63556881077b8c7520221ababdade83 | 37.328571 | 147 | 0.61517 | 4.786798 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/PhoneNumberKit/PhoneNumberKit/PartialFormatter.swift | 3 | 16051 | //
// PartialFormatter.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 29/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/// Partial formatter
public class PartialFormatter {
let metadata = Metadata.sharedInstance
let parser = PhoneNumberParser()
let regex = RegularExpressions.sharedInstance
var defaultRegion: String {
didSet {
updateMetadataForDefaultRegion()
}
}
func updateMetadataForDefaultRegion() {
if let regionMetadata = metadata.fetchMetadataForCountry(defaultRegion) {
defaultMetadata = metadata.fetchMainCountryMetadataForCode(regionMetadata.countryCode)
} else {
defaultMetadata = nil
}
currentMetadata = defaultMetadata
}
var defaultMetadata: MetadataTerritory?
var currentMetadata: MetadataTerritory?
var prefixBeforeNationalNumber = String()
var shouldAddSpaceAfterNationalPrefix = false
var withPrefix = true
//MARK: Status
public var currentRegion: String {
get {
return currentMetadata?.codeID ?? defaultRegion
}
}
//MARK: Lifecycle
/**
Initialise a partial formatter with the default region
- returns: PartialFormatter object
*/
public convenience init() {
let defaultRegion = PhoneNumberKit().defaultRegionCode()
self.init(defaultRegion: defaultRegion)
}
/**
Inits a partial formatter with a custom region
- parameter region: ISO 639 compliant region code.
- returns: PartialFormatter object
*/
public init(defaultRegion: String, withPrefix: Bool = true) {
self.defaultRegion = defaultRegion
updateMetadataForDefaultRegion()
self.withPrefix = withPrefix
}
/**
Formats a partial string (for use in TextField)
- parameter rawNumber: Unformatted phone number string
- returns: Formatted phone number string.
*/
public func formatPartial(rawNumber: String) -> String {
// Always reset variables with each new raw number
resetVariables()
// Check if number is valid for parsing, if not return raw
guard isValidRawNumber(rawNumber) else {
return rawNumber
}
// Determine if number is valid by trying to instantiate a PhoneNumber object with it
let iddFreeNumber = extractIDD(rawNumber)
var nationalNumber = parser.normalizePhoneNumber(iddFreeNumber)
if prefixBeforeNationalNumber.characters.count > 0 {
nationalNumber = extractCountryCallingCode(nationalNumber)
}
nationalNumber = extractNationalPrefix(nationalNumber)
if let formats = availableFormats(nationalNumber) {
if let formattedNumber = applyFormat(nationalNumber, formats: formats) {
nationalNumber = formattedNumber
}
else {
for format in formats {
if let template = createFormattingTemplate(format, rawNumber: nationalNumber) {
nationalNumber = applyFormattingTemplate(template, rawNumber: nationalNumber)
break
}
}
}
}
var finalNumber = String()
if prefixBeforeNationalNumber.characters.count > 0 {
finalNumber.appendContentsOf(prefixBeforeNationalNumber)
}
if shouldAddSpaceAfterNationalPrefix && prefixBeforeNationalNumber.characters.count > 0 && prefixBeforeNationalNumber.characters.last != PhoneNumberConstants.separatorBeforeNationalNumber.characters.first {
finalNumber.appendContentsOf(PhoneNumberConstants.separatorBeforeNationalNumber)
}
if nationalNumber.characters.count > 0 {
finalNumber.appendContentsOf(nationalNumber)
}
if finalNumber.characters.last == PhoneNumberConstants.separatorBeforeNationalNumber.characters.first {
finalNumber = finalNumber.substringToIndex(finalNumber.endIndex.predecessor())
}
return finalNumber
}
//MARK: Formatting Functions
internal func resetVariables() {
currentMetadata = defaultMetadata
prefixBeforeNationalNumber = String()
shouldAddSpaceAfterNationalPrefix = false
}
//MARK: Formatting Tests
internal func isValidRawNumber(rawNumber: String) -> Bool {
do {
// In addition to validPhoneNumberPattern,
// accept any sequence of digits and whitespace, prefixed or not by a plus sign
let validPartialPattern = "[++]?(\\s*\\d)+\\s*$|\(PhoneNumberPatterns.validPhoneNumberPattern)"
let validNumberMatches = try regex.regexMatches(validPartialPattern, string: rawNumber)
let validStart = regex.stringPositionByRegex(PhoneNumberPatterns.validStartPattern, string: rawNumber)
if validNumberMatches.count == 0 || validStart != 0 {
return false
}
}
catch {
return false
}
return true
}
internal func isNanpaNumberWithNationalPrefix(rawNumber: String) -> Bool {
if currentMetadata?.countryCode != 1 {
return false
}
return (rawNumber.characters.first == "1" && String(rawNumber.characters.startIndex.advancedBy(1)) != "0" && String(rawNumber.characters.startIndex.advancedBy(1)) != "1")
}
func isFormatEligible(format: MetadataPhoneNumberFormat) -> Bool {
guard let phoneFormat = format.format else {
return false
}
do {
let validRegex = try regex.regexWithPattern(PhoneNumberPatterns.eligibleAsYouTypePattern)
if validRegex.firstMatchInString(phoneFormat, options: [], range: NSMakeRange(0, phoneFormat.characters.count)) != nil {
return true
}
}
catch {}
return false
}
//MARK: Formatting Extractions
func extractIDD(rawNumber: String) -> String {
var processedNumber = rawNumber
do {
if let internationalPrefix = currentMetadata?.internationalPrefix {
let prefixPattern = String(format: PhoneNumberPatterns.iddPattern, arguments: [internationalPrefix])
let matches = try regex.matchedStringByRegex(prefixPattern, string: rawNumber)
if let m = matches.first {
let startCallingCode = m.characters.count
let index = rawNumber.startIndex.advancedBy(startCallingCode)
processedNumber = rawNumber.substringFromIndex(index)
prefixBeforeNationalNumber = rawNumber.substringToIndex(index)
}
}
}
catch {
return processedNumber
}
return processedNumber
}
func extractNationalPrefix(rawNumber: String) -> String {
var processedNumber = rawNumber
var startOfNationalNumber: Int = 0
if isNanpaNumberWithNationalPrefix(rawNumber) {
prefixBeforeNationalNumber.appendContentsOf("1 ")
}
else {
do {
if let nationalPrefix = currentMetadata?.nationalPrefixForParsing {
let nationalPrefixPattern = String(format: PhoneNumberPatterns.nationalPrefixParsingPattern, arguments: [nationalPrefix])
let matches = try regex.matchedStringByRegex(nationalPrefixPattern, string: rawNumber)
if let m = matches.first {
startOfNationalNumber = m.characters.count
}
}
}
catch {
return processedNumber
}
}
let index = rawNumber.startIndex.advancedBy(startOfNationalNumber)
processedNumber = rawNumber.substringFromIndex(index)
prefixBeforeNationalNumber.appendContentsOf(rawNumber.substringToIndex(index))
return processedNumber
}
func extractCountryCallingCode(rawNumber: String) -> String {
var processedNumber = rawNumber
if rawNumber.isEmpty {
return rawNumber
}
var numberWithoutCountryCallingCode = String()
if prefixBeforeNationalNumber.isEmpty == false && prefixBeforeNationalNumber.characters.first != "+" {
prefixBeforeNationalNumber.appendContentsOf(PhoneNumberConstants.separatorBeforeNationalNumber)
}
if let potentialCountryCode = self.parser.extractPotentialCountryCode(rawNumber, nationalNumber: &numberWithoutCountryCallingCode) where potentialCountryCode != 0 {
processedNumber = numberWithoutCountryCallingCode
currentMetadata = metadata.fetchMainCountryMetadataForCode(potentialCountryCode)
let potentialCountryCodeString = String(potentialCountryCode)
prefixBeforeNationalNumber.appendContentsOf(potentialCountryCodeString)
prefixBeforeNationalNumber.appendContentsOf(" ")
}
else if withPrefix == false && prefixBeforeNationalNumber.isEmpty {
let potentialCountryCodeString = String(currentMetadata?.countryCode)
prefixBeforeNationalNumber.appendContentsOf(potentialCountryCodeString)
prefixBeforeNationalNumber.appendContentsOf(" ")
}
return processedNumber
}
func availableFormats(rawNumber: String) -> [MetadataPhoneNumberFormat]? {
var tempPossibleFormats = [MetadataPhoneNumberFormat]()
var possibleFormats = [MetadataPhoneNumberFormat]()
if let metadata = currentMetadata {
let formatList = metadata.numberFormats
for format in formatList {
if isFormatEligible(format) {
tempPossibleFormats.append(format)
if let leadingDigitPattern = format.leadingDigitsPatterns?.last {
if (regex.stringPositionByRegex(leadingDigitPattern, string: String(rawNumber)) == 0) {
possibleFormats.append(format)
}
}
else {
if (regex.matchesEntirely(format.pattern, string: String(rawNumber))) {
possibleFormats.append(format)
}
}
}
}
if possibleFormats.count == 0 {
possibleFormats.appendContentsOf(tempPossibleFormats)
}
return possibleFormats
}
return nil
}
func applyFormat(rawNumber: String, formats: [MetadataPhoneNumberFormat]) -> String? {
for format in formats {
if let pattern = format.pattern, let formatTemplate = format.format {
let patternRegExp = String(format: PhoneNumberPatterns.formatPattern, arguments: [pattern])
do {
let matches = try regex.regexMatches(patternRegExp, string: rawNumber)
if matches.count > 0 {
if let nationalPrefixFormattingRule = format.nationalPrefixFormattingRule {
let separatorRegex = try regex.regexWithPattern(PhoneNumberPatterns.prefixSeparatorPattern)
let nationalPrefixMatches = separatorRegex.matchesInString(nationalPrefixFormattingRule, options: [], range: NSMakeRange(0, nationalPrefixFormattingRule.characters.count))
if nationalPrefixMatches.count > 0 {
shouldAddSpaceAfterNationalPrefix = true
}
}
let formattedNumber = regex.replaceStringByRegex(pattern, string: rawNumber, template: formatTemplate)
return formattedNumber
}
}
catch {
}
}
}
return nil
}
func createFormattingTemplate(format: MetadataPhoneNumberFormat, rawNumber: String) -> String? {
guard var numberPattern = format.pattern, let numberFormat = format.format else {
return nil
}
guard numberPattern.rangeOfString("|") == nil else {
return nil
}
do {
let characterClassRegex = try regex.regexWithPattern(PhoneNumberPatterns.characterClassPattern)
var nsString = numberPattern as NSString
var stringRange = NSMakeRange(0, nsString.length)
numberPattern = characterClassRegex.stringByReplacingMatchesInString(numberPattern, options: [], range: stringRange, withTemplate: "\\\\d")
let standaloneDigitRegex = try regex.regexWithPattern(PhoneNumberPatterns.standaloneDigitPattern)
nsString = numberPattern as NSString
stringRange = NSMakeRange(0, nsString.length)
numberPattern = standaloneDigitRegex.stringByReplacingMatchesInString(numberPattern, options: [], range: stringRange, withTemplate: "\\\\d")
if let tempTemplate = getFormattingTemplate(numberPattern, numberFormat: numberFormat, rawNumber: rawNumber) {
if let nationalPrefixFormattingRule = format.nationalPrefixFormattingRule {
let separatorRegex = try regex.regexWithPattern(PhoneNumberPatterns.prefixSeparatorPattern)
let nationalPrefixMatch = separatorRegex.firstMatchInString(nationalPrefixFormattingRule, options: [], range: NSMakeRange(0, nationalPrefixFormattingRule.characters.count))
if nationalPrefixMatch != nil {
shouldAddSpaceAfterNationalPrefix = true
}
}
return tempTemplate
}
}
catch { }
return nil
}
func getFormattingTemplate(numberPattern: String, numberFormat: String, rawNumber: String) -> String? {
do {
let matches = try regex.matchedStringByRegex(numberPattern, string: PhoneNumberConstants.longPhoneNumber)
if let match = matches.first {
if match.characters.count < rawNumber.characters.count {
return nil
}
var template = regex.replaceStringByRegex(numberPattern, string: match, template: numberFormat)
template = regex.replaceStringByRegex("9", string: template, template: PhoneNumberConstants.digitPlaceholder)
return template
}
}
catch {
}
return nil
}
func applyFormattingTemplate(template: String, rawNumber: String) -> String {
var rebuiltString = String()
var rebuiltIndex = 0
for character in template.characters {
if character == PhoneNumberConstants.digitPlaceholder.characters.first {
if rebuiltIndex < rawNumber.characters.count {
let nationalCharacterIndex = rawNumber.startIndex.advancedBy(rebuiltIndex)
rebuiltString.append(rawNumber[nationalCharacterIndex])
rebuiltIndex += 1
}
}
else {
if rebuiltIndex < rawNumber.characters.count {
rebuiltString.append(character)
}
}
}
if rebuiltIndex < rawNumber.characters.count {
let nationalCharacterIndex = rawNumber.startIndex.advancedBy(rebuiltIndex)
let remainingNationalNumber: String = rawNumber.substringFromIndex(nationalCharacterIndex)
rebuiltString.appendContentsOf(remainingNationalNumber)
}
rebuiltString = rebuiltString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return rebuiltString
}
}
| apache-2.0 | 7b94b0c27ffe16864983b99ca541e858 | 41.120735 | 215 | 0.625935 | 6.25897 | false | false | false | false |
jensmeder/DarkLightning | Sources/Daemon/Sources/Messages/TCPMessage.swift | 1 | 2347 | /**
*
* DarkLightning
*
*
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Jens Meder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
internal final class TCPMessage: DataDecoding {
private let tcpMode: Memory<Bool>
private let delegate: DeviceDelegate
private let devices: Devices
private let deviceID: Int
private let queue: DispatchQueue
// MARK: Init
internal convenience init(tcpMode: Memory<Bool>, delegate: DeviceDelegate, devices: Devices, deviceID: Int) {
self.init(
tcpMode: tcpMode,
delegate: delegate,
devices: devices,
deviceID: deviceID,
queue: DispatchQueue.main
)
}
internal required init(tcpMode: Memory<Bool>, delegate: DeviceDelegate, devices: Devices, deviceID: Int, queue: DispatchQueue) {
self.tcpMode = tcpMode
self.delegate = delegate
self.devices = devices
self.deviceID = deviceID
self.queue = queue
}
// MARK: DataDecoding
func decode(data: OOData) {
if tcpMode.rawValue {
if let device = devices.device(withID: deviceID).first {
queue.async {
self.delegate.device(device, didReceiveData: data)
}
}
}
}
}
| mit | 777de36f6ac5d399386ddf35324b9a06 | 33.014493 | 132 | 0.677887 | 4.35436 | false | false | false | false |
to4iki/OctavKit | OctavKit/Request/Request.swift | 1 | 1634 | import Foundation
protocol Request {
associatedtype Response
var baseURL: URL { get }
var path: String { get }
var method: HTTPMethod { get }
var parameters: Any? { get }
func response(from data: Data, urlResponse: URLResponse) throws -> Response
}
extension Request {
var baseURL: URL {
return URL(string: "https://api.builderscon.io/v2")!
}
var parameters: Any? {
return ParamtersHolder.dictionary
}
}
extension Request {
func buildURLRequest() -> URLRequest {
let url = baseURL.appendingPathComponent(path)
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)
switch method {
case .get:
let dictionary = parameters as? [String: Any]
let queryItems = dictionary?.map { (key: String, value: Any) in
URLQueryItem(name: key, value: String(describing: value))
}
components?.queryItems = queryItems
default:
fatalError("Unsupported method \(method)")
}
var urlRequest = URLRequest(url: url)
urlRequest.url = components?.url
urlRequest.httpMethod = method.rawValue
return urlRequest
}
}
extension Request where Response: Decodable {
func response(from data: Data, urlResponse: URLResponse) throws -> Response {
if case (200..<300)? = (urlResponse as? HTTPURLResponse)?.statusCode {
return try JSONDecoder().decode(Response.self, from: data)
} else {
// TODO: decode error object
throw OctavAPIError.apiError(NSError())
}
}
}
| mit | 1db4e042a86a2a1160f983fc7a5820af | 29.830189 | 81 | 0.619951 | 4.777778 | false | false | false | false |
marmelroy/PhoneNumberKit | examples/AsYouType/Sample/ViewController.swift | 1 | 2160 | //
// ViewController.swift
// Sample
//
// Created by Roy Marmelstein on 27/09/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import ContactsUI
import Foundation
import PhoneNumberKit
import UIKit
class ViewController: UIViewController, CNContactPickerDelegate {
@IBOutlet var textField: PhoneNumberTextField!
@IBOutlet var withPrefixSwitch: UISwitch!
@IBOutlet var withFlagSwitch: UISwitch!
@IBOutlet var withExamplePlaceholderSwitch: UISwitch!
@IBOutlet var withDefaultPickerUISwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Country picker is only available on >iOS 11.0
if #available(iOS 11.0, *) {
PhoneNumberKit.CountryCodePicker.commonCountryCodes = ["US", "CA", "MX", "AU", "GB", "DE"]
}
self.textField.becomeFirstResponder()
self.withPrefixSwitch.isOn = self.textField.withPrefix
self.withFlagSwitch.isOn = self.textField.withFlag
self.withExamplePlaceholderSwitch.isOn = self.textField.withExamplePlaceholder
if #available(iOS 11.0, *) {
self.withDefaultPickerUISwitch.isOn = self.textField.withDefaultPickerUI
}
if #available(iOS 13.0, *) {
self.view.backgroundColor = .systemBackground
}
}
@IBAction func didTapView(_ sender: Any) {
self.textField.resignFirstResponder()
}
@IBAction func withPrefixDidChange(_ sender: Any) {
self.textField.withPrefix = self.withPrefixSwitch.isOn
}
@IBAction func withFlagDidChange(_ sender: Any) {
self.textField.withFlag = self.withFlagSwitch.isOn
}
@IBAction func withExamplePlaceholderDidChange(_ sender: Any) {
self.textField.withExamplePlaceholder = self.withExamplePlaceholderSwitch.isOn
if !self.textField.withExamplePlaceholder {
self.textField.placeholder = "Enter phone number"
}
}
@IBAction func withDefaultPickerUIDidChange(_ sender: Any) {
if #available(iOS 11.0, *) {
self.textField.withDefaultPickerUI = self.withDefaultPickerUISwitch.isOn
}
}
}
| mit | 7935e13920436d27867f538c107f4748 | 32.215385 | 102 | 0.680871 | 4.554852 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/ViewController/ImageSelectorTableViewController.swift | 1 | 5002 | //
// ImageSelectorTableViewController.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/11.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class ImageSelectorTableViewController: AddAssetTableViewController, AssetSelectorDelegate {
var object: EntryImageItem!
var entry: BaseEntry!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.title = NSLocalizedString("Photos", comment: "Photos")
self.multiSelect = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
/*
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
*/
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
let user = (UIApplication.sharedApplication().delegate as! AppDelegate).currentUser!
switch indexPath.section {
case Section.Buttons.rawValue:
if let cameraButton = cell.viewWithTag(1) as? UIButton {
cameraButton.enabled = self.blog.canUpload(user: user)
}
if let libraryButton = cell.viewWithTag(2) as? UIButton {
libraryButton.enabled = self.blog.canUpload(user: user)
}
if let assetListButton = cell.viewWithTag(3) as? UIButton {
if self.entry is Entry {
assetListButton.enabled = self.blog.canListAssetForEntry(user: user)
} else {
assetListButton.enabled = self.blog.canListAssetForPage(user: user)
}
}
return cell
case Section.Items.rawValue:
return cell
default:
break
}
// Configure the cell...
return UITableViewCell()
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
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 to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@IBAction override func assetListButtonPushed(sender: UIButton) {
let vc = AssetSelectorTableViewController()
let nav = UINavigationController(rootViewController: vc)
vc.blog = self.blog
vc.delegate = self
self.presentViewController(nav, animated: true, completion: nil)
}
func AssetSelectorDone(controller: AssetSelectorTableViewController, asset: Asset) {
self.delegate?.AddAssetDone(self, asset: asset)
}
}
| mit | b76436a9c43486a5ff91ff29072eff4f | 34.971223 | 157 | 0.6512 | 5.382131 | false | false | false | false |
dcunited001/Spectra | Pod/Classes/InflightResourceManager.swift | 1 | 980 | //
// InflightResourcesManager.swift
// Pods
//
// Created by David Conner on 10/6/15.
//
let kInflightResourceCountDefault = 3 // three is magic number
public class InflightResourceManager {
public var inflightResourceCount:Int
public var index:Int = 0
public var inflightResourceSemaphore:dispatch_semaphore_t
init(inflightResourceCount: Int = kInflightResourceCountDefault) {
self.inflightResourceCount = inflightResourceCount
self.inflightResourceSemaphore = dispatch_semaphore_create(self.inflightResourceCount)
}
public func next() {
dispatch_semaphore_signal(inflightResourceSemaphore)
index = (index + 1) % inflightResourceCount
}
public func wait() {
dispatch_semaphore_wait(inflightResourceSemaphore, DISPATCH_TIME_FOREVER)
}
deinit {
for _ in 0...inflightResourceCount-1 {
dispatch_semaphore_signal(inflightResourceSemaphore)
}
}
}
| mit | 0b741a7ae2464f523e5bf43f7093898d | 27.823529 | 94 | 0.696939 | 4.454545 | false | false | false | false |
readium/r2-streamer-swift | r2-streamer-swift/Parser/PDF/PDFParser.swift | 1 | 2972 | //
// PDFParser.swift
// r2-streamer-swift
//
// Created by Mickaël Menu on 05.03.19.
//
// Copyright 2019 Readium Foundation. All rights reserved.
// Use of this source code is governed by a BSD-style license which is detailed
// in the LICENSE file present in the project repository where this source code is maintained.
//
import Foundation
import CoreGraphics
import R2Shared
/// Errors thrown during the parsing of the PDF.
public enum PDFParserError: Error {
// The file at 'path' is missing from the container.
case missingFile(path: String)
// Failed to open the PDF
case openFailed
// The PDF is encrypted with a password. This is not supported right now.
case fileEncryptedWithPassword
// The LCP for PDF Package is malformed.
case invalidLCPDF
}
public final class PDFParser: PublicationParser, Loggable {
enum Error: Swift.Error {
case fileNotReadable
}
private let pdfFactory: PDFDocumentFactory
public init(pdfFactory: PDFDocumentFactory = DefaultPDFDocumentFactory()) {
self.pdfFactory = pdfFactory
}
public func parse(asset: PublicationAsset, fetcher: Fetcher, warnings: WarningLogger?) throws -> Publication.Builder? {
guard asset.mediaType() == .pdf else {
return nil
}
let readingOrder = fetcher.links.filter(byMediaType: .pdf)
guard let firstLink = readingOrder.first else {
throw PDFDocumentError.openFailed
}
let resource = fetcher.get(firstLink)
let document = try pdfFactory.open(resource: resource, password: nil)
let authors = Array(ofNotNil: document.author.map { Contributor(name: $0) })
return Publication.Builder(
mediaType: .pdf,
format: .pdf,
manifest: Manifest(
metadata: Metadata(
identifier: document.identifier,
title: document.title ?? asset.name,
authors: authors,
numberOfPages: document.pageCount
),
readingOrder: readingOrder,
tableOfContents: document.tableOfContents.links(withDocumentHREF: firstLink.href)
),
fetcher: fetcher,
servicesBuilder: PublicationServicesBuilder(
cover: document.cover.map(GeneratedCoverService.makeFactory(cover:)),
positions: PDFPositionsService.makeFactory()
)
)
}
@available(*, unavailable, message: "Use `init(pdfFactory:)` instead")
public convenience init(parserType: PDFFileParser.Type) {
self.init(pdfFactory: PDFFileParserFactory(parserType: parserType))
}
@available(*, unavailable, message: "Use an instance of `Streamer` to open a `Publication`")
public static func parse(at url: URL) throws -> (PubBox, PubParsingCallback) {
fatalError("Not available")
}
}
| bsd-3-clause | 57865add6c1d4de96a6853658d332f3e | 33.546512 | 123 | 0.643218 | 4.693523 | false | false | false | false |
Eonil/HomeworkApp1 | Modules/Monolith/CancellableBlockingIO/Sources/HTTP.ProgressiveDownloading.swift | 3 | 4878 | ////
//// HTTPProgressiveDownload.swift
//// EonilBlockingAsynchronousIO
////
//// Created by Hoon H. on 11/7/14.
//// Copyright (c) 2014 Eonil. All rights reserved.
////
//
//import Foundation
//
//
//
//
//extension HTTP {
//
//
// /// Progressive downloading context.
// ///
// /// 1. Call `progress()` until it returns `Done`.
// /// 2. Call `complete()` to query final state.
// ///
// /// Step 1 can be omitted if you don't want a progress.
// /// Those calls will be blocked using semaphores until meaningful result
// /// comes up.
// ///
// /// This uses `NSURLSession` internally.
// public final class ProgressiveDownloading {
//
// public enum Progress {
// case Continue(range:Range<Int64>, total:Range<Int64>?)
// case Done
// }
//
// public enum Complete {
// case Cancel
// case Error(message:String)
// case Ready(file:NSURL)
// }
//
// public let progress:()->Progress
// public let complete:()->Complete
// public let cancel:()->()
//
// init(cancellation:Cancellation, address:NSURL) {
// let pal1 = Palette()
// var fcmpl1 = false
//
// let conf1 = nil as NSURLSessionConfiguration?
// let dele1 = DownloadController(pal1)
// let sess1 = NSURLSession(configuration: conf1,delegate: dele1, delegateQueue: defaultDownloadingQueue())
// let task1 = sess1.downloadTaskWithURL(address)
//
// progress = { ()->Progress in
// precondition(fcmpl1 == false, "You cannot call this function for once completed downloading.")
// let v1 = pal1.progressChannel.wait()
// return v1
// }
// complete = { ()->Complete in
// let v1 = pal1.completionChannel.wait()
// fcmpl1 = true
// cancellation.unsetObserver()
// return v1
// }
//
// cancel = {
// task1.cancel()
// }
//
//
// cancellation.setObserver(cancel)
// task1.resume()
// }
// }
//}
//
//
//
//
//
//
//
//
//
//
//
//extension HTTP.ProgressiveDownloading.Complete: Printable {
// public var ready:NSURL? {
// get {
// switch self {
// case let .Ready(s): return s
// default: return nil
// }
// }
// }
//
// public var description:String {
// get {
// switch self {
// case Cancel: return "Cancel"
// case let Error(s): return "Error(\(s))"
// case let Ready(s): return "Ready(\(s))"
// }
// }
// }
//}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
///// MARK:
///// MARK: Implementation Details
///// MARK:
//
//
//
//private class Palette {
// typealias Progress = HTTP.ProgressiveDownloading.Progress
// typealias Complete = HTTP.ProgressiveDownloading.Complete
//
// let progressChannel = Channel<Progress>()
// let completionChannel = Channel<Complete>()
//}
//
//
//
//
//private func defaultDownloadingQueue() -> NSOperationQueue {
// struct Slot {
// static let value = NSOperationQueue()
// }
// Slot.value.qualityOfService = NSQualityOfService.Background
// return Slot.value
//}
//
//
//
//
///// All the delegate methods should be called from another thread.
///// Otherwise, it's deadlock.
//private final class DownloadController: NSObject, NSURLSessionDelegate, NSURLSessionDownloadDelegate {
// typealias Progress = HTTP.ProgressiveDownloading.Progress
// typealias Complete = HTTP.ProgressiveDownloading.Complete
//
// let palette:Palette
// init(_ palette:Palette) {
// self.palette = palette
// }
// private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
// self.palette.progressChannel.signal(Progress.Done)
// self.palette.completionChannel.signal(Complete.Ready(file: location))
// }
// private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
//
// }
// private func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
// let r1 = Range<Int64>(start: totalBytesWritten-bytesWritten, end: totalBytesWritten)
// let r2 = totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown ? nil : Range<Int64>(start: 0, end: totalBytesExpectedToWrite) as Range<Int64>?
// self.palette.progressChannel.signal(Progress.Continue(range: r1, total: r2))
// }
// private func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
// self.palette.progressChannel.signal(Progress.Done)
// self.palette.completionChannel.signal(Complete.Error(message: error == nil ? "Unknown error" : error!.description))
// }
// private func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
// self.palette.progressChannel.signal(Progress.Done)
// self.palette.completionChannel.signal(Complete.Error(message: error == nil ? "Unknown error" : error!.description))
// }
//}
//
//
| mit | 4107c740436d7ed6bc7656c9852b33c8 | 24.274611 | 185 | 0.669537 | 3.181996 | false | false | false | false |
stripe/stripe-ios | StripeApplePay/StripeApplePay/Source/PaymentsCore/API/Models/BillingDetails.swift | 1 | 2259 | //
// BillingDetails.swift
// StripeApplePay
//
// Created by David Estes on 7/15/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
extension StripeAPI {
/// Billing information associated with a `STPPaymentMethod` that may be used or required by particular types of payment methods.
/// - seealso: https://stripe.com/docs/api/payment_methods/object#payment_method_object-billing_details
public struct BillingDetails: UnknownFieldsCodable {
/// Billing address.
public var address: Address?
/// The billing address, a property sent in a PaymentMethod response
public struct Address: UnknownFieldsCodable {
/// The first line of the user's street address (e.g. "123 Fake St")
public var line1: String?
/// The apartment, floor number, etc of the user's street address (e.g. "Apartment 1A")
public var line2: String?
/// The city in which the user resides (e.g. "San Francisco")
public var city: String?
/// The state in which the user resides (e.g. "CA")
public var state: String?
/// The postal code in which the user resides (e.g. "90210")
public var postalCode: String?
/// The ISO country code of the address (e.g. "US")
public var country: String?
public var _additionalParametersStorage: NonEncodableParameters?
public var _allResponseFieldsStorage: NonEncodableParameters?
}
/// Email address.
public var email: String?
/// Full name.
public var name: String?
/// Billing phone number (including extension).
public var phone: String?
public var _additionalParametersStorage: NonEncodableParameters?
public var _allResponseFieldsStorage: NonEncodableParameters?
}
}
extension StripeAPI.BillingDetails.Address {
init(
contact: StripeContact
) {
self.city = contact.city
self.country = contact.country
self.line1 = contact.line1
self.line2 = contact.line2
self.postalCode = contact.postalCode
self.state = contact.state
}
}
| mit | ade10a4d18d099b0618271df9ca8ea77 | 32.701493 | 133 | 0.638175 | 4.733753 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICore/Source/Elements/TextOrDropdownElement.swift | 1 | 1214 | //
// TextOrDropdownElement.swift
// StripeUICore
//
// Created by Nick Porter on 9/2/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
/// Describes an element that is either a text or dropdown element
@_spi(STP) public protocol TextOrDropdownElement: Element {
/// The raw data for the element, e.g. the text of a textfield or raw data of a dropdown item
var rawData: String { get }
/// Sets the raw data for this element
func setRawData(_ rawData: String)
}
// MARK: Conformance
extension TextFieldElement: TextOrDropdownElement {
public var rawData: String {
return text
}
public func setRawData(_ rawData: String) {
setText(rawData)
}
}
extension DropdownFieldElement: TextOrDropdownElement {
public var rawData: String {
return items[selectedIndex].rawData
}
public func setRawData(_ rawData: String) {
guard let itemIndex = items.firstIndex(where: {$0.rawData.lowercased() == rawData.lowercased()
|| $0.pickerDisplayName.lowercased() == rawData.lowercased()}) else {
return
}
select(index: itemIndex)
}
}
| mit | d08faf49f76cc95112528ff8021b4476 | 24.270833 | 102 | 0.645507 | 4.379061 | false | false | false | false |
nkirby/Humber | Humber/_src/Theming/ThemeElements.swift | 1 | 631 | // =======================================================
// Humber
// Nathaniel Kirby
// =======================================================
import UIKit
internal enum ColorType {
case PrimaryTextColor
case SecondaryTextColor
case DisabledTextColor
case TintColor
case ViewBackgroundColor
case CellBackgroundColor
case DividerColor
}
internal enum FontType {
case Bold(CGFloat)
case Regular(CGFloat)
case Italic(CGFloat)
}
internal protocol Themable {
var name: String { get }
func color(type type: ColorType) -> UIColor
func font(type type: FontType) -> UIFont
}
| mit | 9009b41d5e8579cd94856f57fcac34bb | 20.758621 | 58 | 0.575277 | 5.486957 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/AlamofireObjectMapperTests/AlamofireObjectMapperTests.swift | 2 | 9431 | //
// AlamofireObjectMapperTests.swift
// AlamofireObjectMapperTests
//
// Created by Tristan Himmelman on 2015-04-30.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Tristan Himmelman
//
// 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 XCTest
import ObjectMapper
import Alamofire
import AlamofireObjectMapper
class AlamofireObjectMapperTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testResponseObject() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseObject { (response: Response<WeatherResponse, NSError>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
func testResponseObjectWithKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseObject("data") { (response: Response<WeatherResponse, NSError>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
func testResponseObjectWithNestedKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/97231a04e6e4970612efcc0b7e0c125a83e3de6e/sample_keypath_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseObject("response.data") { (response: Response<WeatherResponse, NSError>) in
expectation.fulfill()
let mappedObject = response.result.value
XCTAssertNotNil(mappedObject, "Response should not be nil")
XCTAssertNotNil(mappedObject?.location, "Location should not be nil")
XCTAssertNotNil(mappedObject?.threeDayForecast, "ThreeDayForcast should not be nil")
for forecast in mappedObject!.threeDayForecast! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
func testResponseArray() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/f583be1121dbc5e9b0381b3017718a70c31054f7/sample_array_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseArray { (response: Response<[Forecast], NSError>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
func testArrayResponseArrayWithKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/d8bb95982be8a11a2308e779bb9a9707ebe42ede/sample_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseArray("three_day_forecast") { (response: Response<[Forecast], NSError>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
func testArrayResponseArrayWithNestedKeyPath() {
// This is an example of a functional test case.
let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/97231a04e6e4970612efcc0b7e0c125a83e3de6e/sample_keypath_json"
let expectation = expectationWithDescription("\(URL)")
Alamofire.request(.GET, URL).responseArray("response.data.three_day_forecast") { (response: Response<[Forecast], NSError>) in
expectation.fulfill()
let mappedArray = response.result.value
XCTAssertNotNil(mappedArray, "Response should not be nil")
for forecast in mappedArray! {
XCTAssertNotNil(forecast.day, "day should not be nil")
XCTAssertNotNil(forecast.conditions, "conditions should not be nil")
XCTAssertNotNil(forecast.temperature, "temperature should not be nil")
}
}
waitForExpectationsWithTimeout(10) { (error: NSError?) -> Void in
XCTAssertNil(error, "\(error)")
}
}
}
class WeatherResponse: Mappable {
var location: String?
var threeDayForecast: [Forecast]?
required init?(_ map: Map){
}
func mapping(map: Map) {
location <- map["location"]
threeDayForecast <- map["three_day_forecast"]
}
}
class Forecast: Mappable {
var day: String?
var temperature: Int?
var conditions: String?
required init?(_ map: Map){
}
func mapping(map: Map) {
day <- map["day"]
temperature <- map["temperature"]
conditions <- map["conditions"]
}
}
| mit | 1961267bdc317221877b70060dadc520 | 40.364035 | 153 | 0.648924 | 4.955859 | false | true | false | false |
ContinuousLearning/PokemonKit | Carthage/Checkouts/PromiseKit/Sources/Promise.swift | 1 | 15125 | import Foundation.NSError
public let PMKOperationQueue = NSOperationQueue()
public enum CatchPolicy {
case AllErrors
case AllErrorsExceptCancellation
}
/**
A promise represents the future value of a task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or with an `NSError` to become rejected.
@see [PromiseKit `then` Guide](http://promisekit.org/then/)
@see [PromiseKit Chaining Guide](http://promisekit.org/chaining/)
*/
public class Promise<T> {
let state: State
/**
Create a new pending promise.
Use this method when wrapping asynchronous systems that do *not* use
promises so that they can be involved in promise chains.
Don’t use this method if you already have promises! Instead, just return
your promise!
The closure you pass is executed immediately on the calling thread.
func fetchKitten() -> Promise<UIImage> {
return Promise { fulfill, reject in
KittenFetcher.fetchWithCompletionBlock({ img, err in
if err == nil {
fulfill(img)
} else {
reject(err)
}
})
}
}
@param resolvers The provided closure is called immediately. Inside,
execute your asynchronous system, calling fulfill if it suceeds and
reject for any errors.
@return A new promise.
@warning *Note* If you are wrapping a delegate-based system, we recommend
to use instead: defer
@see http://promisekit.org/sealing-your-own-promises/
@see http://promisekit.org/wrapping-delegation/
*/
public convenience init(@noescape resolvers: (fulfill: (T) -> Void, reject: (NSError) -> Void) -> Void) {
self.init(sealant: { sealant in
resolvers(fulfill: sealant.resolve, reject: sealant.resolve)
})
}
/**
Create a new pending promise.
This initializer is convenient when wrapping asynchronous systems that
use common patterns. For example:
func fetchKitten() -> Promise<UIImage> {
return Promise { sealant in
KittenFetcher.fetchWithCompletionBlock(sealant.resolve)
}
}
@see Sealant
@see init(resolvers:)
*/
public init(@noescape sealant: (Sealant<T>) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(Sealant(body: resolve))
}
/**
Create a new fulfilled promise.
*/
public init(_ value: T) {
state = SealedState(resolution: .Fulfilled(value))
}
/**
Create a new rejected promise.
*/
public init(_ error: NSError) {
unconsume(error)
state = SealedState(resolution: .Rejected(error))
}
/**
I’d prefer this to be the designated initializer, but then there would be no
public designated unsealed initializer! Making this convenience would be
inefficient. Not very inefficient, but still it seems distasteful to me.
*/
init(@noescape passthru: ((Resolution) -> Void) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
passthru(resolve)
}
/**
defer_ is convenient for wrapping delegates or larger asynchronous systems.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.defer_()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
@return A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public class func defer_() -> (promise: Promise, fulfill: (T) -> Void, reject: (NSError) -> Void) {
var sealant: Sealant<T>!
let promise = Promise { sealant = $0 }
return (promise, sealant.resolve, sealant.resolve)
}
func pipe(body: (Resolution) -> Void) {
state.get { seal in
switch seal {
case .Pending(let handlers):
handlers.append(body)
case .Resolved(let resolution):
body(resolution)
}
}
}
private convenience init<U>(when: Promise<U>, body: (Resolution, (Resolution) -> Void) -> Void) {
self.init(passthru: { resolve in
when.pipe{ body($0, resolve) }
})
}
/**
The provided block is executed when this Promise is resolved.
If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is fulfilled.
[NSURLConnection GET:url].then(^(NSData *data){
// do something with data
});
@return A new promise that is resolved with the value returned from the provided closure. For example:
[NSURLConnection GET:url].then(^(NSData *data){
return data.length;
}).then(^(NSNumber *number){
//…
});
@see thenInBackground
*/
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> U) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
resolve(.Fulfilled(body(value as! T)))
}
}
}
}
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> Promise<U>) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
body(value as! T).pipe(resolve)
}
}
}
}
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) -> AnyPromise) -> Promise<AnyObject?> {
return Promise<AnyObject?>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
let anypromise = body(value as! T)
anypromise.pipe { obj in
if let error = obj as? NSError {
resolve(.Rejected(error))
} else {
// possibly the value of this promise is a PMKManifold, if so
// calling the objc `value` method will return the first item.
let obj: AnyObject? = anypromise.valueForKey("value")
resolve(.Fulfilled(obj))
}
}
}
}
}
}
/**
The provided closure is executed on the default background queue when this Promise is fulfilled.
This method is provided as a convenience for `then`.
@see then
*/
public func thenInBackground<U>(body: (T) -> U) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
public func thenInBackground<U>(body: (T) -> Promise<U>) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
/**
The provided closure is executed when this Promise is rejected.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
The provided closure always runs on the main queue.
@param policy The default policy does not execute your handler for
cancellation errors. See registerCancellationError for more
documentation.
@param body The handler to execute when this Promise is rejected.
@see registerCancellationError
*/
public func catch_(policy policy: CatchPolicy = .AllErrorsExceptCancellation, _ body: (NSError) -> Void) {
pipe { resolution in
switch resolution {
case .Fulfilled:
break
case .Rejected(let error):
dispatch_async(dispatch_get_main_queue()) {
if policy == .AllErrors || !error.cancelled {
consume(error)
body(error)
}
}
}
}
}
/**
The provided closure is executed when this Promise is rejected giving you
an opportunity to recover from the error and continue the promise chain.
*/
public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (NSError) -> Promise<T>) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
switch resolution {
case .Rejected(let error):
contain_zalgo(q) {
consume(error)
body(error).pipe(resolve)
}
case .Fulfilled:
resolve(resolution)
}
}
}
/**
The provided closure is executed when this Promise is resolved.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is resolved.
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
somePromise().then {
//…
}.finally {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
*/
public func finally(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
contain_zalgo(q) {
body()
resolve(resolution)
}
}
}
/**
@return The value with which this promise was fulfilled or nil if this
promise is not fulfilled.
*/
public var value: T? {
switch state.get() {
case .None:
return nil
case .Some(.Fulfilled(let value)):
return (value as! T)
case .Some(.Rejected):
return nil
}
}
}
/**
Zalgo is dangerous.
Pass as the `on` parameter for a `then`. Causes the handler to be executed
as soon as it is resolved. That means it will be executed on the queue it
is resolved. This means you cannot predict the queue.
In the case that the promise is already resolved the handler will be
executed immediately.
zalgo is provided for libraries providing promises that have good tests
that prove unleashing zalgo is safe. You can also use it in your
application code in situations where performance is critical, but be
careful: read the essay at the provided link to understand the risks.
@see http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
*/
public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil)
/**
Waldo is dangerous.
Waldo is zalgo, unless the current queue is the main thread, in which case
we dispatch to the default background queue.
If your block is likely to take more than a few milliseconds to execute,
then you should use waldo: 60fps means the main thread cannot hang longer
than 17 milliseconds. Don’t contribute to UI lag.
Conversely if your then block is trivial, use zalgo: GCD is not free and
for whatever reason you may already be on the main thread so just do what
you are doing quickly and pass on execution.
It is considered good practice for asynchronous APIs to complete onto the
main thread. Apple do not always honor this, nor do other developers.
However, they *should*. In that respect waldo is a good choice if your
then is going to take a while and doesn’t interact with the UI.
Please note (again) that generally you should not use zalgo or waldo. The
performance gains are neglible and we provide these functions only out of
a misguided sense that library code should be as optimized as possible.
If you use zalgo or waldo without tests proving their correctness you may
unwillingly introduce horrendous, near-impossible-to-trace bugs.
@see zalgo
*/
public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil)
func contain_zalgo(q: dispatch_queue_t, block: () -> Void) {
if q === zalgo {
block()
} else if q === waldo {
if NSThread.isMainThread() {
dispatch_async(dispatch_get_global_queue(0, 0), block)
} else {
block()
}
} else {
dispatch_async(q, block)
}
}
extension Promise {
/**
Creates a rejected Promise with `PMKErrorDomain` and a specified localizedDescription and error code.
*/
public convenience init(error: String, code: Int = PMKUnexpectedError) {
let error = NSError(domain: "PMKErrorDomain", code: code, userInfo: [NSLocalizedDescriptionKey: error])
self.init(error)
}
/**
Promise<Any> is more flexible, and often needed. However Swift won't cast
<T> to <Any> directly. Once that is possible we will deprecate this
function.
*/
public func asAny() -> Promise<Any> {
return Promise<Any>(passthru: pipe)
}
/**
Promise<AnyObject> is more flexible, and often needed. However Swift won't
cast <T> to <AnyObject> directly. Once that is possible we will deprecate
this function.
*/
public func asAnyObject() -> Promise<AnyObject> {
return Promise<AnyObject>(passthru: pipe)
}
/**
Swift (1.2) seems to be much less fussy about Void promises.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
}
extension Promise: CustomDebugStringConvertible {
public var debugDescription: String {
return "Promise: \(state)"
}
}
/**
Firstly can make chains more readable.
Compare:
NSURLConnection.GET(url1).then {
NSURLConnection.GET(url2)
}.then {
NSURLConnection.GET(url3)
}
With:
firstly {
NSURLConnection.GET(url1)
}.then {
NSURLConnection.GET(url2)
}.then {
NSURLConnection.GET(url3)
}
*/
public func firstly<T>(promise: () -> Promise<T>) -> Promise<T> {
return promise()
}
public enum ErrorPolicy {
case AllErrors
case AllErrorsExceptCancellation
}
| mit | c1f2c6d86e7d6cb680a87c1b5722f835 | 30.883966 | 124 | 0.606167 | 4.556226 | false | false | false | false |
WWITDC/Underchess | underchess/UCArenaViewController.swift | 1 | 5223 | //
// UCArenaViewController.swift
// Underchess
//
// Created by Apollonian on 16/2/13.
// Copyright © 2016年 WWITDC. All rights reserved.
//
// MARK: DO NOT Remove Comments in This File
import UIKit
extension UCUserInputError: CustomStringConvertible{
var description:String{
get{
switch self{
case .controlUnownedPiece: return "Control unowned piece"
case .noValidMove: return "No valid move for the selcted piece"
case .needUserSelection: return "Need to select the piece to move by the player"
}
}
}
}
enum UCGamePhase{
case ended, playing, notStarted
}
@objc protocol UCArenaViewControllerDelegate {
@objc optional func endGame()
@objc var base: AnyObject? {get}
@objc optional func didTakeAMove()
}
var newUCArenaViewController = UCArenaViewController()
class UCArenaViewController: UIViewController, UCPieceDataSource, UCPieceViewDelegate {
var needAnimation = true
/// May be Overrided Style with Key: preferedStyle
var pieces : [UCPieceView]?
var arenaView: UCArenaView?
/// false -> player 0(Red); true -> player 1(Green)
public private(set) var boardStatus: [Bool?] = [false,false,nil,true,true]
final var emptySpotIndex: Int! {
return boardStatus.index { $0 == nil }
}
var currentPlayer = false {
willSet {
animateMovablePieces(for: currentPlayer)
}
}
var theOtherPlayer: Bool {
return !currentPlayer
}
var gamingStatus = UCGamePhase.notStarted
var movablePieces = [Int]()
weak var delegate: UCArenaViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .ucBlue
arenaView = UCArenaView(father: view)
arenaView?.dataSource = self
arenaView?.pieceViewDelegate = self
view.addSubview(arenaView!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
arenaView?.performAnimationOnAllPiece((needAnimation) ? .expand : .none)
animateMovablePieces(for: theOtherPlayer)
}
private func setMovablePieces(for player: Bool) {
movablePieces.removeAll()
for i in 0...4 {
if boardStatus[i] == !player && hasValidMove(forPiece: i) {
movablePieces.append(i)
}
}
}
final func animateMovablePieces(for player: Bool){
setMovablePieces(for: player)
if !movablePieces.isEmpty {
arenaView?.setMovablePieces(withTags: movablePieces)
}
}
final func hasValidMove(forPiece selectedIndex: Int) -> Bool{
return !(selectedIndex + emptySpotIndex == 7 || abs(selectedIndex - emptySpotIndex) == 3)
}
final func move(from startIndex: Int, to endIndex: Int){
arenaView?.movePiece(from: startIndex, to: endIndex)
swap(&boardStatus[startIndex], &boardStatus[endIndex])
}
final func hasValidMove(forPlayer player: Bool) -> Bool{
var thisPlayerIndexes = 0, anotherPlayerIndexes = 0
movablePieces.removeAll()
for i in 0...4 {
if boardStatus[i] == player {
thisPlayerIndexes += i
} else if boardStatus[i] != nil {
anotherPlayerIndexes += i
}
}
return !(thisPlayerIndexes == 4 && (anotherPlayerIndexes == 2 || anotherPlayerIndexes == 3))
}
final func touchUpInside(pieceWithIndex touchedIndex: Int) throws {
guard gamingStatus != .ended else { return }
if gamingStatus == .notStarted {
gamingStatus = .playing
}
if boardStatus[touchedIndex] == currentPlayer {
if hasValidMove(forPiece: touchedIndex) {
move(from: touchedIndex, to: emptySpotIndex)
delegate?.didTakeAMove?()
if hasValidMove(forPlayer: theOtherPlayer) {
currentPlayer = theOtherPlayer
} else {
arenaView?.setMovablePieces(withTags: [])
gamingStatus = .ended
if let delegate = delegate, let endGame = delegate.endGame {
endGame()
} else {
startNew()
}
}
} else {
throw UCUserInputError.noValidMove
}
} else {
throw UCUserInputError.controlUnownedPiece
}
}
func get(error: UCUserInputError) {}
final func startNew() {
arenaView?.dataSource = nil
arenaView?.pieceViewDelegate = nil
pieces = nil
arenaView = nil
if let window = delegate?.base as? UIWindow {
window.rootViewController = newUCArenaViewController
} else if let viewController = delegate?.base as? UIViewController{
viewController.show(newUCArenaViewController, sender: nil)
}
self.delegate = nil
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
arenaView?.setupAgain(in: CGRect(origin: .zero, size: size))
}
}
| unlicense | c805d98cb93b094980b297010d25cb51 | 31.02454 | 112 | 0.610728 | 4.554974 | false | false | false | false |
airbnb/lottie-ios | Sources/Public/LottieConfiguration.swift | 2 | 5055 | // Created by Cal Stephens on 12/13/21.
// Copyright © 2021 Airbnb Inc. All rights reserved.
// MARK: - LottieConfiguration
/// Global configuration options for Lottie animations
public struct LottieConfiguration: Hashable {
// MARK: Lifecycle
public init(
renderingEngine: RenderingEngineOption = .automatic,
decodingStrategy: DecodingStrategy = .dictionaryBased)
{
self.renderingEngine = renderingEngine
self.decodingStrategy = decodingStrategy
}
// MARK: Public
/// The global configuration of Lottie,
/// which applies to all `LottieAnimationView`s by default.
public static var shared = LottieConfiguration()
/// The rendering engine implementation to use when displaying an animation
/// - Defaults to `RenderingEngineOption.automatic`, which uses the
/// Core Animation rendering engine for supported animations, and
/// falls back to using the Main Thread rendering engine for
/// animations that use features not supported by the Core Animation engine.
public var renderingEngine: RenderingEngineOption
/// The decoding implementation to use when parsing an animation JSON file
public var decodingStrategy: DecodingStrategy
}
// MARK: - RenderingEngineOption
public enum RenderingEngineOption: Hashable {
/// Uses the Core Animation engine for supported animations, and falls back to using
/// the Main Thread engine for animations that use features not supported by the
/// Core Animation engine.
case automatic
/// Uses the specified rendering engine
case specific(RenderingEngine)
// MARK: Public
/// The Main Thread rendering engine, which supports all Lottie features
/// but runs on the main thread, which comes with some CPU overhead and
/// can cause the animation to play at a low framerate when the CPU is busy.
public static var mainThread: RenderingEngineOption { .specific(.mainThread) }
/// The Core Animation rendering engine, that animates using Core Animation
/// and has better performance characteristics than the Main Thread engine,
/// but doesn't support all Lottie features.
/// - In general, prefer using `RenderingEngineOption.automatic` over
/// `RenderingEngineOption.coreAnimation`. The Core Animation rendering
/// engine doesn't support all features supported by the Main Thread
/// rendering engine. When using `RenderingEngineOption.automatic`,
/// Lottie will automatically fall back to the Main Thread engine
/// when necessary.
public static var coreAnimation: RenderingEngineOption { .specific(.coreAnimation) }
}
// MARK: - RenderingEngine
/// The rendering engine implementation to use when displaying an animation
public enum RenderingEngine: Hashable {
/// The Main Thread rendering engine, which supports all Lottie features
/// but runs on the main thread, which comes with some CPU overhead and
/// can cause the animation to play at a low framerate when the CPU is busy.
case mainThread
/// The Core Animation rendering engine, that animates using Core Animation
/// and has better performance characteristics than the Main Thread engine,
/// but doesn't support all Lottie features.
case coreAnimation
}
// MARK: - RenderingEngineOption + RawRepresentable, CustomStringConvertible
extension RenderingEngineOption: RawRepresentable, CustomStringConvertible {
// MARK: Lifecycle
public init?(rawValue: String) {
if rawValue == "Automatic" {
self = .automatic
} else if let engine = RenderingEngine(rawValue: rawValue) {
self = .specific(engine)
} else {
return nil
}
}
// MARK: Public
public var rawValue: String {
switch self {
case .automatic:
return "Automatic"
case .specific(let engine):
return engine.rawValue
}
}
public var description: String {
rawValue
}
}
// MARK: - RenderingEngine + RawRepresentable, CustomStringConvertible
extension RenderingEngine: RawRepresentable, CustomStringConvertible {
// MARK: Lifecycle
public init?(rawValue: String) {
switch rawValue {
case "Main Thread":
self = .mainThread
case "Core Animation":
self = .coreAnimation
default:
return nil
}
}
// MARK: Public
public var rawValue: String {
switch self {
case .mainThread:
return "Main Thread"
case .coreAnimation:
return "Core Animation"
}
}
public var description: String {
rawValue
}
}
// MARK: - DecodingStrategy
/// How animation files should be decoded
public enum DecodingStrategy: Hashable {
/// Use Codable. This is was the default strategy introduced on Lottie 3, but should be rarely
/// used as it's slower than `dictionaryBased`. Kept here for any possible compatibility issues
/// that may come up, but consider it soft-deprecated.
case legacyCodable
/// Manually deserialize a dictionary into an Animation.
/// This should be at least 2-3x faster than using Codable and due to that
/// it's the default as of Lottie 4.x.
case dictionaryBased
}
| apache-2.0 | de09e449d0adf8dac09a43a48e16a4a4 | 30.391304 | 97 | 0.725762 | 4.969518 | false | false | false | false |
brebory/donger-keyboard | DongerKeyboard/Donger/Views/KeyboardViewController.swift | 1 | 6689 | //
// KeyboardViewController.swift
// Donger
//
// Created by Brendon Roberto on 6/23/16.
// Copyright © 2016 Snackpack Games. All rights reserved.
//
import UIKit
import DongerKit
import ReactiveCocoa
import Result
import Cartography
class KeyboardViewController: UIInputViewController {
typealias DongerCategory = DongerKit.Category
private struct Constants {
private struct Identifiers {
private static let KeyboardCollectionViewCell = "KeyboardCollectionViewCell"
}
private struct Nibs {
private static let KeyboardViewController = "KeyboardViewController"
}
}
@IBOutlet var nextKeyboardButton: UIButton!
@IBOutlet var keyboardPageControl: UIPageControl!
@IBOutlet var keyboardCollectionView: UICollectionView!
@IBOutlet var categoriesTabBar: UITabBar!
lazy var viewModel: KeyboardViewModel = {
let service = DongerLocalService(filename: "dongers")
return KeyboardViewModel(service: service)
}()
lazy var refreshCollectionView: Action<Void, Void, NoError> = { [unowned self] in
return Action({ _ in
self.keyboardCollectionView.reloadData()
return SignalProducer.empty
})
}()
lazy var updatePageControl: Action<Void, Void, NoError> = { [unowned self] in
return Action({ _ in
let pageWidth = CGRectGetWidth(self.keyboardCollectionView.frame)
self.keyboardPageControl.currentPage = Int(self.keyboardCollectionView.contentOffset.x / pageWidth)
return SignalProducer.empty
})
}()
override func updateViewConstraints() {
super.updateViewConstraints()
self.setupConstraints()
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
self.bindActions()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
override func textWillChange(textInput: UITextInput?) {
// The app is about to change the document's contents. Perform any preparation here.
}
override func textDidChange(textInput: UITextInput?) {
// The app has just changed the document's contents, the document context has been updated.
var textColor: UIColor
let proxy = self.textDocumentProxy
if proxy.keyboardAppearance == UIKeyboardAppearance.Dark {
textColor = UIColor.whiteColor()
} else {
textColor = UIColor.blackColor()
}
self.nextKeyboardButton.setTitleColor(textColor, forState: .Normal)
}
private func setupUI() {
let nib = UINib(nibName: Constants.Nibs.KeyboardViewController, bundle: NSBundle(forClass: self.dynamicType.self))
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
self.view = view
self.setupKeyboardCollectionView()
self.setupKeyboardPageControl()
self.setupCategoriesTabBar()
// self.setupConstraints()
}
private func setupKeyboardCollectionView() {
self.keyboardCollectionView.showsHorizontalScrollIndicator = false
self.keyboardCollectionView.pagingEnabled = true
self.keyboardCollectionView.backgroundColor = UIColor.whiteColor()
self.keyboardCollectionView.delegate = self
self.keyboardCollectionView.dataSource = self
// TODO: Use actual dongers collection view cell once it's created, probably with registerNib(forCellWithReuseIdentifier:)
self.keyboardCollectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: Constants.Identifiers.KeyboardCollectionViewCell)
// self.view.addSubview(self.keyboardCollectionView)
}
private func setupKeyboardPageControl() {
// self.view.addSubview(self.keyboardPageControl)
}
private func setupCategoriesTabBar() {
// self.view.addSubview(self.categoriesTabBar)
self.categoriesTabBar.delegate = self
}
private func setupConstraints() {
}
private func bindActions() {
self.racx_scrollViewDidEndDeceleratingSignal <~ self.updatePageControl |< UIScheduler()
self.viewModel.dongers.signal.on(next: { [weak self] _ in self?.keyboardCollectionView.reloadData() })
self.viewModel.categories.signal.map(self.getTabBarItemsFromCategories).on(next: { [weak self] items in self?.categoriesTabBar.setItems(items, animated: true)})
self.viewModel.refreshCategories.apply(nil).start()
}
private func getTabBarItemsFromCategories(categories: [DongerCategory]) -> [UITabBarItem] {
var items = [UITabBarItem]()
let moreItem = UITabBarItem(tabBarSystemItem: .More, tag: 0)
items.appendContentsOf(categories.prefix(4).map(self.getTabBarItemFromCategory))
items.append(moreItem)
return items
}
private func getTabBarItemFromCategory(category: DongerCategory) -> UITabBarItem {
switch category {
case .Node(_, let name, _):
let item = UITabBarItem(title: name, image: nil, selectedImage: nil)
return item
case .Root(_, let name):
let item = UITabBarItem(title: name, image: nil, selectedImage: nil)
return item
}
}
}
// MARK: - UIScrollViewDelegate
extension KeyboardViewController: UIScrollViewDelegate {
}
// MARK: - UICollectionViewDelegate
extension KeyboardViewController: UICollectionViewDelegate {
}
// MARK: - UICollectionViewDelegateFlowLayout
extension KeyboardViewController: UICollectionViewDelegateFlowLayout {
}
// MARK: - UICollectionViewDataSource
extension KeyboardViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.viewModel.dongers.value.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.Identifiers.KeyboardCollectionViewCell,
forIndexPath: indexPath)
self.viewModel.dongers.withValue { [cell] dongers in
if (indexPath.row < dongers.count) {
let label = UILabel(frame: cell.frame)
label.text = dongers[indexPath.row].text
cell.addSubview(label)
}
}
return cell
}
}
// MARK: - UITabBarDelegate
extension KeyboardViewController: UITabBarDelegate {
}
| mit | fcbde7c857f0f506dd41db5126dc24c3 | 32.60804 | 169 | 0.68765 | 5.320605 | false | false | false | false |
galv/reddift | reddift/Model/Subreddit.swift | 1 | 21923 | //
// Subreddit.swift
// reddift
//
// Created by generator.rb via from https://github.com/reddit/reddit/wiki/JSON
// Created at 2015-04-15 11:23:32 +0900
//
import Foundation
/// Protocol to integrate a code for subreddit and multireddit.
public protocol SubredditURLPath {
var path:String {get}
}
/**
Subreddit object.
*/
public struct Subreddit : SubredditURLPath, Thing {
/// identifier of Thing like 15bfi0.
public var id:String
/// name of Thing, that is fullname, like t3_15bfi0.
public var name:String
/// type of Thing, like t3.
public static var kind = "t5"
/**
example:
*/
public let bannerImg:String
/**
example: true
*/
public let userSrThemeEnabled:Bool
/**
example: <!-- SC_OFF --><div class="md"><p><strong>GIFs are banned.</strong>
If you want to post a GIF, please <a href="http://imgur.com">rehost it as a GIFV</a> instead. <a href="http://www.reddit.com/r/woahdude/wiki/html5">(Read more)</a></p>
<p><strong>Link flair is mandatory.</strong>
Click &quot;Add flair&quot; button after you submit. The button will be located under your post title. <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_flair_is_mandatory">(read more)</a></p>
<p><strong>XPOST labels are banned.</strong>
Crossposts are fine, just don&#39;t label them as such. <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_.5Bxpost.5D_tags.2Flabels_are_banned">(read more)</a></p>
<p><strong>Trippy or Mesmerizing content only!</strong>
What is WoahDude-worthy content? <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_what_is_.22woahdude_material.22.3F">(Read more)</a></p>
</div><!-- SC_ON -->
*/
public let submitTextHtml:String
/**
whether the logged-in user is banned from the subreddit
example: false
*/
public let userIsBanned:Bool
/**
example: **GIFs are banned.**
If you want to post a GIF, please [rehost it as a GIFV](http://imgur.com) instead. [(Read more)](http://www.reddit.com/r/woahdude/wiki/html5)
**Link flair is mandatory.**
Click "Add flair" button after you submit. The button will be located under your post title. [(read more)](http://www.reddit.com/r/woahdude/wiki/index#wiki_flair_is_mandatory)
**XPOST labels are banned.**
Crossposts are fine, just don't label them as such. [(read more)](http://www.reddit.com/r/woahdude/wiki/index#wiki_.5Bxpost.5D_tags.2Flabels_are_banned)
**Trippy or Mesmerizing content only!**
What is WoahDude-worthy content? [(Read more)](http://www.reddit.com/r/woahdude/wiki/index#wiki_what_is_.22woahdude_material.22.3F)
*/
public let submitText:String
/**
human name of the subreddit
example: woahdude
*/
public let displayName:String
/**
full URL to the header image, or null
example: http://b.thumbs.redditmedia.com/fnO6IreM4s_Em4dTIU2HtmZ_NTw7dZdlCoaLvtKwbzM.png
*/
public let headerImg:String
/**
sidebar text, escaped HTML format
example: <!-- SC_OFF --><div class="md"><h5><a href="https://www.reddit.com/r/woahdude/comments/2qi1jh/best_of_rwoahdude_2014_results/?">Best of WoahDude 2014 ⇦</a></h5>
<p><a href="#nyanbro"></a></p>
<h4><strong>What is WoahDude?</strong></h4>
<p><em>The best links to click while you&#39;re stoned!</em> </p>
<p>Trippy &amp; mesmerizing games, video, audio &amp; images that make you go &#39;woah dude!&#39;</p>
<p>No one wants to have to sift through the entire internet for fun links when they&#39;re stoned - so make this your one-stop shop!</p>
<p>⇨ <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_what_is_.22woahdude_material.22.3F">more in-depth explanation here</a> ⇦</p>
<h4><strong>Filter WoahDude by flair</strong></h4>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:picture&amp;sort=top&amp;restrict_sr=on">picture</a> - Static images</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:wallpaper+OR+%5BWALLPAPER%5D&amp;sort=top&amp;restrict_sr=on">wallpaper</a> - PC or Smartphone</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair%3Agifv+OR+flair%3Awebm&amp;restrict_sr=on&amp;sort=top&amp;t=all">gifv</a> - Animated images</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:audio&amp;sort=top&amp;restrict_sr=on">audio</a> - Non-musical audio </p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:music&amp;sort=top&amp;restrict_sr=on">music</a> - Include: Band &amp; Song Title</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:musicvideo&amp;sort=top&amp;restrict_sr=on">music video</a> - If slideshow, tag [music] </p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:video&amp;sort=top&amp;restrict_sr=on">video</a> - Non-musical video</p>
<p><a href="http://redd.it/29owi1#movies">movies</a> - Movies</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair:game&amp;restrict_sr=on&amp;sort=top&amp;t=all">game</a> - Goal oriented games</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair%3Ainteractive+OR+sandbox&amp;sort=top&amp;restrict_sr=on&amp;t=all">interactive</a> - Interactive pages</p>
<p><a href="http://www.reddit.com/r/woahdude/comments/1jri9s/woahdude_featured_apps_get_free_download_codes/">mobile app</a> - Mod-curated selection of apps</p>
<p><a href="http://www.reddit.com/r/WoahDude/search?q=flair%3Atext&amp;restrict_sr=on&amp;sort=top&amp;t=all">text</a> - Articles, selfposts &amp; textpics</p>
<p><a href="http://www.reddit.com/r/woahdude/search?q=flair%3Awoahdude%2Bapproved&amp;sort=new&amp;restrict_sr=on&amp;t=all">WOAHDUDE APPROVED</a> - Mod-curated selection of the best WoahDude submissions.</p>
<h4>RULES <a href="http://www.reddit.com/r/woahdude/wiki">⇨ FULL VERSION</a></h4>
<blockquote>
<ol>
<li>LINK FLAIR <strong>is <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_flair_is_mandatory">mandatory</a>.</strong></li>
<li>XPOST <strong>labels are <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_.5Bxpost.5D_tags.2Flabels_are_banned">banned</a>. Crossposts are fine, just don&#39;t label them as such.</strong></li>
<li> NO <strong>hostility!</strong> PLEASE <strong>giggle like a giraffe :)</strong></li>
</ol>
</blockquote>
<p>Certain reposts are allowed. <a href="http://www.reddit.com/r/woahdude/wiki/index#wiki_reposts">Learn more</a>. Those not allowed may be reported via this form:</p>
<p><a href="http://www.reddit.com/message/compose?to=%2Fr%2Fwoahdude&amp;subject=Repost%20Report&amp;message=Here%20%5bLINK%5d%20is%20an%20illegitimate%20repost,%20and%20here%20%5bLINK%5d%20is%20proof%20that%20the%20original%20woahdude%20post%20had%201500%2b%20upvotes.#reportwarning"></a> <a href="http://www.reddit.com/message/compose?to=%2Fr%2Fwoahdude&amp;subject=Repost%20Report&amp;message=Here%20%5bLINK%5d%20is%20an%20illegitimate%20repost,%20and%20here%20%5bLINK%5d%20is%20proof%20that%20the%20original%20woahdude%20post%20had%201500%2b%20upvotes."><strong>REPORT AN ILLEGITIMATE REPOST</strong></a></p>
<h4>WoahDude community</h4>
<ul>
<li><a href="/r/WoahDude">/r/WoahDude</a> - All media</li>
<li><a href="/r/WoahTube">/r/WoahTube</a> - Videos only</li>
<li><a href="/r/WoahTunes">/r/WoahTunes</a> - Music only</li>
<li><a href="/r/StonerPhilosophy">/r/StonerPhilosophy</a> - Text posts only</li>
<li><a href="/r/WoahPoon">/r/WoahPoon</a> - NSFW</li>
<li><strong><a href="http://www.reddit.com/user/rWoahDude/m/woahdude">MULTIREDDIT</a></strong></li>
</ul>
<h5><a href="http://facebook.com/rWoahDude"></a></h5>
<h5><a href="http://twitter.com/rWoahDude"></a></h5>
<h5><a href="http://emilydavis.bandcamp.com/track/sagans-song">http://emilydavis.bandcamp.com/track/sagans-song</a></h5>
</div><!-- SC_ON -->
*/
public let descriptionHtml:String
/**
title of the main page
example: The BEST links to click while you're STONED
*/
public let title:String
/**
example: true
*/
public let collapseDeletedComments:Bool
/**
whether the subreddit is marked as NSFW
example: false
*/
public let over18:Bool
/**
example: <!-- SC_OFF --><div class="md"><p>The best links to click while you&#39;re stoned!</p>
<p>Trippy, mesmerizing, and mindfucking games, video, audio &amp; images that make you go &#39;woah dude!&#39;</p>
<p>If you like to look at amazing stuff while smoking weed or doing other drugs, come inside for some Science, Philosophy, Mindfucks, Math, Engineering, Illusions and Cosmic weirdness.</p>
</div><!-- SC_ON -->
*/
public let publicDescriptionHtml:String
/**
example:
*/
public let iconSize:[Int]
/**
example:
*/
public let iconImg:String
/**
description of header image shown on hover, or null
example: Turn on the stylesheet and click Carl Sagan's head
*/
public let headerTitle:String
/**
sidebar text
example: #####[Best of WoahDude 2014 ⇦](https://www.reddit.com/r/woahdude/comments/2qi1jh/best_of_rwoahdude_2014_results/?)
[](#nyanbro)
####**What is WoahDude?**
*The best links to click while you're stoned!*
Trippy & mesmerizing games, video, audio & images that make you go 'woah dude!'
No one wants to have to sift through the entire internet for fun links when they're stoned - so make this your one-stop shop!
⇨ [more in-depth explanation here](http://www.reddit.com/r/woahdude/wiki/index#wiki_what_is_.22woahdude_material.22.3F) ⇦
####**Filter WoahDude by flair**
[picture](http://www.reddit.com/r/woahdude/search?q=flair:picture&sort=top&restrict_sr=on) - Static images
[wallpaper](http://www.reddit.com/r/woahdude/search?q=flair:wallpaper+OR+[WALLPAPER]&sort=top&restrict_sr=on) - PC or Smartphone
[gifv](http://www.reddit.com/r/woahdude/search?q=flair%3Agifv+OR+flair%3Awebm&restrict_sr=on&sort=top&t=all) - Animated images
[audio](http://www.reddit.com/r/woahdude/search?q=flair:audio&sort=top&restrict_sr=on) - Non-musical audio
[music](http://www.reddit.com/r/woahdude/search?q=flair:music&sort=top&restrict_sr=on) - Include: Band & Song Title
[music video](http://www.reddit.com/r/woahdude/search?q=flair:musicvideo&sort=top&restrict_sr=on) - If slideshow, tag [music]
[video](http://www.reddit.com/r/woahdude/search?q=flair:video&sort=top&restrict_sr=on) - Non-musical video
[movies](http://redd.it/29owi1#movies) - Movies
[game](http://www.reddit.com/r/woahdude/search?q=flair:game&restrict_sr=on&sort=top&t=all) - Goal oriented games
[interactive](http://www.reddit.com/r/woahdude/search?q=flair%3Ainteractive+OR+sandbox&sort=top&restrict_sr=on&t=all) - Interactive pages
[mobile app](http://www.reddit.com/r/woahdude/comments/1jri9s/woahdude_featured_apps_get_free_download_codes/) - Mod-curated selection of apps
[text](http://www.reddit.com/r/WoahDude/search?q=flair%3Atext&restrict_sr=on&sort=top&t=all) - Articles, selfposts & textpics
[WOAHDUDE APPROVED](http://www.reddit.com/r/woahdude/search?q=flair%3Awoahdude%2Bapproved&sort=new&restrict_sr=on&t=all) - Mod-curated selection of the best WoahDude submissions.
####RULES [⇨ FULL VERSION](http://www.reddit.com/r/woahdude/wiki)
> 1. LINK FLAIR **is [mandatory](http://www.reddit.com/r/woahdude/wiki/index#wiki_flair_is_mandatory).**
2. XPOST **labels are [banned](http://www.reddit.com/r/woahdude/wiki/index#wiki_.5Bxpost.5D_tags.2Flabels_are_banned). Crossposts are fine, just don't label them as such.**
3. NO **hostility!** PLEASE **giggle like a giraffe :)**
Certain reposts are allowed. [Learn more](http://www.reddit.com/r/woahdude/wiki/index#wiki_reposts). Those not allowed may be reported via this form:
[](http://www.reddit.com/message/compose?to=%2Fr%2Fwoahdude&subject=Repost%20Report&message=Here%20%5bLINK%5d%20is%20an%20illegitimate%20repost,%20and%20here%20%5bLINK%5d%20is%20proof%20that%20the%20original%20woahdude%20post%20had%201500%2b%20upvotes.#reportwarning) [**REPORT AN ILLEGITIMATE REPOST**](http://www.reddit.com/message/compose?to=%2Fr%2Fwoahdude&subject=Repost%20Report&message=Here%20%5bLINK%5d%20is%20an%20illegitimate%20repost,%20and%20here%20%5bLINK%5d%20is%20proof%20that%20the%20original%20woahdude%20post%20had%201500%2b%20upvotes.)
####WoahDude community
* /r/WoahDude - All media
* /r/WoahTube - Videos only
* /r/WoahTunes - Music only
* /r/StonerPhilosophy - Text posts only
* /r/WoahPoon - NSFW
* **[MULTIREDDIT](http://www.reddit.com/user/rWoahDude/m/woahdude)**
#####[](http://facebook.com/rWoahDude)
#####[](http://twitter.com/rWoahDude)
#####http://emilydavis.bandcamp.com/track/sagans-song
*/
public let description:String
/**
the subreddit's custom label for the submit link button, if any
example: SUBMIT LINK
*/
public let submitLinkLabel:String
/**
number of users active in last 15 minutes
example:
*/
public let accountsActive:Int
/**
whether the subreddit's traffic page is publicly-accessible
example: false
*/
public let publicTraffic:Bool
/**
width and height of the header image, or null
example: [145, 60]
*/
public let headerSize:[Int]
/**
the number of redditors subscribed to this subreddit
example: 778611
*/
public let subscribers:Int
/**
the subreddit's custom label for the submit text button, if any
example: SUBMIT TEXT
*/
public let submitTextLabel:String
/**
whether the logged-in user is a moderator of the subreddit
example: false
*/
public let userIsModerator:Bool
/**
example: 1254666760
*/
public let created:Int
/**
The relative URL of the subreddit. Ex: "/r/pics/"
example: /r/woahdude/
*/
public let url:String
/**
example: false
*/
public let hideAds:Bool
/**
example: 1254663160
*/
public let createdUtc:Int
/**
example:
*/
public let bannerSize:[Int]
/**
whether the logged-in user is an approved submitter in the subreddit
example: false
*/
public let userIsContributor:Bool
/**
Description shown in subreddit search results?
example: The best links to click while you're stoned!
Trippy, mesmerizing, and mindfucking games, video, audio & images that make you go 'woah dude!'
If you like to look at amazing stuff while smoking weed or doing other drugs, come inside for some Science, Philosophy, Mindfucks, Math, Engineering, Illusions and Cosmic weirdness.
*/
public let publicDescription:String
/**
number of minutes the subreddit initially hides comment scores
example: 0
*/
public let commentScoreHideMins:Int
/**
the subreddit's type - one of "public", "private", "restricted", or in very special cases "gold_restricted" or "archived"
example: public
*/
public let subredditType:String
/**
the type of submissions the subreddit allows - one of "any", "link" or "self"
example: any
*/
public let submissionType:String
/**
whether the logged-in user is subscribed to the subreddit
example: true
*/
public let userIsSubscriber:Bool
public var path:String {
return "/r/\(displayName)"
}
public init(subreddit:String) {
self.id = "dummy"
self.name = "\(Subreddit.kind)_\(self.id)"
bannerImg = ""
userSrThemeEnabled = false
submitTextHtml = ""
userIsBanned = false
submitText = ""
displayName = subreddit
headerImg = ""
descriptionHtml = ""
title = ""
collapseDeletedComments = false
over18 = false
publicDescriptionHtml = ""
iconSize = []
iconImg = ""
headerTitle = ""
description = ""
submitLinkLabel = ""
accountsActive = 0
publicTraffic = false
headerSize = []
subscribers = 0
submitTextLabel = ""
userIsModerator = false
created = 0
url = ""
hideAds = false
createdUtc = 0
bannerSize = []
userIsContributor = false
publicDescription = ""
commentScoreHideMins = 0
subredditType = ""
submissionType = ""
userIsSubscriber = false
}
public init(id:String) {
self.id = id
self.name = "\(Subreddit.kind)_\(self.id)"
bannerImg = ""
userSrThemeEnabled = false
submitTextHtml = ""
userIsBanned = false
submitText = ""
displayName = ""
headerImg = ""
descriptionHtml = ""
title = ""
collapseDeletedComments = false
over18 = false
publicDescriptionHtml = ""
iconSize = []
iconImg = ""
headerTitle = ""
description = ""
submitLinkLabel = ""
accountsActive = 0
publicTraffic = false
headerSize = []
subscribers = 0
submitTextLabel = ""
userIsModerator = false
created = 0
url = ""
hideAds = false
createdUtc = 0
bannerSize = []
userIsContributor = false
publicDescription = ""
commentScoreHideMins = 0
subredditType = ""
submissionType = ""
userIsSubscriber = false
}
/**
Parse t5 object.
- parameter data: Dictionary, must be generated parsing "t5".
- returns: Subreddit object as Thing.
*/
public init(data:JSONDictionary) {
id = data["id"] as? String ?? ""
bannerImg = data["banner_img"] as? String ?? ""
userSrThemeEnabled = data["user_sr_theme_enabled"] as? Bool ?? false
submitTextHtml = data["submit_text_html"] as? String ?? ""
userIsBanned = data["user_is_banned"] as? Bool ?? false
submitText = data["submit_text"] as? String ?? ""
displayName = data["display_name"] as? String ?? ""
headerImg = data["header_img"] as? String ?? ""
descriptionHtml = data["description_html"] as? String ?? ""
title = data["title"] as? String ?? ""
collapseDeletedComments = data["collapse_deleted_comments"] as? Bool ?? false
over18 = data["over18"] as? Bool ?? false
publicDescriptionHtml = data["public_description_html"] as? String ?? ""
iconSize = data["icon_size"] as? [Int] ?? []
iconImg = data["icon_img"] as? String ?? ""
headerTitle = data["header_title"] as? String ?? ""
description = data["description"] as? String ?? ""
submitLinkLabel = data["submit_link_label"] as? String ?? ""
accountsActive = data["accounts_active"] as? Int ?? 0
publicTraffic = data["public_traffic"] as? Bool ?? false
headerSize = data["header_size"] as? [Int] ?? []
subscribers = data["subscribers"] as? Int ?? 0
submitTextLabel = data["submit_text_label"] as? String ?? ""
userIsModerator = data["user_is_moderator"] as? Bool ?? false
name = data["name"] as? String ?? ""
created = data["created"] as? Int ?? 0
url = data["url"] as? String ?? ""
hideAds = data["hide_ads"] as? Bool ?? false
createdUtc = data["created_utc"] as? Int ?? 0
bannerSize = data["banner_size"] as? [Int] ?? []
userIsContributor = data["user_is_contributor"] as? Bool ?? false
publicDescription = data["public_description"] as? String ?? ""
commentScoreHideMins = data["comment_score_hide_mins"] as? Int ?? 0
subredditType = data["subreddit_type"] as? String ?? ""
submissionType = data["submission_type"] as? String ?? ""
userIsSubscriber = data["user_is_subscriber"] as? Bool ?? false
}
}
| mit | 12cdac52512076ef3a0b868b0bf1c7d8 | 43.167339 | 680 | 0.644634 | 2.972859 | false | false | false | false |
wawandco/away | Example/Pods/Nimble/Nimble/DSL+Wait.swift | 1 | 1979 | import Foundation
/// Only classes, protocols, methods, properties, and subscript declarations can be
/// bridges to Objective-C via the @objc keyword. This class encapsulates callback-style
/// asynchronous waiting logic so that it may be called from Objective-C and Swift.
internal class NMBWait {
internal class func until(timeout timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void {
var completed = false
var token: dispatch_once_t = 0
let result = pollBlock(pollInterval: 0.01, timeoutInterval: timeout) {
dispatch_once(&token) {
dispatch_async(dispatch_get_main_queue()) {
action() { completed = true }
}
}
return completed
}
if result == PollResult.Failure {
let pluralize = (timeout == 1 ? "" : "s")
fail("Waited more than \(timeout) second\(pluralize)", file: file, line: line)
} else if result == PollResult.Timeout {
fail("Stall on main thread - too much enqueued on main run loop before waitUntil executes.", file: file, line: line)
}
}
internal class func until(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void {
until(timeout: 1, file: file, line: line, action: action)
}
}
/// Wait asynchronously until the done closure is called.
///
/// This will advance the run loop.
public func waitUntil(timeout timeout: NSTimeInterval, file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void {
NMBWait.until(timeout: timeout, file: file, line: line, action: action)
}
/// Wait asynchronously until the done closure is called.
///
/// This will advance the run loop.
public func waitUntil(file: String = __FILE__, line: UInt = __LINE__, action: (() -> Void) -> Void) -> Void {
NMBWait.until(file: file, line: line, action: action)
} | mit | 731e5b0438b7cb5bdaf804730b87c061 | 45.046512 | 150 | 0.617989 | 4.210638 | false | false | false | false |
mrdepth/EVEUniverse | Legacy/Neocom/Neocom/SegmentedPageControl.swift | 2 | 4978 | //
// SegmentedPageControl.swift
// Neocom
//
// Created by Artem Shimanski on 9/27/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
class SegmentedPageControl: UIControl {
@IBInspectable var spacing: CGFloat = 15
@IBInspectable var segments: String? {
didSet {
self.titles = segments?.components(separatedBy: "|") ?? []
}
}
var titles: [String] = [] {
didSet {
var buttons = stackView.arrangedSubviews as? [UIButton] ?? []
for title in titles {
let button = !buttons.isEmpty ? buttons.removeFirst() : {
let button = UIButton(frame: .zero)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(.white, for: .normal)
button.addTarget(self, action: #selector(onButton(_:)), for: .touchUpInside)
stackView.addArrangedSubview(button)
return button
}()
button.setTitle(title, for: .normal)
button.titleLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
}
buttons.forEach {$0.removeFromSuperview()}
setNeedsLayout()
}
}
@IBOutlet weak var scrollView: UIScrollView? {
didSet {
scrollView?.delegate = self
}
}
override init(frame: CGRect) {
super.init(frame: frame)
tintColor = .caption
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private lazy var contentView: UIScrollView = {
let contentView = UIScrollView(frame: self.bounds)
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.delaysContentTouches = true
contentView.canCancelContentTouches = true
contentView.showsHorizontalScrollIndicator = false
contentView.showsVerticalScrollIndicator = false
self.addSubview(contentView)
return contentView
}()
public lazy var stackView: UIStackView = {
let stackView = UIStackView()
stackView.alignment = .center
stackView.distribution = .fillProportionally
stackView.axis = .horizontal
stackView.spacing = self.spacing
stackView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(stackView)
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(s)-[view]-(s)-|", options: [], metrics: ["s": self.spacing], views: ["view": stackView]))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": stackView]))
stackView.widthAnchor.constraint(greaterThanOrEqualTo: self.contentView.widthAnchor, constant: -self.spacing * 2).isActive = true
stackView.heightAnchor.constraint(equalTo: self.contentView.heightAnchor).isActive = true
return stackView
}()
public lazy var indicator: UIView = {
let indicator = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 4))
indicator.backgroundColor = self.tintColor
self.contentView.addSubview(indicator)
return indicator
}()
override func layoutSubviews() {
super.layoutSubviews()
var bounds = self.bounds
bounds.size.height -= 4
contentView.frame = bounds
guard stackView.arrangedSubviews.count > 0 else {return}
stackView.layoutIfNeeded()
contentView.layoutIfNeeded()
guard let scrollView = scrollView, scrollView.bounds.size.width > 0 else {return}
let p = scrollView.contentOffset.x / scrollView.bounds.size.width
let page = Int(round(p))
let lastPage = (stackView.arrangedSubviews.count - 1)
for (i, button) in (stackView.arrangedSubviews as! [UIButton]).enumerated() {
button.setTitleColor(i == page ? tintColor : .lightText, for: .normal)
}
let fromLabel = stackView.arrangedSubviews[Int(trunc(p)).clamped(to: 0...lastPage)]
let toLabel = stackView.arrangedSubviews[Int(ceil(p)).clamped(to: 0...lastPage)]
var from = fromLabel.convert(fromLabel.bounds, to: contentView)
var to = toLabel.convert(toLabel.bounds, to: contentView)
if p < 0 {
from.size.width = 0;
}
else if p > CGFloat(lastPage) {
to.origin.x += to.size.width
to.size.width = 0
}
var rect = from.lerp(to: to, t: 1.0 - (ceil(p) - p))
rect.size.height = 3
rect.origin.y = bounds.size.height - rect.size.height
indicator.frame = rect
let x = indicator.center.x - contentView.bounds.size.width / 2
guard contentView.contentSize.width >= contentView.bounds.size.width else {return}
contentView.contentOffset.x = x.clamped(to: 0...(contentView.contentSize.width - contentView.bounds.size.width))
}
override var intrinsicContentSize: CGSize {
var size = self.contentView.contentSize
size.height += 4
return size
}
@IBAction private func onButton(_ sender: UIButton) {
guard let i = stackView.arrangedSubviews.index(of: sender) else {return}
guard let scrollView = scrollView else {return}
scrollView.setContentOffset(CGPoint(x: CGFloat(i) * scrollView.bounds.size.width, y: 0), animated: true)
}
}
extension SegmentedPageControl: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.setNeedsLayout()
}
}
| lgpl-2.1 | d730b034041a1e4cbd09aac3b550a2d5 | 32.402685 | 174 | 0.723126 | 3.879189 | false | false | false | false |
codefirst/SKK-for-iOS | SKK-Keyboard/ImitationKeyboard/KeyboardKey.swift | 1 | 15070 | //
// KeyboardKey.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 6/9/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// components
// - large letter popup
// - if hold, show extra menu — default if finger slides off
// - translucent buttons
// - light and dark themes
// - iPad sizes
// - iPad slide apart keyboard
// - JSON-like parsing
// > storyboard + custom widget
// > framework
// system bugs
// - attach() receives incorrect enum when using -O
// - inability to use class generics without compiler crashes
// - inability to use method generics without compiler crashes when using -O
// - framework (?) compiler crashes when using -Ofast
// this is more of a view controller than a view, so we'll let the model stuff slide for now
class KeyboardKey: UIControl, KeyboardView {
let model: Key
var keyView: KeyboardKeyBackground
var popup: KeyboardKeyBackground?
var connector: KeyboardConnector?
var color: UIColor { didSet { updateColors() }}
var underColor: UIColor { didSet { updateColors() }}
var borderColor: UIColor { didSet { updateColors() }}
var drawUnder: Bool { didSet { updateColors() }}
var drawBorder: Bool { didSet { updateColors() }}
var textColor: UIColor { didSet { updateColors() }}
var downColor: UIColor? { didSet { updateColors() }}
var downUnderColor: UIColor? { didSet { updateColors() }}
var downBorderColor: UIColor? { didSet { updateColors() }}
var downTextColor: UIColor? { didSet { updateColors() }}
var popupDirection: Direction
var ambiguityTimer: NSTimer! // QQQ:
var constraintStore: [(UIView, NSLayoutConstraint)] = [] // QQQ:
override var enabled: Bool { didSet { updateColors() }}
override var selected: Bool
{
didSet
{
updateColors()
}}
override var highlighted: Bool
{
didSet
{
updateColors()
}}
var text: String! {
didSet {
self.redrawText()
}
}
override var frame: CGRect {
didSet {
self.redrawText()
}
}
init(frame: CGRect, model: Key) {
self.model = model
self.keyView = KeyboardKeyBackground(frame: CGRectZero)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
// self.holder0 = UIVisualEffectView(effect: blurEffect)
// self.holder = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
self.color = UIColor.whiteColor()
self.underColor = UIColor.grayColor()
self.borderColor = UIColor.blackColor()
self.drawUnder = true
self.drawBorder = false
self.textColor = UIColor.blackColor()
self.popupDirection = Direction.Up
super.init(frame: frame)
self.clipsToBounds = false
self.keyView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.keyView)
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
self.addConstraint(NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self.keyView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
self.ambiguityTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerLoop", userInfo: nil, repeats: true)
// self.holder0.contentView.addSubview(self.holder)
// self.holder0.clipsToBounds = false
// self.holder0.contentView.clipsToBounds = false
// self.addSubview(self.holder0)
// self.holder.contentView.addSubview(self.keyView)
// self.holder.clipsToBounds = false
// self.holder.contentView.clipsToBounds = false
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
// override func sizeThatFits(size: CGSize) -> CGSize {
// return super.sizeThatFits(size)
// }
// override func updateConstraints() {
//
// }
func timerLoop() {
if self.popup != nil && self.popup!.hasAmbiguousLayout() {
NSLog("exercising ambiguity...")
self.popup!.exerciseAmbiguityInLayout()
}
}
override func layoutSubviews() {
super.layoutSubviews()
if self.popup != nil {
self.popupDirection = Direction.Up
self.setupPopupConstraints(self.popupDirection)
self.configurePopup(self.popupDirection)
super.layoutSubviews()
let upperLeftCorner = self.popup!.frame.origin
var popupPosition = self.superview!.convertPoint(upperLeftCorner, fromView: self) // TODO: hack
// if popupPosition.y < 0 {
if self.popup!.bounds.height < 10 {
if self.frame.origin.x < self.superview!.bounds.width/2 { // TODO: hack
self.popupDirection = Direction.Right
}
else {
self.popupDirection = Direction.Left
}
self.setupPopupConstraints(self.popupDirection)
self.configurePopup(self.popupDirection)
super.layoutSubviews()
}
}
// self.holder.frame = self.bounds
// self.holder0.frame = self.bounds
self.redrawText()
}
func redrawText() {
// self.keyView.frame = self.bounds
// self.button.frame = self.bounds
//
// self.button.setTitle(self.text, forState: UIControlState.Normal)
self.keyView.text = ((self.text != nil) ? self.text : "")
}
// TODO: StyleKit?
func updateColors() {
var keyboardViews: [KeyboardView] = [self.keyView]
if self.popup != nil { keyboardViews.append(self.popup!) }
if self.connector != nil { keyboardViews.append(self.connector!) }
let switchColors = self.highlighted || self.selected
for kv in keyboardViews {
var keyboardView = kv
keyboardView.color = (switchColors && self.downColor != nil ? self.downColor! : self.color)
keyboardView.underColor = (switchColors && self.downUnderColor != nil ? self.downUnderColor! : self.underColor)
keyboardView.borderColor = (switchColors && self.downBorderColor != nil ? self.downBorderColor! : self.borderColor)
keyboardView.drawUnder = self.drawUnder
keyboardView.drawBorder = self.drawBorder
}
self.keyView.label.textColor = (switchColors && self.downTextColor != nil ? self.downTextColor! : self.textColor)
if self.popup != nil {
self.popup!.label.textColor = (switchColors && self.downTextColor != nil ? self.downTextColor! : self.textColor)
}
}
func setupPopupConstraints(dir: Direction) {
// TODO: superview optional
assert(self.popup != nil, "popup not found")
for (view, constraint) in self.constraintStore {
view.removeConstraint(constraint)
}
self.constraintStore = []
let gap: CGFloat = 8
let gapMinimum: CGFloat = 3
// size ratios
// TODO: fix for direction
let widthConstraint = NSLayoutConstraint(
item: self.popup!,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: self.keyView,
attribute: NSLayoutAttribute.Width,
multiplier: 1,
constant: 26)
self.constraintStore.append((self, widthConstraint) as (UIView, NSLayoutConstraint))
// TODO: is this order right???
let heightConstraint = NSLayoutConstraint(
item: self.popup!,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: self.keyView,
attribute: NSLayoutAttribute.Height,
multiplier: -1,
constant: 94)
heightConstraint.priority = 750
self.constraintStore.append((self, heightConstraint) as (UIView, NSLayoutConstraint))
// gap from key
let directionToAttribute = [
Direction.Up: NSLayoutAttribute.Top,
Direction.Down: NSLayoutAttribute.Bottom,
Direction.Left: NSLayoutAttribute.Left,
Direction.Right: NSLayoutAttribute.Right,
]
let gapConstraint = NSLayoutConstraint(
item: self.keyView,
attribute: directionToAttribute[dir]!,
relatedBy: NSLayoutRelation.Equal,
toItem: self.popup,
attribute: directionToAttribute[dir.opposite()]!,
multiplier: 1,
constant: gap)
gapConstraint.priority = 700
self.constraintStore.append((self, gapConstraint) as (UIView, NSLayoutConstraint))
let gapMinConstraint = NSLayoutConstraint(
item: self.keyView,
attribute: directionToAttribute[dir]!,
relatedBy: NSLayoutRelation.Equal,
toItem: self.popup,
attribute: directionToAttribute[dir.opposite()]!,
multiplier: 1,
constant: (dir.horizontal() ? -1 : 1) * gapMinimum)
gapMinConstraint.priority = 1000
self.constraintStore.append((self, gapMinConstraint) as (UIView, NSLayoutConstraint))
// can't touch top
let cantTouchTopConstraint = NSLayoutConstraint(
item: self.popup!,
attribute: directionToAttribute[dir]!,
relatedBy: (dir == Direction.Right ? NSLayoutRelation.LessThanOrEqual : NSLayoutRelation.GreaterThanOrEqual),
toItem: self.superview,
attribute: directionToAttribute[dir]!,
multiplier: 1,
constant: 2) // TODO: layout
cantTouchTopConstraint.priority = 1000
self.constraintStore.append((self.superview!, cantTouchTopConstraint) as (UIView, NSLayoutConstraint))
if dir.horizontal() {
let cantTouchTopConstraint = NSLayoutConstraint(
item: self.popup!,
attribute: directionToAttribute[Direction.Up]!,
relatedBy: NSLayoutRelation.GreaterThanOrEqual,
toItem: self.superview,
attribute: directionToAttribute[Direction.Up]!,
multiplier: 1,
constant: 5) // TODO: layout
cantTouchTopConstraint.priority = 1000
self.constraintStore.append((self.superview!, cantTouchTopConstraint) as (UIView, NSLayoutConstraint))
}
else {
let cantTouchSideConstraint = NSLayoutConstraint(
item: self.superview!,
attribute: directionToAttribute[Direction.Right]!,
relatedBy: NSLayoutRelation.GreaterThanOrEqual,
toItem: self.popup,
attribute: directionToAttribute[Direction.Right]!,
multiplier: 1,
constant: 17) // TODO: layout
cantTouchSideConstraint.priority = 1000
let cantTouchSideConstraint2 = NSLayoutConstraint(
item: self.superview!,
attribute: directionToAttribute[Direction.Left]!,
relatedBy: NSLayoutRelation.LessThanOrEqual,
toItem: self.popup,
attribute: directionToAttribute[Direction.Left]!,
multiplier: 1,
constant: 17) // TODO: layout
cantTouchSideConstraint2.priority = 1000
self.constraintStore.append((self.superview!, cantTouchSideConstraint) as (UIView, NSLayoutConstraint))
self.constraintStore.append((self.superview!, cantTouchSideConstraint2) as (UIView, NSLayoutConstraint))
}
// centering
let centerConstraint = NSLayoutConstraint(
item: self.keyView,
attribute: (dir.horizontal() ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX),
relatedBy: NSLayoutRelation.Equal,
toItem: self.popup,
attribute: (dir.horizontal() ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX),
multiplier: 1,
constant: 0)
centerConstraint.priority = 500
self.constraintStore.append((self, centerConstraint) as (UIView, NSLayoutConstraint))
for (view, constraint) in self.constraintStore {
view.addConstraint(constraint)
}
}
func configurePopup(direction: Direction) {
assert(self.popup != nil, "popup not found")
self.keyView.attach(direction)
self.popup!.attach(direction.opposite())
let kv = self.keyView
let p = self.popup!
self.connector?.removeFromSuperview()
self.connector = KeyboardConnector(start: kv, end: p, startConnectable: kv, endConnectable: p, startDirection: direction, endDirection: direction.opposite())
self.connector!.layer.zPosition = -1
self.addSubview(self.connector!)
self.drawBorder = true
if direction == Direction.Up {
self.popup!.drawUnder = false
self.connector!.drawUnder = false
}
}
func showPopup() {
if self.popup == nil {
self.layer.zPosition = 1000
self.popup = KeyboardKeyBackground(frame: CGRectZero)
self.popup!.translatesAutoresizingMaskIntoConstraints = false
self.popup!.cornerRadius = 9.0
self.addSubview(self.popup!)
self.popup!.text = self.keyView.text
self.keyView.label.hidden = true
self.popup!.label.font = self.popup!.label.font.fontWithSize(22 * 2.0)
}
}
func hidePopup() {
if self.popup != nil {
self.connector?.removeFromSuperview()
self.connector = nil
self.popup?.removeFromSuperview()
self.popup = nil
self.keyView.label.hidden = false
self.keyView.attach(nil)
self.keyView.drawBorder = false
self.layer.zPosition = 0
}
}
}
| gpl-2.0 | 9ea7382cc3329a3f04e3ebfdfad4ffba | 37.835052 | 217 | 0.608774 | 5.119946 | false | false | false | false |
lorentey/swift | stdlib/public/Darwin/Accelerate/vDSP_ComplexConversion.swift | 8 | 2986 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension vDSP {
/// Converts split complex to interleaved complex; single-precision.
///
/// - Parameter splitComplexVector: Source vector.
/// - Parameter interleavedComplexVector: Destination vector.
@inlinable
public static func convert(splitComplexVector: DSPSplitComplex,
toInterleavedComplexVector interleavedComplexVector: inout [DSPComplex]) {
withUnsafePointer(to: splitComplexVector) {
vDSP_ztoc($0, 1,
&interleavedComplexVector, 2,
vDSP_Length(interleavedComplexVector.count))
}
}
/// Converts interleaved complex to split complex; single-precision.
///
/// - Parameter interleavedComplexVector: Source vector.
/// - Parameter splitComplexVector: Destination vector.
@inlinable
public static func convert(interleavedComplexVector: [DSPComplex],
toSplitComplexVector splitComplexVector: inout DSPSplitComplex) {
vDSP_ctoz(interleavedComplexVector, 2,
&splitComplexVector, 1,
vDSP_Length(interleavedComplexVector.count))
}
/// Converts split complex to interleaved complex; double-precision.
///
/// - Parameter splitComplexVector: Source vector.
/// - Parameter interleavedComplexVector: Destination vector.
@inlinable
public static func convert(splitComplexVector: DSPDoubleSplitComplex,
toInterleavedComplexVector interleavedComplexVector: inout [DSPDoubleComplex]) {
withUnsafePointer(to: splitComplexVector) {
vDSP_ztocD($0, 1,
&interleavedComplexVector, 2,
vDSP_Length(interleavedComplexVector.count))
}
}
/// Converts interleaved complex to split complex; double-precision.
///
/// - Parameter interleavedComplexVector: Source vector.
/// - Parameter splitComplexVector: Destination vector.
@inlinable
public static func convert(interleavedComplexVector: [DSPDoubleComplex],
toSplitComplexVector splitComplexVector: inout DSPDoubleSplitComplex) {
vDSP_ctozD(interleavedComplexVector, 2,
&splitComplexVector, 1,
vDSP_Length(interleavedComplexVector.count))
}
}
| apache-2.0 | 7e23ceedf2848b0a14a5b6a67c72e633 | 41.056338 | 111 | 0.613865 | 5.972 | false | false | false | false |
makelove/Developing-iOS-8-Apps-with-Swift | Lesson2/Calculator/Calculator/ViewController.swift | 1 | 1974 |
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var Display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
Display.text = Display.text! + digit
} else {
Display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation { $0 * $1 }
case "÷": performOperation { $1 / $0 }
case "+": performOperation { $0 + $1 }
case "-": performOperation { $1 - $0 }
case "√": performOperation1 { sqrt($0)}
default: break
}
}
var operandStack = Array<Double>()
func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
//Error: performOperation conflicts with previous declaration with the same Objective-C selector
func performOperation1(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(Display.text!)!.doubleValue
}
set {
Display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
} | apache-2.0 | c7ab2ca4a83fd5af3ade46915e107c39 | 27.157143 | 100 | 0.584772 | 5.472222 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Services/RSTBElementGeneratorService.swift | 1 | 1773 | //
// RSTBElementGeneratorService.swift
// Pods
//
// Created by James Kizer on 1/9/17.
//
//
import ResearchKit
import Gloss
open class RSTBElementGeneratorService: NSObject {
static private var _service: RSTBElementGeneratorService = RSTBElementGeneratorService()
static public var service: RSTBElementGeneratorService {
return _service
}
static public func initialize(services: [RSTBElementGenerator]) {
self._service = RSTBElementGeneratorService(services: services)
}
private var loader: RSTBServiceLoader<RSTBElementGenerator>!
public override convenience init() {
let services:[RSTBElementGenerator] = []
self.init(services: services)
}
public init(services: [RSTBElementGenerator]) {
let loader:RSTBServiceLoader<RSTBElementGenerator> = RSTBServiceLoader()
services.forEach({loader.addService(service: $0)})
self.loader = loader
}
func supportsType(type: String) -> Bool {
let stepGenerators = self.loader.iterator()
for elementGenerator in stepGenerators {
if elementGenerator.supportsType(type: type) {
return true
}
}
return false
}
func generateElements(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> [JSON]? {
let stepGenerators = self.loader.iterator()
for elementGenerator in stepGenerators {
if elementGenerator.supportsType(type: type),
let elements = elementGenerator.generateElements(type: type, jsonObject: jsonObject, helper: helper) {
return elements
}
}
return nil
}
}
| apache-2.0 | ebee7729bac86d97133ccddeff500183 | 27.596774 | 118 | 0.632262 | 4.925 | false | false | false | false |
gregomni/swift | test/Generics/abstract_type_witnesses_in_protocols.swift | 3 | 2362 | // RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-protocol-signatures=on -disable-requirement-machine-concrete-contraction 2>&1 | %FileCheck %s
protocol P {
associatedtype T
}
struct G<T> : P {}
protocol Q {
associatedtype A : P
}
protocol R {}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1]B : P, Self.[Q]A.[P]T == Self.[Q1]B.[P]T>
// GSB: Non-canonical requirement
protocol Q1 : Q {
associatedtype B : P where A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1a@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1a]B : P, Self.[Q]A.[P]T : R, Self.[Q]A.[P]T == Self.[Q1a]B.[P]T>
// GSB: Missing requirement
protocol Q1a : Q {
associatedtype B : P where A.T : R, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q1b@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q1b]B : P, Self.[Q]A.[P]T : R, Self.[Q]A.[P]T == Self.[Q1b]B.[P]T>
// GSB: Non-canonical requirement
protocol Q1b : Q {
associatedtype B : P where B.T : R, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q2@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q2]B : P, Self.[Q]A.[P]T == Self.[Q2]B.[P]T>
// GSB: Missing requirement
protocol Q2 : Q {
associatedtype B : P where A.T == B.T, A == G<B.T>
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q3@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q3]B : P, Self.[Q]A.[P]T == Self.[Q3]B.[P]T>
// GSB: Unsupported recursive requirement
protocol Q3 : Q {
associatedtype B : P where A == G<A.T>, A.T == B.T
}
// CHECK-LABEL: abstract_type_witnesses_in_protocols.(file).Q4@
// CHECK-NEXT: Requirement signature: <Self where Self : Q, Self.[Q]A == G<Self.[Q]A.[P]T>, Self.[Q4]B : P, Self.[Q]A.[P]T == Self.[Q4]B.[P]T>
// GSB: Unsupported recursive requirement
protocol Q4 : Q {
associatedtype B : P where A.T == B.T, A == G<A.T>
}
| apache-2.0 | 046445546bb2d66e5e074c96d099a0ca | 36.492063 | 185 | 0.646486 | 2.627364 | false | false | false | false |
takehiroman/Swift-Shooting-game | swiftsimplegame/swiftsimplegame/GameViewController.swift | 1 | 2170 | //
// GameViewController.swift
// swiftsimplegame
//
// Created by zakimoto on 2014/12/05.
// Copyright (c) 2014年 津崎 豪宏. All rights reserved.
//
import UIKit
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| mit | 7f81cb0ec2e79d357b1fc8e7e1e40e3c | 30.304348 | 104 | 0.625463 | 5.440806 | false | false | false | false |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/EVEContractBids.swift | 1 | 1488 | //
// EVEContractBids.swift
// EVEAPI
//
// Created by Artem Shimanski on 29.11.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
public class EVEContractBidsItem: EVEObject {
public var bidID: Int = 0
public var contractID: Int64 = 0
public var bidderID: Int64 = 0
public var dateBid: Date = Date.distantPast
public var amount: Double = 0
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"bidID":EVESchemeElementType.Int(elementName:nil, transformer:nil),
"contractID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"bidderID":EVESchemeElementType.Int64(elementName:nil, transformer:nil),
"dateBid":EVESchemeElementType.String(elementName:nil, transformer:nil),
"amount":EVESchemeElementType.Double(elementName:nil, transformer:nil),
]
}
}
public class EVEContractBids: EVEResult {
public var bidList: [EVEContractBidsItem] = []
public required init?(dictionary:[String:Any]) {
super.init(dictionary: dictionary)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func scheme() -> [String:EVESchemeElementType] {
return [
"bidList":EVESchemeElementType.Rowset(elementName: nil, type: EVEContractBidsItem.self, transformer: nil),
]
}
}
| mit | d73f5d45231c42ef7f250103fedff0ef | 26.537037 | 109 | 0.737727 | 3.600484 | false | false | false | false |
buscarini/JMSSwiftParse | Source/validation.swift | 1 | 3041 | //
// validation.swift
// JMSSwiftParse
//
// Created by Jose Manuel Sánchez Peñarroja on 10/11/14.
// Copyright (c) 2014 José Manuel Sánchez. All rights reserved.
//
import Foundation
// MARK: Size
public func equal<T: Equatable>(value : T) -> (T) -> Bool {
return { $0==value }
}
public func different<T: Equatable>(value : T) -> (T) -> Bool {
return { !($0==value) }
}
public func smallerThan<T: Comparable>(min : T) -> (T) -> Bool {
return { $0<min }
}
public func smallerThanOrEqual<T: Comparable>(min : T) -> (T) -> Bool {
return { $0<=min }
}
public func greaterThan<T: Comparable>(min : T) -> (T) -> Bool {
return { $0>min }
}
public func greaterThanOrEqual<T: Comparable>(min : T) -> (T) -> Bool {
return { $0>=min }
}
// MARK: Length
public func compareLength(length: Int, operation: (Int,Int) -> Bool ) -> (String) -> Bool {
return { operation($0.lengthOfBytesUsingEncoding(NSUTF8StringEncoding),length) }
}
public func compareLength(length: Int, operation: (Int,Int) -> Bool ) -> (NSString) -> Bool {
return { operation($0.length,length) }
}
public func longerThan(length: Int) -> (String) -> Bool {
return compareLength(length, >)
}
public func longerThanOrEqual(length: Int) -> (String) -> Bool {
return compareLength(length, >=)
}
public func shorterThan(length: Int) -> (String) -> Bool {
return compareLength(length, <)
}
public func shorterThanOrEqual(length: Int) -> (String) -> Bool {
return compareLength(length, <=)
}
/// MARK : Email
public func isEmail(string: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTestPredicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
if let predicate = emailTestPredicate {
return predicate.evaluateWithObject(string)
}
return false
}
/// MARK : Dates
//public func compareDate(date: NSDate,operation: (NSDate,NSDate) -> Bool) -> (NSDate) -> Bool {
// return { operation($0,date) }
//}
public func earlierThan(date: NSDate) -> (NSDate) -> Bool {
return { $0.compare(date)==NSComparisonResult.OrderedAscending }
}
public func earlierThanOrEqual(date: NSDate) -> (NSDate) -> Bool {
return { let result = $0.compare(date)
return result==NSComparisonResult.OrderedAscending || result==NSComparisonResult.OrderedSame }
}
public func laterThan(date: NSDate) -> (NSDate) -> Bool {
return { $0.compare(date)==NSComparisonResult.OrderedDescending }
}
public func laterThanOrEqual(date: NSDate) -> (NSDate) -> Bool {
return { let result = $0.compare(date)
return result==NSComparisonResult.OrderedDescending || result==NSComparisonResult.OrderedSame }
}
// MARK: Function operators
public func &&<T>(lhs: (T) -> Bool,rhs : (T) -> Bool) -> (T) -> Bool {
return {
(val) in
if !lhs(val){
return false
}
return rhs(val)
}
}
public func ||<T>(lhs: (T) -> Bool,rhs : (T) -> Bool) -> (T) -> Bool {
return {
(val) in
if lhs(val){
return true
}
return rhs(val)
}
}
prefix public func !<T>(validator: (T) -> Bool) -> (T) -> Bool {
return { !validator($0) }
}
| mit | a79ecd6ee902eed0c528f19466c2a24a | 23.691057 | 97 | 0.654593 | 3.156965 | false | false | false | false |
huangboju/Moots | 算法学习/LeetCode/LeetCode/Backtrack/Permute.swift | 1 | 880 | //
// Permute.swift
// LeetCode
//
// Created by jourhuang on 2021/3/29.
// Copyright © 2021 伯驹 黄. All rights reserved.
//
import Foundation
// https://leetcode.cn/problems/permutations/
class Permute {
var result: [[Int]] = []
func permute(_ nums: [Int]) -> [[Int]] {
var path: [Int] = []
var used = Array(repeating: false, count: nums.count)
backtrack(nums, &path, &used)
return result
}
func backtrack(_ nums: [Int], _ path: inout [Int], _ used: inout [Bool]) {
if path.count == nums.count {
result.append(path)
return
}
for (i, n) in nums.enumerated() {
if used[i] { continue }
used[i] = true
path.append(n)
backtrack(nums, &path, &used)
path.removeLast()
used[i] = false
}
}
}
| mit | e5ba874a9e2115dc16190560c332b510 | 21.384615 | 78 | 0.512027 | 3.607438 | false | false | false | false |
kkolli/MathGame | client/Speedy/GameScene.swift | 1 | 6856 | //
// GameScene.swift
// Speedy
//
// Created by Tyler Levine on 1/27/15.
// Copyright (c) 2015 Krishna Kolli. All rights reserved.
//
import SpriteKit
class GameScene : SKScene, SKPhysicsContactDelegate {
var contentCreated = false
var scoreHandler: ((op1: Int, op2: Int, oper: Operator) -> ((Int, Bool)))?
var currentJoint: SKPhysicsJoint?
var joinedNodeA: NumberCircle?
var joinedNodeB: OperatorCircle?
var targetNumber: Int?
var activeNode: SKNode?
var freezeAction = false
var releaseNumber: NumberCircle?
var releaseOperator: OperatorCircle?
// this shouldn't be here?
//var boardController: BoardController?
var gameFrame: CGRect?
override init(size: CGSize){
super.init(size: size)
let background = SKSpriteNode(imageNamed: "background_graph_paper")
addChild(background)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
//setUpPhysics()
}
func setGameFrame(frame: CGRect) {
gameFrame = frame
setupBoardHeader()
}
func setupBoardHeader() {
if let gf = gameFrame {
let frame = CGRectMake(gf.origin.x, gf.origin.y, gf.width, self.frame.height - gf.height)
//header = BoardHeader(size: frame, )
}
}
func getActiveNode() -> SKNode? {
return activeNode
}
func determineClosestAnchorPair(position: CGPoint, nodeA: GameCircle, nodeB: GameCircle) -> (CGPoint, CGPoint) {
func distBetweenPoints(pointA: CGPoint, pointB: CGPoint) -> CGFloat {
let dx = CGFloat(abs(pointA.x - pointB.x))
let dy = CGFloat(abs(pointA.y - pointB.y))
let sumSquares = dx * dx + dy * dy
return sqrt(sumSquares)
}
let aLeftAnchor = nodeA.getLeftAnchor()
let aRightAnchor = nodeA.getRightAnchor()
let bLeftAnchor = nodeB.getLeftAnchor()
let bRightAnchor = nodeB.getRightAnchor()
let aLeftDist = distBetweenPoints(position, aLeftAnchor)
let bLeftDist = distBetweenPoints(position, bLeftAnchor)
let aRightDist = distBetweenPoints(position, aRightAnchor)
let bRightDist = distBetweenPoints(position, bRightAnchor)
let d1 = aLeftDist + bRightDist
let d2 = aRightDist + bLeftDist
return (d1 < d2) ? (nodeA.getLeftAnchor(), nodeB.getRightAnchor()) : (nodeA.getRightAnchor(),nodeB.getLeftAnchor())
}
func createBestJoint(touchPoint: CGPoint, nodeA: GameCircle, nodeB: GameCircle) -> SKPhysicsJoint {
let (anchorPointA, anchorPointB) = determineClosestAnchorPair(touchPoint, nodeA: nodeA, nodeB: nodeB)
let myJoint = SKPhysicsJointPin.jointWithBodyA(nodeA.physicsBody, bodyB: nodeB.physicsBody, anchor: anchorPointA)
myJoint.frictionTorque = 1.0
currentJoint = myJoint
return myJoint
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
// println("in touchesbegan and freezeaction is: " + String(freezeAction.description))
if (freezeAction == true) {
return
}
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
var touchedNode = nodeAtPoint(touchLocation)
while !(touchedNode is GameCircle) {
if touchedNode is SKScene {
// can't move the scene, finger probably fell off a circle?
if let physBody = activeNode?.physicsBody {
physBody.dynamic = true
}
return
}
touchedNode = touchedNode.parent!
}
/*Make the touched node do something*/
if let physBody = touchedNode.physicsBody {
physBody.dynamic = false
}
activeNode = touchedNode
if activeNode! is NumberCircle{
let liftup = SKAction.scaleTo(GameCircleProperties.pickupScaleFactor, duration: 0.2)
activeNode!.runAction(liftup)
}
}
func adjustPositionIntoGameFrame(position: CGPoint) -> CGPoint {
if let frame = gameFrame {
let nodeRadius = GameCircleProperties.nodeRadius * GameCircleProperties.pickupScaleFactor
let maxHeight = frame.height - nodeRadius
if maxHeight < position.y {
return CGPointMake(position.x, maxHeight)
}
}
return position
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
// println("in touchesmoved and freezeaction is: " + String(freezeAction.description))
releaseNumber = nil
releaseOperator = nil
if (freezeAction == true) {
return
}
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(self)
if activeNode != nil{
while !(activeNode is GameCircle) {
if activeNode is SKScene {
// can't move the scene, finger probably fell off a circle?
if let physBody = activeNode?.physicsBody {
physBody.dynamic = true
}
return
}
activeNode = activeNode!.parent!
}
//Only number circles can be moved
if activeNode is NumberCircle{
activeNode!.position = adjustPositionIntoGameFrame(touchLocation)
}
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
//Break the node joint if touch is released
breakJoint()
if let physBody = activeNode?.physicsBody {
physBody.dynamic = true
}
if activeNode != nil && activeNode! is NumberCircle{
let dropDown = SKAction.scaleTo(1.0, duration: 0.2)
activeNode!.runAction(dropDown, withKey: "drop")
}
activeNode = nil
}
func breakJoint(){
if currentJoint != nil {
println("breakjoint")
self.physicsWorld.removeJoint(currentJoint!)
currentJoint = nil
if joinedNodeA != nil{
joinedNodeA!.neighbor = nil
}
if joinedNodeB != nil{
joinedNodeB!.neighbor = nil
}
releaseNumber = joinedNodeA
releaseOperator = joinedNodeB
joinedNodeA = nil
joinedNodeB = nil
}
}
}
| gpl-2.0 | 90e8d5e339980a08c9b21760e1cad836 | 31.647619 | 123 | 0.579492 | 4.872779 | false | false | false | false |
ycaihua/Paranormal | Paranormal/Paranormal/GPUImageFilters/BlendFilters/BlendSmoothFilter.swift | 3 | 1596 | import Foundation
import GPUImage
import OpenGL
class BlendSmoothFilter : BlendFilter {
var blurRadius : CGFloat = 10
var replaceAlphaFilter : GPUImageFilter!
var blurFilter : GPUImageGaussianBlurFilter!
var normalizeFilter : GPUImageFilter!
var blendAddFilter : BlendAddFilter!
override init() {
super.init()
replaceAlphaFilter = GPUImageTwoInputFilter(fragmentShaderFromFile: "ReplaceAlpha")
self.addFilter(replaceAlphaFilter)
self.blurFilter = GPUImageGaussianBlurFilter()
blurFilter.blurRadiusInPixels = blurRadius;
self.addFilter(blurFilter)
let normalizeFilter = GPUImageFilter(fragmentShaderFromFile: "Normalize")
self.addFilter(normalizeFilter)
self.blendAddFilter = BlendAddFilter()
self.addFilter(blendAddFilter)
blurFilter.addTarget(replaceAlphaFilter, atTextureLocation: 0)
replaceAlphaFilter.addTarget(normalizeFilter, atTextureLocation: 1)
normalizeFilter.addTarget(blendAddFilter, atTextureLocation: 1)
initialFilters = [replaceAlphaFilter, blurFilter]
terminalFilter = blendAddFilter
}
override func setInputs(#top: GPUImageOutput, base: GPUImageOutput) {
base.addTarget(self.blurFilter)
base.addTarget(self.blendAddFilter, atTextureLocation: 0)
top.addTarget(self.replaceAlphaFilter)
}
override func setOpacity(opacity: Float) {
if let filter = self.blendAddFilter.filterWithOpacity {
filter.setFloat(GLfloat(opacity), forUniformName: "opacity")
}
}
}
| mit | 37f439f6160aab363548c0df61129529 | 32.25 | 91 | 0.718672 | 4.612717 | false | false | false | false |
mmrmmlrr/ExamMaster | Pods/ModelsTreeKit/ModelsTreeDemo/ModelsTreeDemo/ViewController.swift | 1 | 1268 | //
// ViewController.swift
// ModelsTreeDemo
//
// Created by Aleksey on 20.08.16.
// Copyright © 2016 Aleksey Chernish. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var searchBar: UISearchBar!
private var adapter: TableViewAdapter<Int>!
private let list = OrderedList<Int>(parent: nil)
private var dataAdapter: OrderedListDataAdapter<Int>!
override func viewDidLoad() {
super.viewDidLoad()
dataAdapter = OrderedListDataAdapter(list: list)
dataAdapter.groupingCriteria = { $0 > 3 ? "2" : "1" }
adapter = TableViewAdapter(dataSource: dataAdapter, tableView: tableView)
adapter.registerCellClass(TestCell.self)
adapter.nibNameForObjectMatching = { _ in String(TestCell) }
var arr = [Int]()
for i in 0...5 {
arr.append(i)
}
list.performUpdates { $0.append(arr) }
}
@IBAction func addMore(sender: AnyObject?) {
list.replaceWith([1, 2, 3])
// let last = list.objects.last!
// var arr = [Int]()
// for i in last...last + 20 {
// arr.append(i)
// }
// list.performUpdates {
// $0.delete([3])
// }
}
}
| mit | 8d3b722c8d0e35d7620dfe9b81de707e | 24.857143 | 79 | 0.629045 | 3.827795 | false | false | false | false |
mightydeveloper/swift | stdlib/public/SDK/Foundation/ExtraStringAPIs.swift | 10 | 962 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Random access for String.UTF16View, only when Foundation is
// imported. Making this API dependent on Foundation decouples the
// Swift core from a UTF16 representation.
extension String.UTF16View.Index : RandomAccessIndexType {
/// Construct from an integer offset.
public init(_ offset: Int) {
_precondition(offset >= 0, "Negative UTF16 index offset not allowed")
self.init(_offset: offset)
// self._offset = offset
}
}
| apache-2.0 | 33523aaa153d8bb38534520b895d5a67 | 40.826087 | 80 | 0.610187 | 4.834171 | false | false | false | false |
paynerc/video-quickstart-swift | VideoCallKitQuickStart/ViewController.swift | 1 | 14244 | //
// ViewController.swift
// VideoCallKitQuickStart
//
// Copyright © 2016-2017 Twilio, Inc. All rights reserved.
//
import UIKit
import TwilioVideo
import CallKit
class ViewController: UIViewController {
// MARK: View Controller Members
// Configure access token manually for testing, if desired! Create one manually in the console
// at https://www.twilio.com/user/account/video/dev-tools/testing-tools
var accessToken = "TWILIO_ACCESS_TOKEN"
// Configure remote URL to fetch token from
var tokenUrl = "http://localhost:8000/token.php"
// Video SDK components
var room: TVIRoom?
var camera: TVICameraCapturer?
var localVideoTrack: TVILocalVideoTrack?
var localAudioTrack: TVILocalAudioTrack?
var participant: TVIParticipant?
var remoteView: TVIVideoView?
// CallKit components
let callKitProvider:CXProvider
let callKitCallController:CXCallController
var callKitCompletionHandler: ((Bool)->Swift.Void?)? = nil
// MARK: UI Element Outlets and handles
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var simulateIncomingButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var roomTextField: UITextField!
@IBOutlet weak var roomLine: UIView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var micButton: UIButton!
// `TVIVideoView` created from a storyboard
@IBOutlet weak var previewView: TVIVideoView!
required init?(coder aDecoder: NSCoder) {
let configuration = CXProviderConfiguration(localizedName: "CallKit Quickstart")
configuration.maximumCallGroups = 1
configuration.maximumCallsPerCallGroup = 1
configuration.supportsVideo = true
if let callKitIcon = UIImage(named: "iconMask80") {
configuration.iconTemplateImageData = UIImagePNGRepresentation(callKitIcon)
}
callKitProvider = CXProvider(configuration: configuration)
callKitCallController = CXCallController()
super.init(coder: aDecoder)
callKitProvider.setDelegate(self, queue: nil)
}
deinit {
// CallKit has an odd API contract where the developer must call invalidate or the CXProvider is leaked.
callKitProvider.invalidate()
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if PlatformUtils.isSimulator {
self.previewView.removeFromSuperview()
} else {
// Preview our local camera track in the local video preview view.
self.startPreview()
}
// Disconnect and mic button will be displayed when the Client is connected to a Room.
self.disconnectButton.isHidden = true
self.micButton.isHidden = true
self.roomTextField.autocapitalizationType = .none
self.roomTextField.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
self.view.addGestureRecognizer(tap)
}
func setupRemoteVideoView() {
// Creating `TVIVideoView` programmatically
self.remoteView = TVIVideoView.init(frame: CGRect.zero, delegate: self)
self.view.insertSubview(self.remoteView!, at: 0)
// `TVIVideoView` supports scaleToFill, scaleAspectFill and scaleAspectFit
// scaleAspectFit is the default mode when you create `TVIVideoView` programmatically.
self.remoteView!.contentMode = .scaleAspectFit;
let centerX = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerX,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerX,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.centerY,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.centerY,
multiplier: 1,
constant: 0);
self.view.addConstraint(centerY)
let width = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.width,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.width,
multiplier: 1,
constant: 0);
self.view.addConstraint(width)
let height = NSLayoutConstraint(item: self.remoteView!,
attribute: NSLayoutAttribute.height,
relatedBy: NSLayoutRelation.equal,
toItem: self.view,
attribute: NSLayoutAttribute.height,
multiplier: 1,
constant: 0);
self.view.addConstraint(height)
}
// MARK: IBActions
@IBAction func connect(sender: AnyObject) {
performStartCallAction(uuid: UUID.init(), roomName: self.roomTextField.text)
self.dismissKeyboard()
}
@IBAction func disconnect(sender: AnyObject) {
if let room = room, let uuid = room.uuid {
logMessage(messageText: "Attempting to disconnect from room \(room.name)")
performEndCallAction(uuid: uuid)
}
}
@IBAction func toggleMic(sender: AnyObject) {
if (self.localAudioTrack != nil) {
self.localAudioTrack?.isEnabled = !(self.localAudioTrack?.isEnabled)!
// Update the button title
if (self.localAudioTrack?.isEnabled == true) {
self.micButton.setTitle("Mute", for: .normal)
} else {
self.micButton.setTitle("Unmute", for: .normal)
}
}
}
// MARK: Private
func startPreview() {
if PlatformUtils.isSimulator {
return
}
// Preview our local camera track in the local video preview view.
camera = TVICameraCapturer(source: .frontCamera, delegate: self)
localVideoTrack = TVILocalVideoTrack.init(capturer: camera!)
if (localVideoTrack == nil) {
logMessage(messageText: "Failed to create video track")
} else {
// Add renderer to video track for local preview
localVideoTrack!.addRenderer(self.previewView)
logMessage(messageText: "Video track created")
// We will flip camera on tap.
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.flipCamera))
self.previewView.addGestureRecognizer(tap)
}
}
func flipCamera() {
if (self.camera?.source == .frontCamera) {
self.camera?.selectSource(.backCameraWide)
} else {
self.camera?.selectSource(.frontCamera)
}
}
func prepareLocalMedia() {
// We will share local audio and video when we connect to the Room.
// Create an audio track.
if (localAudioTrack == nil) {
localAudioTrack = TVILocalAudioTrack.init()
if (localAudioTrack == nil) {
logMessage(messageText: "Failed to create audio track")
}
}
// Create a video track which captures from the camera.
if (localVideoTrack == nil) {
self.startPreview()
}
}
// Update our UI based upon if we are in a Room or not
func showRoomUI(inRoom: Bool) {
self.connectButton.isHidden = inRoom
self.simulateIncomingButton.isHidden = inRoom
self.roomTextField.isHidden = inRoom
self.roomLine.isHidden = inRoom
self.roomLabel.isHidden = inRoom
self.micButton.isHidden = !inRoom
self.disconnectButton.isHidden = !inRoom
UIApplication.shared.isIdleTimerDisabled = inRoom
}
func dismissKeyboard() {
if (self.roomTextField.isFirstResponder) {
self.roomTextField.resignFirstResponder()
}
}
func cleanupRemoteParticipant() {
if ((self.participant) != nil) {
if ((self.participant?.videoTracks.count)! > 0) {
self.participant?.videoTracks[0].removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
self.participant = nil
}
func logMessage(messageText: String) {
NSLog(messageText)
messageLabel.text = messageText
}
func holdCall(onHold: Bool) {
localAudioTrack?.isEnabled = !onHold
localVideoTrack?.isEnabled = !onHold
}
}
// MARK: UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.connect(sender: textField)
return true
}
}
// MARK: TVIRoomDelegate
extension ViewController : TVIRoomDelegate {
func didConnect(to room: TVIRoom) {
// At the moment, this example only supports rendering one Participant at a time.
logMessage(messageText: "Connected to room \(room.name) as \(String(describing: room.localParticipant?.identity))")
if (room.participants.count > 0) {
self.participant = room.participants[0]
self.participant?.delegate = self
}
let cxObserver = callKitCallController.callObserver
let calls = cxObserver.calls
// Let the call provider know that the outgoing call has connected
if let uuid = room.uuid, let call = calls.first(where:{$0.uuid == uuid}) {
if call.isOutgoing {
callKitProvider.reportOutgoingCall(with: uuid, connectedAt: nil)
}
}
self.callKitCompletionHandler!(true)
}
func room(_ room: TVIRoom, didDisconnectWithError error: Error?) {
logMessage(messageText: "Disconncted from room \(room.name), error = \(String(describing: error))")
self.cleanupRemoteParticipant()
self.room = nil
self.showRoomUI(inRoom: false)
self.callKitCompletionHandler = nil
}
func room(_ room: TVIRoom, didFailToConnectWithError error: Error) {
logMessage(messageText: "Failed to connect to room with error: \(error.localizedDescription)")
self.callKitCompletionHandler!(false)
self.room = nil
self.showRoomUI(inRoom: false)
}
func room(_ room: TVIRoom, participantDidConnect participant: TVIParticipant) {
if (self.participant == nil) {
self.participant = participant
self.participant?.delegate = self
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) connected")
}
func room(_ room: TVIRoom, participantDidDisconnect participant: TVIParticipant) {
if (self.participant == participant) {
cleanupRemoteParticipant()
}
logMessage(messageText: "Room \(room.name), Participant \(participant.identity) disconnected")
}
}
// MARK: TVIParticipantDelegate
extension ViewController : TVIParticipantDelegate {
func participant(_ participant: TVIParticipant, addedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) added video track")
if (self.participant == participant) {
setupRemoteVideoView()
videoTrack.addRenderer(self.remoteView!)
}
}
func participant(_ participant: TVIParticipant, removedVideoTrack videoTrack: TVIVideoTrack) {
logMessage(messageText: "Participant \(participant.identity) removed video track")
if (self.participant == participant) {
videoTrack.removeRenderer(self.remoteView!)
self.remoteView?.removeFromSuperview()
self.remoteView = nil
}
}
func participant(_ participant: TVIParticipant, addedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) added audio track")
}
func participant(_ participant: TVIParticipant, removedAudioTrack audioTrack: TVIAudioTrack) {
logMessage(messageText: "Participant \(participant.identity) removed audio track")
}
func participant(_ participant: TVIParticipant, enabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) enabled \(type) track")
}
func participant(_ participant: TVIParticipant, disabledTrack track: TVITrack) {
var type = ""
if (track is TVIVideoTrack) {
type = "video"
} else {
type = "audio"
}
logMessage(messageText: "Participant \(participant.identity) disabled \(type) track")
}
}
// MARK: TVIVideoViewDelegate
extension ViewController : TVIVideoViewDelegate {
func videoView(_ view: TVIVideoView, videoDimensionsDidChange dimensions: CMVideoDimensions) {
self.view.setNeedsLayout()
}
}
// MARK: TVICameraCapturerDelegate
extension ViewController : TVICameraCapturerDelegate {
func cameraCapturer(_ capturer: TVICameraCapturer, didStartWith source: TVICameraCaptureSource) {
self.previewView.shouldMirror = (source == .frontCamera)
}
}
| mit | 478eddfe369db6b4d3276cacd334f68c | 36.091146 | 123 | 0.612371 | 5.434185 | false | false | false | false |
VeinGuo/VGPlayer | VGPlayerExample/VGPlayerExample/CustomPlayerView/VGCustomViewController2.swift | 1 | 5101 | //
// VGCustomViewController2.swift
// VGPlayerExample
//
// Created by Vein on 2017/6/19.
// Copyright © 2017年 Vein. All rights reserved.
//
import UIKit
import VGPlayer
import SnapKit
class VGCustomViewController2: UIViewController {
var nextCount = 0
var player : VGPlayer!
var playerView : VGCustomPlayerView2!
var dataScource : [String] = []
@IBOutlet weak var adsButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configurePlayer()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: false)
self.player.play()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: false)
UIApplication.shared.setStatusBarHidden(false, with: .none)
self.player.pause()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getVideos() -> URL{
self.dataScource = ["http://baobab.wdjcdn.com/1451826889080C.mp4",
"http://baobab.wdjcdn.com/14399887845852_x264.mp4",
"http://baobab.wdjcdn.com/1442142801331138639111.mp4",
"http://baobab.wdjcdn.com/143625320119607.mp4",
"http://baobab.wdjcdn.com/145345719887961975219.mp4",
"http://baobab.wdjcdn.com/1442142801331138639111.mp4",
"http://baobab.wdjcdn.com/143323298510702.mp4"]
nextCount = nextCount % self.dataScource.count
let url = URL(string: self.dataScource[nextCount])!
nextCount += 1
return url
}
@IBAction func addAdsAction(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
self.playerView.isAds = sender.isSelected
}
}
// MARK: - player
extension VGCustomViewController2 {
func configurePlayer() {
self.playerView = VGCustomPlayerView2()
self.player = VGPlayer(playerView: playerView)
self.player.replaceVideo(getVideos())
view.addSubview(self.player.displayView)
self.player.backgroundMode = .suspend
self.player.delegate = self
self.player.displayView.delegate = self
self.player.displayView.snp.makeConstraints { [weak self] (make) in
guard let strongSelf = self else { return }
make.top.equalTo(strongSelf.view.snp.top)
make.left.equalTo(strongSelf.view.snp.left)
make.right.equalTo(strongSelf.view.snp.right)
make.height.equalTo(strongSelf.view.snp.width).multipliedBy(9.0/16.0) // you can 9.0/16.0
}
self.playerView.nextCallBack = ({ [weak self] () -> Void in
guard let strongSelf = self else { return }
strongSelf.player.replaceVideo(strongSelf.getVideos())
strongSelf.player.play()
})
self.playerView.skipCallBack = ({ [weak self] () -> Void in
guard let strongSelf = self else { return }
strongSelf.adsButton.isSelected = false
strongSelf.player.replaceVideo(strongSelf.getVideos())
strongSelf.player.play()
strongSelf.playerView.isAds = false
})
// Default, the first for the ads
self.playerView.isAds = true
}
}
// MARK: - VGPlayerDelegate
extension VGCustomViewController2: VGPlayerDelegate {
func vgPlayer(_ player: VGPlayer, playerFailed error: VGPlayerError) {
print(error)
}
func vgPlayer(_ player: VGPlayer, stateDidChange state: VGPlayerState) {
// aotu play next
if state == .playFinished {
self.player.replaceVideo(getVideos())
self.player.play()
}
}
func vgPlayer(_ player: VGPlayer, bufferStateDidChange state: VGPlayerBufferstate) {
print("buffer State", state)
}
}
// MARK: - VGPlayerViewDelegate
extension VGCustomViewController2: VGPlayerViewDelegate {
func vgPlayerView(_ playerView: VGPlayerView, willFullscreen fullscreen: Bool) {
self.playerView.updateCustomView()
}
func vgPlayerView(didTappedClose playerView: VGPlayerView) {
if playerView.isFullScreen {
playerView.exitFullscreen()
} else {
self.navigationController?.popViewController(animated: true)
}
}
func vgPlayerView(didDisplayControl playerView: VGPlayerView) {
UIApplication.shared.setStatusBarHidden(!playerView.isDisplayControl, with: .fade)
}
}
| mit | 74b50939647e0eec12007be6469e6be8 | 34.901408 | 101 | 0.641428 | 4.531556 | false | false | false | false |
sergiog90/PagedUITableViewController | Example/PagedUITableViewController/ViewController.swift | 1 | 4147 | //
// ViewController.swift
// PagedUITableViewController
//
// Created by Sergio García on 09/23/2016.
// Copyright (c) 2016 Sergio García. All rights reserved.
//
import UIKit
import PagedUITableViewController
class TableViewController: PagedUITableViewController {
private var dataSource = [[User]]()
private var currentRequest: NSURLSessionTask?
override func viewDidLoad() {
self.tableView.estimatedRowHeight = 55
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.tableFooterView = UIView()
self.tableView.registerNib(UINib(nibName: String(LoadingTableViewCell), bundle: nil), forCellReuseIdentifier: String(LoadingTableViewCell))
self.tableView.registerNib(UINib(nibName: String(UserTableViewCell), bundle: nil), forCellReuseIdentifier: String(UserTableViewCell))
self.pagedDataSource = self
self.pagedDelegate = self
super.viewDidLoad()
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
self.dataSource[indexPath.section].removeAtIndex(indexPath.row)
self.pagedActionsDelegate.deleteItem(atIndexPath: indexPath)
}
}
private func downloadUsers(offset offset: Int, onSuccess: (pageSize: Int, data: [AnyObject], totalItems: Int) -> (), onError: (delayTime: NSTimeInterval) -> ()) {
currentRequest = User.users(offset: offset, onSuccess: onSuccess, onError: onError)
}
private func setImageFromUrl(urlImage: String, forImageView imageView: UIImageView) {
if let url = NSURL(string: urlImage) {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response, error) in
guard let data = data where error == nil
else {
print(error?.localizedDescription)
return
}
let image = UIImage(data: data)
dispatch_async(dispatch_get_main_queue(), {
imageView.image = image
})
}
task.resume()
}
}
}
extension TableViewController: PagedUITableViewDataSource {
func downloadData(offset offset: Int, onSuccess: (pageSize: Int, data: [AnyObject], totalItems: Int) -> (), onError: (delayTime: NSTimeInterval) -> ()) {
self.downloadUsers(offset: offset, onSuccess: onSuccess, onError: onError)
}
func appendData(data: [AnyObject], forOffset offset: Int) {
self.dataSource.append(data as? [User] ?? [])
}
func numberOfSectionsInPagedTableView(pagedTableView: UITableView) -> Int {
return dataSource.count
}
func pagedTableView(pagedTableView: UITableView, numberOfRowsInPagedSection section: Int) -> Int {
return dataSource[section].count
}
func loadingCellForPagedTableView(pagedTableView: UITableView, forIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(String(LoadingTableViewCell), forIndexPath: indexPath) as! LoadingTableViewCell
}
func pagedTableView(pagedTableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let user = dataSource[indexPath.section][indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(String(UserTableViewCell), forIndexPath: indexPath) as! UserTableViewCell
self.setImageFromUrl(user.avatar, forImageView: cell.userImage)
cell.userId.text = "id: \(user.userId)"
cell.userFirstName.text = user.firstName.capitalizedString
cell.userLastName.text = user.lastName.capitalizedString
return cell
}
}
extension TableViewController: PagedUITableViewDelegate {
func resetDataSource() {
dataSource.removeAll()
}
func cancelCurrentRequest() {
if let currentRequest = currentRequest {
currentRequest.cancel()
}
}
}
| mit | 3b047b7c7d70dfbc80d6f51af436517b | 39.242718 | 166 | 0.676236 | 5.28699 | false | false | false | false |
ajsnow/Shear | Shear/Transform.swift | 1 | 2909 | // 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)})
}
}
| mit | 4bc4f093167939c98d0fd92ca280ca45 | 34.91358 | 106 | 0.621863 | 4.234352 | false | false | false | false |
uxmstudio/UXMPDFKit | Pod/Classes/Renderer/PDFSinglePageViewer.swift | 1 | 9331 | //
// PDFSinglePageViewer.swift
// Pods
//
// Created by Chris Anderson on 3/6/16.
//
//
import UIKit
public protocol PDFSinglePageViewerDelegate {
func singlePageViewer(_ collectionView: PDFSinglePageViewer, didDisplayPage page: Int)
func singlePageViewer(_ collectionView: PDFSinglePageViewer, loadedContent content: PDFPageContentView)
func singlePageViewer(_ collectionView: PDFSinglePageViewer, selected action: PDFAction)
func singlePageViewer(_ collectionView: PDFSinglePageViewer, selected annotation: PDFAnnotationView)
func singlePageViewer(_ collectionView: PDFSinglePageViewer, tapped recognizer: UITapGestureRecognizer)
func singlePageViewerDidBeginDragging()
func singlePageViewerDidEndDragging()
}
open class PDFSinglePageFlowLayout: UICollectionViewFlowLayout {
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
}
open class PDFSinglePageViewer: UICollectionView {
open var singlePageDelegate: PDFSinglePageViewerDelegate?
open var document: PDFDocument?
var internalPage: Int = 0
var scrollDirection: UICollectionView.ScrollDirection {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
return flowLayout.scrollDirection
}
private static var flowLayout: UICollectionViewFlowLayout {
let layout = PDFSinglePageFlowLayout()
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets.zero
layout.minimumLineSpacing = 0.0
layout.minimumInteritemSpacing = 0.0
return layout
}
public init(frame: CGRect, document: PDFDocument) {
self.document = document
super.init(frame: frame, collectionViewLayout: PDFSinglePageViewer.flowLayout)
setupCollectionView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
collectionViewLayout = PDFSinglePageViewer.flowLayout
setupCollectionView()
}
func setupCollectionView() {
isPagingEnabled = true
backgroundColor = UIColor.groupTableViewBackground
showsHorizontalScrollIndicator = false
register(PDFSinglePageCell.self, forCellWithReuseIdentifier: "ContentCell")
delegate = self
dataSource = self
guard let document = document else { return }
displayPage(document.currentPage, animated: false)
if let pageContentView = getPageContent(document.currentPage) {
singlePageDelegate?.singlePageViewer(self, loadedContent: pageContentView)
}
}
open func indexForPage(_ page: Int) -> Int {
let currentPage = page - 1
if currentPage <= 0 {
return 0
} else if let pageCount = document?.pageCount, currentPage > pageCount {
return pageCount - 1
} else {
return currentPage
}
}
open func displayPage(_ page: Int, animated: Bool) {
let currentPage = indexForPage(page)
let indexPath = IndexPath(item: currentPage, section: 0)
switch scrollDirection {
case .horizontal:
scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated)
case .vertical:
scrollToItem(at: indexPath, at: .top, animated: animated)
}
}
open func getPageContent(_ page: Int) -> PDFPageContentView? {
if document == nil { return nil }
let currentPage = indexForPage(page)
if let cell = self.collectionView(self, cellForItemAt: IndexPath(item: currentPage, section: 0)) as? PDFSinglePageCell,
let pageContentView = cell.pageContentView {
return pageContentView
}
return nil
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
self.isScrollEnabled = !(result is ResizableBorderView)
return result
}
}
extension PDFSinglePageViewer: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let document = self.document else {
return 0
}
return document.pageCount
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = self.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! PDFSinglePageCell
let contentSize = self.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
let contentFrame = CGRect(origin: CGPoint.zero, size: contentSize)
let page = indexPath.row + 1
cell.pageContentView = PDFPageContentView(frame: contentFrame, document: document!, page: page)
cell.pageContentView?.contentDelegate = self
return cell
}
}
extension PDFSinglePageViewer: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let pdfCell = cell as? PDFSinglePageCell, let pageContentView = pdfCell.pageContentView {
singlePageDelegate?.singlePageViewer(self, loadedContent: pageContentView)
}
}
}
extension PDFSinglePageViewer: UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
switch scrollDirection {
case .horizontal:
var size = bounds.size
let contentInsetHeight = contentInset.bottom + contentInset.top + 1
size.height -= contentInsetHeight
return size
case .vertical:
let page = indexPath.row + 1
let contentViewSize = PDFPageContentView(frame: bounds, document: document!, page: page).contentSize
// Find proper aspect ratio so that cell is full width
let widthMultiplier: CGFloat
let heightMultiplier: CGFloat
if contentViewSize.width == bounds.width {
widthMultiplier = bounds.height / contentViewSize.height
heightMultiplier = 1
} else if contentViewSize.height == bounds.height {
heightMultiplier = bounds.width / contentViewSize.width
widthMultiplier = 1
} else {
fatalError()
}
return CGSize(width: bounds.size.width * widthMultiplier, height: bounds.size.height * heightMultiplier)
}
}
}
extension PDFSinglePageViewer: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
self.singlePageDelegate?.singlePageViewerDidBeginDragging()
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.singlePageDelegate?.singlePageViewerDidEndDragging()
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
didDisplayPage(scrollView)
}
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
didDisplayPage(scrollView)
}
private func didDisplayPage(_ scrollView: UIScrollView) {
let page: Int
switch scrollDirection {
case .horizontal:
page = Int((scrollView.contentOffset.x + scrollView.frame.width) / scrollView.frame.width)
case .vertical:
let currentlyShownIndexPath = indexPathsForVisibleItems.first ?? IndexPath(item: 0, section: 0)
page = currentlyShownIndexPath.row + 1
}
/// If nothing has changed, dont reload
if page == internalPage {
return
}
internalPage = page
singlePageDelegate?.singlePageViewer(self, didDisplayPage: page)
let indexPath = IndexPath(row: page - 1, section: 0)
if let cell = cellForItem(at: indexPath) as? PDFSinglePageCell {
if let pageContentView = cell.pageContentView {
singlePageDelegate?.singlePageViewer(self, loadedContent: pageContentView)
}
}
}
}
extension PDFSinglePageViewer: PDFPageContentViewDelegate {
public func contentView(_ contentView: PDFPageContentView, didSelect action: PDFAction) {
if let singlePageDelegate = singlePageDelegate {
singlePageDelegate.singlePageViewer(self, selected: action)
} else if let action = action as? PDFActionGoTo {
displayPage(action.pageIndex, animated: true)
}
}
public func contentView(_ contentView: PDFPageContentView, didSelect annotation: PDFAnnotationView) {
singlePageDelegate?.singlePageViewer(self, selected: annotation)
}
public func contentView(_ contentView: PDFPageContentView, tapped recognizer: UITapGestureRecognizer) {
singlePageDelegate?.singlePageViewer(self, tapped: recognizer)
}
public func contentView(_ contentView: PDFPageContentView, doubleTapped recognizer: UITapGestureRecognizer) {}
}
| mit | 57e06fd230e1c328c3d73e1fa010b9c1 | 36.324 | 167 | 0.688994 | 5.547562 | false | false | false | false |
milseman/swift | test/decl/protocol/req/func.swift | 10 | 7666 | // RUN: %target-typecheck-verify-swift
// Test function requirements within protocols, as well as conformance to
// said protocols.
// Simple function
protocol P1 {
func f0()
}
// Simple match
struct X1a : P1 {
func f0() {}
}
// Simple match selecting among two overloads.
struct X1b : P1 {
func f0() -> Int {}
func f0() {}
}
// Function with an associated type
protocol P2 {
associatedtype Assoc : P1 // expected-note{{ambiguous inference of associated type 'Assoc': 'X1a' vs. 'X1b'}}
// expected-note@-1{{protocol requires nested type 'Assoc'}}
func f1(_ x: Assoc) // expected-note{{protocol requires function 'f1' with type '(X2w.Assoc) -> ()'}} expected-note{{protocol requires function 'f1' with type '(X2y.Assoc) -> ()'}}
}
// Exact match.
struct X2a : P2 {
typealias Assoc = X1a
func f1(_ x: X1a) {}
}
// Select among overloads.
struct X2d : P2 {
typealias Assoc = X1a
func f1(_ x: Int) { }
func f1(_ x: X1a) { }
}
struct X2e : P2 {
typealias Assoc = X1a
func f1(_ x: X1b) { }
func f1(_ x: X1a) { }
}
// Select among overloads distinguished by name.
struct X2f : P2 {
typealias Assoc = X1a
func f1(y: X1a) { }
func f1(_ x: X1a) { }
}
// Infer associated type from function parameter
struct X2g : P2 {
func f1(_ x: X1a) { }
}
// Static/non-static mismatch.
struct X2w : P2 { // expected-error{{type 'X2w' does not conform to protocol 'P2'}}
typealias Assoc = X1a
static func f1(_ x: X1a) { } // expected-note{{candidate operates on a type, not an instance as required}}
}
// Deduction of type that doesn't meet requirements
struct X2x : P2 { // expected-error{{type 'X2x' does not conform to protocol 'P2'}}
func f1(x: Int) { }
}
// Mismatch in parameter types
struct X2y : P2 { // expected-error{{type 'X2y' does not conform to protocol 'P2'}}
typealias Assoc = X1a
func f1(x: X1b) { } // expected-note{{candidate has non-matching type '(X1b) -> ()'}}
}
// Ambiguous deduction
struct X2z : P2 { // expected-error{{type 'X2z' does not conform to protocol 'P2'}}
func f1(_ x: X1a) { } // expected-note{{matching requirement 'f1' to this declaration inferred associated type to 'X1a'}}
func f1(_ x: X1b) { } // expected-note{{matching requirement 'f1' to this declaration inferred associated type to 'X1b'}}
}
// Protocol with prefix unary function
prefix operator ~~
protocol P3 {
associatedtype Assoc : P1
static prefix func ~~(_: Self) -> Assoc // expected-note{{protocol requires function '~~' with type '(X3z) -> X3z.Assoc'}}
}
// Global operator match
struct X3a : P3 {
typealias Assoc = X1a
}
prefix func ~~(_: X3a) -> X1a {} // expected-note{{candidate has non-matching type '(X3a) -> X1a'}} expected-note{{candidate is prefix, not postfix as required}}
// FIXME: Add example with overloaded prefix/postfix
// Prefix/postfix mismatch.
struct X3z : P3 { // expected-error{{type 'X3z' does not conform to protocol 'P3'}}
typealias Assoc = X1a
}
postfix func ~~(_: X3z) -> X1a {} // expected-note{{candidate is postfix, not prefix as required}} expected-note{{candidate has non-matching type '(X3z) -> X1a'}}
// Protocol with postfix unary function
postfix operator ~~
protocol P4 {
associatedtype Assoc : P1
static postfix func ~~ (_: Self) -> Assoc // expected-note{{protocol requires function '~~' with type '(X4z) -> X4z.Assoc'}}
}
// Global operator match
struct X4a : P4 {
typealias Assoc = X1a
}
postfix func ~~(_: X4a) -> X1a {} // expected-note{{candidate has non-matching type '(X4a) -> X1a'}} expected-note{{candidate is postfix, not prefix as required}}
// Prefix/postfix mismatch.
struct X4z : P4 { // expected-error{{type 'X4z' does not conform to protocol 'P4'}}
typealias Assoc = X1a
}
prefix func ~~(_: X4z) -> X1a {} // expected-note{{candidate has non-matching type '(X4z) -> X1a'}} expected-note{{candidate is prefix, not postfix as required}}
// Objective-C protocol
@objc protocol P5 {
func f2(_ x: Int, withInt a: Int)
func f2(_ x: Int, withOtherInt a: Int)
}
// Exact match.
class X5a : P5 {
@objc func f2(_ x: Int, withInt a: Int) {}
@objc func f2(_ x: Int, withOtherInt a: Int) {}
}
// Body parameter names can vary.
class X5b : P5 {
@objc func f2(_ y: Int, withInt a: Int) {}
@objc func f2(_ y: Int, withOtherInt a: Int) {}
}
class X5c : P5 {
@objc func f2(_ y: Int, withInt b: Int) {}
@objc func f2(_ y: Int, withOtherInt b: Int) {}
}
// Names need to match up for an Objective-C protocol as well.
class X5d : P5 {
@objc(f2WithY:withInt:) func f2(_ y: Int, withInt a: Int) {} // expected-error {{Objective-C method 'f2WithY:withInt:' provided by method 'f2(_:withInt:)' does not match the requirement's selector ('f2:withInt:')}}
@objc(f2WithY:withOtherValue:) func f2(_ y: Int, withOtherInt a: Int) {} // expected-error{{Objective-C method 'f2WithY:withOtherValue:' provided by method 'f2(_:withOtherInt:)' does not match the requirement's selector ('f2:withOtherInt:')}}
}
// Distinguish names within tuple arguments.
typealias T0 = (x: Int, y: String)
typealias T1 = (xx: Int, y: String)
func f(_ args: T0) {
}
func f(_ args: T1) {
}
f(T0(1, "Hi"))
infix operator ~>> : MaxPrecedence
precedencegroup MaxPrecedence { higherThan: BitwiseShiftPrecedence }
func ~>> (x: Int, args: T0) {}
func ~>> (x: Int, args: T1) {}
3~>>T0(1, "Hi")
3~>>T1(2, "Hi")
protocol Crankable {
static func ~>> (x: Self, args: T0)
static func ~>> (x: Self, args: T1)
}
extension Int : Crankable {}
// Invalid witnesses.
protocol P6 {
func foo(_ x: Int)
func bar(x: Int) // expected-note{{protocol requires function 'bar(x:)' with type '(Int) -> ()'}}
}
struct X6 : P6 { // expected-error{{type 'X6' does not conform to protocol 'P6'}}
func foo(_ x: Missing) { } // expected-error{{use of undeclared type 'Missing'}}
func bar() { } // expected-note{{candidate has non-matching type '() -> ()'}}
}
protocol P6Ownership {
func foo(_ x: __shared Int) // expected-note{{protocol requires function 'foo' with type '(__shared Int) -> ()'}}
func foo2(_ x: Int) // expected-note{{protocol requires function 'foo2' with type '(Int) -> ()'}}
func bar(x: Int)
func bar2(x: __owned Int)
}
struct X6Ownership : P6Ownership { // expected-error{{type 'X6Ownership' does not conform to protocol 'P6Ownership'}}
func foo(_ x: Int) { } // expected-note{{candidate has non-matching type '(Int) -> ()'}}
func foo2(_ x: __shared Int) { } // expected-note{{candidate has non-matching type '(__shared Int) -> ()'}}
func bar(x: __owned Int) { } // no diagnostic
func bar2(x: Int) { } // no diagnostic
}
protocol P7 {
func foo(_ x: Blarg) // expected-error{{use of undeclared type 'Blarg'}}
}
struct X7 : P7 { }
// Selecting the most specialized witness.
prefix operator %%%
protocol P8 {
func foo()
}
prefix func %%% <T : P8>(x: T) -> T { }
protocol P9 : P8 {
static prefix func %%% (x: Self) -> Self
}
struct X9 : P9 {
func foo() {}
}
prefix func %%%(x: X9) -> X9 { }
protocol P10 {
associatedtype Assoc
func bar(_ x: Assoc)
}
struct X10 : P10 {
typealias Assoc = Int
func bar(_ x: Int) { }
func bar<T>(_ x: T) { }
}
protocol P11 {
static func ==(x: Self, y: Self) -> Bool
}
protocol P12 {
associatedtype Index : P1 // expected-note{{unable to infer associated type 'Index' for protocol 'P12'}}
func getIndex() -> Index
}
struct XIndexType : P11 { }
struct X12 : P12 { // expected-error{{type 'X12' does not conform to protocol 'P12'}}
func getIndex() -> XIndexType { return XIndexType() } // expected-note{{inferred type 'XIndexType' (by matching requirement 'getIndex()') is invalid: does not conform to 'P1'}}
}
func ==(x: X12.Index, y: X12.Index) -> Bool { return true }
| apache-2.0 | c608da9b708c34acdc18b3011c289188 | 28.259542 | 244 | 0.650535 | 3.112464 | false | false | false | false |
SahilDhawan/On-The-Map | OnTheMap/LoginViewController.swift | 1 | 5855 | //
// LoginViewController.swift
// OnTheMap
//
// Created by Sahil Dhawan on 03/04/17.
// Copyright © 2017 Sahil Dhawan. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
//MARK: Outlets
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var logInButton: UIButton!
@IBOutlet weak var debugLabel: UILabel!
//Current User Details
static var firstName : String = ""
static var lastName : String = ""
static var userId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
emailTextField.delegate = self
passwordTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.isHidden = true
//Clearing Text Field Data
self.emailTextField.text = ""
self.passwordTextField.text = ""
self.logInButton.isEnabled = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.navigationBar.isHidden = false
}
//MARK: Login and Data Fetch
@IBAction func loginButtonPressed(_ sender: Any)
{
Alert().activityView(true, self.view)
self.logInButton.isEnabled = false
guard (emailTextField.text == "" || passwordTextField.text == "") else
{
//Udacity Login
UdacityUser().udacityLogIn(emailTextField.text!,passwordTextField.text!){(result,error) in
if error == nil
{
let range = Range(5 ..< result!.count)
let newData = result?.subdata(in: range)
do
{
let dataDictionary = try JSONSerialization.jsonObject(with: newData!, options: .allowFragments) as! NSDictionary
let resultDict = dataDictionary["account"] as! [String:AnyObject?]
let userId = resultDict["key"] as! String
UdacityUser().gettingStudentDetails(userId, { (result, errorString) in
if errorString == nil
{
do
{
print(NSString(data: result!, encoding: String.Encoding.utf8.rawValue)!)
let dataDict = try JSONSerialization.jsonObject(with: result!, options: .allowFragments) as! [String : AnyObject]
let userDict = dataDict["user"] as! [String:AnyObject]
//passing Data to Current User Data
DispatchQueue.main.async {
LoginViewController.lastName = userDict["last_name"] as! String
print(userDict)
print(LoginViewController.lastName)
LoginViewController.userId = userId
LoginViewController.firstName = userDict["first_name"] as! String
//Segue
Alert().activityView(false,self.view)
self.performSegue(withIdentifier: "loginSegue", sender: self)
}
}
catch{
DispatchQueue.main.async {
Alert().showAlert("cannot serialise getStudentDetails Data",self)
Alert().activityView(false,self.view)
self.logInButton.isEnabled = true
}
}
}
else
{
//handling data fetch error
Alert().showAlert(errorString!,self)
}
})
}
catch{
Alert().showAlert("cannot serialise udacityLogin Data",self)
Alert().activityView(false,self.view)
self.logInButton.isEnabled = true
}
}
else
{
//handling Udacity login error
DispatchQueue.main.async {
Alert().showAlert(error!,self)
Alert().activityView(false,self.view)
self.logInButton.isEnabled = true
}
}
}
return
}
// Alert for email and password
Alert().showAlert("Email or Password can't be empty",self)
Alert().activityView(false,self.view)
self.logInButton.isEnabled = true
}
//Alert Function
@IBAction func signUpButtonPressed(_ sender: Any) {
let url = URL(string:"https://auth.udacity.com/sign-up?next=https%3A%2F%2Fclassroom.udacity.com%2Fauthenticated")
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
//MARK: TextFieldDelegate
extension LoginViewController : UITextFieldDelegate
{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | c36f97715c6ec1cefdbfbe0f58d67765 | 39.652778 | 149 | 0.47933 | 6.356135 | false | false | false | false |
wess/reddift | reddift/Network/Session+multireddit.swift | 1 | 14405 | //
// Session+multireddit.swift
// reddift
//
// Created by sonson on 2015/05/19.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
public typealias RedditColor = UIColor
#elseif os(OSX)
import Cocoa
public typealias RedditColor = NSColor
#endif
/**
Parse JSON dictionary object to the list of Multireddit.
:param: json JSON dictionary object is generated NSJSONSeirialize class.
:returns: Result object. Result object has any Thing or Listing object, otherwise error object.
*/
func parseMultiredditFromJSON(json: JSON) -> Result<Multireddit> {
if let json = json as? JSONDictionary {
if let kind = json["kind"] as? String {
if kind == "LabeledMulti" {
if let data = json["data"] as? JSONDictionary {
let obj = Multireddit(json: data)
return Result(value: obj)
}
}
}
}
return Result(error: ReddiftError.ParseThing.error)
}
func parseJSONToSubredditName(json: JSON) -> Result<String> {
if let json = json as? JSONDictionary {
if let subreddit = json["name"] as? String {
return Result(value: subreddit)
}
}
return Result(error: ReddiftError.ParseThing.error)
}
extension Session {
/**
Create a new multireddit. Responds with 409 Conflict if it already exists.
:param: multipath Multireddit url path
:param: displayName A string no longer than 50 characters.
:param: descriptionMd Raw markdown text.
:param: iconName Icon name as MultiIconName.
:param: keyColor Color. as RedditColor object.(does not implement. always uses white.)
:param: subreddits List of subreddits as String array.
:param: visibility Visibility as MultiVisibilityType.
:param: weightingScheme One of `classic` or `fresh`.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func createMultireddit(displayName:String, descriptionMd:String, iconName:MultiredditIconName = .None, keyColor:RedditColor = RedditColor.whiteColor(), visibility:MultiredditVisibility = .Private, weightingScheme:String = "classic", completion:(Result<Multireddit>) -> Void) -> NSURLSessionDataTask? {
var multipath = "/user/\(token.name)/m/\(displayName)"
var json:[String:AnyObject] = [:]
var names:[[String:String]] = []
json["description_md"] = descriptionMd
json["display_name"] = displayName
json["icon_name"] = ""
json["key_color"] = "#FFFFFF"
json["subreddits"] = names
json["visibility"] = "private"
json["weighting_scheme"] = "classic"
if let data:NSData = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.allZeros, error: nil) {
if let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) {
let customAllowedSet = NSCharacterSet.URLQueryAllowedCharacterSet()
let escapedJsonString = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
if let escapedJsonString = escapedJsonString {
var parameter:[String:String] = ["model":escapedJsonString]
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/" + multipath, parameter:parameter, method:"POST", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseMultiredditFromJSON
completion(result)
})
task.resume()
}
}
}
return nil
}
/**
Copy the mulitireddit.
:param: multi Multireddit object to be copied.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func copyMultireddit(multi:Multireddit, newDisplayName:String, completion:(Result<Multireddit>) -> Void) -> NSURLSessionDataTask? {
var error:NSError? = nil
let regex = NSRegularExpression(pattern:"/[^/]+?$",
options: .CaseInsensitive,
error: &error)
let to = regex?.stringByReplacingMatchesInString(multi.path, options: .allZeros, range: NSMakeRange(0, count(multi.path)), withTemplate: "/" + newDisplayName)
var parameter:[String:String] = [:]
parameter["display_name"] = newDisplayName
parameter["from"] = multi.path
parameter["to"] = to
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/copy", parameter:parameter, method:"POST", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseMultiredditFromJSON
completion(result)
})
task.resume()
return task
}
/**
Rename the mulitireddit.
:param: multi Multireddit object to be copied.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func renameMultireddit(multi:Multireddit, newDisplayName:String, completion:(Result<Multireddit>) -> Void) -> NSURLSessionDataTask? {
var error:NSError? = nil
let regex = NSRegularExpression(pattern:"/[^/]+?$",
options: .CaseInsensitive,
error: &error)
let to = regex?.stringByReplacingMatchesInString(multi.path, options: .allZeros, range: NSMakeRange(0, count(multi.path)), withTemplate: "/" + newDisplayName)
var parameter:[String:String] = [:]
parameter["display_name"] = newDisplayName
parameter["from"] = multi.path
parameter["to"] = to
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/rename", parameter:parameter, method:"POST", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseMultiredditFromJSON
completion(result)
})
task.resume()
return task
}
/**
Delete the multi.
:param: multi Multireddit object to be deleted.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func deleteMultireddit(multi:Multireddit, completion:(Result<String>) -> Void) -> NSURLSessionDataTask? {
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/" + multi.path, method:"DELETE", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeAsString
completion(result)
})
task.resume()
return task
}
/**
Update the multireddit. Responds with 409 Conflict if it already exists.
:param: multi Multireddit object to be updated.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func updateMultireddit(multi:Multireddit, completion:(Result<Multireddit>) -> Void) -> NSURLSessionDataTask? {
var multipath = multi.path
var json:[String:AnyObject] = [:]
var names:[[String:String]] = []
json["description_md"] = multi.descriptionMd
json["display_name"] = multi.name
json["icon_name"] = multi.iconName.rawValue
json["key_color"] = "#FFFFFF"
json["subreddits"] = names
json["visibility"] = multi.visibility.rawValue
json["weighting_scheme"] = "classic"
if let data:NSData = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.allZeros, error: nil) {
if let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) {
let customAllowedSet = NSCharacterSet.URLQueryAllowedCharacterSet()
let escapedJsonString = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
if let escapedJsonString:String = escapedJsonString {
var parameter:[String:String] = ["model":escapedJsonString]
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/" + multipath, parameter:parameter, method:"PUT", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseMultiredditFromJSON
completion(result)
})
task.resume()
return task
}
}
}
return nil
}
/**
Add a subreddit to multireddit.
:param: multireddit
:param: subreddit
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func addSubredditToMultireddit(multireddit:Multireddit, subredditDisplayName:String, completion:(Result<String>) -> Void) -> NSURLSessionDataTask? {
let jsonString = "{\"name\":\"\(subredditDisplayName)\"}"
let customAllowedSet = NSCharacterSet.URLQueryAllowedCharacterSet()
let escapedJsonString = jsonString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
if let escapedJsonString:String = escapedJsonString {
let srname = subredditDisplayName
let parameter = ["model":escapedJsonString, "srname":srname]
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/" + multireddit.path + "/r/" + srname, parameter:parameter, method:"PUT", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseJSONToSubredditName
completion(result)
})
task.resume()
return task
}
return nil
}
/**
Get users own multireddit.
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getMineMultireddit(completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/mine", method:"GET", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON
completion(result)
})
task.resume()
return task
}
/**
Get the description of the specified Multireddit.
:param: multireddit
:param: completion The completion handler to call when the load request is complete.
:returns: Data task which requests search to reddit.com.
*/
func getMultiredditDescription(multireddit:Multireddit, completion:(Result<RedditAny>) -> Void) -> NSURLSessionDataTask? {
var request:NSMutableURLRequest = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(Session.baseURL, path:"/api/multi/" + multireddit.path + "/description", method:"GET", token:token)
let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData!, response:NSURLResponse!, error:NSError!) -> Void in
self.updateRateLimitWithURLResponse(response)
let responseResult = resultFromOptionalError(Response(data: data, urlResponse: response), error)
let result = responseResult >>> parseResponse >>> decodeJSON >>> parseListFromJSON
completion(result)
})
task.resume()
return task
}
} | mit | 0a505ac3d128f9c114d430d88921cf3d | 49.540351 | 305 | 0.662223 | 5.082216 | false | false | false | false |
prolificinteractive/simcoe | SimcoeTests/Mocks/CartLoggingFake.swift | 1 | 892 | //
// CartLoggingFake.swift
// Simcoe
//
// Created by Michael Campbell on 11/16/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
@testable import Simcoe
internal final class CartLoggingFake: CartLogging, Failable {
let name = "Cart Logging [Fake]"
var shouldFail = false
var cartAdditionCount = 0
var cartRemovalCount = 0
func logAddToCart<T: SimcoeProductConvertible>(_ product: T, eventProperties: Properties?) -> TrackingResult {
cartAdditionCount += 1
if shouldFail {
return .error(message: "Error")
}
return .success
}
func logRemoveFromCart<T : SimcoeProductConvertible>(_ product: T, eventProperties: Properties?) -> TrackingResult {
cartRemovalCount += 1
if shouldFail {
return .error(message: "Error")
}
return .success
}
}
| mit | b1f9ac21af0d22d74ac2ff499664717e | 21.275 | 120 | 0.641975 | 4.325243 | false | false | false | false |
alblue/swift-corelibs-foundation | Foundation/NSDictionary.swift | 1 | 26823 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
import Dispatch
open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID())
internal var _storage: [NSObject: AnyObject]
open var count: Int {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func object(forKey aKey: Any) -> Any? {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
if let val = _storage[_SwiftValue.store(aKey)] {
return _SwiftValue.fetch(nonOptional: val)
}
return nil
}
open func value(forKey key: String) -> Any? {
NSUnsupported()
}
open func keyEnumerator() -> NSEnumerator {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.keys.map { _SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
@available(*, deprecated)
public convenience init?(contentsOfFile path: String) {
self.init(contentsOf: URL(fileURLWithPath: path))
}
@available(*, deprecated)
public convenience init?(contentsOf url: URL) {
do {
guard let plistDoc = try? Data(contentsOf: url) else { return nil }
let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any>
guard let plistDictionary = plistDict else { return nil }
self.init(dictionary: plistDictionary)
} catch {
return nil
}
}
public override convenience init() {
self.init(objects: [], forKeys: [], count: 0)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
_storage = [NSObject : AnyObject](minimumCapacity: cnt)
for idx in 0..<cnt {
let key = keys[idx].copy()
let value = objects[idx]
_storage[key as! NSObject] = value
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject }
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(objects: objects as! [NSObject], forKeys: keys)
} else {
var objects = [AnyObject]()
var keys = [NSObject]()
var count = 0
while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"),
let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
keys.append(key as! NSObject)
objects.append(object as! NSObject)
count += 1
}
self.init(objects: objects, forKeys: keys)
}
}
open func encode(with aCoder: NSCoder) {
if let keyedArchiver = aCoder as? NSKeyedArchiver {
keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys")
keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects")
} else {
NSUnimplemented()
}
}
public static var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableDictionary.self {
let dictionary = NSDictionary()
dictionary._storage = self._storage
return dictionary
}
return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject}))
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
// always create and return an NSMutableDictionary
let mutableDictionary = NSMutableDictionary()
mutableDictionary._storage = self._storage
return mutableDictionary
}
return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { _SwiftValue.store($0) } )
}
public convenience init(object: Any, forKey key: NSCopying) {
self.init(objects: [object], forKeys: [key as! NSObject])
}
public convenience init(objects: [Any], forKeys keys: [NSObject]) {
let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count)
keyBuffer.initialize(from: keys, count: keys.count)
let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count)
valueBuffer.initialize(from: objects.map { _SwiftValue.store($0) }, count: objects.count)
self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count)
keyBuffer.deinitialize(count: keys.count)
valueBuffer.deinitialize(count: objects.count)
keyBuffer.deallocate()
valueBuffer.deallocate()
}
public convenience init(dictionary otherDictionary: [AnyHashable : Any]) {
self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { _SwiftValue.store($0) })
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Dictionary<AnyHashable, Any>:
return isEqual(to: other)
case let other as NSDictionary:
return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other))
default:
return false
}
}
open override var hash: Int {
return self.count
}
open var allKeys: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.keys)
} else {
var keys = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
keys.append(key)
}
return keys
}
}
open var allValues: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.values)
} else {
var values = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
values.append(object(forKey: key)!)
}
return values
}
}
/// Alternative pseudo funnel method for fastpath fetches from dictionaries
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
for (key, value) in _storage {
keys.append(_SwiftValue.fetch(nonOptional: key))
objects.append(_SwiftValue.fetch(nonOptional: value))
}
} else {
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
let value = object(forKey: key)!
keys.append(key)
objects.append(value)
}
}
}
open subscript (key: Any) -> Any? {
return object(forKey: key)
}
open func allKeys(for anObject: Any) -> [Any] {
var matching = Array<Any>()
enumerateKeysAndObjects(options: []) { key, value, _ in
if let val = value as? AnyHashable,
let obj = anObject as? AnyHashable {
if val == obj {
matching.append(key)
}
}
}
return matching
}
/// A string that represents the contents of the dictionary, formatted as
/// a property list (read-only)
///
/// If each key in the dictionary is an NSString object, the entries are
/// listed in ascending order by key, otherwise the order in which the entries
/// are listed is undefined. This property is intended to produce readable
/// output for debugging purposes, not for serializing data. If you want to
/// store dictionary data for later retrieval, see
/// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i)
/// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i).
open override var description: String {
return description(withLocale: nil)
}
private func getDescription(of object: Any) -> String? {
switch object {
case is NSArray.Type:
return (object as! NSArray).description(withLocale: nil, indent: 1)
case is NSDecimalNumber.Type:
return (object as! NSDecimalNumber).description(withLocale: nil)
case is NSDate.Type:
return (object as! NSDate).description(with: nil)
case is NSOrderedSet.Type:
return (object as! NSOrderedSet).description(withLocale: nil)
case is NSSet.Type:
return (object as! NSSet).description(withLocale: nil)
case is NSDictionary.Type:
return (object as! NSDictionary).description(withLocale: nil)
default:
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
return hashableObject._nsObject.description(withLocale: nil, indent: 1)
} else {
return nil
}
}
}
open var descriptionInStringsFileFormat: String {
var lines = [String]()
for key in self.allKeys {
let line = NSMutableString(capacity: 0)
line.append("\"")
if let descriptionByType = getDescription(of: key) {
line.append(descriptionByType)
} else {
line.append("\(key)")
}
line.append("\"")
line.append(" = ")
line.append("\"")
let value = self.object(forKey: key)!
if let descriptionByTypeValue = getDescription(of: value) {
line.append(descriptionByTypeValue)
} else {
line.append("\(value)")
}
line.append("\"")
line.append(";")
lines.append(line._bridgeToSwift())
}
return lines.joined(separator: "\n")
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
///
/// - parameter level: Specifies a level of indentation, to make the output
/// more readable: the indentation is (4 spaces) * level.
///
/// - returns: A string object that represents the contents of the dictionary,
/// formatted as a property list.
open func description(withLocale locale: Locale?, indent level: Int) -> String {
if level > 100 { return "..." }
var lines = [String]()
let indentation = String(repeating: " ", count: level * 4)
lines.append(indentation + "{")
for key in self.allKeys {
var line = String(repeating: " ", count: (level + 1) * 4)
if key is NSArray {
line += (key as! NSArray).description(withLocale: locale, indent: level + 1)
} else if key is Date {
line += (key as! NSDate).description(with: locale)
} else if key is NSDecimalNumber {
line += (key as! NSDecimalNumber).description(withLocale: locale)
} else if key is NSDictionary {
line += (key as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if key is NSOrderedSet {
line += (key as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if key is NSSet {
line += (key as! NSSet).description(withLocale: locale)
} else {
line += "\(key)"
}
line += " = "
let object = self.object(forKey: key)!
if object is NSArray {
line += (object as! NSArray).description(withLocale: locale, indent: level + 1)
} else if object is Date {
line += (object as! NSDate).description(with: locale)
} else if object is NSDecimalNumber {
line += (object as! NSDecimalNumber).description(withLocale: locale)
} else if object is NSDictionary {
line += (object as! NSDictionary).description(withLocale: locale, indent: level + 1)
} else if object is NSOrderedSet {
line += (object as! NSOrderedSet).description(withLocale: locale, indent: level + 1)
} else if object is NSSet {
line += (object as! NSSet).description(withLocale: locale)
} else {
if let hashableObject = object as? Dictionary<AnyHashable, Any> {
line += hashableObject._nsObject.description(withLocale: nil, indent: level+1)
} else {
line += "\(object)"
}
}
line += ";"
lines.append(line)
}
lines.append(indentation + "}")
return lines.joined(separator: "\n")
}
open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool {
if count != otherDictionary.count {
return false
}
for key in keyEnumerator() {
if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable,
let value = object(forKey: key)! as? AnyHashable {
if otherValue != value {
return false
}
} else {
let otherBridgeable = otherDictionary[key as! AnyHashable]
let bridgeable = object(forKey: key)!
let equal = _SwiftValue.store(optional: otherBridgeable)?.isEqual(_SwiftValue.store(bridgeable))
if equal != true {
return false
}
}
}
return true
}
public struct Iterator : IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
public mutating func next() -> (key: Any, value: Any)? {
if let key = keyGenerator.next() {
return (key, dictionary.object(forKey: key)!)
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
internal struct ObjectGenerator: IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
mutating func next() -> Any? {
if let key = keyGenerator.next() {
return dictionary.object(forKey: key)!
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
open func objectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(ObjectGenerator(self))
}
open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] {
var objects = [Any]()
for key in keys {
if let object = object(forKey: key) {
objects.append(object)
} else {
objects.append(marker)
}
}
return objects
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
}
// the atomically flag is ignored if url of a type that cannot be written atomically.
open func write(to url: URL, atomically: Bool) -> Bool {
do {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: .xml, options: 0)
try pListData.write(to: url, options: atomically ? .atomic : [])
return true
} catch {
return false
}
}
open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateKeysAndObjects(options: [], using: block)
}
open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) {
let count = self.count
var keys = [Any]()
var objects = [Any]()
var sharedStop = ObjCBool(false)
let lock = NSLock()
getObjects(&objects, andKeys: &keys, count: count)
withoutActuallyEscaping(block) { (closure: @escaping (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) -> () in
let iteration: (Int) -> Void = { (idx) in
lock.lock()
var stop = sharedStop
lock.unlock()
if stop.boolValue { return }
closure(keys[idx], objects[idx], &stop)
if stop.boolValue {
lock.lock()
sharedStop = stop
lock.unlock()
return
}
}
if opts.contains(.concurrent) {
DispatchQueue.concurrentPerform(iterations: count, execute: iteration)
} else {
for idx in 0..<count {
iteration(idx)
}
}
}
}
open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return keysSortedByValue(options: [], usingComparator: cmptr)
}
open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
let sorted = allKeys.sorted { lhs, rhs in
return cmptr(lhs, rhs) == .orderedSame
}
return sorted
}
open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return keysOfEntries(options: [], passingTest: predicate)
}
open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var matching = Set<AnyHashable>()
enumerateKeysAndObjects(options: opts) { key, value, stop in
if predicate(key, value, stop) {
matching.insert(key as! AnyHashable)
}
}
return matching
}
override open var _cfTypeID: CFTypeID {
return CFDictionaryGetTypeID()
}
required public convenience init(dictionaryLiteral elements: (Any, Any)...) {
var keys = [NSObject]()
var values = [Any]()
for (key, value) in elements {
keys.append(_SwiftValue.store(key))
values.append(value)
}
self.init(objects: values, forKeys: keys)
}
}
extension NSDictionary : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) }
internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableDictionary {
internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) }
}
extension CFDictionary : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) }
internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject }
}
extension Dictionary : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() }
internal var _cfObject: CFDictionary { return _nsObject._cfObject }
}
open class NSMutableDictionary : NSDictionary {
open func removeObject(forKey aKey: Any) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage.removeValue(forKey: _SwiftValue.store(aKey))
}
/// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys)
open func setObject(_ anObject: Any, forKey aKey: AnyHashable) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage[_SwiftValue.store(aKey)] = _SwiftValue.store(anObject)
}
public convenience required init() {
self.init(capacity: 0)
}
public convenience init(capacity numItems: Int) {
self.init(objects: [], forKeys: [], count: 0)
// It is safe to reset the storage here because we know is empty
_storage = [NSObject: AnyObject](minimumCapacity: numItems)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
super.init(objects: objects, forKeys: keys, count: cnt)
}
}
extension NSMutableDictionary {
open func addEntries(from otherDictionary: [AnyHashable : Any]) {
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
open func removeAllObjects() {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
_storage.removeAll()
} else {
for key in allKeys {
removeObject(forKey: key)
}
}
}
open func removeObjects(forKeys keyArray: [Any]) {
for key in keyArray {
removeObject(forKey: key)
}
}
open func setDictionary(_ otherDictionary: [AnyHashable : Any]) {
removeAllObjects()
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
/// - Note: See setObject(_:,forKey:) for details on the differential here
public subscript (key: AnyHashable) -> Any? {
get {
return object(forKey: key)
}
set {
if let val = newValue {
setObject(val, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
}
extension NSDictionary : Sequence {
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
// MARK - Shared Key Sets
extension NSDictionary {
/* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:.
The keys are copied from the array and must be copyable.
If the array parameter is nil or not an NSArray, an exception is thrown.
If the array of keys is empty, an empty key set is returned.
The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used).
As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant.
Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage.
*/
open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any { NSUnimplemented() }
}
extension NSMutableDictionary {
/* Create a mutable dictionary which is optimized for dealing with a known set of keys.
Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal.
As with any dictionary, the keys must be copyable.
If keyset is nil, an exception is thrown.
If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown.
*/
public convenience init(sharedKeySet keyset: Any) { NSUnimplemented() }
}
extension NSDictionary : ExpressibleByDictionaryLiteral { }
extension NSDictionary : CustomReflectable {
public var customMirror: Mirror { NSUnimplemented() }
}
extension NSDictionary : _StructTypeBridgeable {
public typealias _StructType = Dictionary<AnyHashable,Any>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | 075ec8569c27d96ba7b9a6cf5c39c126 | 37.252496 | 188 | 0.595637 | 4.908475 | false | false | false | false |
rahulsend89/MemoryGame | MemoryGameTests/StubResponse.swift | 1 | 580 | //
// StubResponse.swift
// MemoryGame
//
// Created by Rahul Malik on 7/16/17.
// Copyright © 2017 aceenvisage. All rights reserved.
//
import Foundation
open class StubResponse {
let headers: Dictionary<String, String>?
let statusCode: Int
let data: Data?
let requestTime: TimeInterval
public init(data: Data?=nil, statusCode: Int, headers: Dictionary<String, String>? = nil, requestTime: TimeInterval=0.0) {
self.data = data
self.statusCode = statusCode
self.headers = headers
self.requestTime = requestTime
}
}
| mit | 47533c93e5a7c4c9c4c7dd390009e1ea | 23.125 | 126 | 0.668394 | 3.885906 | false | false | false | false |
sggtgb/Sea-Cow | seaCow/ReadingListViewController.swift | 1 | 5697 | //
// ReadingListViewController.swift
// seaCow
//
// Created by Scott Gavin on 4/16/15.
// Copyright (c) 2015 Scott G Gavin. All rights reserved.
//
import UIKit
import TwitterKit
import Fabric
class ReadingListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var myTableView: UITableView!
var readingList = NYTArticles()
var allArticles: [ArticleData]?
var selectedArticle: ArticleData?
// A set of constant and variable strings for making up the URL for article searching using NYT's API
let articleSearchBaseUrl = "http://api.nytimes.com/svc/mostpopular/v2"
let articleSearchResourceType = "mostviewed" // mostemailed | mostshared | mostviewed
let articleSearchSections = "all-sections"
let articlesSearchNumOfDays = 1 // 1 | 7 | 30
let articleSearchReturnFormat = ".json"
let articleSearchAPIKey = "b772e34fc2a53d05fe60d6c63d0c0e4c:9:71573042"
var testArticles: ReadingList?
override func viewDidLoad() {
super.viewDidLoad()
var articleSearchUrl = articleSearchBaseUrl + "/" + articleSearchResourceType + "/" + articleSearchSections + "/" + "\(articlesSearchNumOfDays)" + articleSearchReturnFormat + "?" + "&API-Key=" + articleSearchAPIKey
// load articles from the NYT API
readingList.load(articleSearchUrl, loadCompletionHandler: {
(nytArticles, errorString) -> Void in
if let unwrappedErrorString = errorString {
println(unwrappedErrorString)
} else {
println(self.readingList.articles.count)
self.myTableView.reloadData()
}
})
allArticles = testArticles?.getArticles()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if allArticles != nil {
return allArticles!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: CustomCell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! CustomCell
if(allArticles!.count > 0) {
//cell.title?.text = readingList.articles[indexPath.row].title
cell.title?.text = allArticles![indexPath.row].title
cell.title?.font = UIFont(name: "Gotham Light", size: 18)
//let url = NSURL(string: readingList.articles[indexPath.row].imageUrl)
let url = NSURL(string: allArticles![indexPath.row].imageUrl)
let data = NSData(contentsOfURL: url!)
cell.backgroundImage.image = UIImage(data: data!)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
selectedArticle = allArticles![indexPath.row]
performSegueWithIdentifier("showArticle", sender: self)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal , title: "Share", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) in
let composer = TWTRComposer()
composer.setText("Check out this awesome article!\n\n" + self.allArticles![indexPath.row].url + "\n\n#seaCow #articleTags? #whatever")
composer.setImage(UIImage(named: "fabric"))
composer.showWithCompletion { (result) -> Void in
if (result == TWTRComposerResult.Cancelled) {
println("Tweet composition cancelled")
}
else {
println("Sending tweet!")
}
}
self.myTableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
return
})
shareAction.backgroundColor = UIColor.blueColor()
var deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default , title: "Delete", handler: { (action: UITableViewRowAction!, indexPath: NSIndexPath!) in
self.allArticles?.removeAtIndex(indexPath.row)
self.testArticles?.removeArticle(indexPath.row)
self.myTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
self.testArticles!.save()
return
})
return [deleteAction, shareAction]
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "showArticle"){
let destinationViewController = segue.destinationViewController as! ArticleViewController
destinationViewController.article = selectedArticle
}
}
@IBAction func back(sender: AnyObject) {
performSegueWithIdentifier("returnToCards", sender: self)
}
@IBAction func returnToReadingList(segue: UIStoryboardSegue) {
}
}
| mpl-2.0 | 05cd356431b991354d7976b287391224 | 36.235294 | 222 | 0.628576 | 5.531068 | false | false | false | false |
CodingGirl1208/FlowerField | FlowerField/FlowerField/Category.swift | 1 | 2277 | //
// Category.swift
// FlowerField
//
// Created by 易屋之家 on 16/8/12.
// Copyright © 2016年 xuping. All rights reserved.
//
import UIKit
class Category: NSObject , NSCoding{
// 专题创建时间
var createDate : String?
// 专题类型ID
var id : String?
// 专题类型名称
var name : String?
// 专题序号
var order : Int?
// 遍历构造器
init(dict: [String : AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
// MARK: - 序列化和反序列化
private let createDate_Key = "createDate"
private let id_Key = "id"
private let name_Key = "name"
private let order_Key = "order"
// 序列化
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(createDate, forKey: createDate_Key)
aCoder.encodeObject(id, forKey: id_Key)
aCoder.encodeObject(order, forKey: order_Key)
aCoder.encodeObject(name, forKey: name_Key)
}
// 反序列化
required init?(coder aDecoder: NSCoder) {
createDate = aDecoder.decodeObjectForKey(createDate_Key) as? String
id = aDecoder.decodeObjectForKey(id_Key) as? String
order = aDecoder.decodeObjectForKey(order_Key) as? Int
name = aDecoder.decodeObjectForKey(name_Key) as? String
}
// MARK: - 保存和获取所有分类
static let CategoriesKey = "CategoriesKey"
/**
保存所有的分类
- parameter categories: 分类数组
*/
class func savaCategories(categories: [Category]) {
let data = NSKeyedArchiver.archivedDataWithRootObject(categories)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: Category.CategoriesKey)
}
/**
取出本地保存的分类
- returns: 分类数组或者nil
*/
class func loadLocalCategories() -> [Category]?
{
if let array = NSUserDefaults.standardUserDefaults().objectForKey(Category.CategoriesKey)
{
return NSKeyedUnarchiver.unarchiveObjectWithData(array as! NSData) as? [Category]
}
return nil
}
}
| mit | 8fd4502c835c49b85c59e87c8cdd2baa | 23.321839 | 97 | 0.617675 | 4.266129 | false | false | false | false |
ycaihua/codecombat-ios | CodeCombat/TomeInventoryItem.swift | 1 | 1639 | //
// TomeInventoryItem.swift
// CodeCombat
//
// Created by Michael Schmatz on 8/6/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
class TomeInventoryItem {
let itemData: JSON
var properties: [TomeInventoryItemProperty] = []
var name: String {
return itemData["name"].toString(pretty: false)
}
var imageURL: NSURL {
var b = itemData["imageURL"]
var url: String = itemData["imageURL"].toString(pretty: false)
if url.isEmpty {
url = "/file/db/thang.type/53e4108204c00d4607a89f78/programmicon.png"
}
return NSURL(string: url, relativeToURL: WebManager.sharedInstance.rootURL!)!
}
init(itemData: JSON) {
self.itemData = itemData
}
convenience init(itemData: JSON, propertiesData: JSON) {
self.init(itemData: itemData)
for (propIndex, prop) in itemData["programmableProperties"] {
for (anotherPropIndex, anotherProp) in propertiesData {
if anotherProp["name"].asString! == prop.asString! {
properties.append(TomeInventoryItemProperty(propertyData: anotherProp, primary: true))
break
}
}
}
for (propIndex, prop) in itemData["moreProgrammableProperties"] {
for (anotherPropIndex, anotherProp) in propertiesData {
if anotherProp["name"].asString! == prop.asString! {
properties.append(TomeInventoryItemProperty(propertyData: anotherProp, primary: false))
break
}
}
}
}
func addProperty(property: TomeInventoryItemProperty) {
properties.append(property)
}
func removeAllProperties() {
properties.removeAll(keepCapacity: true)
}
}
| mit | 4288473755d1a5596f9fbf8a6444db89 | 28.8 | 97 | 0.674192 | 4.087282 | false | false | false | false |
eljeff/AudioKit | Sources/AudioKit/Sequencing/Apple Sequencer/MusicTrack+Load.swift | 2 | 3754 | // Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
extension MusicTrackManager {
func loadMIDI(filePath: String) {
Log("loading file from exists @ \(filePath)")
let fileURL = URL(fileURLWithPath: filePath)
var tempSeq: MusicSequence?
NewMusicSequence(&tempSeq)
if let newSeq = tempSeq {
let status: OSStatus = MusicSequenceFileLoad(newSeq, fileURL as CFURL, .midiType, MusicSequenceLoadFlags())
if status != OSStatus(noErr) {
Log("error reading midi file url: \(fileURL), read status: \(status)")
}
var numTracks = UInt32(0)
MusicSequenceGetTrackCount(newSeq, &numTracks)
Log("Sequencer has \(numTracks) tracks")
var tempTrack: MusicTrack?
MusicSequenceGetIndTrack(newSeq, 0, &tempTrack)
if let sourceTrack = tempTrack, let destTrack = self.internalMusicTrack {
MusicTrackCopyInsert(sourceTrack, 0, self.length, destTrack, 0)
var tempIterator: MusicEventIterator?
NewMusicEventIterator(sourceTrack, &tempIterator)
if let iterator = tempIterator {
var hasEvent = DarwinBoolean(false)
MusicEventIteratorHasCurrentEvent(iterator, &hasEvent)
var i = 0
while hasEvent.boolValue {
MusicEventIteratorNextEvent(iterator)
var eventTime = MusicTimeStamp(0)
var eventType = MusicEventType(0)
var eventData: UnsafeRawPointer?
var eventDataSize: UInt32 = 0
MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize)
if let event = MusicTrackManagerEventType(rawValue: eventType) {
Log("event \(i) at time \(eventTime) type is \(event.description)")
}
MusicEventIteratorHasCurrentEvent(iterator, &hasEvent)
i += 1
}
}
}
}
return
}
}
enum MusicTrackManagerEventType: UInt32 {
case kMusicEventType_NULL = 0
case kMusicEventType_ExtendedNote = 1
case undefined2 = 2
case kMusicEventType_ExtendedTempo = 3
case kMusicEventType_User = 4
case kMusicEventType_Meta = 5
case kMusicEventType_MIDINoteMessage = 6
case kMusicEventType_MIDIChannelMessage = 7
case kMusicEventType_MIDIRawData = 8
case kMusicEventType_Parameter = 9
case kMusicEventType_AUPreset = 10
var description: String {
switch self {
case .kMusicEventType_NULL:
return "kMusicEventType_NULL"
case .kMusicEventType_ExtendedNote:
return "kMusicEventType_ExtendedNote"
case .kMusicEventType_ExtendedTempo:
return "kMusicEventType_ExtendedTempo"
case .kMusicEventType_User:
return "kMusicEventType_User"
case .kMusicEventType_Meta:
return "kMusicEventType_Meta"
case .kMusicEventType_MIDINoteMessage:
return "kMusicEventType_MIDINoteMessage"
case .kMusicEventType_MIDIChannelMessage:
return "kMusicEventType_MIDIChannelMessage"
case .kMusicEventType_MIDIRawData:
return "kMusicEventType_MIDIRawData"
case .kMusicEventType_Parameter:
return "kMusicEventType_Parameter"
case .kMusicEventType_AUPreset:
return "kMusicEventType_AUPreset"
default:
return "undefined"
}
}
}
| mit | fe14dd51d0a3632dd65ef65c4ea989d6 | 41.659091 | 119 | 0.607885 | 5.038926 | false | false | false | false |
hshidara/iOS | Ready?/Ready?/Records.swift | 1 | 4576 | //
// Records.swift
// Ready?
//
// Created by Hidekazu Shidara on 9/18/15.
// Copyright (c) 2015 Hidekazu Shidara. All rights reserved.
//
import UIKit
import CoreData
class Records: UIViewController, UITableViewDataSource, UITableViewDelegate {
var records : RecordsData!
var convert = conversionToString()
//MARK: Data
// var recordsHighestAltitude = 0.0
// var recordsCalories = 0.0
//===========
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.setSelection()
self.setNavBar()
self.dataFill()
// Do any additional setup after loading the view.
}
func dataFill(){
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "RecordsData")
var error: NSError?
let count: Int = (managedContext?.countForFetchRequest(fetchRequest, error: &error))!
if ((count == NSNotFound) || (count == 0)) {
let entity = NSEntityDescription.entityForName("RecordsData",
inManagedObjectContext:managedContext!)
let records = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
records.setValue(0.0, forKey: "highestAltitude")
records.setValue(0.0,forKey: "longestRun")
records.setValue(0.0,forKey: "mostCaloriesInARun")
records.setValue(0,forKey: "mostStepsTakenAtOnce")
do {
try managedContext!.save()
self.fetch(managedContext!,fetchRequest: fetchRequest)
// self.setCells()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
print("sup")
}
}
else{
self.fetch(managedContext!,fetchRequest: fetchRequest)
// self.setCells()
}
}
func fetch(managedContext: NSManagedObjectContext, fetchRequest: NSFetchRequest){
do {
var results =
try managedContext.executeFetchRequest(fetchRequest)
records = results[0] as! RecordsData
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
} catch {
print("sup")
}
}
func setNavBar(){
//customize
}
func setSelection(){
tableView.allowsSelection = false
tableView.allowsMultipleSelectionDuringEditing = false
tableView.allowsMultipleSelection = false
tableView.allowsSelectionDuringEditing = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section{
case 0:
return "Highest Altitude"
case 1:
return "Most Calories Burned in 1 Run"
case 2:
return "Longest Run"
case 3:
return "Most Steps Taken At Once"
default:
return ""
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60.0
}
// func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// let headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! UITableViewCell
//
// return headerCell
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = "\(records.valueForKey("highestAltitude")!)"
return cell
}
}
| mit | f18a740a78ce516917a3699b60826309 | 30.777778 | 109 | 0.601399 | 5.408983 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/LinearEquations/Project/Bar/VLinearEquationsProjectBarCell.swift | 1 | 1463 | import UIKit
class VLinearEquationsBarCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private let kAlphaSelected:CGFloat = 0.3
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
self.imageView = imageView
addSubview(imageView)
NSLayoutConstraint.equals(
view:imageView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
//MARK: public
func config(model:MLinearEquationsProjectBarItem)
{
hover()
imageView.image = model.image
}
}
| mit | 57a1bea9a02638a9636c55e793c59741 | 19.605634 | 67 | 0.560492 | 5.670543 | false | false | false | false |
damonthecricket/my-utils | Source/UI/Extensions/Image/Image+Extensions.swift | 1 | 4087 | //
// UIImage+Extensions.swift
// Click fight
//
// Created by Optimus Prime on 10.11.16.
// Copyright © 2016 Tren Lab. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(watchOS)
import UIKit
import WatchKit
#elseif os(tvOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
import CoreGraphics
// MARK: - MYImageOrientation
/**
Represents image orientation.
*/
public enum MYImageOrientation: Int {
case portret = 0
case album
case square
}
// MARK: - Orientation
public extension MYImage {
/**
Returns `true` if an image has a portret orientation. Otherwise returns `false`.
*/
public var isPortret: Bool {
return orientation == .portret
}
/**
Returns `true` if an image has an album orientation. Otherwise returns `false`.
*/
public var isAlbum: Bool {
return orientation == .album
}
/**
Returns `true` if an image has a sguare orientation. Otherwise returns `false`.
*/
public var isSquare: Bool {
return orientation == .square
}
/**
Returns current image orientation.
*/
public var orientation: MYImageOrientation {
if size.width < size.height {
return .portret
} else if size.width > size.height {
return .album
} else {
return .square
}
}
}
// MARK: - Load
public extension MYImage {
/**
Downloads an image from specified url.
- Parameters:
- url: Image resource url.
- completion: The completion closure to be executed when operation has been completed.
*/
public static func from(URL url: URL, completion: MYImageDownloadCompletion? = nil) {
if let cachedImageData = cache[url.absoluteString] {
completion?(MYImage(data: cachedImageData as! Data))
return
}
DispatchQueue.global().async {
var img: MYImage? = nil
if let imgData = try? Data(contentsOf: url) {
img = MYImage(data: imgData)
cache[url.absoluteString] = imgData as AnyObject?
}
DispatchQueue.main.async {
completion?(img)
}
}
}
}
// MARK: - Cache
public extension MYImage {
/**
Image cache.
*/
class var cache: Cache {
set {
ImageCache = newValue
} get {
return ImageCache
}
}
}
fileprivate var ImageCache = Cache.create(withName: "image")
// MARK: - Draw
/**
Draws an image with specified size and adjusted in `draw` closure.
- Parameters:
- size: A size of image.
- draw: A draw closure, accepts the current graphic context.
*/
public func MYImageDraw(size: CGSize, draw: ((CGContext) -> Void)? = nil) -> MYImage {
#if os(iOS) || os(watchOS) || os(tvOS)
UIGraphicsBeginImageContextWithOptions(size, false, 1)
draw?(UIGraphicsGetCurrentContext()!)
let image: MYImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
#elseif os(macOS)
let image = MYImage.init(size: size)
let rep = NSBitmapImageRep(bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: NSCalibratedRGBColorSpace,
bytesPerRow: 0,
bitsPerPixel: 0)
image.addRepresentation(rep!)
image.lockFocus()
let ctx = NSGraphicsContext.current()?.cgContext
draw?(ctx!)
image.unlockFocus()
return image
#endif
}
| mit | d29cf1c82e4d6d6050373a0ca893122e | 24.5375 | 94 | 0.544542 | 4.946731 | false | false | false | false |
brentsimmons/Evergreen | Mac/Scriptability/AppDelegate+Scriptability.swift | 1 | 7593 | //
// AppDelegate+Scriptability.swift
// NetNewsWire
//
// Created by Olof Hellman on 2/7/18.
// Copyright © 2018 Olof Hellman. All rights reserved.
//
/*
Note: strictly, the AppDelegate doesn't appear as part of the scripting model,
so this file is rather unlike the other Object+Scriptability.swift files.
However, the AppDelegate object is the de facto scripting accessor for some
application elements and properties. For, example, the main window is accessed
via the AppDelegate's MainWindowController, and the main window itself has
selected feeds, selected articles and a current article. This file supplies the glue to access
these scriptable objects, while being completely separate from the core AppDelegate code,
*/
import Foundation
import Articles
import Zip
protocol AppDelegateAppleEvents {
func installAppleEventHandlers()
func getURL(_ event: NSAppleEventDescriptor, _ withReplyEvent: NSAppleEventDescriptor)
}
protocol ScriptingAppDelegate {
var scriptingCurrentArticle: Article? {get}
var scriptingSelectedArticles: [Article] {get}
var scriptingMainWindowController:ScriptingMainWindowController? {get}
}
extension AppDelegate : AppDelegateAppleEvents {
// MARK: GetURL Apple Event
func installAppleEventHandlers() {
NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(AppDelegate.getURL(_:_:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
@objc func getURL(_ event: NSAppleEventDescriptor, _ withReplyEvent: NSAppleEventDescriptor) {
guard var urlString = event.paramDescriptor(forKeyword: keyDirectObject)?.stringValue else {
return
}
// Handle themes
if urlString.hasPrefix("netnewswire://theme") {
guard let comps = URLComponents(string: urlString),
let queryItems = comps.queryItems,
let themeURLString = queryItems.first(where: { $0.name == "url" })?.value else {
return
}
if let themeURL = URL(string: themeURLString) {
let request = URLRequest(url: themeURL)
let task = URLSession.shared.downloadTask(with: request) { location, response, error in
guard let location = location else {
return
}
do {
try ArticleThemeDownloader.shared.handleFile(at: location)
} catch {
NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error": error])
}
}
task.resume()
}
return
}
// Special case URL with specific scheme handler x-netnewswire-feed: intended to ensure we open
// it regardless of which news reader may be set as the default
let nnwScheme = "x-netnewswire-feed:"
if urlString.hasPrefix(nnwScheme) {
urlString = urlString.replacingOccurrences(of: nnwScheme, with: "feed:")
}
let normalizedURLString = urlString.normalizedURL
if !normalizedURLString.mayBeURL {
return
}
DispatchQueue.main.async {
self.addWebFeed(normalizedURLString)
}
}
}
class NetNewsWireCreateElementCommand : NSCreateCommand {
override func performDefaultImplementation() -> Any? {
let classDescription = self.createClassDescription
if (classDescription.className == "webFeed") {
return ScriptableWebFeed.handleCreateElement(command:self)
} else if (classDescription.className == "folder") {
return ScriptableFolder.handleCreateElement(command:self)
}
return nil
}
}
/*
NSDeleteCommand is kind of an oddball AppleScript command in that the command dispatch
goes to the container of the object(s) to be deleted, and the container needs to
figure out what to delete. In the code below, 'receivers' is the container object(s)
and keySpecifier is the thing to delete, relative to the container(s). Because there
is ambiguity about whether specifiers are lists or single objects, the code switches
based on which it is.
*/
class NetNewsWireDeleteCommand : NSDeleteCommand {
/*
delete(objectToDelete:, from container:)
At this point in handling the command, we know what the container is.
Here the code unravels the case of objectToDelete being a list or a single object,
ultimately calling container.deleteElement(element) for each element to delete
*/
func delete(objectToDelete:Any, from container:ScriptingObjectContainer) {
if let objectList = objectToDelete as? [Any] {
for nthObject in objectList {
self.delete(objectToDelete:nthObject, from:container)
}
} else if let element = objectToDelete as? ScriptingObject {
container.deleteElement(element)
}
}
/*
delete(specifier:, from container:)
At this point in handling the command, the container could be a list or a single object,
and what to delete is still an unresolved NSScriptObjectSpecifier.
Here the code unravels the case of container being a list or a single object. Once the
container(s) is known, it is possible to resolve the keySpecifier based on that container.
After resolving, we call delete(objectToDelete:, from container:) with the container and
the resolved objects
*/
func delete(specifier:NSScriptObjectSpecifier, from container:Any) {
if let containerList = container as? [Any] {
for nthObject in containerList {
self.delete(specifier:specifier, from:nthObject)
}
} else if let container = container as? ScriptingObjectContainer {
if let resolvedObjects = specifier.objectsByEvaluating(withContainers:container) {
self.delete(objectToDelete:resolvedObjects, from:container)
}
}
}
/*
performDefaultImplementation()
This is where handling the delete event starts. receiversSpecifier should be the container(s) of
the item to be deleted. keySpecifier is the thing in that container(s) to be deleted
The first step is to resolve the receiversSpecifier and then call delete(specifier:, from container:)
*/
override func performDefaultImplementation() -> Any? {
if let receiversSpecifier = self.receiversSpecifier {
if let receiverObjects = receiversSpecifier.objectsByEvaluatingSpecifier {
self.delete(specifier:self.keySpecifier, from:receiverObjects)
}
}
return nil
}
}
class NetNewsWireExistsCommand : NSExistsCommand {
// cocoa default behavior doesn't work here, because of cases where we define an object's property
// to be another object type. e.g., 'permalink of the current article' parses as
// <property> of <property> of <top level object>
// cocoa would send the top level object (the app) a doesExist message for a nested property, and
// it errors out because it doesn't know how to handle that
// What we do instead is simply see if the defaultImplementation errors, and if it does, the object
// must not exist. Otherwise, we return the result of the defaultImplementation
// The wrinkle is that it is possible that the direct object is a list, so we need to
// handle that case as well
override func performDefaultImplementation() -> Any? {
guard let result = super.performDefaultImplementation() else { return NSNumber(booleanLiteral:false) }
return result
}
}
| mit | a58c7e9493342fb79f18800879cdfdb2 | 39.59893 | 192 | 0.696523 | 4.612394 | false | false | false | false |
superk589/DereGuide | DereGuide/Common/BeatmapHashManager.swift | 2 | 657 | //
// BeatmapHashManager.swift
// DereGuide
//
// Created by zzk on 2017/2/14.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
class BeatmapHashManager {
var path = Path.cache + "/beatmapHash.plist"
static let `default` = BeatmapHashManager()
private init() {
if let array = NSDictionary.init(contentsOfFile: path) as? [String: String] {
hashTable = array
} else {
hashTable = [String: String]()
}
}
var hashTable: [String: String] {
didSet {
(hashTable as NSDictionary).write(toFile: path, atomically: true)
}
}
}
| mit | f9e21e0410ba99119873c517103eeca3 | 20.16129 | 85 | 0.573171 | 3.975758 | false | false | false | false |
dpettigrew/Swallow | SwallowExample/SwallowExample/StoreService.swift | 1 | 2654 | //
// StoreService.swift
// Swallow
//
// Created by Angelo Di Paolo on 2/24/15.
// Copyright (c) 2015 SetDirection. All rights reserved.
//
import Foundation
import THGWebService
// MARK - Web Service Configuration
extension WebService {
static let baseURL = "http://somehapi.herokuapp.com/"
static func StoresService() -> WebService {
return WebService(baseURLString: baseURL)
}
}
// MARK - Request Configuration
extension WebService {
public func fetchStores(zipCode aZipCode: String) -> ServiceTask {
return GET("/stores", parameters: ["zip" : aZipCode])
}
public func setFavoriteStoreWithID(storeID: String) -> ServiceTask {
return POST("/stores",
parameters: ["storeID" : storeID],
options: [.ParameterEncoding(.JSON),
.Header("custom-header", "12345"),
.Header(Request.Headers.userAgent, "my app ua")]
)
}
}
// MARK - Response Processing
extension ServiceTask {
public typealias StoreServiceSuccess = ([StoreModel]?) -> Void
public typealias StoreServiceError = (NSError?) -> Void
func responseAsStores(handler: StoreServiceSuccess) -> Self {
return responseJSON { json in
if let models = self.parseJSONAsStoreModels(json) {
handler(models)
} else {
self.throwError(self.modelParseError())
}
}
}
private func parseJSONAsStoreModels(json: AnyObject?) -> [StoreModel]? {
if let dictionary = json as? NSDictionary {
if let array = dictionary["stores"] as? NSArray {
var models = [StoreModel]()
for item in array {
let model = StoreModel(dictionary: item as! NSDictionary)
models.append(model)
}
return models
}
}
return nil
}
private func modelParseError() -> NSError {
return NSError(domain: "com.THGWebService.storeservice", code: 500, userInfo: [NSLocalizedDescriptionKey: "Failed to parse model JSON"])
}
}
// MARK: - Model
public struct StoreModel {
struct JSONKeys {
static let name = "name"
static let phoneNumber = "phoneNumber"
}
var phoneNumber: String?
var address: String?
var storeID: String?
var name: String?
init(dictionary: NSDictionary) {
self.name = dictionary[JSONKeys.name] as? String
self.phoneNumber = dictionary[JSONKeys.phoneNumber] as? String
}
}
| mit | 0941078ad09e92afbc0b4acb437522b1 | 25.54 | 144 | 0.586285 | 4.756272 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/Challenges/TimeFrameBudgetChallengeViewController.swift | 1 | 12529 | //
// TimeFrameBudgetChallengeViewController.swift
// Yona
//
// Created by Chandan on 19/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
import UIKit
protocol BudgetChallengeDelegate: class {
func callGoalsMethod()
}
class TimeFrameBudgetChallengeViewController: BaseViewController,UIAlertViewDelegate {
weak var delegate: BudgetChallengeDelegate?
@IBOutlet var headerView: UIView!
@IBOutlet weak var setChallengeButton: UIButton!
@IBOutlet weak var timeZoneLabel: UILabel!
@IBOutlet weak var minutesPerDayLabel: UILabel!
@IBOutlet weak var budgetChallengeTitle: UILabel!
@IBOutlet weak var budgetChallengeDescription: UILabel!
@IBOutlet weak var bottomLabelText: UILabel!
@IBOutlet weak var minutesLabel: UILabel!
@IBOutlet weak var minutesSlider: UISlider!
@IBOutlet var deleteGoalButton: UIBarButtonItem!
@IBOutlet var footerGradientView: GradientLargeView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var tableView: UITableView!
@IBOutlet weak var appList: UILabel!
var isFromActivity :Bool?
var activitiyToPost: Activities?
var goalCreated: Goal?
var maxDurationMinutes: String = "0"
var scaledMinutes: Float = 5
override func viewDidLoad() {
super.viewDidLoad()
// if let activityName = self.goalCreated?.GoalName{
// ActivitiesRequestManager.sharedInstance.getActivityApplications(activityName, onCompletion: { (success, message, code, apps, error) in
// if success {
// self.appList.text = apps
// }
// })
// } else if let activityName = self.activitiyToPost?.activityCategoryName {
// ActivitiesRequestManager.sharedInstance.getActivityApplications(activityName, onCompletion: { (success, message, code, apps, error) in
// if success {
// self.appList.text = apps
// }
// })
// }
setTimeBucketTabToDisplay(.budget, key: YonaConstants.nsUserDefaultsKeys.timeBucketTabToDisplay)
setChallengeButton.backgroundColor = UIColor.clear
setChallengeButton.layer.cornerRadius = 25.0
setChallengeButton.layer.borderWidth = 1.5
setChallengeButton.layer.borderColor = UIColor.yiMidBlueColor().cgColor
footerGradientView.colors = [UIColor.yiWhiteTwoColor(), UIColor.yiWhiteTwoColor()]
self.setChallengeButton.setTitle(NSLocalizedString("challenges.addBudgetGoal.setChallengeButton", comment: "").uppercased(), for: UIControl.State())
self.timeZoneLabel.text = NSLocalizedString("challenges.addBudgetGoal.budgetLabel", comment: "")
self.minutesPerDayLabel.text = NSLocalizedString("challenges.addBudgetGoal.minutesPerDayLabel", comment: "")
//self.bottomLabelText.text = NSLocalizedString("challenges.addBudgetGoal.bottomLabelText", comment: "")
if let maxDurationMinutesUnwrapped = goalCreated?.maxDurationMinutes {
maxDurationMinutes = String(Int(Float(maxDurationMinutesUnwrapped) / scaledMinutes))
}
let localizedString = NSLocalizedString("challenges.addBudgetGoal.budgetChallengeDescription", comment: "")
self.navigationItem.rightBarButtonItem = nil
if isFromActivity == true {
self.budgetChallengeTitle.text = activitiyToPost?.activityCategoryName
if let activityName = activitiyToPost?.activityCategoryName {
self.budgetChallengeDescription.text = String(format: localizedString, activityName)
}
self.navigationItem.rightBarButtonItem?.tintColor? = UIColor.clear
self.navigationItem.rightBarButtonItem?.isEnabled = false
self.updateValues()
} else {
if ((goalCreated?.editLinks?.isEmpty) != nil) {
self.navigationItem.rightBarButtonItem = self.deleteGoalButton
} else {
self.navigationItem.rightBarButtonItem?.tintColor? = UIColor.clear
self.navigationItem.rightBarButtonItem?.isEnabled = false
}
self.budgetChallengeTitle.text = goalCreated?.GoalName
if let activityName = goalCreated?.GoalName {
self.budgetChallengeDescription.text = String(format: localizedString, activityName)
}
}
self.updateValues()
}
func listActivities(_ activities: [String]){
let activityApps = activities
var appString = ""
for activityApp in activityApps as [String] {
appString += "" + activityApp + ", "
}
self.appList.text = appString
}
override func viewWillAppear(_ animated: Bool) {
if let str = activitiyToPost?.activityDescription {
appList.text = str
}
let tracker = GAI.sharedInstance().defaultTracker
tracker?.set(kGAIScreenName, value: "TimeFrameBudgetChallengeViewController")
let builder = GAIDictionaryBuilder.createScreenView()
tracker?.send(builder?.build() as? [AnyHashable: Any])
}
// MARK: - functions
func updateValues()
{
self.minutesLabel.text = String(Int(maxDurationMinutes)! * Int(scaledMinutes))
self.minutesSlider.value = Float(maxDurationMinutes)!
if self.minutesSlider.value > 0{
setChallengeButton.alpha = 1.0
self.setChallengeButton.isEnabled = true
}else{
setChallengeButton.alpha = 0.0
self.setChallengeButton.isEnabled = false
}
}
// MARK: - Actions
@IBAction func back(_ sender: AnyObject) {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "backActionTimeFrameBudgetChallengeViewController", label: "Back from time budget challenge page", value: nil).build() as? [AnyHashable: Any])
self.navigationController?.popToRootViewController(animated: true)
}
@IBAction func minutesDidChange(_ sender: AnyObject) {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "minutesDidChange", label: "Change minutes", value: nil).build() as? [AnyHashable: Any])
maxDurationMinutes = String(Int(minutesSlider.value))
self.updateValues()
}
@IBAction func postNewBudgetChallengeButtonTapped(_ sender: AnyObject) {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "postNewBudgetChallengeButtonTapped", label: "Post new budget challenge", value: nil).build() as? [AnyHashable: Any])
if isFromActivity == true {
if let activityCategoryLink = activitiyToPost?.selfLinks! {
let bodyBudgetGoal: [String: AnyObject] = [
"@type": "BudgetGoal" as AnyObject,
"_links": ["yona:activityCategory":
["href": activityCategoryLink]
] as AnyObject,
"maxDurationMinutes": String(Int(Float(maxDurationMinutes)! * scaledMinutes)) as AnyObject
]
Loader.Show()
GoalsRequestManager.sharedInstance.postUserGoals(bodyBudgetGoal) { (success, serverMessage, serverCode, goal, nil, err) in
Loader.Hide()
if success {
self.delegate?.callGoalsMethod()
if let goalUnwrap = goal {
self.goalCreated = goalUnwrap
}
self.navigationItem.rightBarButtonItem = self.deleteGoalButton
self.navigationController?.popToRootViewController(animated: true)
UserDefaults.standard.set(true, forKey: YonaConstants.nsUserDefaultsKeys.isGoalsAdded)
UserDefaults.standard.synchronize()
} else {
if let message = serverMessage {
self.displayAlertMessage(message, alertDescription: "")
}
}
}
}
} else {
//EDIT Implementation
if let activityCategoryLink = goalCreated?.activityCategoryLink! {
let bodyBudgetGoal: [String: AnyObject] = [
"@type": "BudgetGoal" as AnyObject,
"_links": ["yona:activityCategory":
["href": activityCategoryLink]
] as AnyObject,
"maxDurationMinutes": String(Int(Float(maxDurationMinutes)! * scaledMinutes)) as AnyObject
]
Loader.Show()
GoalsRequestManager.sharedInstance.updateUserGoal(goalCreated?.editLinks, body: bodyBudgetGoal, onCompletion: { (success, serverMessage, server, goal, goals, error) in
Loader.Hide()
if success {
self.delegate?.callGoalsMethod()
if let goalUnwrap = goal {
self.goalCreated = goalUnwrap
}
self.navigationController?.popToRootViewController(animated: true)
} else {
if let message = serverMessage {
self.displayAlertMessage(message, alertDescription: "")
}
}
})
}
}
}
@IBAction func deletebuttonTapped(_ sender: AnyObject) {
weak var tracker = GAI.sharedInstance().defaultTracker
tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "deletebuttonTapped", label: "Delete time bucket challenge", value: nil).build() as? [AnyHashable: Any])
if #available(iOS 8, *) {
let alert = UIAlertController(title: NSLocalizedString("addfriend.alert.title.text", comment: ""), message: NSLocalizedString("challenges.timezone.deletetimezonemessage", comment: ""), preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("cancel", comment: ""), style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: UIAlertAction.Style.default, handler: {void in
self.deleteGoal()
}))
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: NSLocalizedString("addfriend.alert.title.text", comment: ""), message: NSLocalizedString("challenges.timezone.deletetimezonemessage", comment: ""), delegate: self, cancelButtonTitle: NSLocalizedString("cancel", comment: ""), otherButtonTitles: NSLocalizedString("OK", comment: "") )
alert.show()
}
}
func alertView( _ alertView: UIAlertView,clickedButtonAt buttonIndex: Int){
if buttonIndex == 1 {
deleteGoal()
}
}
func deleteGoal() {
if let goalUnwrap = self.goalCreated,
let goalEditLink = goalUnwrap.editLinks {
Loader.Show()
GoalsRequestManager.sharedInstance.deleteUserGoal(goalEditLink) { (success, serverMessage, serverCode, goal, goals, error) in
Loader.Hide()
if success {
if goals?.count == 1 {
UserDefaults.standard.set(false, forKey: YonaConstants.nsUserDefaultsKeys.isGoalsAdded)
}
self.delegate?.callGoalsMethod()
self.navigationController?.popToRootViewController(animated: true)
} else {
if let message = serverMessage {
self.displayAlertMessage(message, alertDescription: "")
}
}
}
}
}
}
private extension Selector {
static let back = #selector(TimeFrameBudgetChallengeViewController.back(_:))
}
| mpl-2.0 | d7566424a78e9bda7718aee38353733b | 44.556364 | 325 | 0.607998 | 5.428076 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.