repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
410Labs/aerogear-ios-oauth2 | AeroGearOAuth2/OAuth2WebViewController.swift | 1 | 2344 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import UIKit
/**
OAuth2WebViewController is a UIViewController to be used when the Oauth2 flow used an embedded view controller
rather than an external browser approach.
*/
open class OAuth2WebViewController: UIViewController, UIWebViewDelegate {
/// Login URL for OAuth.
var url: URL? {
didSet {
if isViewLoaded, webView.window != nil {
loadAddressURL()
}
}
}
/// WebView instance used to load login page.
let webView: UIWebView = UIWebView()
init(url: URL) {
super.init(nibName: nil, bundle: nil)
self.url = url
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if let url = aDecoder.decodeObject(forKey: "url") as? URL {
self.url = url
}
}
open override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
guard let url = url else {
return
}
aCoder.encode(url, forKey: "url")
}
/// Override of viewDidLoad to load the login page.
override open func viewDidLoad() {
super.viewDidLoad()
webView.frame = UIScreen.main.bounds
webView.delegate = self
self.view.addSubview(webView)
loadAddressURL()
}
override open func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.webView.frame = self.view.bounds
}
func loadAddressURL() {
guard let url = url else {
return
}
let req = URLRequest(url: url)
webView.loadRequest(req)
}
}
| apache-2.0 | 2795f6c01c9cc37ee2a74a800fbdbada | 26.576471 | 110 | 0.625853 | 4.614173 | false | false | false | false |
cismet/belis-app | belis-app/Veranlassung.swift | 1 | 4638 | //
// Veranlassung.swift
// Experiments
//
// Created by Thorsten Hell on 10/12/14.
// Copyright (c) 2014 cismet. All rights reserved.
//
import Foundation
import ObjectMapper
class Veranlassung : BaseEntity, CellDataProvider {
var dokumente: [DMSUrl] = []
var standorte: [Standort] = []
var infobausteine: [Infobaustein] = []
var beschreibung: String?
var bemerkungen: String?
var infobaustein_template: InfobausteinTemplate?
var geometrien: [StandaloneGeom] = []
var nummer: String?
var mauerlaschen: [Mauerlasche] = []
var art: Veranlassungsart?
var username: String?
var abzweigdosen: [Abzweigdose] = []
var leuchten: [Leuchte] = []
var bezeichnung: String?
var datum: Date?
var schaltstellen: [Schaltstelle] = []
var leitungen: [Leitung] = []
// MARK: - required init because of ObjectMapper
required init?(map: Map) {
super.init(map: map)
}
// MARK: - essential overrides BaseEntity
override func mapping(map: Map) {
id <- map["id"];
dokumente <- map["ar_dokumente"];
standorte <- map["ar_standorte"];
infobausteine <- map["ar_infobausteine"];
beschreibung <- map["beschreibung"];
bemerkungen <- map["bemerkungen"];
infobaustein_template <- map["fk_infobaustein_template"];
geometrien <- map["ar_geometrien"];
nummer <- map["nummer"];
mauerlaschen <- map["ar_mauerlaschen"];
art <- map["fk_art"];
username <- map["username"];
abzweigdosen <- map["ar_abzweigdosen"];
leuchten <- map["ar_leuchten"];
bezeichnung <- map["bezeichnung"];
datum <- (map["datum"], DateTransformFromString(format: "yyyy-MM-dd"))
schaltstellen <- map["ar_schaltstellen"];
leitungen <- map["ar_leitungen"];
}
override func getType() -> Entity {
return Entity.VERANLASSUNGEN
}
// MARK: - CellDataProvider Impl
@objc func getTitle() -> String {
return "Veranlassung"
}
@objc func getDetailGlyphIconString() -> String {
return "icon-switch"
}
@objc func getAllData() -> [String: [CellData]] {
var data: [String: [CellData]] = ["main":[]]
data["main"]?.append(SingleTitledInfoCellData(title: "Nummer", data: nummer ?? "?"))
data["main"]?.append(SingleTitledInfoCellData(title: "Bezeichnung", data: bezeichnung ?? "-"))
data["main"]?.append(SingleTitledInfoCellData(title: "Grund (Art)", data: art?.bezeichnung ?? "-"))
data["main"]?.append(MemoTitledInfoCellData(title: "Beschreibung", data: beschreibung ?? ""))
data["main"]?.append(DoubleTitledInfoCellData(titleLeft: "angelegt von", dataLeft: username ?? "-", titleRight: "angelegt am", dataRight: datum?.toDateString() ?? "-"))
data["main"]?.append(MemoTitledInfoCellData(title: "Bemerkungen", data: bemerkungen ?? ""))
if dokumente.count>0 {
data["Dokumente"]=[]
for url in dokumente {
data["Dokumente"]?.append(SimpleUrlPreviewInfoCellData(title: url.description ?? "Dokument", url: url.getUrl()))
}
}
data["DeveloperInfo"]=[]
data["DeveloperInfo"]?.append(SingleTitledInfoCellData(title: "Key", data: "\(getType().tableName())/\(id)"))
return data
}
@objc func getDataSectionKeys() -> [String] {
return ["main","Dokumente","DeveloperInfo"]
}
}
class Infobaustein: BaseEntity {
var schluessel: String?
var pflichtfeld: Bool?
var wert: String?
var bezeichnung: String?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
id <- map["id"];
schluessel <- map["schluessel"];
pflichtfeld <- map["pflichtfeld"];
wert <- map["wert"];
bezeichnung <- map["bezeichnung"];
}
}
class InfobausteinTemplate: BaseEntity {
var schluessel: String?
var bezeichnung: String?
var bausteine: [Infobaustein]=[]
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
id <- map["id"];
schluessel <- map["schluessel"];
bezeichnung <- map["bezeichnung"];
bausteine <- map["ar_bausteine"];
}
}
class Veranlassungsart: BaseEntity {
var schluessel: String?
var bezeichnung: String?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
id <- map["id"];
schluessel <- map["schluessel"];
bezeichnung <- map["bezeichnung"];
}
}
| mit | 303ac0fca1aebf15fb426bad052222e5 | 31.661972 | 176 | 0.599396 | 3.378004 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Exercise3.playgroundpage/Sources/SetUp.swift | 1 | 3618 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
let world = loadGridWorld(named: "9.4")
let actor = Actor()
var gemRandomizer: RandomizedQueueObserver?
public func playgroundPrologue() {
world.successCriteria = .count(collectedGems: 7, openSwitches: 0)
placeActor()
placeRandomPlaceholders()
world.place(Wall(edges: .bottom), at: Coordinate(column: 2, row: 2))
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomGems()
}
//// ----
generateGemsOverTime()
}
func placeActor() {
world.place(actor, facing: south, at: Coordinate(column: 2, row: 4))
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeRandomPlaceholders() {
let gem = Gem()
let actorCoordinate = [Coordinate(column: 2, row: 4)]
let coordinates = Set(world.coordinates(inColumns: [2], intersectingRows: 2...6)).subtracting(Set(actorCoordinate))
for i in coordinates {
world.place(RandomNode(resembling: gem), at: i)
}
}
func placeBlocks() {
world.removeNodes(at: world.coordinates(inColumns:[0,4]))
world.removeNodes(at: world.coordinates(inColumns: [1,3], intersectingRows: [0,1,7]))
world.placeWater(at: world.coordinates(inColumns:[0,4]))
world.placeWater(at: world.coordinates(inColumns: [1,3], intersectingRows: [0,1,7]))
world.removeNodes(at: world.coordinates(inColumns: [2], intersectingRows: [7]))
world.placeWater(at: world.coordinates(inColumns: [2], intersectingRows: [7]))
world.placeBlocks(at: world.coordinates(inColumns: [1,2,3], intersectingRows: 2...6))
world.placeBlocks(at: world.coordinates(inColumns: [1,3], intersectingRows: 2...6))
let tiers = [
Coordinate(column: 1, row: 6),
Coordinate(column: 3, row: 6),
Coordinate(column: 1, row: 6),
Coordinate(column: 3, row: 6),
Coordinate(column: 1, row: 5),
Coordinate(column: 3, row: 5),
Coordinate(column: 1, row: 4),
Coordinate(column: 3, row: 4),
]
world.placeBlocks(at: tiers)
world.place(Stair(), facing: south, at: Coordinate(column: 2, row: 1))
}
func realizeRandomGems() {
let coordinates = world.coordinates(inColumns: [2], intersectingRows: [2,3,5,6])
for coordinate in coordinates {
let random = Int(arc4random_uniform(8))
if random % 2 == 0 {
world.place(Gem(), at: coordinate)
}
}
}
func generateGemsOverTime() {
gemRandomizer = RandomizedQueueObserver(randomRange: 0...5, world: world) { world in
let existingGemCount = world.existingGems(at: world.coordinates(inColumns: [2], intersectingRows: [2,3,4,5,6])).count
guard existingGemCount < 3 else { return }
for coordinate in Set(world.coordinates(inColumns: [2], intersectingRows: [2,3,4,5,6])) {
if world.existingGems(at: [coordinate]).isEmpty {
world.place(Gem(), at: coordinate)
// Only place one gem.
return
}
}
}
}
| mit | 5f6652a660d9c6ab90dfc1bc2e572ed8 | 31.017699 | 125 | 0.61885 | 3.873662 | false | false | false | false |
chengxianghe/MissGe | MissGe/MissGe/Class/Helper/Emoji/String+Emoji.swift | 1 | 2124 | //
// String+Emoji.swift
// emoji-swift
//
// Created by Safx Developer on 2015/04/07.
// Copyright (c) 2015 Safx Developers. All rights reserved.
//
import Foundation
extension String {
public static var emojiDictionary = emoji {
didSet {
emojiUnescapeRegExp = createEmojiUnescapeRegExp()
emojiEscapeRegExp = createEmojiEscapeRegExp()
}
}
fileprivate static var emojiUnescapeRegExp = createEmojiUnescapeRegExp()
fileprivate static var emojiEscapeRegExp = createEmojiEscapeRegExp()
fileprivate static func createEmojiUnescapeRegExp() -> NSRegularExpression {
return try! NSRegularExpression(pattern: emojiDictionary.keys.map { ":\($0):" } .joined(separator: "|"), options: [])
}
fileprivate static func createEmojiEscapeRegExp() -> NSRegularExpression {
let v = emojiDictionary.values.sorted().reversed()
return try! NSRegularExpression(pattern: v.joined(separator: "|"), options: [])
}
public var emojiUnescapedString: String {
var s = self as NSString
let ms = String.emojiUnescapeRegExp.matches(in: self, options: [], range: NSMakeRange(0, s.length))
ms.reversed().forEach { m in
let r = m.range
let p = s.substring(with: r)
let px = p.substring(with: p.characters.index(after: p.startIndex) ..< p.characters.index(before: p.endIndex))
if let t = String.emojiDictionary[px] {
s = s.replacingCharacters(in: r, with: t) as NSString
}
}
return s as String
}
public var emojiEscapedString: String {
var s = self as NSString
let ms = String.emojiEscapeRegExp.matches(in: self, options: [], range: NSMakeRange(0, s.length))
ms.reversed().forEach { m in
let r = m.range
let p = s.substring(with: r)
let fs = String.emojiDictionary.lazy.filter { $0.1 == p }
if let kv = fs.first {
s = s.replacingCharacters(in: r, with: ":\(kv.0):") as NSString
}
}
return s as String
}
}
| mit | 98ea440968784cc4c56af5054dade3e1 | 34.4 | 125 | 0.616761 | 4.248 | false | false | false | false |
itouch2/LeetCode | LeetCode/BestTimetoBuyandSellStock.swift | 1 | 1281 | //
// BestTimetoBuyandSellStock.swift
// LeetCode
//
// Created by You Tu on 2017/8/20.
// Copyright © 2017年 You Tu. All rights reserved.
//
/*
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
*/
import Cocoa
class BestTimetoBuyandSellStock: NSObject {
func maxProfit(_ prices: [Int]) -> Int {
guard prices.count > 0 else {
return 0
}
var maxProfit = 0
var currentMinPrice = prices[0]
let remainingPrices = prices[1..<prices.count]
for price in remainingPrices {
let possibleMaxProfit = price - currentMinPrice
maxProfit = possibleMaxProfit > maxProfit ? possibleMaxProfit : maxProfit
currentMinPrice = price < currentMinPrice ? price : currentMinPrice
}
return maxProfit
}
}
| mit | f9f150c38c094f9288d8721d7cfae6f9 | 27.4 | 158 | 0.640063 | 3.803571 | false | false | false | false |
yojkim/YKUpDownIndicator | YKUpDownIndicator/YKCircleLayer.swift | 1 | 747 | //
// YKCircleLayer.swift
// YKUpDownIndicator
//
// Created by yojkim on 2017. 5. 17..
// Copyright © 2017년 yojkim. All rights reserved.
//
import UIKit
class YKCircleLayer: CALayer {
var circle = CALayer()
var color = UIColor.clear.cgColor
init(frame: CGRect = .zero) {
super.init()
self.frame = frame
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
self.circle.frame = bounds
self.circle.cornerRadius = bounds.width / 2
self.circle.masksToBounds = true
self.circle.backgroundColor = color
addSublayer(self.circle)
}
}
| mit | 4e1ea229213e80b31557b9f60fa9cebc | 20.257143 | 51 | 0.598118 | 3.97861 | false | false | false | false |
rnystrom/GitHawk | Classes/Issues/Comments/IssueCollapsedBodies.swift | 1 | 1189 | //
// IssueCollapsedBodies.swift
// Freetime
//
// Created by Ryan Nystrom on 6/1/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
private func bodyIsCollapsible(body: Any) -> Bool {
if body is IssueCommentHrModel,
body is IssueCommentHtmlModel {
return false
} else {
return true
}
}
func IssueCollapsedBodies(bodies: [AnyObject], width: CGFloat) -> (AnyObject, CGFloat)? {
let cap: CGFloat = 300
// minimum height to collapse so expanding shows significant amount of content
let minDelta = IssueCommentBaseCell.collapseCellMinHeight * 3
var totalHeight: CGFloat = 0
for body in bodies {
let height = BodyHeightForComment(
viewModel: body,
width: width,
webviewCache: nil,
imageCache: nil
)
totalHeight += height
if bodyIsCollapsible(body: body),
totalHeight > cap,
totalHeight - cap > minDelta {
let collapsedBodyHeight = max(cap - (totalHeight - height), IssueCommentBaseCell.collapseCellMinHeight)
return (body, collapsedBodyHeight)
}
}
return nil
}
| mit | c801019cbe47d1987e4ba44525e056e6 | 27.285714 | 115 | 0.632155 | 4.534351 | false | false | false | false |
dbahat/conventions-ios | Conventions/Conventions/model/ConventionEvent.swift | 1 | 14465 | //
// ConventionEvent.swift
// Conventions
//
// Created by David Bahat on 2/1/16.
// Copyright © 2016 Amai. All rights reserved.
//
import Foundation
import UIKit
import Firebase
class ConventionEvent {
/*
* An NSNotification event, fired when a user decides to attend an event
*/
static let AttendingWasSetEventName = Notification.Name("AttendingWasSetEventName")
private static let availableTicketsForEventUrl = "https://api.sf-f.org.il/program/available_tickets_per_event.php?slug="+Convention.name+"&id="
var id: String
var serverId: Int
var color: UIColor?
var textColor: UIColor?
var title: String
var lecturer: String?
var startTime: Date
var endTime: Date
var type: EventType
var hall: Hall
var images: Array<Int>?
var description: String?
var category: String
var price: Int
var tags: Array<String>
var url: URL
var availableTickets: Int?
var virtualUrl: String?
var isTicketless = false
var availableTicketsLastModified: Date?
let feedbackQuestions: Array<FeedbackQuestion> = [
FeedbackQuestion(question:"האם נהנית באירוע?", answerType: .Smiley),
//FeedbackQuestion(question:"ההנחיה באירוע היתה:", answerType: .Smiley),
//FeedbackQuestion(question:"האם תרצה לבוא לאירועים בנושאים דומים בעתיד?", answerType: .Smiley),
FeedbackQuestion(question:"נשמח לדעת למה", answerType: .Text),
]
init(id:String, serverId:Int, color: UIColor?, textColor: UIColor?, title: String, lecturer: String?, startTime: Date, endTime: Date, type: EventType, hall: Hall, description: String?, category: String, price: Int, tags: Array<String>, url: URL) {
self.id = id
self.serverId = serverId
self.color = color
self.textColor = textColor
self.title = title
self.lecturer = lecturer
self.startTime = startTime
self.endTime = endTime
self.type = type
self.hall = hall
self.description = description
self.category = category
self.price = price
self.tags = tags
self.url = url
}
static func parse(_ json: Dictionary<String, AnyObject>, halls: Array<Hall>) -> ConventionEvent? {
guard
let id = json["id"] as? String,
let serverId = json["serverId"] as? Int,
let title = json["title"] as? String,
let lecturer = json["lecturer"] as? String,
let startTime = json["startTime"] as? Double,
let endTime = json["endTime"] as? Double,
let type = json["type"] as? String,
let hall = json["hall"] as? String,
let description = json["description"] as? String,
let category = json["category"] as? String,
let price = json["price"] as? Int,
let tags = json["tags"] as? Array<String>,
let url = json["url"] as? String,
let presentationMode = json["presentationMode"] as? String,
let presentationLocation = json["presentationLocation"] as? String
else {
return nil
}
let event = ConventionEvent(id: id,
serverId: serverId,
color: Colors.eventTimeDefaultBackgroundColor,
textColor: nil,
title: title,
lecturer: lecturer,
startTime: Date(timeIntervalSince1970: startTime),
endTime: Date(timeIntervalSince1970: endTime),
type: EventType(backgroundColor: nil,
description: type,
presentation: EventType.Presentation(mode: EventType.PredentationMode(rawValue: presentationMode)!,
location: EventType.PredentationLocation(rawValue: presentationLocation)!)),
hall: ConventionEvent.findHall(halls, hallName: hall),
description: description,
category: category,
price: price,
tags: tags,
url: URL(string: url)!)
if let availableTickets = json["availableTickets"] as? Int? {
event.availableTickets = availableTickets
}
if let availableTicketsLastModified = json["availableTicketsLastModified"] as? Double {
event.availableTicketsLastModified = Date(timeIntervalSince1970: availableTicketsLastModified)
}
if let virtualUrl = json["virtualUrl"] as? String {
event.virtualUrl = virtualUrl
}
if let isTicketless = json["isTicketless"] as? Bool {
event.isTicketless = isTicketless
}
return event
}
fileprivate static func findHall(_ halls: Array<Hall>, hallName: String) -> Hall {
if let hall = halls.filter({hall in hall.name == hallName}).first {
return hall
}
return Hall(name: hallName)
}
func toJson() -> Dictionary<String, AnyObject> {
return [
"id": self.id as AnyObject,
"serverId": self.serverId as AnyObject,
"title": self.title as AnyObject,
"lecturer": (self.lecturer ?? "") as AnyObject,
"startTime": self.startTime.timeIntervalSince1970 as AnyObject,
"endTime": self.endTime.timeIntervalSince1970 as AnyObject,
"type": self.type.description as AnyObject,
"hall": self.hall.name as AnyObject,
"description": (self.description ?? "") as AnyObject,
"category": self.category as AnyObject,
"price": self.price as AnyObject,
"tags": self.tags as AnyObject,
"url": self.url.absoluteString as AnyObject,
"availableTickets": self.availableTickets as AnyObject,
"availableTicketsLastModified": self.availableTicketsLastModified?.timeIntervalSince1970 as AnyObject,
"presentationMode": self.type.presentation.mode.rawValue as AnyObject,
"presentationLocation": self.type.presentation.location.rawValue as AnyObject,
"virtualUrl": (self.virtualUrl ?? "") as AnyObject,
"isTicketless": self.isTicketless as AnyObject
]
}
var directWatchAvailable: Bool {
get {
return directWatchUrl != nil
}
}
var directWatchUrl: URL? {
if let unwrapped = virtualUrl, unwrapped != "" {
return URL(string: unwrapped)
} else {
return nil
}
}
var feedbackAnswers: Array<FeedbackAnswer> {
get {
guard let input = Convention.instance.eventsInputs.getInput(id) else {
return []
}
return input.feedbackUserInput.answers
}
}
var attending: Bool {
get {
guard let input = Convention.instance.eventsInputs.getInput(id) else {
return false
}
return input.attending
}
set {
if newValue {
NotificationsSchedualer.scheduleEventAboutToStartNotification(self)
NotificationsSchedualer.scheduleEventFeedbackReminderNotification(self)
NotificationCenter.default.post(name: ConventionEvent.AttendingWasSetEventName, object: self)
Analytics.logEvent("Favorites", parameters: [
"name": newValue ? "Added" : "Remove" as NSObject
])
Messaging.messaging().subscribe(toTopic: Convention.name.lowercased() + "_event_" + serverId.description)
} else {
NotificationsSchedualer.removeEventAboutToStartNotification(self)
NotificationsSchedualer.removeEventFeedbackReminderNotification(self)
Messaging.messaging().unsubscribe(fromTopic: Convention.name.lowercased() + "event_" + serverId.description)
}
if let input = Convention.instance.eventsInputs.getInput(id) {
input.attending = newValue
} else {
let input = UserInput.ConventionEventInput(attending: newValue, feedbackUserInput: UserInput.Feedback())
Convention.instance.eventsInputs.setInput(input, forEventId: id)
}
Convention.instance.eventsInputs.save()
}
}
func provide(feedback answer: FeedbackAnswer) {
if let input = Convention.instance.eventsInputs.getInput(id) {
// If the answer already exists, override it
if let existingAnswerIndex = input.feedbackUserInput.answers.firstIndex(where: {$0.questionText == answer.questionText}) {
input.feedbackUserInput.answers.remove(at: existingAnswerIndex)
}
input.feedbackUserInput.answers.append(answer)
Convention.instance.eventsInputs.save()
return
}
let feedback = UserInput.Feedback()
feedback.answers.append(answer)
let input = UserInput.ConventionEventInput(attending: false, feedbackUserInput: feedback)
Convention.instance.eventsInputs.setInput(input, forEventId: id)
Convention.instance.eventsInputs.save()
}
func clear(feedback question: FeedbackQuestion) {
guard let input = Convention.instance.eventsInputs.getInput(id) else {
// no inputs means nothing to clear
return
}
guard let existingAnswerIndex = input.feedbackUserInput.answers.firstIndex(where: {$0.questionText == question.question}) else {
// no existing answer means nothing to clear
return
}
input.feedbackUserInput.answers.remove(at: existingAnswerIndex)
Convention.instance.eventsInputs.save()
}
func submitFeedback(_ callback: ((_ success: Bool) -> Void)?) {
guard let input = Convention.instance.eventsInputs.getInput(id) else {
// In case the user tries to submit empty feedback auto-fail the submission request
callback?(false)
return
}
Convention.instance.eventFeedbackForm.submit(
conventionName: Convention.displayName,
event: self,
answers: input.feedbackUserInput.answers,
callback: {success in
input.feedbackUserInput.isSent = success
Analytics.logEvent("Feedback", parameters: [
"submit": success
])
callback?(success)
})
}
func isEventAvailable() -> Bool {
return startTime.timeIntervalSince1970 <= Date.now().timeIntervalSince1970 && endTime.timeIntervalSince1970 >= Date.now().timeIntervalSince1970
}
func canFillFeedback() -> Bool {
// Check if the event will end in 15 minutes or less
return startTime.addMinutes(30).timeIntervalSince1970 < Date.now().timeIntervalSince1970
}
func didSubmitFeedback() -> Bool {
guard let input = Convention.instance.eventsInputs.getInput(id) else {
return false
}
return input.feedbackUserInput.isSent
}
func hasStarted() -> Bool {
return startTime.timeIntervalSince1970 < Date.now().timeIntervalSince1970
}
func hasEnded() -> Bool {
return endTime.timeIntervalSince1970 < Date.now().timeIntervalSince1970
}
func refreshAvailableTickets(_ callback:((_ success: Bool) -> Void)?) {
let url = URL(string: ConventionEvent.availableTicketsForEventUrl + String(serverId))!
URLSession.shared.dataTask(with: url, completionHandler:{(data, response, error) -> Void in
guard
let availableTicketsCallResponse = response as? HTTPURLResponse,
let availableTicketsLastModifiedString = availableTicketsCallResponse.allHeaderFields["Last-Modified"] as? String,
let unwrappedData = data
else {
DispatchQueue.main.async {
callback?(false)
}
return
}
if (availableTicketsCallResponse.statusCode != 200) {
DispatchQueue.main.async {
callback?(false)
}
return
}
guard
let deserializedResult = ((try? JSONSerialization.jsonObject(with: unwrappedData, options: []) as? Dictionary<String, AnyObject>) as Dictionary<String, AnyObject>??),
let result = deserializedResult
else {
print("Failed to deserialize available tickets result");
DispatchQueue.main.async {
callback?(false)
}
return
}
if let tickets = result["available_tickets"] as? Int
{
self.availableTickets = tickets
}
self.availableTicketsLastModified = Date.parse(availableTicketsLastModifiedString, dateFormat: "EEE, dd MMM yyyy HH:mm:ss zzz")
DispatchQueue.main.async {
callback?(true)
}
}).resume()
}
}
extension Array where Element: FeedbackAnswer {
// "Weighted rating" represents the overall rating the user gave to this event amongst the smiley
// questions
func getFeedbackWeightedRating() -> FeedbackAnswer.Smiley? {
// We assume the smiley questions are sorted by importance
return self
.filter({answer in answer as? FeedbackAnswer.Smiley != nil})
.map({answer in answer as! FeedbackAnswer.Smiley})
.first
}
}
| apache-2.0 | 5568d04d0d3d109bf61df238c7710c21 | 39.075209 | 251 | 0.575103 | 5.225935 | false | false | false | false |
siuying/SignalKit | SignalKitTests/Utilities/BagTests.swift | 1 | 1978 | //
// BagTests.swift
// SignalKit
//
// Created by Yanko Dimitrov on 7/15/15.
// Copyright (c) 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
import XCTest
class BagTests: XCTestCase {
func testBagIsInitiallyEmpty() {
var bag = Bag<Int>()
XCTAssertEqual(bag.count, 0, "Initially the bag should be empty")
}
func testInsertItem() {
class FakeGenerator: TokenGeneratorType {
func nextToken() -> Token {
return "1"
}
}
var bag = Bag<String>(keyGenerator: FakeGenerator())
let token = bag.insert("John")
XCTAssertEqual(token, "1", "Should be able to insert a new item in the bag")
XCTAssertEqual(bag.count, 1, "Should contain one item")
}
func testInsertDuplicateItems() {
var bag = Bag<Int>()
bag.insert(1)
bag.insert(1)
bag.insert(1)
XCTAssertEqual(bag.count, 3, "Should be able to insert non unique items")
}
func testRemoveItem() {
var bag = Bag<Int>()
let token = bag.insert(1)
bag.removeItemWithToken(token)
XCTAssertEqual(bag.count, 0, "Should be able to remove an item from the bag")
}
func testRemoveAllItems() {
var bag = Bag<Int>()
bag.insert(1)
bag.insert(2)
bag.insert(3)
bag.removeItems()
XCTAssertEqual(bag.count, 0, "Should remove all bag items")
}
func testIterateOverItems() {
var bag = Bag<Int>()
var sum = 0
bag.insert(1)
bag.insert(2)
bag.insert(3)
for (key, item) in bag {
sum += item
}
XCTAssertEqual(sum, 6, "Should be able to iterate over the bag collection")
}
}
| mit | f3ca62aace2cbf3106ae6f2c61485e2f | 21.477273 | 85 | 0.510111 | 4.526316 | false | true | false | false |
tavultesoft/keymanweb | ios/keyman/Keyman/Keyman/Classes/MainViewController/MainViewController.swift | 1 | 39823 | //
// MainViewController.swift
// Keyman
//
// Created by Gabriel Wong on 2017-09-07.
// Copyright © 2017 SIL International. All rights reserved.
//
import KeymanEngine
import UIKit
import QuartzCore
// Internal strings
private let baseUri = "https://r.keymanweb.com/20/fonts/get_mobileconfig.php?id="
private let profileKey = "profile"
private let checkedProfilesKey = "CheckedProfiles"
// External strings
let userTextKey = "UserText"
let userTextSizeKey = "UserTextSize"
let dontShowGetStartedKey = "DontShowGetStarted" // older preference setting name, use shouldShowGetStartedKey
let shouldShowGetStartedKey = "ShouldShowGetStarted"
let shouldReportErrorsKey = "ShouldReportErrors"
let launchedFromUrlNotification = NSNotification.Name("LaunchedFromUrlNotification")
let urlKey = "url"
class MainViewController: UIViewController, TextViewDelegate, UIActionSheetDelegate {
private let minTextSize: CGFloat = 9.0
private let maxTextSize: CGFloat = 72.0
private let getStartedViewTag = 7183
private let activityIndicatorViewTag = 6573
private let dropDownListTag = 686876
var textView: TextView!
var textSize: CGFloat = 0.0
var navbarBackground: KMNavigationBarBackgroundView!
private var getStartedVC: GetStartedViewController!
private var infoView: InfoViewController!
private var popover: UIViewController?
private var textSizeController: UISlider!
private var dropdownItems: [UIBarButtonItem]!
private var profilesToInstall: [String] = []
private var checkedProfiles: [String] = []
private var profileName: String?
private var keyboardToDownload: InstallableKeyboard?
private var customKeyboardToDownload: URL?
private var wasKeyboardVisible: Bool = false
private var screenWidth: CGFloat = 0.0
private var screenHeight: CGFloat = 0.0
private var portLeftMargin: CGFloat = 0.0
private var portRightMargin: CGFloat = 0.0
private var lscpeLeftMargin: CGFloat = 0.0
private var lscpeRightMargin: CGFloat = 0.0
private var didKeyboardLoad = false
private var keyboardLoadedObserver: NotificationObserver?
private var languagesUpdatedObserver: NotificationObserver?
private var languagesDownloadFailedObserver: NotificationObserver?
private var keyboardPickerDismissedObserver: NotificationObserver?
private var keyboardChangedObserver: NotificationObserver?
private var keyboardRemovedObserver: NotificationObserver?
var appDelegate: AppDelegate! {
return UIApplication.shared.delegate as? AppDelegate
}
var overlayWindow: UIWindow! {
return appDelegate?.overlayWindow
}
convenience init() {
if UIDevice.current.userInterfaceIdiom == .phone {
self.init(nibName: "MainViewController_iPhone", bundle: nil)
} else {
self.init(nibName: "MainViewController_iPad", bundle: nil)
}
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Setup Notifications
NotificationCenter.default.addObserver(self, selector: #selector(self.onKeyboardWillShow),
name: UIResponder.keyboardWillShowNotification, object: nil)
// `keyboardDidShow` apparently matches an internal Apple API and will fail an app submission.
// So, cheap workaround: just prefix the thing.
NotificationCenter.default.addObserver(self, selector: #selector(self.onKeyboardDidShow),
name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.onKeyboardWillHide),
name: UIResponder.keyboardWillHideNotification, object: nil)
keyboardLoadedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardLoaded,
observer: self,
function: MainViewController.keyboardLoaded)
keyboardChangedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardChanged,
observer: self,
function: MainViewController.keyboardChanged)
keyboardPickerDismissedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardPickerDismissed,
observer: self,
function: MainViewController.keyboardPickerDismissed)
keyboardRemovedObserver = NotificationCenter.default.addObserver(
forName: Notifications.keyboardRemoved,
observer: self,
function: MainViewController.keyboardRemoved)
// Unfortunately, it's the main app with the file definitions.
// We have to gerry-rig this so that the framework-based SettingsViewController
// can launch the app-based DocumentViewController.
Manager.shared.fileBrowserLauncher = { navVC in
let vc = PackageBrowserViewController(documentTypes: ["com.keyman.kmp"],
in: .import,
navVC: navVC)
// Present the "install from file" browser within the specified navigation view controller.
// (Allows displaying from within the Settings menu)
navVC.present(vc, animated: true)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
extendedLayoutIncludesOpaqueBars = true
let systemFonts = Set<String>(UIFont.familyNames)
// Setup Keyman Manager & fetch keyboards list
Manager.shared.canRemoveDefaultKeyboard = true
// Pre-load for use in update checks.
if !ResourceDownloadManager.shared.updateCacheIsCurrent {
// TODO: Actually use the query's results once available.
// That said, this is as far as older versions used the query here.
ResourceDownloadManager.shared.queryKeysForUpdatablePackages { _, _ in }
}
view?.backgroundColor = UIColor(named: "InputBackground")!
// Check for configuration profiles/fonts to install
FontManager.shared.registerCustomFonts()
let kmFonts = FontManager.shared.fonts
var profilesByFontName: [String: String] = [:]
for (url, font) in kmFonts where url.lastPathComponent != Resources.oskFontFilename {
let profile = url.deletingPathExtension().appendingPathExtension("mobileconfig").lastPathComponent
profilesByFontName[font.name] = profile
}
let customFonts = UIFont.familyNames.filter { !systemFonts.contains($0) && !($0 == "KeymanwebOsk") }
let userData = AppDelegate.activeUserDefaults()
checkedProfiles = userData.object(forKey: checkedProfilesKey) as? [String] ?? [String]()
profilesToInstall = [String]()
for name in customFonts {
if let profile = profilesByFontName[UIFont.fontNames(forFamilyName: name)[0]] {
profilesToInstall.append(profile)
}
}
// Setup NavigationBar
if let navbar = navigationController?.navigationBar {
if #available(iOS 13.0, *) {
// Dark mode settings must be applied through this new property,
// its class, and others like it.
navbar.standardAppearance.configureWithOpaqueBackground()
} else {
// Fallback on earlier versions
}
navbarBackground = KMNavigationBarBackgroundView()
navbarBackground.addToNavbar(navbar)
navbarBackground.setOrientation(UIApplication.shared.statusBarOrientation)
}
// Setup Keyman TextView
textSize = 16.0
textView = TextView(frame: view.frame)
textView.setKeymanDelegate(self)
textView.viewController = self
textView.backgroundColor = UIColor(named: "InputBackground")!
textView.isScrollEnabled = true
textView.isUserInteractionEnabled = true
textView.font = textView.font?.withSize(textSize)
view?.addSubview(textView!)
// Setup Info View
infoView = InfoViewController()
if UIDevice.current.userInterfaceIdiom != .phone {
textSize *= 2
textView.font = textView?.font?.withSize(textSize)
}
infoView.view?.isHidden = true
infoView.view?.backgroundColor = UIColor(named: "InputBackground")!
view?.addSubview(infoView!.view)
resizeViews(withKeyboardVisible: textView.isFirstResponder)
// Setup Text Size Controller
textSizeController = UISlider()
textSizeController.frame = CGRect.zero
textSizeController.minimumValue = 0.0
textSizeController.maximumValue = Float(maxTextSize - minTextSize)
textSizeController.value = Float(textSize - minTextSize)
let textSizeUp = #imageLiteral(resourceName: "textsize_up.png").resize(to: CGSize(width: 20, height: 20))
textSizeController.maximumValueImage = textSizeUp
let textSizeDown = #imageLiteral(resourceName: "textsize_up.png").resize(to: CGSize(width: 15, height: 15))
textSizeController.minimumValueImage = textSizeDown
textSizeController.addTarget(self, action: #selector(self.sliderValueChanged), for: .valueChanged)
setNavBarButtons()
loadSavedUserText()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
wasKeyboardVisible = textView.isFirstResponder
}
private func setNavBarButtons() {
let orientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
let imageScaleF: CGFloat = 0.9
let moreButton = createNavBarButton(with: UIImage(named: "IconMore")!,
highlightedImage: UIImage(named: "IconMoreSelected")!,
imageScale: imageScaleF,
action: #selector(self.showDropDownMenu),
orientation: orientation)
moreButton.title = NSLocalizedString("menu-more", comment: "")
let infoButton = createNavBarButton(with: UIImage(named: "IconInfo")!,
highlightedImage: UIImage(named: "IconInfoSelected")!,
imageScale: imageScaleF,
action: #selector(self.infoButtonClick),
orientation: orientation)
infoButton.title = NSLocalizedString("menu-help", comment: "")
let getStartedButton = createNavBarButton(with: UIImage(named: "IconNotepad")!,
highlightedImage: UIImage(named: "IconNotepadSelected")!,
imageScale: imageScaleF,
action: #selector(self.showGetStartedView),
orientation: orientation)
getStartedButton.title = NSLocalizedString("menu-get-started", comment: "")
let trashButton = createNavBarButton(with: UIImage(named: "IconTrash")!,
highlightedImage: UIImage(named: "IconTrashSelected")!,
imageScale: imageScaleF,
action: #selector(self.trashButtonClick),
orientation: orientation)
trashButton.title = NSLocalizedString("menu-clear-text", comment: "")
let textSizeButton = createNavBarButton(with: UIImage(named: "IconTextSize")!,
highlightedImage: UIImage(named: "IconTextSizeSelected")!,
imageScale: imageScaleF,
action: #selector(self.textSizeButtonClick),
orientation: orientation)
textSizeButton.title = NSLocalizedString("menu-text-size", comment: "")
let browserButton = createNavBarButton(with: UIImage(named: "IconBrowser")!,
highlightedImage: UIImage(named: "IconBrowserSelected")!,
imageScale: 1.0,
action: #selector(self.showKMWebBrowserView),
orientation: orientation)
browserButton.title = NSLocalizedString("menu-show-browser", comment: "")
let actionButton = createNavBarButton(with: UIImage(named: "IconShare")!,
highlightedImage: UIImage(named: "IconShareSelected")!,
imageScale: imageScaleF,
action: #selector(self.actionButtonClick),
orientation: orientation)
actionButton.title = NSLocalizedString("menu-share", comment: "")
let settingsButton = createNavBarButton(with: UIImage(named: "IconMore")!,
highlightedImage: UIImage(named: "IconMoreSelected")!,
imageScale: imageScaleF,
action: #selector(self.settingsButtonClick),
orientation: orientation)
settingsButton.title = NSLocalizedString("menu-settings", comment: "")
dropdownItems = [textSizeButton, trashButton, infoButton, getStartedButton, settingsButton]
var scaleF: CGFloat = (UIScreen.main.scale == 2.0) ? 2.0 : 1.5
scaleF *= (UIDevice.current.userInterfaceIdiom == .phone) ? 1.0 : 2.0
fixedSpace.width = 10 * scaleF
if UIDevice.current.userInterfaceIdiom == .phone {
navigationItem.rightBarButtonItems = [moreButton, fixedSpace, browserButton, fixedSpace, actionButton]
} else {
navigationItem.rightBarButtonItems = [settingsButton, fixedSpace, infoButton, fixedSpace, getStartedButton,
fixedSpace, trashButton, fixedSpace, textSizeButton, fixedSpace, browserButton, fixedSpace, actionButton]
}
}
private func createNavBarButton(with image: UIImage,
highlightedImage imageHighlighted: UIImage,
imageScale scaleF: CGFloat,
action selector: Selector,
orientation: UIInterfaceOrientation) -> UIBarButtonItem {
let size = CGSize(width: image.size.width * scaleF, height: image.size.height * scaleF)
let vAdjPort: CGFloat = UIScreen.main.scale == 2.0 ? -3.6 : -2.6
let vAdjLscpe: CGFloat = -1.6
let vAdj = orientation.isPortrait ? vAdjPort : vAdjLscpe
let navBarHeight = self.navBarHeight()
let y = (navBarHeight - size.height) / 2.0 + vAdj
let customButton = UIButton(type: .custom)
customButton.setImage(image, for: .normal)
customButton.setImage(imageHighlighted, for: .highlighted)
customButton.frame = CGRect(x: 0.0, y: y, width: size.width, height: size.height)
customButton.addTarget(self, action: selector, for: .touchUpInside)
let containerView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: size.width, height: navBarHeight))
containerView.backgroundColor = UIColor.clear
containerView.addSubview(customButton)
return UIBarButtonItem(customView: containerView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if wasKeyboardVisible {
textView.becomeFirstResponder()
}
if !didKeyboardLoad {
showActivityIndicator()
} else if shouldShowGetStarted {
perform(#selector(self.showGetStartedView), with: nil, afterDelay: 1.0)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
let orientation: UIInterfaceOrientation = toInterfaceOrientation
for view in overlayWindow.subviews {
UIView.animate(withDuration: duration, delay: 0.0, options: ([]), animations: {() -> Void in
view.transform = self.transform(for: orientation)
}, completion: nil)
}
if let navbarBackground = navbarBackground {
navbarBackground.setOrientation(toInterfaceOrientation)
}
popover?.dismiss(animated: false)
_ = dismissDropDownMenu()
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
if infoView?.view?.isHidden ?? true {
setNavBarButtons()
}
resizeViews(withKeyboardVisible: textView.isFirstResponder)
}
private func resizeViews(withKeyboardVisible keyboardVisible: Bool) {
// Resize textView and infoView
let mainScreen: CGRect = UIScreen.main.bounds
let margin: CGFloat = 2.0
let barHeights: CGFloat = AppDelegate.statusBarHeight() + navBarHeight()
let kbHeight: CGFloat = keyboardVisible ? textView.inputView?.frame.height ?? 0 : 0
let width: CGFloat = mainScreen.size.width
let height: CGFloat = mainScreen.size.height - barHeights - kbHeight
textView.frame = CGRect(x: margin, y: barHeights + margin,
width: width - 2 * margin, height: height - 2 * margin)
infoView?.view?.frame = CGRect(x: 0, y: barHeights, width: width, height: height + kbHeight)
}
private func navBarWidth() -> CGFloat {
return navigationController!.navigationBar.frame.width
}
private func navBarHeight() -> CGFloat {
return navigationController!.navigationBar.frame.height
}
@objc func onKeyboardWillShow(_ notification: Notification) {
_ = dismissDropDownMenu()
resizeViews(withKeyboardVisible: true)
}
@objc func onKeyboardDidShow(_ notification: Notification) {
// Workaround to display overlay window above keyboard
let windows = UIApplication.shared.windows
let lastWindow = windows.last
overlayWindow.windowLevel = lastWindow!.windowLevel + 1
}
@objc func onKeyboardWillHide(_ notification: Notification) {
resizeViews(withKeyboardVisible: false)
}
// MARK: - Keyman Notifications
private func keyboardLoaded() {
didKeyboardLoad = true
dismissActivityIndicator()
textView.becomeFirstResponder()
if shouldShowGetStarted {
perform(#selector(self.showGetStartedView), with: nil, afterDelay: 1.0)
}
}
private func keyboardChanged(_ kb: InstallableKeyboard) {
checkProfile(forFullID: kb.fullID, doListCheck: true)
}
private func keyboardPickerDismissed() {
textView.becomeFirstResponder()
if UIDevice.current.userInterfaceIdiom == .pad && shouldShowGetStarted {
perform(#selector(self.showGetStartedView), with: nil, afterDelay: 1.0)
}
}
private func keyboardRemoved(_ keyboard: InstallableKeyboard) {
guard let font = keyboard.font,
let profile = profileName(withFont: font) else {
return
}
profilesToInstall = profilesToInstall.filter { $0 != profile }
profilesToInstall.append(profile)
checkedProfiles = checkedProfiles.filter { $0 != profile }
let userData = AppDelegate.activeUserDefaults()
userData.set(checkedProfiles, forKey: checkedProfilesKey)
userData.synchronize()
}
// MARK: - View Actions
@objc func infoButtonClick(_ sender: Any?) {
UIView.setAnimationDelegate(self)
let animSelector = NSSelectorFromString("animationDidStop:finished:context:")
UIView.setAnimationDidStop(animSelector)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.75)
UIView.setAnimationTransition((!textView.isHidden ? .flipFromRight : .flipFromLeft), for: view, cache: true)
if !textView.isHidden {
textView.isHidden = true
infoView.view.isHidden = false
infoView.reloadKeymanHelp()
} else {
textView.isHidden = false
infoView.view.isHidden = true
}
UIView.commitAnimations()
if !textView.isHidden {
navigationItem.titleView = nil
navigationItem.rightBarButtonItem = nil
setNavBarButtons()
if wasKeyboardVisible {
perform(#selector(self.displayKeyboard), with: nil, afterDelay: 0.75)
}
if shouldShowGetStarted {
perform(#selector(self.showGetStartedView), with: nil, afterDelay: 0.75)
}
} else {
_ = dismissDropDownMenu()
popover?.dismiss(animated: false)
wasKeyboardVisible = textView.isFirstResponder
textView.dismissKeyboard()
navigationItem.rightBarButtonItems = nil
let vAdjPort: CGFloat = UIScreen.main.scale == 2.0 ? -3.6 : -2.6
let vAdjLscpe: CGFloat = -1.6
let infoDoneButton = UIBarButtonItem(title: "Done", style: .plain, target: self,
action: #selector(self.infoButtonClick))
infoDoneButton.setBackgroundVerticalPositionAdjustment(vAdjPort, for: UIBarMetrics.default)
infoDoneButton.setBackgroundVerticalPositionAdjustment(vAdjLscpe, for: UIBarMetrics.compact)
navigationItem.rightBarButtonItem = infoDoneButton
let versionLabel = UILabel()
let infoDict = Bundle.main.infoDictionary
let version = infoDict?["KeymanVersionWithTag"] as? String ?? ""
versionLabel.text = String.init(format: NSLocalizedString("version-label", comment: ""), version)
versionLabel.font = UIFont.systemFont(ofSize: 9.0)
versionLabel.textAlignment = .right
versionLabel.sizeToFit()
let frame: CGRect = versionLabel.frame
versionLabel.frame = frame.insetBy(dx: -8, dy: 0)
versionLabel.backgroundColor = UIColor.clear
navigationItem.titleView = versionLabel
}
}
@objc func settingsButtonClick(_ sender: Any) {
_ = dismissDropDownMenu()
popover?.dismiss(animated: false)
Manager.shared.showKeymanEngineSettings(inVC: self)
}
func showInstalledLanguages() {
Manager.shared.hideKeyboard()
// Allows us to set a custom UIToolbar for download/update status displays.
let nc = UINavigationController(navigationBarClass: nil, toolbarClass: ResourceDownloadStatusToolbar.self)
// Grab our newly-generated toolbar instance and inform it of its parent NavigationController.
// This will help streamline use of the 'toolbar' as a status/update bar.
let toolbar = nc.toolbar as? ResourceDownloadStatusToolbar
toolbar?.navigationController = nc
// As it's the first added view controller, settingsVC will function as root automatically.
let settingsVC = SettingsViewController()
nc.pushViewController(settingsVC, animated: false)
nc.modalTransitionStyle = .coverVertical
nc.modalPresentationStyle = .pageSheet
let installedLanguagesVC = InstalledLanguagesViewController()
nc.pushViewController(installedLanguagesVC, animated: true)
self.present(nc, animated: true) {
// Requires a host NavigationViewController, hence calling it afterward.
installedLanguagesVC.launchKeyboardSearch()
}
}
@objc func actionButtonClick(_ sender: Any) {
_ = dismissDropDownMenu()
popover?.dismiss(animated: false)
let lrm = "\u{200e}"
let rlm = "\u{200f}"
var text: String! = textView.text
if text.hasPrefix(lrm) || text.hasPrefix(rlm) {
text = String(text[text.index(after: text.startIndex)...])
}
let activityProvider = ActivityItemProvider(text: text, font: textView.font)
let printText = UISimpleTextPrintFormatter(text: textView.text)
printText.font = textView.font
let activityVC = UIActivityViewController(activityItems: [activityProvider, printText], applicationActivities: nil)
activityVC.excludedActivityTypes = [UIActivity.ActivityType.assignToContact,
UIActivity.ActivityType.postToWeibo,
UIActivity.ActivityType.saveToCameraRoll]
activityVC.completionWithItemsHandler = {(_ activityType: UIActivity.ActivityType?, _ completed: Bool,
_ returnedItems: [Any]?, _ activityError: Error?) -> Void in
// If a share was completed -OR- if the user backed out of the share selection menu.
if completed || activityType == nil {
self.textView.isUserInteractionEnabled = true
} // else (if the user started to share but backed out to the menu) do nothing.
}
textView.isUserInteractionEnabled = false
if UIDevice.current.userInterfaceIdiom == .phone {
present(activityVC, animated: true, completion: nil)
} else {
activityVC.modalPresentationStyle = UIModalPresentationStyle.popover
activityVC.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItems?[12]
self.present(activityVC, animated: true)
popover = activityVC
}
}
@objc func textSizeButtonClick(_ sender: Any) {
_ = dismissDropDownMenu()
popover?.dismiss(animated: false)
let textSizeVC = UIViewController()
textSizeVC.modalPresentationStyle = .overCurrentContext
textSizeVC.view.backgroundColor = UIColor.clear
let mframe: CGRect = textSizeVC.view.frame
let w: CGFloat = 304
let h: CGFloat = 142
let sframe = CGRect(x: mframe.size.width / 2.0 - w / 2.0, y: mframe.size.height, width: w, height: h)
let eframe = CGRect(x: sframe.origin.x, y: sframe.origin.y - h - 8, width: w, height: h)
let containerView = UIView(frame: sframe)
containerView.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
containerView.backgroundColor = Colors.systemBackground
containerView.tag = 1
containerView.layer.cornerRadius = 4.0
let doneButton = UIButton(type: .roundedRect)
doneButton.addTarget(self, action: #selector(self.dismissTextSizeVC), for: .touchUpInside)
doneButton.setTitle("Done", for: .normal)
doneButton.titleLabel?.font = doneButton.titleLabel?.font?.withSize(21.0)
doneButton.setTitleColor(UIColor(red: 0.0, green: 0.5, blue: 1.0, alpha: 1.0), for: .normal)
doneButton.layer.cornerRadius = 4.0
let bframe = CGRect(x: 0, y: h - 42, width: sframe.size.width, height: 42)
doneButton.frame = bframe
containerView.addSubview(doneButton)
let lframe = CGRect(x: 0, y: bframe.origin.y - 1, width: sframe.size.width, height: 1)
let borderLine = UIView(frame: lframe)
if #available(iOS 13.0, *) {
borderLine.backgroundColor = UIColor.separator
} else {
let c: CGFloat = 230.0 / 255.0
borderLine.backgroundColor = UIColor(red: c, green: c, blue: c, alpha: 1.0)
}
containerView.addSubview(borderLine)
let tframe = CGRect(x: 0, y: 0, width: bframe.size.width, height: 40)
let textSizeTitle = UILabel(frame: tframe)
textSizeTitle.tag = 2
textSizeTitle.backgroundColor = UIColor.clear
textSizeTitle.text = String.init(format: NSLocalizedString("text-size-label", comment: ""), Int(textSize))
textSizeTitle.textAlignment = .center
if #available(iOS 13.0, *) {
textSizeTitle.textColor = UIColor.secondaryLabel
} else {
textSizeTitle.textColor = UIColor.gray
}
textSizeTitle.font = textSizeTitle.font.withSize(14.0)
containerView.addSubview(textSizeTitle)
let sliderFrame = CGRect(x: 12, y: 45, width: bframe.size.width - 24, height: 50)
textSizeController.frame = sliderFrame
containerView.addSubview(textSizeController)
textSizeVC.view.addSubview(containerView)
if UIDevice.current.userInterfaceIdiom == .phone {
wasKeyboardVisible = textView.isFirstResponder
textView.dismissKeyboard()
present(textSizeVC, animated: false, completion: {() -> Void in
UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseIn, animations: {() -> Void in
containerView.frame = eframe
textSizeVC.view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4)
}, completion: nil)
})
} else {
let vc = UIViewController()
vc.modalPresentationStyle = .popover
vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItems?[8]
vc.view = containerView
vc.preferredContentSize = containerView.frame.size
present(vc, animated: true, completion: nil)
}
}
@objc func dismissTextSizeVC(_ sender: Any) {
let presentedVC = presentedViewController
if UIDevice.current.userInterfaceIdiom == .phone {
let containerView: UIView! = presentedVC?.view?.viewWithTag(1)
let sframe = containerView.frame
let eframe = CGRect(x: sframe.origin.x, y: sframe.origin.y + sframe.height + 8,
width: sframe.width, height: sframe.height)
UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseIn, animations: {() -> Void in
containerView.frame = eframe
presentedVC?.view?.backgroundColor = UIColor.clear
}, completion: {(_ finished: Bool) -> Void in
presentedVC?.dismiss(animated: false, completion: {() -> Void in
if self.wasKeyboardVisible {
self.textView.becomeFirstResponder()
}
})
})
} else {
presentedVC?.dismiss(animated: true, completion: nil)
}
}
@objc func trashButtonClick(_ sender: Any) {
_ = dismissDropDownMenu()
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let clear = UIAlertAction(title: NSLocalizedString("menu-clear-text", comment: ""),
style: .destructive,
handler: {(_ action: UIAlertAction) -> Void in
self.textView.text = ""
})
let cancel = UIAlertAction(title: NSLocalizedString("menu-cancel", comment: ""),
style: .default, handler: nil)
alert.addAction(clear)
alert.addAction(cancel)
alert.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItems?[6]
present(alert, animated: true, completion: nil)
}
func showActivityIndicator() {
if !overlayWindow.isHidden && overlayWindow.viewWithTag(activityIndicatorViewTag) != nil {
return
}
dismissGetStartedView(nil)
overlayWindow.isHidden = false
let activityView = UIActivityIndicatorView(style: .whiteLarge)
let containerView = UIView(frame: activityView.bounds.insetBy(dx: -10.0, dy: -10.0))
containerView.backgroundColor = Colors.spinnerBackground
containerView.layer.cornerRadius = 6.0
containerView.center = overlayWindow.center
containerView.tag = activityIndicatorViewTag
containerView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin,
.flexibleBottomMargin]
activityView.center = CGPoint(x: containerView.bounds.size.width * 0.5, y: containerView.bounds.size.height * 0.5)
activityView.startAnimating()
containerView.addSubview(activityView)
overlayWindow.addSubview(containerView)
}
@objc func dismissActivityIndicator() {
overlayWindow.viewWithTag(activityIndicatorViewTag)?.removeFromSuperview()
overlayWindow.isHidden = true
}
@objc func sliderValueChanged(_ sender: UISlider) {
textSize = CGFloat(sender.value + Float(minTextSize)).rounded()
textView.font = textView.font?.withSize(textSize)
let textSizeTitle = presentedViewController?.view.viewWithTag(2) as? UILabel
textSizeTitle?.text = String.init(format: NSLocalizedString("text-size-label", comment: ""), Int(textSize))
}
private func rectForBarButtonItem(_ barButtonItem: UIBarButtonItem) -> CGRect {
let view = barButtonItem.value(forKey: "view") as? UIView
return view?.frame ?? CGRect.zero
}
private func resetTextViewCursor() {
textView.selectedRange = NSRange(location: 0, length: 0)
// TODO: Figure out what this does
if let size = textView.font?.pointSize {
textView.font = textView.font?.withSize(size + 5)
textView.font = textView.font?.withSize(size - 5)
}
}
private func loadSavedUserText() {
let userData = AppDelegate.activeUserDefaults()
let userText = userData.object(forKey: userTextKey) as? String
let userTextSize = userData.object(forKey: userTextSizeKey) as? String
if let text = userText, !text.isEmpty {
textView.text = text
}
if let sizeString = userTextSize, let size = Float(sizeString) {
textSize = CGFloat(size)
textView.font = textView.font?.withSize(textSize)
textSizeController.value = (Float(textSize - minTextSize))
}
}
private func params(of query: String) -> [String: String] {
let components = query.components(separatedBy: "&")
return components.reduce([String: String]()) { prevParams, s in
var params = prevParams
let components = s.components(separatedBy: "=")
if components.count == 2 {
params[components[0]] = components[1]
}
return params
}
}
private func profileName(withFullID fullID: FullKeyboardID) -> String? {
guard let keyboard = AppDelegate.activeUserDefaults().userKeyboard(withFullID: fullID),
let font = keyboard.font else {
return nil
}
return profileName(withFont: font)
}
private func profileName(withFont font: Font) -> String? {
return font.source.first { $0.lowercased().hasSuffix(FileExtensions.configurationProfile) }
}
private func checkProfile(forFullID fullID: FullKeyboardID, doListCheck: Bool) {
if fullID == Defaults.keyboard.fullID {
return
}
if profileName != nil {
return // already installing a profile
}
guard let profile = profileName(withFullID: fullID) else {
return
}
var doInstall: Bool = false
if doListCheck {
for value in profilesToInstall where !checkedProfiles.contains(value) && profile == value {
doInstall = true
break
}
} else {
doInstall = true
}
if doInstall {
profileName = profile
let keyboard = AppDelegate.activeUserDefaults().userKeyboard(withFullID: fullID)!
let languageName = keyboard.languageName
let title = String.init(format: NSLocalizedString("language-for-font", comment: ""), languageName)
let msg = String.init(
format: NSLocalizedString(
"font-install-description",
comment: "Long-form used when installing a font in order to display a language properly."),
languageName)
confirmInstall(withTitle: title, message: msg,
cancelButtonHandler: handleUserDecisionAboutInstallingProfile,
installButtonHandler: handleUserDecisionAboutInstallingProfile)
} else {
profileName = nil
}
}
// showKeyboard matches an internal Apple API, so it's not available for use as a selector.
@objc func displayKeyboard() {
textView.becomeFirstResponder()
}
private func confirmInstall(withTitle title: String, message msg: String,
cancelButtonHandler cbHandler: ((UIAlertAction) -> Swift.Void)? = nil,
installButtonHandler installHandler: ((UIAlertAction) -> Swift.Void)?) {
dismissGetStartedView(nil)
let alertController = UIAlertController(title: title, message: msg,
preferredStyle: UIAlertController.Style.alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("menu-cancel", comment: ""),
style: UIAlertAction.Style.cancel,
handler: cbHandler))
alertController.addAction(UIAlertAction(title: NSLocalizedString("confirm-install", comment: ""),
style: UIAlertAction.Style.default,
handler: installHandler))
self.present(alertController, animated: true, completion: nil)
}
private func handleUserDecisionAboutInstallingProfile(withAction action: UIAlertAction) {
if let profileName = profileName {
checkedProfiles.append(profileName)
let userData = AppDelegate.activeUserDefaults()
userData.set(checkedProfiles, forKey: checkedProfilesKey)
userData.synchronize()
if action.style == .default {
UIApplication.shared.open(URL(string: "\(baseUri)\(profileName)")!)
}
self.profileName = nil
}
}
private func showGetStartedIfNeeded(withAction action: UIAlertAction) {
if shouldShowGetStarted {
showGetStartedView(nil)
}
}
@objc func showDropDownMenu(_ sender: Any) {
if dismissDropDownMenu() {
return
}
wasKeyboardVisible = textView.isFirstResponder
textView.dismissKeyboard()
let w: CGFloat = 160
let h: CGFloat = 44
let x: CGFloat = navBarWidth() - w
let y: CGFloat = AppDelegate.statusBarHeight() + navBarHeight()
let dropDownList = DropDownListView(listItems: dropdownItems, itemSize: CGSize(width: w, height: h),
position: CGPoint(x: x, y: y))
dropDownList.tag = dropDownListTag
navigationController?.view?.addSubview(dropDownList)
}
private func dismissDropDownMenu() -> Bool {
let view = navigationController?.view?.viewWithTag(dropDownListTag)
if view != nil && wasKeyboardVisible {
textView.becomeFirstResponder()
}
view?.removeFromSuperview()
return view != nil
}
@objc func showGetStartedView(_ sender: Any?) {
if !overlayWindow.isHidden && overlayWindow.viewWithTag(getStartedViewTag) != nil {
return
}
popover?.dismiss(animated: false)
_ = dismissDropDownMenu()
overlayWindow.isHidden = false
getStartedVC = GetStartedViewController()
getStartedVC.mainViewController = self
let containerView: UIView! = getStartedVC.view
let navBar = containerView?.viewWithTag(786586) as? UINavigationBar
let doneButton = navBar?.topItem?.rightBarButtonItem
doneButton?.target = self
doneButton?.action = #selector(self.dismissGetStartedView)
Manager.shared.hideKeyboard()
containerView.frame = containerView.frame.insetBy(dx: 15, dy: 140)
containerView.backgroundColor = UIColor.white
containerView.layer.cornerRadius = 6.0
containerView.center = overlayWindow.center
containerView.tag = getStartedViewTag
containerView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin,
.flexibleBottomMargin]
let orientation = UIApplication.shared.statusBarOrientation
containerView.transform = transform(for: orientation)
overlayWindow.addSubview(containerView)
}
@objc func dismissGetStartedView(_ sender: Any?) {
overlayWindow.viewWithTag(getStartedViewTag)?.removeFromSuperview()
overlayWindow.isHidden = true
Manager.shared.showKeyboard()
}
private var shouldShowGetStarted: Bool {
// Do not display "Get started" when MainView is not visible
if navigationController?.visibleViewController != self {
return false
}
let userData = AppDelegate.activeUserDefaults()
if userData.bool(forKey: dontShowGetStartedKey) {
return false
}
// Needs a nil check to ensure Get Started displays for the initial install - userData.bool defaults to false.
if !userData.bool(forKey: shouldShowGetStartedKey) && userData.object(forKey: shouldShowGetStartedKey) != nil {
return false
}
if !AppDelegate.isKeymanEnabledSystemWide() {
return true
}
guard let userKbs = userData.userKeyboards else {
return true
}
if userKbs.isEmpty {
return true
}
if userKbs.count >= 2 {
return false
}
let firstKB = userKbs[0]
return firstKB.id == Defaults.keyboard.id && firstKB.languageID == Defaults.keyboard.languageID
}
@objc func showKMWebBrowserView(_ sender: Any) {
popover?.dismiss(animated: false)
_ = dismissDropDownMenu()
let webBrowserVC = WebBrowserViewController()
if let fontFamily = textView.font?.fontName {
webBrowserVC.fontFamily = fontFamily
}
present(webBrowserVC, animated: true, completion: nil)
}
private func transform(for orientation: UIInterfaceOrientation) -> CGAffineTransform {
return CGAffineTransform.identity
}
}
| apache-2.0 | 34921469453e4104c5f6be1060e4697d | 39.80123 | 119 | 0.683642 | 4.86881 | false | false | false | false |
ThumbWorks/i-meditated | IMeditated/HealthAPI.swift | 1 | 9223 | //
// HealthAPI.swift
// IMeditated
//
// Created by Bob Spryn on 8/19/16.
// Copyright © 2016 Thumbworks. All rights reserved.
//
import Foundation
import RxSwift
import HealthKit
protocol HealthAPIType {
// Any value returned means things went smoothly, otherwise, going to throw a HealthAPIError
func authorize() -> Observable<Void>
// Any value returned means things went smoothly, otherwise, going to throw a HealthAPIError
func saveMeditation(sample:MeditationSample) -> Observable<Void>
// retrieve meditations. a nil value for start or end date swaps in the min/max time in that direction
func getMeditations(startDate: Date?, endDate: Date?, ascending: Bool) -> Observable<[MeditationSample]>
// Any value returned means things went smoothly, otherwise, going to throw a HealthAPIError
func delete(meditationSample: MeditationSample) -> Observable<Void>
}
enum HealthAPIError: Error {
case apiFailure(Error?)
case authorizationFailure(Error?)
case notFound
}
struct HealthAPI {
fileprivate let healthStore = HKHealthStore()
fileprivate let disposables = DisposeBag()
}
extension HealthAPI: HealthAPIType {
fileprivate static let dateFormatter = { () -> DateFormatter in
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return formatter
}()
func authorize() -> Observable<Void> {
let hkTypesToRead = Set([HKObjectType.categoryType(forIdentifier: .mindfulSession)!])
let hkTypesToWrite = Set([HKSampleType.categoryType(forIdentifier: .mindfulSession)!])
if !HKHealthStore.isHealthDataAvailable()
{
return Observable.error(HealthAPIError.authorizationFailure(nil))
}
let authorize: ConnectableObservable<Void> = Observable.create { subscriber in
self.healthStore.requestAuthorization(toShare: hkTypesToWrite, read: hkTypesToRead) { (success, error) in
if error == nil {
let writeStatus = self.healthStore.authorizationStatus(for: HKSampleType.categoryType(forIdentifier: .mindfulSession)!)
if (writeStatus != .sharingAuthorized) {
subscriber.onError(HealthAPIError.authorizationFailure(nil))
} else {
subscriber.onNext()
subscriber.onCompleted()
}
} else {
subscriber.onError(HealthAPIError.authorizationFailure(error))
}
}
return Disposables.create()
}.publish()
authorize.connect().addDisposableTo(self.disposables)
return authorize
}
internal func getMeditations(startDate: Date?, endDate: Date?, ascending: Bool) -> Observable<[MeditationSample]> {
// For fastlane snapshots only
if(UserDefaults.standard.bool(forKey: "FASTLANE_SNAPSHOT") && startDate == Date.distantPast && endDate == Date.distantFuture) {
// runtime check that we are in snapshot mode
return Observable.just(HealthAPI.snapshotData())
}
let startDate = startDate ?? Date.distantPast
let endDate = endDate ?? Date.distantFuture
// 1. Predicate
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
// 2. Order the samples by date
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: ascending)
// 3. Create the query
let queryObservable: ConnectableObservable<[MeditationSample]> = Observable.create { subscriber in
let sampleQuery = HKSampleQuery(sampleType: HKCategoryType.categoryType(forIdentifier: .mindfulSession)!, predicate: predicate, limit: 0, sortDescriptors: [sortDescriptor]) { (sampleQuery, results, error ) -> Void in
guard error == nil else {
subscriber.onError(HealthAPIError.apiFailure(error))
return
}
// I believe results can be nil if no results are found. There's no definitive way to check if we have read access (security concerns)
// so instead we just assume no results if it's nil
subscriber.onNext(results?.map(MeditationSample.init) ?? [])
subscriber.onCompleted()
}
// 4. Execute the query
self.healthStore.execute(sampleQuery)
return Disposables.create()
}.publish()
queryObservable.connect().addDisposableTo(self.disposables)
return queryObservable
}
internal func saveMeditation(sample:MeditationSample) -> Observable<Void> {
let mindfulType = HKCategoryType.categoryType(forIdentifier: .mindfulSession)
let mindfulSample = HKCategorySample(type: mindfulType!, value: 0, start: sample.start, end: sample.end)
let save: ConnectableObservable<Void> = Observable.create { subscriber in
self.healthStore.save(mindfulSample) { success, error in
guard success && error == nil else {
let theError = HealthAPIError.apiFailure(error)
subscriber.onError(theError)
return
}
subscriber.onNext()
subscriber.onCompleted()
}
return Disposables.create()
}.publish()
save.connect().addDisposableTo(self.disposables)
return save
}
internal func delete(meditationSample: MeditationSample) -> Observable<Void> {
// query for the sample so that we aren't worrying about storing a reference to HKSample in the non-HK model
let predicate = HKQuery.predicateForSamples(withStart: meditationSample.start, end: meditationSample.end, options: [])
let query: Observable<HKSample?> = Observable.create { subscriber in
let sampleQuery = HKSampleQuery(sampleType: HKCategoryType.categoryType(forIdentifier: .mindfulSession)!, predicate: predicate, limit: 0, sortDescriptors: nil) { (sampleQuery, results, error ) -> Void in
guard let results = results else {
subscriber.onError(HealthAPIError.notFound)
return
}
subscriber.onNext(results.first)
subscriber.onCompleted()
}
// 4. Execute the query
self.healthStore.execute(sampleQuery)
return Disposables.create()
}
let delete: ConnectableObservable<Void> = query
.flatMap { sample -> Observable<Void> in
guard let sample = sample else {
return Observable.error(HealthAPIError.notFound)
}
return Observable<Void>.create { subscriber in
self.healthStore.delete(sample, withCompletion: { success, error in
guard success else {
subscriber.onError(HealthAPIError.apiFailure(error))
return
}
subscriber.onNext(())
subscriber.onCompleted()
})
return Disposables.create()
}
}.publish()
delete.connect().addDisposableTo(self.disposables)
return delete
}
}
extension HealthAPI {
fileprivate static func snapshotData() -> [MeditationSample] {
let df = HealthAPI.dateFormatter
return [
MeditationSample(start: df.date(from: "2017-2-7 01:10:00")!, end: df.date(from: "2017-2-7 02:10:00")!),
MeditationSample(start: df.date(from: "2017-2-6 07:13:00")!, end: df.date(from: "2017-2-6 07:23:00")!),
MeditationSample(start: df.date(from: "2017-2-6 13:13:00")!, end: df.date(from: "2017-2-6 13:23:00")!),
MeditationSample(start: df.date(from: "2017-2-5 08:34:00")!, end: df.date(from: "2017-2-5 08:54:00")!),
MeditationSample(start: df.date(from: "2017-2-3 10:00:00")!, end: df.date(from: "2017-2-3 10:45:00")!),
MeditationSample(start: df.date(from: "2017-2-3 14:23:00")!, end: df.date(from: "2017-2-3 14:43:00")!),
MeditationSample(start: df.date(from: "2017-2-3 21:06:00")!, end: df.date(from: "2017-2-3 21:21:00")!),
MeditationSample(start: df.date(from: "2017-2-2 20:03:00")!, end: df.date(from: "2017-2-2 21:03:00")!),
MeditationSample(start: df.date(from: "2017-2-1 18:00:00")!, end: df.date(from: "2017-2-3 18:21:00")!),
MeditationSample(start: df.date(from: "2017-1-28 22:15:00")!, end: df.date(from: "2017-1-28 22:45:00")!),
MeditationSample(start: df.date(from: "2017-1-28 12:15:00")!, end: df.date(from: "2017-1-28 12:45:00")!),
MeditationSample(start: df.date(from: "2017-1-27 00:02:00")!, end: df.date(from: "2017-1-27 00:32:00")!),
MeditationSample(start: df.date(from: "2017-1-26 22:15:00")!, end: df.date(from: "2017-1-28 22:45:00")!),
]
}
}
| mit | 65d414d9b9c254786751acbcd6ed1092 | 47.282723 | 228 | 0.611364 | 4.54062 | false | false | false | false |
waltflanagan/AdventOfCode | 2015/AOC11.playground/Contents.swift | 1 | 4437 | //: Playground - noun: a place where people can play
import UIKit
func incrementString(string:String) -> String{
if let lastCharacter = string.characters.last {
let firstPart = string.substringToIndex(string.endIndex.advancedBy(-1))
if lastCharacter == "z".characters.last! {
return incrementString(firstPart) + "a"
} else {
let characterValue = String(lastCharacter).unicodeScalars.first!.value
let newCharacter = String(Character(UnicodeScalar(characterValue + 1)))
return firstPart + newCharacter
}
}
return "foo"
}
func hasDouble(string:String) -> Bool {
let characters = string.characters
var hasDoubleDouble = false
var firstRange: NSRange? = nil
for (index,letter) in characters.enumerate() {
guard index+1 < characters.count else { break }
let nextCharacter = characters[characters.startIndex.advancedBy(index+1)]
if hasDoubleDouble == false && nextCharacter == letter {
let doubleRange = NSMakeRange(index, 2)
if let firstRange = firstRange where NSIntersectionRange(firstRange, doubleRange).length == 0 {
hasDoubleDouble = true
} else {
firstRange = doubleRange
}
}
}
return hasDoubleDouble
}
func hasRun(string:String) -> Bool {
let characters = string.characters
for (index,letter) in characters.enumerate() {
guard index+2 < characters.count else { return false }
let next = characters[characters.startIndex.advancedBy(index+1)]
let nextNext = characters[characters.startIndex.advancedBy(index+2)]
let nextValue = next.value
let letterValue = letter.value
let difference = Int(nextValue) - Int(letterValue)
if ( difference == 1 ) && ( nextNext.value - next.value == 1 ) {
return true
}
}
return false
}
func validPassword(password:String) -> Bool {
let characters = password.characters
var hasDoubleDouble = false
var firstRange: NSRange?
var hasRun = false
for (index,letter) in characters.enumerate() {
guard letter != "i" else { return false }
guard letter != "o" else { return false }
guard letter != "l" else { return false }
guard index+1 < characters.count else { break }
let nextCharacter = characters[characters.startIndex.advancedBy(index+1)]
if hasDoubleDouble == false && nextCharacter == letter {
let doubleRange = NSMakeRange(index, 2)
if let firstRange = firstRange where NSIntersectionRange(firstRange, doubleRange).length == 0 {
hasDoubleDouble = true
} else {
firstRange = doubleRange
}
}
hasRun = {
guard index+2 < characters.count else { return false }
let next = characters[characters.startIndex.advancedBy(index+1)]
let nextNext = characters[characters.startIndex.advancedBy(index+2)]
let nextValue = next.value
let letterValue = letter.value
let difference = Int(nextValue) - Int(letterValue)
if ( difference == 1 ) && ( nextNext.value - next.value == 1 ) {
return true
}
return false
}()
}
return hasDoubleDouble && hasRun
}
extension Character {
var value: Int {
return Int(String(self).unicodeScalars.first!.value)
}
}
"hxbaabcc"
var otherPassword = "hxbxyaaa"
var newPassword = "hxbxxyzz"
hasDouble(newPassword)
hasRun(newPassword)
func valid2(password:String) -> Bool {
for (index,letter) in password.characters.enumerate() {
guard letter != "i" else { return false }
guard letter != "o" else { return false }
guard letter != "l" else { return false }
}
return hasDouble(password) && hasRun(password)
}
var foo = valid2(newPassword)
foo
var shouldBreak = false
//
while !shouldBreak {
// newPassword
newPassword = incrementString(newPassword)
shouldBreak = valid2(newPassword)
}
newPassword
//
//
//
| mit | 5d8d468953ed4a2f241ad8bdbf45b3dc | 23.926966 | 107 | 0.583728 | 4.78125 | false | false | false | false |
xmartlabs/XLSwiftKit | Sources/Overload2D.swift | 1 | 10502 | import CoreGraphics
/// Arithmetic extensions for CGPoint, CGSize, and CGVector.
/// All of the operators +, -, *, /, and unary minus are supported. Where
/// applicable, operators can be applied to point/size/vector + point/size/vector,
/// as well as point/size/vector + CGFloat and CGFloat + point/size/vector.
protocol Overload2D {
/// Really for internal use, but publicly available so the unit tests can use them.
var aa: CGFloat { get set }
var bb: CGFloat { get set }
/// So we can create any one of our types without needing argument names
/// - Parameters:
/// - xx: depending on the object being created, this is the x-coordinate,
/// or the width, or the dx component
/// - yy: depending on the object being created, this is the y-coordinate,
/// or the height, or the dy component
init(_ xx: CGFloat, _ yy: CGFloat)
/// Convenience function for easy conversion to CGPoint from the others,
/// to make arithmetic operations between the types easier to write and read.
func asPoint() -> CGPoint
/// Convenience function for easy conversion to CGSize from the others,
/// to make arithmetic operations between the types easier to write and read.
func asSize() -> CGSize
/// Convenience function for easy conversion to CGVector from the others,
/// to make arithmetic operations between the types easier to write and read.
func asVector() -> CGVector
/// So we can create any one of our types without needing argument names
///
/// Same functionality as init(_:,_:)
///
/// - Parameters:
/// - x: depending on the object being created, this is the x-coordinate,
/// or the width, or the dx component
/// - y: depending on the object being created, this is the y-coordinate,
/// or the height, or the dy component
static func makeTuple(_ xx: CGFloat, _ yy: CGFloat) -> Self
/// Unary minus: negates both scalars in the tuple
static prefix func - (_ myself: Self) -> Self
/// Basic arithmetic with tuples on both sides of the operator.
/// These return a new tuple with lhsTuple.0 (op) rhsTuple.0, lhsTuple.1 (op) rhsTuple.1.
///
/// Examples:
///
/// CGPoint(x: 10, y: 3) + CGPoint(17, 37) = CGPoint(x: 10 + 17, y: 3 + 37)
///
/// CGSize(width: 5, height: 7) * CGSize(width: 12, height: 13) = CGSize(width: 5 * 12, height: 7 * 13)
static func + (_ lhs: Self, _ rhs: Self) -> Self
static func - (_ lhs: Self, _ rhs: Self) -> Self
static func * (_ lhs: Self, _ rhs: Self) -> Self
static func / (_ lhs: Self, _ rhs: Self) -> Self
/// Basic arithmetic with tuple (op) CGFloat, or CGFloat (op) tuple
/// These return a new tuple with lhsTuple.0 (op) rhs, lhsTuple.1 (op) rhs.
///
/// Examples:
///
/// CGPoint(x: 10, y: 3) / 42 = CGPoint(x: 10 / 42, y: 3 / 42)
///
/// CGSize(width: 5, height: 7) - 137 = CGSize(width: 5 - 137, height: 7 - 137)
static func + (_ lhs: Self, _ rhs: CGFloat) -> Self
static func - (_ lhs: Self, _ rhs: CGFloat) -> Self
static func * (_ lhs: Self, _ rhs: CGFloat) -> Self
static func / (_ lhs: Self, _ rhs: CGFloat) -> Self
static func + (_ lhs: CGFloat, _ rhs: Self) -> Self
static func - (_ lhs: CGFloat, _ rhs: Self) -> Self
static func * (_ lhs: CGFloat, _ rhs: Self) -> Self
static func / (_ lhs: CGFloat, _ rhs: Self) -> Self
/// Compound assignment operators. These all work the same as the basic operators,
/// applying compound assignment the same as the usual arithmetic versions.
static func += (_ lhs: inout Self, _ rhs: Self)
static func -= (_ lhs: inout Self, _ rhs: Self)
static func *= (_ lhs: inout Self, _ rhs: Self)
static func /= (_ lhs: inout Self, _ rhs: Self)
static func += (_ lhs: inout Self, _ rhs: CGFloat)
static func -= (_ lhs: inout Self, _ rhs: CGFloat)
static func *= (_ lhs: inout Self, _ rhs: CGFloat)
static func /= (_ lhs: inout Self, _ rhs: CGFloat)
}
// MARK: Implementations
extension Overload2D {
static prefix func - (_ myself: Self) -> Self {
return myself * -1.0
}
static func + (_ lhs: Self, _ rhs: Self) -> Self {
return makeTuple(lhs.aa + rhs.aa, lhs.bb + rhs.bb)
}
static func - (_ lhs: Self, _ rhs: Self) -> Self {
return makeTuple(lhs.aa - rhs.aa, lhs.bb - rhs.bb)
}
static func * (_ lhs: Self, _ rhs: Self) -> Self {
return makeTuple(lhs.aa * rhs.aa, lhs.bb * rhs.bb)
}
static func / (_ lhs: Self, _ rhs: Self) -> Self {
return makeTuple(lhs.aa / rhs.aa, lhs.bb / rhs.bb)
}
static func + (_ lhs: Self, _ rhs: CGFloat) -> Self {
return makeTuple(lhs.aa + rhs, lhs.bb + rhs)
}
static func - (_ lhs: Self, _ rhs: CGFloat) -> Self {
return makeTuple(lhs.aa - rhs, lhs.bb - rhs)
}
static func * (_ lhs: Self, _ rhs: CGFloat) -> Self {
return makeTuple(lhs.aa * rhs, lhs.bb * rhs)
}
static func / (_ lhs: Self, _ rhs: CGFloat) -> Self {
return makeTuple(lhs.aa / rhs, lhs.bb / rhs)
}
static func + (_ lhs: CGFloat, _ rhs: Self) -> Self {
return makeTuple(lhs + rhs.aa, lhs + rhs.bb)
}
static func - (_ lhs: CGFloat, _ rhs: Self) -> Self {
return makeTuple(lhs - rhs.aa, lhs - rhs.bb)
}
static func * (_ lhs: CGFloat, _ rhs: Self) -> Self {
return makeTuple(lhs * rhs.aa, lhs * rhs.bb)
}
static func / (_ lhs: CGFloat, _ rhs: Self) -> Self {
return makeTuple(lhs / rhs.aa, lhs / rhs.bb)
}
static func += (_ lhs: inout Self, _ rhs: Self) {
lhs.aa += rhs.aa; lhs.bb += rhs.bb
}
static func -= (_ lhs: inout Self, _ rhs: Self) {
lhs.aa -= rhs.aa; lhs.bb -= rhs.bb
}
static func *= (_ lhs: inout Self, _ rhs: Self) {
lhs.aa *= rhs.aa; lhs.bb *= rhs.bb
}
static func /= (_ lhs: inout Self, _ rhs: Self) {
lhs.aa /= rhs.aa; lhs.bb /= rhs.bb
}
static func += (_ lhs: inout Self, _ rhs: CGFloat) {
lhs.aa += rhs; lhs.bb += rhs
}
static func -= (_ lhs: inout Self, _ rhs: CGFloat) {
lhs.aa -= rhs; lhs.bb -= rhs
}
static func *= (_ lhs: inout Self, _ rhs: CGFloat) {
lhs.aa *= rhs; lhs.bb *= rhs
}
static func /= (_ lhs: inout Self, _ rhs: CGFloat) {
lhs.aa /= rhs; lhs.bb /= rhs
}
}
extension Overload2D where Self == CGVector {
func magnitude() -> CGFloat {
return sqrt(self.dx * self.dx + self.dy * self.dy)
}
}
extension Overload2D where Self == CGPoint {
func distance(to otherPoint: CGPoint) -> CGFloat {
return (otherPoint - self).asVector().magnitude()
}
static func random(in range: Range<CGFloat>) -> CGPoint {
return CGPoint(x: CGFloat.random(in: range), y: CGFloat.random(in: range))
}
static func random(xRange: Range<CGFloat>, yRange: Range<CGFloat>) -> CGPoint {
return CGPoint(x: CGFloat.random(in: xRange), y: CGFloat.random(in: yRange))
}
}
extension Overload2D where Self == CGSize {
static func random(in range: Range<CGFloat>) -> CGSize {
return CGSize(width: CGFloat.random(in: range), height: CGFloat.random(in: range))
}
static func random(widthRange: Range<CGFloat>, heightRange: Range<CGFloat>) -> CGSize {
return CGSize(width: CGFloat.random(in: widthRange), height: CGFloat.random(in: heightRange))
}
}
extension Overload2D where Self == CGVector {
static func random(in range: Range<CGFloat>) -> CGVector {
return CGVector(dx: CGFloat.random(in: range), dy: CGFloat.random(in: range))
}
static func random(dxRange: Range<CGFloat>, dyRange: Range<CGFloat>) -> CGVector {
return CGVector(dx: CGFloat.random(in: dxRange), dy: CGFloat.random(in: dyRange))
}
}
extension CGPoint: Overload2D {
var aa: CGFloat { get { return self.x } set { self.x = newValue } }
var bb: CGFloat { get { return self.y } set { self.y = newValue } }
init(_ xx: CGFloat, _ yy: CGFloat) {
self.init(x: xx, y: yy)
}
static func makeTuple(_ xx: CGFloat, _ yy: CGFloat) -> CGPoint {
return CGPoint(x: xx, y: yy)
}
static func makeTuple(_ xx: CGFloat, _ yy: CGFloat) -> CGSize {
return CGSize.makeTuple(xx, yy)
}
static func makeTuple(_ xx: CGFloat, _ yy: CGFloat) -> CGVector {
return CGVector.makeTuple(xx, yy)
}
func asPoint() -> CGPoint {
return CGPoint(x: x, y: y)
}
func asSize() -> CGSize {
return CGSize(width: x, height: y)
}
func asVector() -> CGVector {
return CGVector(dx: x, dy: y)
}
}
extension CGSize: Overload2D {
var aa: CGFloat { get { return self.width } set { self.width = newValue } }
var bb: CGFloat { get { return self.height } set { self.height = newValue } }
init(_ width: CGFloat, _ height: CGFloat) {
self.init(width: width, height: height)
}
static func makeTuple(_ width: CGFloat, _ height: CGFloat) -> CGPoint {
return CGPoint.makeTuple(width, height)
}
static func makeTuple(_ width: CGFloat, _ height: CGFloat) -> CGSize {
return CGSize(width: width, height: height)
}
static func makeTuple(_ width: CGFloat, _ height: CGFloat) -> CGVector {
return CGVector.makeTuple(width, height)
}
func asPoint() -> CGPoint {
return CGPoint(x: width, y: height)
}
func asSize() -> CGSize {
return CGSize(width: width, height: height)
}
func asVector() -> CGVector {
return CGVector(dx: width, dy: height)
}
}
extension CGVector: Overload2D {
var aa: CGFloat { get { return self.dx } set { self.dx = newValue } }
var bb: CGFloat { get { return self.dy } set { self.dy = newValue } }
init(_ dx: CGFloat, _ dy: CGFloat) {
self.init(dx: dx, dy: dy)
}
static func makeTuple(_ dx: CGFloat, _ dy: CGFloat) -> CGPoint {
return CGPoint.makeTuple(dx, dy)
}
static func makeTuple(_ dx: CGFloat, _ dy: CGFloat) -> CGSize {
return CGSize.makeTuple(dx, dy)
}
static func makeTuple(_ dx: CGFloat, _ dy: CGFloat) -> CGVector {
return CGVector(dx: dx, dy: dy)
}
func asPoint() -> CGPoint {
return CGPoint(x: dx, y: dy)
}
func asSize() -> CGSize {
return CGSize(width: dx, height: dy)
}
func asVector() -> CGVector {
return CGVector(dx: dx, dy: dy)
}
}
| mit | 8874e6126776cf4431f7765a3dfc0b83 | 34.241611 | 107 | 0.590649 | 3.643997 | false | false | false | false |
tkremenek/swift | benchmark/single-source/ArraySubscript.swift | 24 | 1409 | //===--- ArraySubscript.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks the performance of modifying an array element.
import TestsUtils
public let ArraySubscript = BenchmarkInfo(
name: "ArraySubscript",
runFunction: run_ArraySubscript,
tags: [.validation, .api, .Array],
legacyFactor: 4)
@inline(never)
public func run_ArraySubscript(_ N: Int) {
SRand()
let numArrays = 50
let numArrayElements = 100
func bound(_ x: Int) -> Int { return min(x, numArrayElements-1) }
for _ in 1...N {
var arrays = [[Int]](repeating: [], count: numArrays)
for i in 0..<numArrays {
for _ in 0..<numArrayElements {
arrays[i].append(Int(truncatingIfNeeded: Random()))
}
}
// Do a max up the diagonal.
for i in 1..<numArrays {
arrays[i][bound(i)] =
max(arrays[i-1][bound(i-1)], arrays[i][bound(i)])
}
CheckResults(arrays[0][0] <= arrays[numArrays-1][bound(numArrays-1)])
}
}
| apache-2.0 | e66122f6e13f9153f828bb5f5154b0e5 | 29.630435 | 80 | 0.601136 | 3.980226 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSNotification.swift | 1 | 7246 | // 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
//
open class NSNotification: NSObject, NSCopying, NSCoding {
public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
public private(set) var rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(lhs: Name, rhs: Name) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func <(lhs: Name, rhs: Name) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
private(set) open var name: Name
private(set) open var object: Any?
private(set) open var userInfo: [AnyHashable : Any]?
public convenience override init() {
/* do not invoke; not a valid initializer for this class */
fatalError()
}
public init(name: Name, object: Any?, userInfo: [AnyHashable : Any]? = nil) {
self.name = name
self.object = object
self.userInfo = userInfo
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
guard let name = aDecoder.decodeObject(of: NSString.self, forKey:"NS.name") else {
return nil
}
let object = aDecoder.decodeObject(forKey: "NS.object")
// let userInfo = aDecoder.decodeObject(of: NSDictionary.self, forKey: "NS.userinfo")
self.init(name: Name(rawValue: String._unconditionallyBridgeFromObjectiveC(name)), object: object as! NSObject, userInfo: nil)
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
aCoder.encode(self.name.rawValue._bridgeToObjectiveC(), forKey:"NS.name")
aCoder.encode(self.object, forKey:"NS.object")
aCoder.encode(self.userInfo?._bridgeToObjectiveC(), forKey:"NS.userinfo")
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override var description: String {
var str = "\(type(of: self)) \(Unmanaged.passUnretained(self).toOpaque()) {"
str += "name = \(self.name.rawValue)"
if let object = self.object {
str += "; object = \(object)"
}
if let userInfo = self.userInfo {
str += "; userInfo = \(userInfo)"
}
str += "}"
return str
}
}
private class NSNotificationReceiver : NSObject {
fileprivate weak var object: NSObject?
fileprivate var name: Notification.Name?
fileprivate var block: ((Notification) -> Void)?
fileprivate var sender: AnyObject?
}
extension Sequence where Iterator.Element : NSNotificationReceiver {
/// Returns collection of `NSNotificationReceiver`.
///
/// Will return:
/// - elements that property `object` is not equal to `observerToFilter`
/// - elements that property `name` is not equal to parameter `name` if specified.
/// - elements that property `sender` is not equal to parameter `object` if specified.
///
fileprivate func filterOutObserver(_ observerToFilter: AnyObject, name:Notification.Name? = nil, object: Any? = nil) -> [Iterator.Element] {
return self.filter { observer in
let differentObserver = observer.object !== observerToFilter
let nameSpecified = name != nil
let differentName = observer.name != name
let objectSpecified = object != nil
let differentSender = observer.sender !== _SwiftValue.store(object)
return differentObserver || (nameSpecified && differentName) || (objectSpecified && differentSender)
}
}
/// Returns collection of `NSNotificationReceiver`.
///
/// Will return:
/// - elements that property `sender` is `nil` or equals specified parameter `sender`.
/// - elements that property `name` is `nil` or equals specified parameter `name`.
///
fileprivate func observersMatchingName(_ name:Notification.Name? = nil, sender: Any? = nil) -> [Iterator.Element] {
return self.filter { observer in
let emptyName = observer.name == nil
let sameName = observer.name == name
let emptySender = observer.sender == nil
let sameSender = observer.sender === _SwiftValue.store(sender)
return (emptySender || sameSender) && (emptyName || sameName)
}
}
}
private let _defaultCenter: NotificationCenter = NotificationCenter()
open class NotificationCenter: NSObject {
private var _observers: [NSNotificationReceiver]
private let _observersLock = NSLock()
public required override init() {
_observers = [NSNotificationReceiver]()
}
open class var `default`: NotificationCenter {
return _defaultCenter
}
open func post(_ notification: Notification) {
let sendTo = _observersLock.synchronized({
return _observers.observersMatchingName(notification.name, sender: notification.object)
})
for observer in sendTo {
guard let block = observer.block else {
continue
}
block(notification)
}
}
open func post(name aName: Notification.Name, object anObject: AnyObject?, userInfo aUserInfo: [AnyHashable : Any]? = nil) {
let notification = Notification(name: aName, object: anObject, userInfo: aUserInfo)
post(notification)
}
open func removeObserver(_ observer: AnyObject) {
removeObserver(observer, name: nil, object: nil)
}
open func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object: Any?) {
guard let observer = observer as? NSObject else {
return
}
_observersLock.synchronized({
self._observers = _observers.filterOutObserver(observer, name: aName, object: object)
})
}
open func addObserver(forName name: Notification.Name?, object obj: Any?, queue: OperationQueue?, usingBlock block: @escaping (Notification) -> Void) -> NSObjectProtocol {
if queue != nil {
NSUnimplemented()
}
let object = NSObject()
let newObserver = NSNotificationReceiver()
newObserver.object = object
newObserver.name = name
newObserver.block = block
newObserver.sender = _SwiftValue.store(obj)
_observersLock.synchronized({
_observers.append(newObserver)
})
return object
}
}
| apache-2.0 | c1dc0c06fe7ec170f9c81bebabee5be1 | 33.669856 | 175 | 0.619376 | 4.895946 | false | false | false | false |
dcunited001/SpectraNu | Spectra/MetalXML/MetalParser.swift | 1 | 13231 | //
// MetalXSD
//
//
// Created by David Conner on 10/12/15.
//
//
import Foundation
import Fuzi
import Swinject
public enum MetalNodeType: String {
// TODO: add MTLLibrary node? how to specify method to retrieve libraries?
// TODO: add MTLDevice node? how to specify?
case VertexFunction = "vertex-function"
case FragmentFunction = "fragment-function"
case ComputeFunction = "compute-function"
case ClearColor = "clear-color"
case VertexDescriptor = "vertex-descriptor"
case VertexAttributeDescriptor = "vertex-attribute-descriptor"
case VertexBufferLayoutDescriptor = "vertex-buffer-layout-descriptor"
case TextureDescriptor = "texture-descriptor"
case SamplerDescriptor = "sampler-descriptor"
case StencilDescriptor = "stencil-descriptor"
case DepthStencilDescriptor = "depth-stencil-descriptor"
case RenderPipelineColorAttachmentDescriptor = "render-pipeline-color-attachment-descriptor"
case RenderPipelineDescriptor = "render-pipeline-descriptor"
case ComputePipelineDescriptor = "compute-pipeline-descriptor"
case RenderPassColorAttachmentDescriptor = "render-pass-color-attachment-descriptor"
case RenderPassDepthAttachmentDescriptor = "render-pass-depth-attachment-descriptor"
case RenderPassStencilAttachmentDescriptor = "render-pass-stencil-attachment-descriptor"
case RenderPassDescriptor = "render-pass-descriptor"
}
public class MetalParser {
// NOTE: if device/library
public var nodes: Container!
// TODO: copy on resolve setting (false == never copy, true == always copy)
public init(nodes: Container = Container()) {
self.nodes = nodes
}
public init(parentContainer: Container) {
self.nodes = Container(parent: parentContainer)
}
public func getMetalEnum(name: String, id: String) -> UInt {
return nodes.resolve(MetalEnum.self, name: name)!.getValue(id)
}
public func getVertexFunction(id: String) -> FunctionNode {
let n = nodes.resolve(FunctionNode.self, name: id)!
return n.copy()
}
public func getFragmentFunction(id: String) -> FunctionNode {
let n = nodes.resolve(FunctionNode.self, name: id)!
return n.copy()
}
public func getComputeFunction(id: String) -> FunctionNode {
let n = nodes.resolve(FunctionNode.self, name: id)!
return n.copy()
}
public func getVertexDescriptor(id: String) -> MetalVertexDescriptorNode {
let n = nodes.resolve(MetalVertexDescriptorNode.self, name: id)!
return n.copy()
}
public func getTextureDescriptor(id: String) -> TextureDescriptorNode {
let n = nodes.resolve(TextureDescriptorNode.self, name: id)!
return n.copy()
}
public func getSamplerDescriptor(id: String) -> SamplerDescriptorNode {
let n = nodes.resolve(SamplerDescriptorNode.self, name: id)!
return n.copy()
}
public func getStencilDescriptor(id: String) -> StencilDescriptorNode {
let n = nodes.resolve(StencilDescriptorNode.self, name: id)!
return n.copy()
}
public func getDepthStencilDescriptor(id: String) -> DepthStencilDescriptorNode {
let n = nodes.resolve(DepthStencilDescriptorNode.self, name: id)!
return n.copy()
}
public func getRenderPipelineColorAttachmentDescriptor(id: String) -> RenderPipelineColorAttachmentDescriptorNode {
let n = nodes.resolve(RenderPipelineColorAttachmentDescriptorNode.self, name: id)!
return n.copy()
}
public func getRenderPipelineDescriptor(id: String) -> RenderPipelineDescriptorNode {
let n = nodes.resolve(RenderPipelineDescriptorNode.self, name: id)!
return n.copy()
}
public func getClearColor(id: String) -> ClearColorNode {
let n = nodes.resolve(ClearColorNode.self, name: id)!
return n.copy()
}
public func getRenderPassColorAttachmentDescriptor(id: String) -> RenderPassColorAttachmentDescriptorNode {
let n = nodes.resolve(RenderPassColorAttachmentDescriptorNode.self, name: id)!
return n.copy()
}
public func getRenderPassDepthAttachmentDescriptor(id: String) -> RenderPassDepthAttachmentDescriptorNode {
let n = nodes.resolve(RenderPassDepthAttachmentDescriptorNode.self, name: id)!
return n.copy()
}
public func getRenderPassStencilAttachmentDescriptor(id: String) -> RenderPassStencilAttachmentDescriptorNode {
let n = nodes.resolve(RenderPassStencilAttachmentDescriptorNode.self, name: id)!
return n.copy()
}
public func getRenderPassDescriptor(id: String) -> RenderPassDescriptorNode {
let n = nodes.resolve(RenderPassDescriptorNode.self, name: id)!
return n.copy()
}
public func getComputePipelineDescriptor(id: String) -> ComputePipelineDescriptorNode {
let n = nodes.resolve(ComputePipelineDescriptorNode.self, name: id)!
return n.copy()
}
// TODO: figure out how to break this out into parseNode() -> MetalNode
// - however, the problem is that
public func parseXML(xml: XMLDocument) {
for elem in xml.root!.children {
parseNode(elem)
}
}
public func parseNode(elem: XMLElement) {
let (tag, id, ref) = (elem.tag!, elem.attributes["id"], elem.attributes["ref"])
if let nodeType = MetalNodeType(rawValue: tag) {
switch nodeType {
case .VertexFunction:
let node = FunctionNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .FragmentFunction:
let node = FunctionNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .ComputeFunction:
let node = FunctionNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
// TODO: case: .OptionSet? : break
case .VertexDescriptor:
let node = MetalVertexDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .VertexAttributeDescriptor:
let node = VertexAttributeDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .VertexBufferLayoutDescriptor:
let node = VertexBufferLayoutDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .TextureDescriptor:
let node = TextureDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .SamplerDescriptor:
let node = SamplerDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .StencilDescriptor:
let node = StencilDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .DepthStencilDescriptor:
let node = DepthStencilDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPipelineColorAttachmentDescriptor:
let node = RenderPipelineColorAttachmentDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPipelineDescriptor:
let node = RenderPipelineDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .ComputePipelineDescriptor:
let node = ComputePipelineDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .ClearColor:
let node = ClearColorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPassColorAttachmentDescriptor:
let node = RenderPassColorAttachmentDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPassDepthAttachmentDescriptor:
let node = RenderPassDepthAttachmentDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPassStencilAttachmentDescriptor:
let node = RenderPassStencilAttachmentDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
case .RenderPassDescriptor:
let node = RenderPassDescriptorNode(nodes: nodes, elem: elem)
if (node.id != nil) { node.register(nodes, objectScope: .None) }
default: break
}
}
}
public static func initMetalEnums(container: Container) -> Container {
let xmlData = MetalXSD.readXSD("MetalEnums")
let xsd = MetalXSD(data: xmlData)
xsd.parseEnumTypes(container)
return container
}
// TODO: remove this, since both are only used on generate()
public static func initMetal(container: Container) -> Container {
// TODO: decide whether or not to let the device persist for the lifetime of the top-level container
// - many classes require the device (and for some, i think object id matters, like for MTLLibrary)
let dev = MTLCreateSystemDefaultDevice()!
let lib = dev.newDefaultLibrary()!
container.register(MTLDevice.self, name: "default") { _ in
return dev
}.inObjectScope(.None)
container.register(MTLLibrary.self, name: "default") { _ in
return lib
}.inObjectScope(.None)
return container
}
public static func readXML(bundle: NSBundle, filename: String, bundleResourceName: String?) -> XMLDocument? {
var resourceBundle: NSBundle = bundle
if let resourceName = bundleResourceName {
let bundleURL = bundle.URLForResource(resourceName, withExtension: "bundle")
resourceBundle = NSBundle(URL: bundleURL!)!
}
let path = resourceBundle.pathForResource(filename, ofType: "xml")
let data = NSData(contentsOfFile: path!)
do {
return try XMLDocument(data: data!)
} catch let err as XMLError {
switch err {
case .ParserFailure, .InvalidData: print(err)
case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)")
default: break
}
} catch let err {
print("error: \(err)")
}
return nil
}
}
public class MetalEnum {
var name: String
var values: [String: UInt] = [:] // private?
public init(elem: XMLElement) {
values = [:]
name = elem.attributes["name"]!
let valuesSelector = "xs:restriction > xs:enumeration"
for child in elem.css(valuesSelector) {
let val = child.attributes["id"]!
let key = child.attributes["value"]!
self.values[key] = UInt(val)
}
}
public func getValue(id: String) -> UInt {
return values[id]!
}
// public func convertToEnum(key: String, val: Int) -> AnyObject {
// switch key {
// case "mtlStorageAction": return MTLStorageMode(rawValue: UInt(val))!
// default: val
// }
// }
}
public class MetalXSD {
public var xsd: XMLDocument?
var enumTypes: [String: MetalEnum] = [:]
public init(data: NSData) {
do {
xsd = try XMLDocument(data: data)
} catch let err as XMLError {
switch err {
case .ParserFailure, .InvalidData: print(err)
case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)")
default: break
}
} catch let err {
print("error: \(err)")
}
}
public class func readXSD(filename: String) -> NSData {
let bundle = NSBundle(forClass: MetalXSD.self)
let path = bundle.pathForResource(filename, ofType: "xsd")
let data = NSData(contentsOfFile: path!)
return data!
}
public func parseEnumTypes(container: Container) {
let enumTypesSelector = "xs:simpleType[mtl-enum=true]"
for enumChild in xsd!.css(enumTypesSelector) {
let enumType = MetalEnum(elem: enumChild)
container.register(MetalEnum.self, name: enumType.name) { _ in
return enumType
}
}
}
}
| mit | 2eb784c5f32ce92f77804f776a304e1e | 40.476489 | 119 | 0.624669 | 4.571873 | false | false | false | false |
inder/ios-ranking-visualization | RankViz/RankViz/EquityMetricsColumnHeadersViewController.swift | 1 | 5866 | //
// EquityMetricsColumnHeadersViewController.swift
// Reverse Graph
//
// Created by Inder Sabharwal on 1/22/15.
// Copyright (c) 2015 truquity. All rights reserved.
//
import Foundation
import UIKit
class EquityMetricsColumnHeadersViewController : SimpleBidirectionalTableViewController, SimpleBidirectionalTableViewDelegate {
var portfolio: Portfolio = CustomPortfolios.sharedInstance.portfolios[0]
var columnHeaderDimensions: CGSize!
weak var controller: LineChartVizViewController?
init(portfolio: Portfolio, headerDimensions: CGSize) {
self.portfolio = portfolio
self.columnHeaderDimensions = headerDimensions
super.init(direction: .Horizontal)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
self.view.clipsToBounds = true
self.tableView.tableViewDelegate = self
}
func numberOfCells(source: SimpleBidirectionalTableView) -> Int {
return self.portfolio.interestedMetrics.count + 1
}
func heightOfCells(source: SimpleBidirectionalTableView) -> CGFloat {
return self.columnHeaderDimensions.height
}
func widthOfCells(source: SimpleBidirectionalTableView) -> CGFloat {
return self.columnHeaderDimensions.width
}
func viewForCell(atIndex idx: Int, source: SimpleBidirectionalTableView) -> UIView? {
if (idx > portfolio.interestedMetrics.count) {
return nil
}
var view = MetricCellView(frame: CGRectMake(0, 0, columnHeaderDimensions.width, columnHeaderDimensions.height))
if (idx == 0) {
var rankMeta = MetricMetaInformation(name: "Rank", importance: 0, isHigherBetter: nil)
view.metric = rankMeta
}
else {
var metric = portfolio.interestedMetricTypes[idx - 1]
view.metric = metric
}
return view
}
func didShowCellsInRange(fromStartIdx startIdx: Int, toEndIndex endIdx: Int, withStartOffset startOffset: CGFloat, source: SimpleBidirectionalTableView)
{
controller?.didXShowCellsInRange(fromStartIdx: startIdx, toEndIndex: endIdx, withStartOffset: startOffset, source: source)
}
}
class MetricCellView : UIView {
//the std height and width based on which scaling factors are calculated.
let StdHeight: CGFloat = 120
let StdWidth = CGFloat(40)
let bandColor = UIColor(red: 43.0/255, green: 63.0/255, blue: 86.0/255, alpha: 1.0)
let smallBandColor = UIColor(red: 102.0/255, green: 204.0/244, blue: 255.0/255, alpha: 1.0)
// MARK: - scaled offsets and sizes
var xOffset : CGFloat {
return (6 * self.bounds.width)/StdHeight
}
var yOffset : CGFloat {
return (4 * self.bounds.height)/StdWidth
}
var tickerFontSize : CGFloat {
return (14 * self.bounds.height)/StdWidth
}
var nameFontSize : CGFloat {
return (8 * self.bounds.height)/StdWidth
}
var priceFontSize : CGFloat {
return (12 * self.bounds.height)/StdWidth
}
override var backgroundColor : UIColor? {
didSet {
setNeedsDisplay()
}
}
var metric: MetricMetaInformation? {
didSet {
self.setNeedsDisplay()
}
}
// MARK: - setup and init
override init(frame: CGRect) {
super.init(frame: frame)
}
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK : - drawing.
override func drawRect(rect: CGRect) {
super.drawRect(rect)
var path = UIBezierPath(rect: self.bounds)
UIColor.whiteColor().setFill()
path.addClip()
path.fill()
var tickerName: NSMutableAttributedString
var price: NSAttributedString
var longName: NSAttributedString
if let metric = self.metric {
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.Center
var tickerFont = UIFont(name: "HelveticaNeue-CondensedBold", size: tickerFontSize)
var attributes : [NSString: AnyObject] = [NSFontAttributeName : tickerFont!, NSParagraphStyleAttributeName : paragraphStyle]
var tickerString = NSMutableAttributedString(string: metric.name.uppercaseString, attributes: attributes)
var textBounds : CGRect = CGRect()
textBounds.origin = CGPointMake(self.xOffset, 2*self.yOffset)
textBounds.size = CGSizeMake(self.bounds.width - 2*self.xOffset, self.bounds.height - 3*self.yOffset)
tickerString.drawInRect(textBounds)
}
let bigBandOffset : CGFloat = 2.0
//draw the separator line
path = UIBezierPath()
path.moveToPoint(CGPoint(x: bigBandOffset, y: self.bounds.height - 3))
path.addLineToPoint(CGPoint(x: self.bounds.width - bigBandOffset, y: self.bounds.height - 3))
path.lineWidth = 6
bandColor.setStroke()
path.stroke()
path = UIBezierPath()
if let metric = self.metric {
let smallBandWidth = self.bounds.width/2 * CGFloat(metric.translatedWeight)
path = UIBezierPath()
path.moveToPoint(CGPoint(x: (self.bounds.width - smallBandWidth)/2, y: self.bounds.height - 3))
path.addLineToPoint(CGPoint(x: (self.bounds.width + smallBandWidth)/2, y: self.bounds.height - 3))
path.lineWidth = 6
smallBandColor.setStroke()
path.stroke()
}
}
} | apache-2.0 | 4d211fdf1482017d200f19dcd83261a4 | 31.594444 | 156 | 0.628708 | 4.70409 | false | false | false | false |
Neku/easy-hodl | ios/CryptoSaver/Carthage/Checkouts/QRCodeReader.swift/Sources/QRCodeReaderViewControllerBuilder.swift | 2 | 3108 | /*
* QRCodeReader.swift
*
* Copyright 2014-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import Foundation
/**
The QRCodeViewControllerBuilder aims to create a simple configuration object for
the QRCode view controller.
*/
public final class QRCodeReaderViewControllerBuilder {
// MARK: - Configuring the QRCodeViewController Objects
/**
The builder block.
The block gives a reference of builder you can configure.
*/
public typealias QRCodeReaderViewControllerBuilderBlock = (QRCodeReaderViewControllerBuilder) -> Void
/**
The title to use for the cancel button.
*/
public var cancelButtonTitle = "Cancel"
/**
The code reader object used to scan the bar code.
*/
public var reader = QRCodeReader()
/**
The reader container view used to display the video capture and the UI components.
*/
public var readerView = QRCodeReaderContainer(displayable: QRCodeReaderView())
/**
Flag to know whether the view controller start scanning the codes when the view will appear.
*/
public var startScanningAtLoad = true
/**
Flag to display the cancel button.
*/
public var showCancelButton = true
/**
Flag to display the switch camera button.
*/
public var showSwitchCameraButton = true
/**
Flag to display the toggle torch button. If the value is true and there is no torch the button will not be displayed.
*/
public var showTorchButton = false
/**
Flag to display the guide view.
*/
public var showOverlayView = true
/**
Flag to display the guide view.
*/
public var handleOrientationChange = true
// MARK: - Initializing a Flap View
/**
Initialize a QRCodeViewController builder with default values.
*/
public init() {}
/**
Initialize a QRCodeReaderViewController builder with default values.
- parameter buildBlock: A QRCodeReaderViewController builder block to configure itself.
*/
public init(buildBlock: QRCodeReaderViewControllerBuilderBlock) {
buildBlock(self)
}
}
| mit | 1b5445f3635b12fca091586395d07003 | 29.174757 | 120 | 0.734878 | 4.964856 | false | false | false | false |
PrazAs/ArithmeticSolver | ArithmeticSolver/Models/Operator.swift | 1 | 1398 | //
// Operator.swift
// ArithmeticSolver
//
// Created by Justin Makaila on 6/12/15.
// Copyright (c) 2015 Tabtor. All rights reserved.
//
import Foundation
struct Operator: Printable {
enum Associativity: String {
case Left = "Left"
case Right = "Right"
}
let precedence: Int
let associativity: Associativity
let symbol: String
let function: (Float, Float) -> Float
}
extension Operator: Printable {
var description: String {
return symbol
}
}
// MARK: - Commonly Used Operators
// Define the exponential operator
let exponentialOperator = Operator(precedence: 4, associativity: .Right, symbol: "^", function: { lhs, rhs in
return pow(lhs, rhs)
})
// Define the division operator
let divisionOperator = Operator(precedence: 3, associativity: .Left, symbol: "/", function: { lhs, rhs in
return lhs / rhs
})
// Define the multiplication operator
let multiplicationOperator = Operator(precedence: 3, associativity: .Left, symbol: "*", function: { lhs, rhs in
return lhs * rhs
})
// Define the addition operator
let additionOperator = Operator(precedence: 2, associativity: .Left, symbol: "+", function: { lhs, rhs in
return lhs + rhs
})
// Define the subtraction operator
let subtractionOperator = Operator(precedence: 2, associativity: .Left, symbol: "-", function: { lhs, rhs in
return lhs - rhs
})
| apache-2.0 | d4ce237d7c4f2d1172c89985ffe25473 | 24.418182 | 111 | 0.679542 | 4.063953 | false | false | false | false |
mischarouleaux/Smack | Smack/Pods/Socket.IO-Client-Swift/Source/SocketEngine.swift | 2 | 21478 | //
// SocketEngine.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/3/15.
//
// 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 Dispatch
import Foundation
import StarscreamSocketIO
/// The class that handles the engine.io protocol and transports.
/// See `SocketEnginePollable` and `SocketEngineWebsocket` for transport specific methods.
public final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, SocketEngineWebsocket {
// MARK: Properties
/// The queue that all engine actions take place on.
public let engineQueue = DispatchQueue(label: "com.socketio.engineHandleQueue")
/// The connect parameters sent during a connect.
public var connectParams: [String: Any]? {
didSet {
(urlPolling, urlWebSocket) = createURLs()
}
}
/// A queue of engine.io messages waiting for POSTing
///
/// **You should not touch this directly**
public var postWait = [String]()
/// `true` if there is an outstanding poll. Trying to poll before the first is done will cause socket.io to
/// disconnect us.
///
/// **Do not touch this directly**
public var waitingForPoll = false
/// `true` if there is an outstanding post. Trying to post before the first is done will cause socket.io to
/// disconnect us.
///
/// **Do not touch this directly**
public var waitingForPost = false
/// `true` if this engine is closed.
public private(set) var closed = false
/// If `true` the engine will attempt to use WebSocket compression.
public private(set) var compress = false
/// `true` if this engine is connected. Connected means that the initial poll connect has succeeded.
public private(set) var connected = false
/// An array of HTTPCookies that are sent during the connection.
public private(set) var cookies: [HTTPCookie]?
/// A dictionary of extra http headers that will be set during connection.
public private(set) var extraHeaders: [String: String]?
/// When `true`, the engine is in the process of switching to WebSockets.
///
/// **Do not touch this directly**
public private(set) var fastUpgrade = false
/// When `true`, the engine will only use HTTP long-polling as a transport.
public private(set) var forcePolling = false
/// When `true`, the engine will only use WebSockets as a transport.
public private(set) var forceWebsockets = false
/// `true` If engine's session has been invalidated.
public private(set) var invalidated = false
/// If `true`, the engine is currently in HTTP long-polling mode.
public private(set) var polling = true
/// If `true`, the engine is currently seeing whether it can upgrade to WebSockets.
public private(set) var probing = false
/// The URLSession that will be used for polling.
public private(set) var session: URLSession?
/// The session id for this engine.
public private(set) var sid = ""
/// The path to engine.io.
public private(set) var socketPath = "/engine.io/"
/// The url for polling.
public private(set) var urlPolling = URL(string: "http://localhost/")!
/// The url for WebSockets.
public private(set) var urlWebSocket = URL(string: "http://localhost/")!
/// If `true`, then the engine is currently in WebSockets mode.
public private(set) var websocket = false
/// The WebSocket for this engine.
public private(set) var ws: WebSocket?
/// The client for this engine.
public weak var client: SocketEngineClient?
private weak var sessionDelegate: URLSessionDelegate?
private let logType = "SocketEngine"
private let url: URL
private var pingInterval: Double?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var probeWait = ProbeWaitQueue()
private var secure = false
private var security: SSLSecurity?
private var selfSigned = false
// MARK: Initializers
/// Creates a new engine.
///
/// - parameter client: The client for this engine.
/// - parameter url: The url for this engine.
/// - parameter config: An array of configuration options for this engine.
public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) {
self.client = client
self.url = url
for option in config {
switch option {
case let .connectParams(params):
connectParams = params
case let .cookies(cookies):
self.cookies = cookies
case let .extraHeaders(headers):
extraHeaders = headers
case let .sessionDelegate(delegate):
sessionDelegate = delegate
case let .forcePolling(force):
forcePolling = force
case let .forceWebsockets(force):
forceWebsockets = force
case let .path(path):
socketPath = path
if !socketPath.hasSuffix("/") {
socketPath += "/"
}
case let .secure(secure):
self.secure = secure
case let .selfSigned(selfSigned):
self.selfSigned = selfSigned
case let .security(security):
self.security = security
case .compress:
self.compress = true
default:
continue
}
}
super.init()
sessionDelegate = sessionDelegate ?? self
(urlPolling, urlWebSocket) = createURLs()
}
/// Creates a new engine.
///
/// - parameter client: The client for this engine.
/// - parameter url: The url for this engine.
/// - parameter options: The options for this engine.
public convenience init(client: SocketEngineClient, url: URL, options: NSDictionary?) {
self.init(client: client, url: url, config: options?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
// MARK: Methods
private func checkAndHandleEngineError(_ msg: String) {
do {
let dict = try msg.toNSDictionary()
guard let error = dict["message"] as? String else { return }
/*
0: Unknown transport
1: Unknown sid
2: Bad handshake request
3: Bad request
*/
didError(reason: error)
} catch {
client?.engineDidError(reason: "Got unknown error from server \(msg)")
}
}
private func handleBase64(message: String) {
// binary in base64 string
let noPrefix = message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex]
if let data = Data(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) {
client?.parseEngineBinaryData(data)
}
}
private func closeOutEngine(reason: String) {
sid = ""
closed = true
invalidated = true
connected = false
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason: reason)
}
/// Starts the connection to the server.
public func connect() {
engineQueue.async {
self._connect()
}
}
private func _connect() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
disconnect(reason: "reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: logType, args: url)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
var reqPolling = URLRequest(url: urlPolling, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(for: reqPolling)
}
private func createURLs() -> (URL, URL) {
if client == nil {
return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!)
}
var urlPolling = URLComponents(string: url.absoluteString)!
var urlWebSocket = URLComponents(string: url.absoluteString)!
var queryString = ""
urlWebSocket.path = socketPath
urlPolling.path = socketPath
if secure {
urlPolling.scheme = "https"
urlWebSocket.scheme = "wss"
} else {
urlPolling.scheme = "http"
urlWebSocket.scheme = "ws"
}
if connectParams != nil {
for (key, value) in connectParams! {
let keyEsc = key.urlEncode()!
let valueEsc = "\(value)".urlEncode()!
queryString += "&\(keyEsc)=\(valueEsc)"
}
}
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
return (urlPolling.url!, urlWebSocket.url!)
}
private func createWebsocketAndConnect() {
ws?.delegate = nil
ws = WebSocket(url: urlWebSocketWithSid as URL)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.callbackQueue = engineQueue
ws?.enableCompression = compress
ws?.delegate = self
ws?.disableSSLCertValidation = selfSigned
ws?.security = security
ws?.connect()
}
/// Called when an error happens during execution. Causes a disconnection.
public func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
client?.engineDidError(reason: reason)
disconnect(reason: reason)
}
/// Disconnects from the server.
///
/// - parameter reason: The reason for the disconnection. This is communicated up to the client.
public func disconnect(reason: String) {
engineQueue.async {
self._disconnect(reason: reason)
}
}
private func _disconnect(reason: String) {
guard connected else { return closeOutEngine(reason: reason) }
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return closeOutEngine(reason: reason)
}
if websocket {
sendWebSocketMessage("", withType: .close, withData: [])
closeOutEngine(reason: reason)
} else {
disconnectPolling(reason: reason)
}
}
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
private func disconnectPolling(reason: String) {
postWait.append(String(SocketEnginePacketType.close.rawValue))
doRequest(for: createRequestForPostWithPostWait()) {_, _, _ in }
closeOutEngine(reason: reason)
}
/// Called to switch from HTTP long-polling to WebSockets. After calling this method the engine will be in
/// WebSocket mode.
///
/// **You shouldn't call this directly**
public func doFastUpgrade() {
if waitingForPoll {
DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .upgrade, withData: [])
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
for waiter in probeWait {
write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
probeWait.removeAll(keepingCapacity: false)
if postWait.count != 0 {
flushWaitingForPostToWebSocket()
}
}
/// Causes any packets that were waiting for POSTing to be sent through the WebSocket. This happens because when
/// the engine is attempting to upgrade to WebSocket it does not do any POSTing.
///
/// **You shouldn't call this directly**
public func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else { return }
for msg in postWait {
ws.write(string: msg)
}
postWait.removeAll(keepingCapacity: false)
}
private func handleClose(_ reason: String) {
client?.engineDidClose(reason: reason)
}
private func handleMessage(_ message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
guard let json = try? openData.toNSDictionary() else {
didError(reason: "Error parsing open packet")
return
}
guard let sid = json["sid"] as? String else {
didError(reason: "Open packet contained no sid")
return
}
let upgradeWs: Bool
self.sid = sid
connected = true
pongsMissed = 0
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen(reason: "Connect")
}
private func handlePong(with message: String) {
pongsMissed = 0
// We should upgrade
if message == "3probe" {
upgradeTransport()
}
}
/// Parses raw binary received from engine.io.
///
/// - parameter data: The data to parse.
public func parseEngineData(_ data: Data) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
}
/// Parses a raw engine.io packet.
///
/// - parameter message: The message to parse.
/// - parameter fromPolling: Whether this message is from long-polling.
/// If `true` we might have to fix utf8 encoding.
public func parseEngineMessage(_ message: String) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let reader = SocketStringReader(message: message)
if message.hasPrefix("b4") {
return handleBase64(message: message)
}
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
checkAndHandleEngineError(message)
return
}
switch type {
case .message:
handleMessage(String(message.characters.dropFirst()))
case .noop:
handleNOOP()
case .pong:
handlePong(with: message)
case .open:
handleOpen(openData: String(message.characters.dropFirst()))
case .close:
handleClose(message)
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
// Puts the engine back in its default state
private func resetEngine() {
let queue = OperationQueue()
queue.underlyingQueue = engineQueue
closed = false
connected = false
fastUpgrade = false
polling = true
probing = false
invalidated = false
session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: queue)
sid = ""
waitingForPoll = false
waitingForPost = false
websocket = false
}
private func sendPing() {
guard connected else { return }
// Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose(reason: "Ping timeout")
return
}
guard let pingInterval = pingInterval else { return }
pongsMissed += 1
write("", withType: .ping, withData: [])
engineQueue.asyncAfter(deadline: DispatchTime.now() + Double(pingInterval)) {[weak self] in self?.sendPing() }
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: .noop, withData: [])
// After this point, we should not send anymore polling messages
}
}
/// Writes a message to engine.io, independent of transport.
///
/// - parameter msg: The message to send.
/// - parameter withType: The type of this message.
/// - parameter withData: Any data that this message has.
public func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) {
engineQueue.async {
guard self.connected else { return }
if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendWebSocketMessage(msg, withType: type, withData: data)
} else if !self.probing {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendPollMessage(msg, withType: type, withData: data)
} else {
self.probeWait.append((msg, type, data))
}
}
}
// MARK: Starscream delegate conformance
/// Delegate method for connection.
public func websocketDidConnect(socket: WebSocket) {
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
/// Delegate method for disconnection.
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
probing = false
if closed {
client?.engineDidClose(reason: "Disconnect")
return
}
guard websocket else {
flushProbeWait()
return
}
connected = false
websocket = false
if let reason = error?.localizedDescription {
didError(reason: reason)
} else {
client?.engineDidClose(reason: "Socket Disconnected")
}
}
}
extension SocketEngine {
// MARK: URLSessionDelegate methods
/// Delegate called when the session becomes invalid.
public func URLSession(session: URLSession, didBecomeInvalidWithError error: NSError?) {
DefaultSocketLogger.Logger.error("Engine URLSession became invalid", type: "SocketEngine")
didError(reason: "Engine URLSession became invalid")
}
}
| mit | b79a37e35449ab84bbb6bfbddd4e6f0c | 31.444109 | 130 | 0.609321 | 5.047709 | false | false | false | false |
WalterCreazyBear/Swifter30 | BlueLib/BlueLib/LibraryAPI.swift | 1 | 2275 | //
// LibraryAPI.swift
// BlueLibrarySwift
//
// Created by Yi Gu on 5/6/16.
// Copyright © 2016 Raywenderlich. All rights reserved.
//
import UIKit
class LibraryAPI: NSObject {
// MARK: - Singleton Pattern
static let sharedInstance = LibraryAPI()
// MARK: - Variables
fileprivate let persistencyManager: PersistencyManager
fileprivate let httpClient: HTTPClient
fileprivate let isOnline: Bool
fileprivate override init() {
persistencyManager = PersistencyManager()
httpClient = HTTPClient()
isOnline = false
super.init()
NotificationCenter.default.addObserver(self, selector:#selector(LibraryAPI.downloadImage(_:)), name: NSNotification.Name(rawValue: downloadImageNotification), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Public API
func getAlbums() -> [Album] {
return persistencyManager.getAlbums()
}
func addAlbum(_ album: Album, index: Int) {
persistencyManager.addAlbum(album, index: index)
if isOnline {
let _ = httpClient.postRequest("/api/addAlbum", body: album.description)
}
}
func deleteAlbum(_ index: Int) {
persistencyManager.deleteAlbumAtIndex(index)
if isOnline {
let _ = httpClient.postRequest("/api/deleteAlbum", body: "\(index)")
}
}
func downloadImage(_ notification: Notification) {
// retrieve info from notification
let userInfo = (notification as NSNotification).userInfo as! [String: AnyObject]
let imageView = userInfo["imageView"] as! UIImageView?
let coverUrl = userInfo["coverUrl"] as! String
// get image
if let imageViewUnWrapped = imageView {
imageViewUnWrapped.image = persistencyManager.getImage(URL(string: coverUrl)!.lastPathComponent)
if imageViewUnWrapped.image == nil {
DispatchQueue.global().async {
let downloadedImage = self.httpClient.downloadImage(coverUrl as String)
DispatchQueue.main.async {
imageViewUnWrapped.image = downloadedImage
self.persistencyManager.saveImage(downloadedImage, filename: URL(string: coverUrl)!.lastPathComponent)
}
}
}
}
}
func saveAlbums() {
persistencyManager.saveAlbums()
}
}
| mit | adf2976f8e3d8a2aaf2db27fb37c9cdc | 28.153846 | 175 | 0.682938 | 4.640816 | false | false | false | false |
aquarchitect/MyKit | Sources/Shared/Extensions/CoreData/NSManagedObjectContext+.swift | 1 | 972 | //
// NSManagedObjectContext+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2016 Hai Nguyen.
//
import CoreData
public extension NSManagedObjectContext {
convenience init(appName name: String, type: String, at directory: FileManager.SearchPathDirectory = .documentDirectory) throws {
let url = FileManager.default
.urls(for: directory, in: .userDomainMask)
.last?
.appendingPathComponent("\(name)Data")
let model = Bundle.main
.url(forResource: name, withExtension: "momd")
.flatMap(NSManagedObjectModel.init(contentsOf:))
self.init(concurrencyType: .mainQueueConcurrencyType)
self.persistentStoreCoordinator = try model
.map(NSPersistentStoreCoordinator.init(managedObjectModel:))?
.then { try $0.addPersistentStore(ofType: type, configurationName: nil, at: url, options: nil) }
self.undoManager = UndoManager()
}
}
| mit | 2a09d81187c49b5d36f204e9c4dedc63 | 32.517241 | 133 | 0.667695 | 4.909091 | false | false | false | false |
milseman/swift | test/SILGen/generic_literals.swift | 14 | 2432 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// CHECK-LABEL: sil hidden @_T016generic_literals0A14IntegerLiteralyx1x_ts013ExpressibleBycD0RzlF
func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) {
var x = x
// CHECK: [[TCONV:%.*]] = witness_method $T, #ExpressibleByIntegerLiteral.init!allocator.1
// CHECK: [[ADDR:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[BUILTINCONV:%.*]] = witness_method $T.IntegerLiteralType, #_ExpressibleByBuiltinIntegerLiteral.init!allocator.1
// CHECK: [[LITVAR:%.*]] = alloc_stack $T.IntegerLiteralType
// CHECK: [[LITMETA:%.*]] = metatype $@thick T.IntegerLiteralType.Type
// CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.Int2048, 17
// CHECK: [[LIT:%.*]] = apply [[BUILTINCONV]]<T.IntegerLiteralType>([[LITVAR]], [[INTLIT]], [[LITMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.Int2048, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[TCONV]]<T>([[ADDR]], [[LITVAR]], [[TMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in τ_0_0.IntegerLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 17
}
// CHECK-LABEL: sil hidden @_T016generic_literals0A15FloatingLiteral{{[_0-9a-zA-Z]*}}F
func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(x: T) {
var x = x
// CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByFloatLiteral.init!allocator.1
// CHECK: [[TVAL:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.FloatLiteralType, #_ExpressibleByBuiltinFloatLiteral.init!allocator.1
// CHECK: [[FLT_VAL:%.*]] = alloc_stack $T.FloatLiteralType
// CHECK: [[TFLT_META:%.*]] = metatype $@thick T.FloatLiteralType.Type
// CHECK: [[LIT_VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4004000000000000|0x4000A000000000000000}}
// CHECK: apply [[BUILTIN_CONV]]<T.FloatLiteralType>([[FLT_VAL]], [[LIT_VALUE]], [[TFLT_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinFloatLiteral> (Builtin.FPIEEE{{64|80}}, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[CONV]]<T>([[TVAL]], [[FLT_VAL]], [[TMETA]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : ExpressibleByFloatLiteral> (@in τ_0_0.FloatLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 2.5
}
| apache-2.0 | e80236ad0f1311555ad98aa66088847f | 72.151515 | 246 | 0.666114 | 3.371508 | false | false | false | false |
MaximShoustin/Swift-Extension-Helper | MyExtensions.swift | 1 | 2162 | import Foundation
extension NSData {
func toString() -> String {
return NSString(data: self, encoding: NSUTF8StringEncoding)!
}
}
extension Double {
func format(f: String) -> String {
return NSString(format: "%\(f)f", self)
}
func toString() -> String {
return String(format: "%.1f",self)
}
func toInt() -> Int{
var temp:Int64 = Int64(self)
return Int(temp)
}
}
extension String {
func split(splitter: String) -> Array<String> {
let regEx = NSRegularExpression(pattern: splitter, options: NSRegularExpressionOptions(), error: nil)!
let stop = "SomeStringThatYouDoNotExpectToOccurInSelf"
let modifiedString = regEx.stringByReplacingMatchesInString(self, options: NSMatchingOptions(), range: NSMakeRange(0, countElements(self)), withTemplate: stop)
return modifiedString.componentsSeparatedByString(stop)
}
func startWith(find: String) -> Bool {
return self.hasPrefix(find)
}
func equals(find: String) -> Bool {
return self == find
}
func contains(find: String) -> Bool{
if let temp = self.rangeOfString(find){
return true
}
return false
}
func replace(replaceStr:String, with withStr:String) -> String{
return self.stringByReplacingOccurrencesOfString(
replaceStr,
withString: withStr,
options: .allZeros, // or just nil
range: nil)
}
func equalsIgnoreCase(find: String) -> Bool {
return self.lowercaseString == find.lowercaseString
}
func trim() -> String {
return self.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
}
func removeCharsFromEnd(count:Int) -> String{
let stringLength = countElements(self)
let substringIndex = (stringLength < count) ? 0 : stringLength - count
return self.substringToIndex(advance(self.startIndex, substringIndex))
}
func length() -> Int {
return countElements(self)
}
}
| mit | 6151feb9cf5385e8b4dafb9cd33cef98 | 24.435294 | 175 | 0.608696 | 4.891403 | false | false | false | false |
rohan1989/FacebookOauth2Swift | OAuthSwift-master/Demo/Common/Services.swift | 4 | 1795 | //
// Services.swift
// OAuthSwift
// Copyright (c) 2015 Dongri Jin. All rights reserved.
//
import Foundation
// Class which contains services parameters like consumer key and secret
typealias ServicesValue = String
class Services {
var parameters : [String: [String: ServicesValue]]
init() {
self.parameters = [:]
}
subscript(service: String) -> [String:ServicesValue]? {
get {
return parameters[service]
}
set {
if let value = newValue , !Services.parametersEmpty(value) {
parameters[service] = value
}
}
}
func loadFromFile(_ path: String) {
if let newParameters = NSDictionary(contentsOfFile: path) as? [String: [String: ServicesValue]] {
for (service, dico) in newParameters {
if parameters[service] != nil && Services.parametersEmpty(dico) { // no value to set
continue
}
updateService(service, dico: dico)
}
}
}
func updateService(_ service: String, dico: [String: ServicesValue]) {
var resultdico = dico
if let oldDico = self.parameters[service] {
resultdico = oldDico
resultdico += dico
}
self.parameters[service] = resultdico
}
static func parametersEmpty(_ dico: [String: ServicesValue]) -> Bool {
return Array(dico.values).filter({ (p) -> Bool in !p.isEmpty }).isEmpty
}
var keys: [String] {
return Array(self.parameters.keys)
}
}
func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
| mit | af505d05f6f4cf38e680f5323a99d812 | 26.615385 | 114 | 0.573816 | 4.388753 | false | false | false | false |
henryhsin/vapor_helloPersistance | Sources/App/Models/Acronym.swift | 1 | 1079 | //
// Acronym.swift
// helloPersistance
//
// Created by 辛忠翰 on 2017/4/8.
//
//
import Foundation
import Vapor
final class Acronym: Model{
var short: String
var long: String
var id: Node?
var exists = false
init(short: String, long: String){
self.id = nil
self.short = short
self.long = long
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
short = try node.extract("short")
long = try node.extract("long")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"short": short,
"long": long
])
}
static func prepare(_ database: Database) throws {
try database.create("acronyms"){ (users) in
users.id()
users.string("short")
users.string("long")
}
}
static func revert(_ database: Database) throws {
try database.delete("acronyms")
}
}
| mit | 6c76c23644e8154e631557e616f63362 | 18.509091 | 54 | 0.514445 | 4.079848 | false | false | false | false |
kwizzad/kwizzad-ios | Example/KwizzadExampleUITests/KwizzadExampleUITests.swift | 1 | 2041 | //
// KwizzadExampleUITests.swift
// KwizzadExampleUITests
//
// Created by Fares Ben Hamouda on 23.05.17.
// Copyright © 2017 Kwizzad. All rights reserved.
//
import XCTest
import KwizzadSDK
class KwizzadExampleUITests: XCTestCase {
let kwizzad = KwizzadSDK.instance
let app = XCUIApplication()
override func setUp() {
super.setUp()
continueAfterFailure = false
app.launch()
}
func testPlayAd() {
// opening the Ad after preloading
let webView = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).children(matching: .other).element.children(matching: .other).element(boundBy: 0).children(matching: .other).element(boundBy: 1).children(matching: .other).element
// waiting ( some delay) : expect to open webview
let exists = NSPredicate(format: "exists == 1")
expectation(for: exists, evaluatedWith: webView, handler: nil)
waitForExpectations(timeout: 5, handler: nil)
webView.tap()
// Answering quizz
let firstQuizzButton = app.buttons.allElementsBoundByAccessibilityElement[1]
firstQuizzButton.tap()
app.tap()
let secondQuizzButton = app.buttons.allElementsBoundByAccessibilityElement[1]
secondQuizzButton.tap()
app.tap()
let thirdQuizzButton = app.buttons.allElementsBoundByAccessibilityElement[2]
thirdQuizzButton.tap()
app.tap()
let fourthQuizzButton = app.buttons.allElementsBoundByAccessibilityElement[1]
fourthQuizzButton.tap()
app.tap()
app.tap()
// tap Close icon
let element = app.children(matching: .window).element(boundBy: 0).children(matching: .other).element(boundBy: 1).children(matching: .other).element
element.children(matching: .button).element.tap()
app.alerts.buttons["Yay!"].tap()
}
}
| mit | 104c03c064ecb0f6b214e62d827d5ae0 | 29.447761 | 285 | 0.633824 | 4.258873 | false | true | false | false |
ducn/DNImagePicker | DNImagePicker/Classes/Cropper/WDCropBorderView.swift | 2 | 2646 | //
// WDCropBorderView.swift
// WDImagePicker
//
// Created by Wu Di on 27/8/15.
// Copyright (c) 2015 Wu Di. All rights reserved.
//
import UIKit
internal class WDCropBorderView: UIView {
fileprivate let kNumberOfBorderHandles: CGFloat = 8
fileprivate let kHandleDiameter: CGFloat = 24
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setStrokeColor(UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor)
context?.setLineWidth(1.5)
context?.addRect(CGRect(x: kHandleDiameter / 2, y: kHandleDiameter / 2,
width: rect.size.width - kHandleDiameter, height: rect.size.height - kHandleDiameter))
context?.strokePath()
context?.setFillColor(red: 1, green: 1, blue: 1, alpha: 0.95)
for handleRect in calculateAllNeededHandleRects() {
context?.fillEllipse(in: handleRect)
}
}
fileprivate func calculateAllNeededHandleRects() -> [CGRect] {
let width = self.frame.width
let height = self.frame.height
let leftColX: CGFloat = 0
let rightColX = width - kHandleDiameter
let centerColX = rightColX / 2
let topRowY: CGFloat = 0
let bottomRowY = height - kHandleDiameter
let middleRowY = bottomRowY / 2
//starting with the upper left corner and then following clockwise
let topLeft = CGRect(x: leftColX, y: topRowY, width: kHandleDiameter, height: kHandleDiameter)
let topCenter = CGRect(x: centerColX, y: topRowY, width: kHandleDiameter, height: kHandleDiameter)
let topRight = CGRect(x: rightColX, y: topRowY, width: kHandleDiameter, height: kHandleDiameter)
let middleRight = CGRect(x: rightColX, y: middleRowY, width: kHandleDiameter, height: kHandleDiameter)
let bottomRight = CGRect(x: rightColX, y: bottomRowY, width: kHandleDiameter, height: kHandleDiameter)
let bottomCenter = CGRect(x: centerColX, y: bottomRowY, width: kHandleDiameter, height: kHandleDiameter)
let bottomLeft = CGRect(x: leftColX, y: bottomRowY, width: kHandleDiameter, height: kHandleDiameter)
let middleLeft = CGRect(x: leftColX, y: middleRowY, width: kHandleDiameter, height: kHandleDiameter)
return [topLeft, topCenter, topRight, middleRight, bottomRight, bottomCenter, bottomLeft,
middleLeft]
}
}
| mit | a9284043e46653f8d53bc825425e13b2 | 37.911765 | 112 | 0.677249 | 4.027397 | false | false | false | false |
izotx/iTenWired-Swift | appDataRequester.swift | 1 | 2146 | //
// appDataRequester.swift
// Conference App
//
// Created by George Gruse on 4/15/16.
// Copyright © 2016 Chrystech Systems. All rights reserved.
//
import Foundation
class appDataRequester {
var path: NSString
var mainFile: String
//Make sure that this url is the main json request
var dataPath: NSURL = NSURL(string: "http://djmobilesoftware.com/jsondata.json")!
init()
{
let dir:NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!
mainFile = "jsonData.dat"
path = dir.stringByAppendingPathComponent(mainFile);
}
func initData()
{
let data:NSData = getDataFromURL(dataPath)!
data.writeToFile(path.stringByAppendingPathExtension(mainFile)!, atomically: true)
}
func getDataFromFile()-> NSDictionary
{
return NSDictionary.init(contentsOfFile:(path.stringByAppendingPathExtension(mainFile)!))!
}
func getDataFromURL(requestURL: NSURL) -> NSData?{
var locked = true // Flag to make sure the
var returnData:NSData?
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
returnData = data!
}else{
print("Error while retriving data!")
}
locked = false
}
}
task.resume()
while(locked){ // Runs untill the response is received
}
return returnData
}
//Credit to http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file by user Adam on the stack
//overflow site
}
| bsd-2-clause | f2347d35e7337690893db919a984a0ff | 31.014925 | 155 | 0.597203 | 5.322581 | false | false | false | false |
xedin/swift | test/PlaygroundTransform/init.swift | 9 | 1207 | // RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift -module-name main
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
class B {
init() {
}
}
class C : B {
var i : Int
var j : Int
override init() {
i = 3
j = 5
i + j
}
}
let c = C()
// CHECK: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log[='8']
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [{{.*}}] __builtin_log[c='main.C']
| apache-2.0 | ac78dbbcd9db8d15c69b5cd1dc53cbfa | 34.5 | 262 | 0.649544 | 3.071247 | false | false | false | false |
balitax/AutoCompleteAddressMaps | AutoCompleteAddress/SearchResultsController.swift | 1 | 4934 | //
// SearchResultsController.swift
// PlacesLookup
//
// Created by Malek T. on 9/30/15.
// Copyright © 2015 Medigarage Studios LTD. All rights reserved.
//
import UIKit
protocol LocateOnTheMap{
func locateWithLongitude(_ lon:Double, andLatitude lat:Double, andTitle title: String)
}
class SearchResultsController: UITableViewController {
var searchResults: [String]!
var delegate: LocateOnTheMap!
override func viewDidLoad() {
super.viewDidLoad()
self.searchResults = Array()
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellIdentifier")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchResults.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath)
cell.textLabel?.text = self.searchResults[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath){
// 1
self.dismiss(animated: true, completion: nil)
// 2
let urlpath = "https://maps.googleapis.com/maps/api/geocode/json?address=\(self.searchResults[indexPath.row])&sensor=false".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
let url = URL(string: urlpath!)
// print(url!)
let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) -> Void in
// 3
do {
if data != nil{
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary
let lat = (((((dic.value(forKey: "results") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "geometry") as! NSDictionary).value(forKey: "location") as! NSDictionary).value(forKey: "lat")) as! Double
let lon = (((((dic.value(forKey: "results") as! NSArray).object(at: 0) as! NSDictionary).value(forKey: "geometry") as! NSDictionary).value(forKey: "location") as! NSDictionary).value(forKey: "lng")) as! Double
// 4
self.delegate.locateWithLongitude(lon, andLatitude: lat, andTitle: self.searchResults[indexPath.row])
}
}catch {
print("Error")
}
}
// 5
task.resume()
}
func reloadDataWithArray(_ array:[String]){
self.searchResults = array
self.tableView.reloadData()
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override 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 false 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.
}
*/
}
| mit | 95798e3ee5d0bc87272553ce417680c3 | 35.272059 | 231 | 0.630853 | 5.187171 | false | false | false | false |
ZeeQL/ZeeQL3 | Sources/ZeeQL/Access/DatabaseContext.swift | 1 | 2105 | //
// DatabaseContext.swift
// ZeeQL
//
// Created by Helge Hess on 03/03/2017.
// Copyright © 2017-2019 ZeeZide GmbH. All rights reserved.
//
/**
* DatabaseContext
*
* This is an object store which works on top of Database. It just manages the
* database channels to fetch objects.
*
* E.g. it can be wrapped in an `ObjectTrackingContext` which serves as an
* object uniquer.
*/
public class DatabaseContext : ObjectStore, SmartDescription {
public enum Error : Swift.Error {
case FetchSpecificationHasUnresolvedBindings(FetchSpecification)
case TODO
}
public let database : Database
public init(_ database: Database) {
self.database = database
}
/* fetching objects */
// public struct TypedFetchSpecification<Object: DatabaseObject>
public func objectsWith<T>(fetchSpecification fs : TypedFetchSpecification<T>,
in tc : ObjectTrackingContext,
_ cb : ( T ) -> Void) throws
{
if fs.requiresAllQualifierBindingVariables {
if let keys = fs.qualifier?.bindingKeys, !keys.isEmpty {
throw Error.FetchSpecificationHasUnresolvedBindings(fs)
}
}
let ch = TypedDatabaseChannel<T>(database: database)
try ch.selectObjectsWithFetchSpecification(fs, tc)
while let o : T = ch.fetchObject() {
cb(o)
}
}
public func objectsWith(fetchSpecification fs : FetchSpecification,
in tc : ObjectTrackingContext,
_ cb : ( Any ) -> Void) throws
{
if fs.requiresAllQualifierBindingVariables {
if let keys = fs.qualifier?.bindingKeys, !keys.isEmpty {
throw Error.FetchSpecificationHasUnresolvedBindings(fs)
}
}
let ch = DatabaseChannel(database: database)
try ch.selectObjectsWithFetchSpecification(fs, tc)
while let o = ch.fetchObject() {
cb(o)
}
}
// MARK: - Description
public func appendToDescription(_ ms: inout String) {
ms += " \(database)"
}
}
| apache-2.0 | 119725a8aafe4cd797e568c1dfd8d067 | 26.324675 | 80 | 0.624049 | 4.420168 | false | false | false | false |
soapyigu/Swift30Projects | Project 06 - CandySearch/CandySearch/AppDelegate.swift | 1 | 2934 | /*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
splitViewController.delegate = self
UISearchBar.appearance().barTintColor = UIColor.candyGreen()
UISearchBar.appearance().tintColor = UIColor.white
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = UIColor.candyGreen()
return true
}
// MARK: - Split view
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailCandy == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
extension UIColor {
static func candyGreen() -> UIColor {
return UIColor(red: 67.0/255.0, green: 205.0/255.0, blue: 135.0/255.0, alpha: 1.0)
}
}
| apache-2.0 | 33350611a9ee57e640dd58710f6b1f98 | 47.9 | 187 | 0.781527 | 5.324864 | false | false | false | false |
CGRrui/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBTalentCell.swift | 1 | 3126 | //
// CBTalentCell.swift
// TestKitchen
//
// Created by Rui on 16/8/22.
// Copyright © 2016年 Rui. All rights reserved.
//
import UIKit
class CBTalentCell: UITableViewCell {
@IBOutlet weak var talentImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
@IBOutlet weak var fansLabel: UILabel!
//显示数据
var dataArray: Array<CBRecommendWidgetDataModel>?{
didSet{
showData()
}
}
func showData(){
//图片
if dataArray?.count > 0 {
let imageModel = dataArray![0]
if imageModel.type == "image" {
let url = NSURL(string: imageModel.content!)
talentImageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
//名字
if dataArray?.count > 1 {
let nameModel = dataArray![1]
if nameModel.type == "text" {
nameLabel.text = nameModel.content
}
}
//描述文字
if dataArray?.count > 2 {
let descModel = dataArray![2]
if descModel.type == "text" {
descLabel.text = descModel.content
}
}
//粉丝数
if dataArray?.count > 3 {
let fansModel = dataArray![3]
if fansModel.type == "text" {
fansLabel.text = fansModel.content
}
}
}
//创建cell的方法
class func createTalentCellFor(tableView: UITableView, atIndexPath indexPath:NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBTalentCell {
let cellId = "talentCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBTalentCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CBTalentCell", owner: nil, options: nil).last as? CBTalentCell
}
//indexPath.row 0 1 2
//listModel.data {0-3} {4-7} {8-11}
//(indexPath.row*4 , 4)
//为了防治传过来的json数据会越界,所以先判断(if)一下
if listModel.widget_data?.count > indexPath.row*4+3 {
//先转换成array
let array = NSArray(array: listModel.widget_data!)
let curArray = array.subarrayWithRange(NSMakeRange(indexPath.row*4, 4))
cell?.dataArray = curArray as? Array<CBRecommendWidgetDataModel>
}
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 5e1eff3470d319fd4cba53497b38bbca | 16.146893 | 168 | 0.533443 | 4.81746 | false | false | false | false |
tad-iizuka/swift-sdk | Source/TextToSpeechV1/Models/Customization.swift | 3 | 2279 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A custom voice model supported by the Text to Speech service. */
public struct Customization: JSONDecodable {
/// The GUID of the custom voice model.
public let customizationID: String
/// The name of the custom voice model.
public let name: String
/// The language of the custom voice model
public let language: String
/// GUID of the service credentials for the owner of the custom voice model.
public let owner: String
/// The UNIX timestamp that indicates when the custom voice model was created.
/// The timestamp is a count of seconds since the UNIX Epoch of January 1, 1970
/// Coordinated Universal Time (UTC).
public let created: Int? // TODO: change to `Int` after service bug is fixed
/// The UNIX timestamp that indicates when the custom voice model was last modified.
/// Equals created when a new voice model is first added but has yet to be changed.
public let lastModified: Int? // TODO: change to `Int` after service bug is fixed
/// A description of the custom voice model.
public let description: String?
/// Used internally to initialize a `Customization` model from JSON.
public init(json: JSON) throws {
customizationID = try json.getString(at: "customization_id")
name = try json.getString(at: "name")
language = try json.getString(at: "language")
owner = try json.getString(at: "owner")
created = try? json.getInt(at: "created")
lastModified = try? json.getInt(at: "last_modified")
description = try? json.getString(at: "description")
}
}
| apache-2.0 | 5185210714ce0f8829e32111fdfc0cf5 | 38.982456 | 88 | 0.691093 | 4.576305 | false | false | false | false |
bradhowes/vhtc | VariableHeightTableCells/VariableHeightTableViewController.swift | 1 | 3808 | //
// VariableHeightTableViewController
// VariableHeightTableCells
//
// Created by Brad Howes on 1/5/17.
// Copyright © 2017 Brad Howes. All rights reserved.
//
import UIKit
enum Strategy {
case estimated
case cached
}
/**
Adaptation of UITableViewController for one with cells that have varying heights. Relies on an instance of DataSource
to provide data for the table, and a height calculating strategy class which hopefully provides fast answers to the
question of how high a cell is.
*/
final class VariableHeightTableViewController: UITableViewController {
private var dataSource: DataSource!
private var heightCalculationStrategy: HeightCalculationStrategy!
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = DataSource(count: 300)
tableView.dataSource = dataSource
for ident in CellIdent.all {
tableView.register(ident: ident)
}
heightCalculationStrategy = make(strategy: .cached)
}
/**
Notification that the managed view is about to appear to the user. Make sure that our height calculating strategy
is ready with accurate answers.
- parameter animated: true if the view will appear in an animation
*/
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// SOP to scroll to a given row - do so in DispatchQueue.main.async block
DispatchQueue.main.async {
self.heightCalculationStrategy.cellWidth = self.view.frame.width
self.tableView.scrollToRow(at: IndexPath(row: self.dataSource.count - 1, section: 0), at: .bottom,
animated: false)
}
}
/**
Notification that the managed view is about to transform in size. Causes the recalculation of cell heights after
the transformation is complete.
- parameter size: the new size for the view
- parameter coordinator: the object that is managing the transformation
*/
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in }) { _ in
self.heightCalculationStrategy.cellWidth = size.width
}
}
/**
Tell table view how many sections there are
- parameter tableView: the table to inform
- returns: 1
*/
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
/**
Tell table view the height of a specific row element
- parameter tableView: the table to inform
- parameter indexPath: the index of the row to report on
- returns: the height
*/
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return heightCalculationStrategy.getHeight(for: self.dataSource[indexPath.row], at: indexPath)
}
/*
Notification that memory is running low.
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Create the desired height calculation strategy.
- parameter useFast: create
- returns: strategy instance
*/
private func make(strategy: Strategy) -> HeightCalculationStrategy {
switch strategy {
case .estimated:
return EstimatedHeightCalculationStrategy(idents: CellIdent.all, tableView: tableView,
estimatedHeight: 80.0)
case .cached: return CachedHeightArrayStrategy(idents: CellIdent.all, tableView: tableView,
dataSource: dataSource)
}
}
}
| mit | 909e9b18b906e7e62fc83a448b898b76 | 33.609091 | 118 | 0.662464 | 5.258287 | false | false | false | false |
shahmishal/swift | test/IDE/complete_function_builder.swift | 1 | 6102 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_TOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_NONTOP | %FileCheck %s -check-prefix=IN_CLOSURE_TOP
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=IN_CLOSURE_COLOR_CONTEXT_DOT | %FileCheck %s -check-prefix=IN_CLOSURE_COLOR_CONTEXT_DOT
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXTUAL_TYPE_1 | %FileCheck %s -check-prefix=CONTEXTUAL_TYPE_VALID
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXTUAL_TYPE_2 | %FileCheck %s -check-prefix=CONTEXTUAL_TYPE_VALID
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXTUAL_TYPE_3 | %FileCheck %s -check-prefix=CONTEXTUAL_TYPE_VALID
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXTUAL_TYPE_4 | %FileCheck %s -check-prefix=CONTEXTUAL_TYPE_VALID
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=CONTEXTUAL_TYPE_5 | %FileCheck %s -check-prefix=CONTEXTUAL_TYPE_INVALID
struct Tagged<Tag, Entity> {
let tag: Tag
let entity: Entity
static func fo
}
protocol Taggable {
}
extension Taggable {
func tag<Tag>(_ tag: Tag) -> Tagged<Tag, Self> {
return Tagged(tag: tag, entity: self)
}
}
extension Int: Taggable { }
extension String: Taggable { }
@_functionBuilder
struct TaggedBuilder<Tag> {
static func buildBlock() -> () { }
static func buildBlock<T1>(_ t1: Tagged<Tag, T1>) -> Tagged<Tag, T1> {
return t1
}
static func buildBlock<T1, T2>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>) {
return (t1, t2)
}
static func buildBlock<T1, T2, T3>(_ t1: Tagged<Tag, T1>, _ t2: Tagged<Tag, T2>, _ t2: Tagged<Tag, T3>) -> (Tagged<Tag, T1>, Tagged<Tag, T2>, Tagged<Tag, T3>) {
return (t1, t2, t3)
}
}
enum Color {
case red, green, blue
}
func acceptColorTagged<Result>(@TaggedBuilder<Color> body: (Color) -> Result) {
print(body(.blue))
}
var globalIntVal: Int = 1
let globalStringVal: String = ""
func testAcceptColorTagged(paramIntVal: Int, paramStringVal: String) {
let taggedValue = paramIntVal.tag(Color.red)
acceptColorTagged { color in
#^IN_CLOSURE_TOP^#
// IN_CLOSURE_TOP_CONTEXT: Begin completions
// IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: taggedValue[#Tagged<Color, Int>#]; name=taggedValue
// IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalIntVal[#Int#]; name=globalIntVal
// IN_CLOSURE_TOP-DAG: Decl[GlobalVar]/CurrModule: globalStringVal[#String#]; name=globalStringVal
// IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: color; name=color
// IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal
// IN_CLOSURE_TOP-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal
// IN_CLOSURE_TOP: End completions
}
acceptColorTagged { color in
paramIntVal.tag(.red)
#^IN_CLOSURE_NONTOP^#
// Same as IN_CLOSURE_TOP.
}
acceptColorTagged { color in
paramIntVal.tag(#^IN_CLOSURE_COLOR_CONTEXT^#)
// IN_CLOSURE_COLOR_CONTEXT: Begin completions
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[InstanceMethod]/CurrNominal: ['(']{#(tag): Color#}[')'][#Tagged<Color, Int>#]; name=tag: Color
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local/TypeRelation[Identical]: color[#Color#]; name=color
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: taggedValue[#Tagged<Color, Int>#]; name=taggedValue
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramIntVal[#Int#]; name=paramIntVal
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[LocalVar]/Local: paramStringVal[#String#]; name=paramStringVal
// IN_CLOSURE_COLOR_CONTEXT-DAG: Decl[Enum]/CurrModule/TypeRelation[Identical]: Color[#Color#]; name=Color
// IN_CLOSURE_COLOR_CONTEXT: End completions
}
acceptColorTagged { color in
paramIntVal.tag(.#^IN_CLOSURE_COLOR_CONTEXT_DOT^#)
// IN_CLOSURE_COLOR_CONTEXT_DOT: Begin completions, 3 items
// IN_CLOSURE_COLOR_CONTEXT_DOT-DAG: Decl[EnumElement]/ExprSpecific: red[#Color#]; name=red
// IN_CLOSURE_COLOR_CONTEXT_DOT-DAG: Decl[EnumElement]/ExprSpecific: green[#Color#]; name=green
// IN_CLOSURE_COLOR_CONTEXT_DOT-DAG: Decl[EnumElement]/ExprSpecific: blue[#Color#]; name=blue
// IN_CLOSURE_COLOR_CONTEXT_DOT: End completions
}
}
enum MyEnum {
case east, west
case north, south
}
@_functionBuilder
struct EnumToVoidBuilder {
static func buildBlock() {}
static func buildBlock(_ :MyEnum) {}
static func buildBlock(_ :MyEnum, _: MyEnum) {}
static func buildBlock(_ :MyEnum, _: MyEnum, _: MyEnum) {}
}
func acceptBuilder(@EnumToVoidBuilder body: () -> Void) {}
// CONTEXTUAL_TYPE_INVALID-NOT: Begin completions
// CONTEXTUAL_TYPE_VALID: Begin completions, 4 items
// CONTEXTUAL_TYPE_VALID-DAG: Decl[EnumElement]/ExprSpecific: east[#MyEnum#]; name=east
// CONTEXTUAL_TYPE_VALID-DAG: Decl[EnumElement]/ExprSpecific: west[#MyEnum#]; name=west
// CONTEXTUAL_TYPE_VALID-DAG: Decl[EnumElement]/ExprSpecific: north[#MyEnum#]; name=north
// CONTEXTUAL_TYPE_VALID-DAG: Decl[EnumElement]/ExprSpecific: south[#MyEnum#]; name=south
// CONTEXTUAL_TYPE_VALID: End completions
func testContextualType() {
acceptBuilder {
.#^CONTEXTUAL_TYPE_1^#
}
acceptBuilder {
.#^CONTEXTUAL_TYPE_2^#;
.north;
}
acceptBuilder {
.north;
.#^CONTEXTUAL_TYPE_3^#;
}
acceptBuilder {
.north;
.east;
.#^CONTEXTUAL_TYPE_4^#
}
acceptBuilder {
.north;
.east;
.south;
// NOTE: Invalid because 'EnumToVoidBuilder' doesn't have 4 params overload.
.#^CONTEXTUAL_TYPE_5^#
}
}
| apache-2.0 | 7d17baffc4384ef261bc5b97befb9703 | 40.22973 | 178 | 0.69846 | 3.39755 | false | true | false | false |
hmily-xinxiang/BBSwiftFramework | BBSwiftFramework/Class/Extern/Root/BBRootViewController.swift | 1 | 8237 | //
// BBRootViewController.swift
// BBSwiftFramework
//
// Created by Bei Wang on 9/30/15.
// Copyright © 2015 BooYah. All rights reserved.
//
import UIKit
class BBRootViewController: UIViewController, UINavigationControllerDelegate, UIGestureRecognizerDelegate, BBFullScreenMaskViewDelegate {
private var applicationWindow_: UIWindow!
private var maskView_: BBFullScreenMaskView!
// MARK: - --------------------System--------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
applicationWindow_ = (UIApplication.sharedApplication().delegate?.window)!
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configLeftBarButtonItem()
self.navigationController?.delegate = self
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.navigationController?.delegate = nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - --------------------功能函数--------------------
private func configLeftBarButtonItem() {
if (self.navigationController != nil) {
if (self.navigationController?.viewControllers.count > 1) {
self.setBackBarButtonWithTarget(self, action: #selector(BBRootViewController.clickedBackBarButtonAction))
} else if (self.navigationController?.viewControllers.count == 1) {
var rootViewController = applicationWindow_.rootViewController
if ((rootViewController?.isKindOfClass(BBNavigationController)) != nil) {
let tempViewController: BBNavigationController = rootViewController as! BBNavigationController
rootViewController = tempViewController.topViewController
if (rootViewController?.presentedViewController != nil) {
self.setCloseBarButtonWithTarget(self, action: #selector(BBRootViewController.clickedCloseBarButtonAction))
}
}
}
} else {
self.setCloseBarButtonWithTarget(self, action: #selector(BBRootViewController.clickedCloseBarButtonAction))
}
}
private func setLeftBarButtonItem(item: UIBarButtonItem) {
self.navigationItem.leftBarButtonItem = item
}
private func setRightBarButtonItem(item: UIBarButtonItem) {
self.navigationItem.rightBarButtonItem = item
}
// MARK: - --------------------手势事件--------------------
// MARK: 各种手势处理函数注释
// MARK: - --------------------按钮事件--------------------
// MARK: 按钮点击函数注释
func clickedBackBarButtonAction() {
self.navigationController?.popViewControllerAnimated(true)
}
func clickedCloseBarButtonAction() {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - --------------------代理方法--------------------
// MARK: UINavigationControllerDelegate
func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
if (navigationController.respondsToSelector(Selector("interactivePopGestureRecognizer"))) {
navigationController.interactivePopGestureRecognizer?.enabled = true
}
}
// MARK: BBFullScreenMaskViewDelegate
func maskViewwillRemoveFromSuperView(maskView: BBFullScreenMaskView, superView: UIView) {
maskView_ = nil
}
// MARK: - --------------------属性相关--------------------
// MARK: 属性操作函数注释
// MARK: - --------------------接口API--------------------
// MARK: 局部代码分隔
func local(closure: ()->()) {
closure()
}
// MARK: 设置自定义标题
func setCustomTitle(title: String) {
self.title = title
// let titleLabel = UILabel(frame: CGRectMake(0, 0, BBDevice.deviceWidth(), kNavigationBarTitleViewMaxHeight))
// local { () -> () in
// titleLabel.textAlignment = NSTextAlignment.Center
// titleLabel.font = BBFont.customFontWithSize(17)
// titleLabel.textColor = BBColor.titleColor()
// titleLabel.text = title as String
// titleLabel.backgroundColor = BBColor.redColor()
// }
// self.navigationItem.titleView = titleLabel
}
// MARK: 返回按钮
func setBackBarButtonWithTarget(target: AnyObject?, action: Selector) {
let backItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_back_arrow"), style: UIBarButtonItemStyle.Plain, target: target, action: action)
setLeftBarButtonItem(backItem)
}
// MARK: 关闭按钮
func setCloseBarButtonWithTarget(target: AnyObject?, action: Selector) {
let backItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_close_cross"), style: UIBarButtonItemStyle.Plain, target: target, action: action)
setLeftBarButtonItem(backItem)
}
// MARK: 更多按钮
func setMoreBarButtonWithTarget(target: AnyObject?, action: Selector) {
let backItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_more_normal"), style: UIBarButtonItemStyle.Plain, target: target, action: action)
setLeftBarButtonItem(backItem)
}
// MARK: 消息按钮
func setInboxBarButtonWithTarget(target: AnyObject?, action: Selector) {
let backItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_inbox_normal"), style: UIBarButtonItemStyle.Plain, target: target, action: action)
setRightBarButtonItem(backItem)
}
// MARK: 添加按钮
func setAddBarButtonWithTarget(target: AnyObject?, action: Selector) {
let backItem:UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "btn_add_normal"), style: UIBarButtonItemStyle.Plain, target: target, action: action)
setRightBarButtonItem(backItem)
}
// MARK: 右边文字按钮
func setRightBarButtonWithTitle(title: String, target: AnyObject?, action: Selector) {
let rightItem:UIBarButtonItem = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: action)
setRightBarButtonItem(rightItem)
}
// MARK: 获取顶层视图
class func getCurrentViewController() -> UIViewController {
let applicationWindow: UIWindow! = (UIApplication.sharedApplication().delegate?.window)!
var rootViewController = applicationWindow.rootViewController
if ((rootViewController?.isKindOfClass(BBNavigationController)) != nil) {
let tempViewController: BBNavigationController = rootViewController as! BBNavigationController
rootViewController = tempViewController.visibleViewController
}
return rootViewController!
}
// MARK: 添加遮盖层
func showCoverViewWithContentView(contentView: UIView, alpha: CGFloat) {
self.showCoverViewWithContentView(contentView, isHideWhenTouchBackground: true, backgroundAlpha: alpha)
}
func showCoverViewWithContentView(contentView: UIView, isHideWhenTouchBackground: Bool, backgroundAlpha: CGFloat) {
if (maskView_ == nil) {
maskView_ = UIView.init(frame: (applicationWindow_?.bounds)!) as! BBFullScreenMaskView
maskView_.delegate = self
maskView_.alpha = 0.0
maskView_.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(backgroundAlpha)
}
contentView.center = CGPointMake(maskView_.bounds.size.width/2.0, maskView_.bounds.size.height/2.0)
maskView_.isHideWhenTouchBackground = isHideWhenTouchBackground
maskView_.addSubview(contentView)
applicationWindow_.addSubview(maskView_)
UIView.animateWithDuration(0.5) { () -> Void in
self.maskView_.alpha = 1.0
}
}
}
| mit | 3118533ee269325bb4ed0a690f4898b2 | 41.094241 | 164 | 0.656095 | 5.374332 | false | false | false | false |
DrabWeb/Azusa | Source/Yui/Yui/Objects/Album.swift | 1 | 3928 | //
// Album.swift
// Yui
//
// Created by Ushio on 2/11/17.
//
import Foundation
/// The object to represent an album in the user's music collection
public class Album: CustomStringConvertible {
// MARK: - Properties
// MARK: Public Properties
public var name : String = "";
public var songs : [Song] = [];
public var artists : [Artist] {
var noDuplicateArtists : [Artist] = [];
self.songs.map { $0.artist }.forEach { artist in
if(!noDuplicateArtists.contains(artist)) {
noDuplicateArtists.append(artist);
}
}
return noDuplicateArtists;
}
public var duration : Int {
var length : Int = 0;
self.songs.forEach { song in
length += song.duration;
}
return length;
}
public var genres : [Genre] {
var noDuplicateGenres : [Genre] = [];
self.songs.map { $0.genre }.forEach { genre in
if(!noDuplicateGenres.contains(genre)) {
noDuplicateGenres.append(genre);
}
}
return noDuplicateGenres;
};
public var year : Int {
var releaseYear : Int = -1;
self.songs.forEach {
releaseYear = $0.year;
}
return releaseYear;
};
public var displayName : String {
return ((self.name != "") ? self.name : "Unknown Album");
}
/// Gets the user readable version of this album's artist(s)
///
/// - Parameter shorten: If there are multiple artists, should the string be shortened to "Various Artists"?
/// - Returns: The user readable version of this album's artist(s)
public func displayArtists(shorten : Bool) -> String {
let artists : [Artist] = self.artists;
//
// "Various Artists"
// "Kuricorder Quartet"
// "Heart of Air, Kow Otani"
// "Unknown Artist"
//
if(artists.count == 1) {
return self.artists[0].displayName;
}
else if(artists.count > 1) {
if(shorten) {
return "Various Artists";
}
else {
var displayArtistsString : String = "";
for(index, artist) in artists.enumerated() {
displayArtistsString += "\(artist.displayName)\((index == (artists.count - 1)) ? "" : ", ")";
}
return displayArtistsString;
}
}
else {
return "Unknown Artist";
}
}
public var displayGenres : String {
var displayGenreString : String = "";
let albumGenres : [Genre] = self.genres;
for(index, genre) in albumGenres.enumerated() {
if(genre.name != "") {
displayGenreString += "\(genre.name)\((index == (albumGenres.count - 1)) ? "" : ", ")";
}
}
if(displayGenreString == "") {
displayGenreString = "Unknown Genre";
}
return displayGenreString;
}
public var displayYear : String {
let year : Int = self.year;
return (year == -1 || year == 0) ? "Unknown Year" : "\(year)";
}
public var description : String {
return "Album: \(self.displayName) by \(self.artists)(\(self.genres)), \(self.songs.count) songs, released in \(year)"
}
// MARK: - Initialization and Deinitialization
public init(name : String, songs : [Song]) {
self.name = name;
self.songs = songs;
}
public init(name : String) {
self.name = name;
self.songs = [];
}
public init() {
self.name = "";
self.songs = [];
}
}
| gpl-3.0 | d434119615376f3f23d09af734b4661c | 25.186667 | 126 | 0.492872 | 4.62662 | false | false | false | false |
FindGF/_BiliBili | WTBilibili/Other-其他/NetworkTools.swift | 1 | 12843 | //
// NetworkTools.swift
// WTBilibili
//
// Created by 耿杰 on 16/5/4.
// Copyright © 2016年 无头骑士 GJ. All rights reserved.
// 网络工具类
import UIKit
import AFNetworking
import SwiftyJSON
enum WTRequestMethod: String {
case GET = "GET"
case POST = "POST"
}
class NetworkTools: AFHTTPSessionManager
{
// 单例
static let shareInstance: NetworkTools = {
let tools = NetworkTools()
// _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"image/png",nil];
tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/html", "text/plain", "text/xml") as? Set<String>
return tools
}()
/// 处理结果的Block
let handleArrayBlock = {(result: AnyObject?, error: NSError?, finished: (result: [[String: AnyObject]]?, error: NSError?) -> ()) -> Void in
// 2.1、错误检验
if error != nil
{
finished(result: nil, error: error)
return
}
// 2.2、将AnyObject转成字典
guard let resultDict = result else{
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "将结果转成字典失败"]))
return
}
// 2.3、从result字典取出数组
guard let resultArray = resultDict["data"] as? [[String: AnyObject]] else {
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "从字典中通过data取出字典数组失败"]))
return
}
// 2.4、回调结果
finished(result: resultArray, error: error)
}
/// 处理结果的Block
let handleDictBlock = {(result: AnyObject?, error: NSError?, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) -> Void in
// 2.1、错误检验
if error != nil
{
finished(result: nil, error: error)
return
}
// 2.2、将AnyObject转成字典
guard let resultDict = result else{
print("error:\(result)")
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "将结果转成字典失败"]))
return
}
// 2.3、从result字典取出数组
guard let dataResult = resultDict["data"] as? [String: AnyObject] else {
print("error:\(result)")
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "从字典中通过data取出字典数组失败"]))
return
}
// 2.4、回调结果
finished(result: dataResult, error: error)
}
/// 处理结果的Block
let handleDictBlockWithKey = {(key: String?, result: AnyObject?, error: NSError?, finished: (result: [[String: AnyObject]]?, error: NSError?) -> ()) -> Void in
// 2.1、错误检验
if error != nil
{
finished(result: nil, error: error)
return
}
// 2.2、将AnyObject转成字典
guard let resultDict = result else{
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "将结果转成字典失败"]))
return
}
// 2.3、从result字典取出数组
guard let resultArray = resultDict[key!] as? [[String: AnyObject]] else {
finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "从字典中通过\(key)取出字典数组失败"]))
return
}
// 2.4、回调结果
finished(result: resultArray, error: error)
}
}
// MARK: - 封装网络请求
extension NetworkTools
{
func request(method: WTRequestMethod, urlString: String, parameters: [String: AnyObject]?, finished: (result: AnyObject?, error: NSError?) -> ())
{
// 1、定义成功的回调闭包
let success = {(task: NSURLSessionDataTask, result: AnyObject?) -> Void in
finished(result: result, error: nil)
}
// 2、定义失败的回调闭包
let failure = {(task: NSURLSessionDataTask?, error: NSError) -> Void in
finished(result: nil, error: error)
}
// 3、发送请求
if method == .GET
{
GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
else
{
POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
}
}
}
// MARK: - 首页->直播
extension NetworkTools
{
// MARK: 加载直播首页的数据
func loadHomeLiveData(finished: (result: [String: AnyObject]?, error: NSError?) -> ())
{
requestSerializer = AFJSONRequestSerializer()
// 1、url
let urlString = "http://live.bilibili.com/AppIndex/home?access_key=a2dbcc35a5ddf9f2d2222ccedef1e5b4&actionKey=appkey&appkey=27eb53fc9058f8c3&build=3170&device=phone&platform=ios&scale=2&sign=b8458855b19667a3a741d2686baea127&ts=1462706479"
// 2、发送请求
request(.GET, urlString: urlString, parameters: nil) { (result, error) in
self.handleDictBlock(result, error, finished)
}
}
// MARK: 根据room_id查询出直播详情信息 418
func loadHomeLiveDetailData418(room_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ())
{
requestSerializer = AFJSONRequestSerializer()
// 1、url
let urlString418 = "http://live.bilibili.com/api/room_info?_device=iphone&_hwid=a1761fdacd4633fd&_ulv=10000&access_key=a2dbcc35a5ddf9f2d2222ccedef1e5b4&appkey=\(APP_KEY)&appver=3220&build=3220&buld=3220&platform=ios&room_id=\(room_id)&type=json&sign=\(WTBilibiliTool.encodeHomeLiveDetailSign418(room_id))"
// 2、发送请求
request(.GET, urlString: urlString418, parameters: nil) { (result, error) in
self.handleDictBlock(result, error, finished)
}
}
// MARK: 根据room_id查询出直播详情信息 420
func loadHomeLiveDetailData420(room_id: Int, finished: (result: [String: AnyObject]?, error: NSError?) -> ())
{
requestSerializer = AFJSONRequestSerializer()
let urlString420 = "http://live.bilibili.com/AppRoom/index?actionKey=appkey&appkey=\(APP_KEY)&build=3300&device=phone&platform=ios&room_id=\(room_id)&sign=\(WTBilibiliTool.encodeHomeLiveDetailSign420(room_id, timeInterval: WTTimeInterval))&ts=\(WTTimeInterval)"
// 2、发送请求
request(.GET, urlString: urlString420, parameters: nil) { (result, error) in
self.handleDictBlock(result, error, finished)
}
}
// MARK: 根据cid获取直播地址
func getLivePlayerURL(cid: Int, finished: (result: String?, error: NSError?) -> ())
{
requestSerializer = AFJSONRequestSerializer()
// 1、url
let urlString = "http://live.bilibili.com/api/playurl?player=1&quality=0&cid=\(cid)"
// 2、发送请求
// manager.responseSerializer = [AFHTTPResponseSerializer serializer]
// self.responseSerializer = AFHTTPResponseSerializer()
request(.GET, urlString: urlString, parameters: nil) { (result, error) in
// 2.1、错误检验
if error != nil
{
finished(result: nil, error: error)
return
}
let json = JSON(result!)
let url = json["durl"][0]["url"].string
finished(result: url, error: nil)
}
}
}
// MARK: - 首页->推荐
extension NetworkTools
{
// MARK: 广告
func loadHomeRecommendBanner(finished: (result: [[String: AnyObject]]?, error: NSError?) -> ())
{
requestSerializer = AFJSONRequestSerializer()
// 1、url
let urlString = "http://app.bilibili.com/x/banner?build=3170&channel=appstore&plat=2"
// 2、发送请求
request(.GET, urlString: urlString, parameters: nil) { (result, error) in
self.handleArrayBlock(result, error, finished)
}
}
}
// MARK: - 我的
extension NetworkTools
{
// MARK: 加载游戏中心数据
func loadGrameCenter(finished: (result: [[String: AnyObject]]?, error: NSError?) -> ())
{
requestSerializer.setValue("Mozilla/5.0 BiliGameApi", forHTTPHeaderField: "User-Agent")
requestSerializer.setValue("api.biligame.com", forHTTPHeaderField: "Host")
requestSerializer.setValue("-1465740144", forHTTPHeaderField: "Display-ID")
requestSerializer.setValue("*/*", forHTTPHeaderField: "Accept")
requestSerializer.setValue("zh-cn", forHTTPHeaderField: "Accept-Language")
requestSerializer.setValue("53EF0CF2-937A-4B7C-86A8-BF64B543CF2C12522infoc", forHTTPHeaderField: "Buvid")
requestSerializer.setValue("*/*", forHTTPHeaderField: "Accept")
// 1、url
let timeInterval = WTTimeInterval
let udid = WTUDID
let urlString = "http://api.biligame.com/app/iOS/homePage?actionKey=appkey&appkey=\(APP_KEY)&build=3300&cli_version=4.20&device=phone&platform=ios&sign=\(WTBilibiliTool.encodeGameCenterSign(timeInterval, udid: udid))&svr_version=1.1×tamp=\(timeInterval * 1000)&ts=\(timeInterval)&udid=a1761fdacd4633fdf16dfb77b84236d4"
//let urlString = "http://api.biligame.com/app/iOS/homePage?actionKey=appkey&appkey=27eb53fc9058f8c3&build=3300&cli_version=4.20&device=phone&platform=ios&sign=fe333baf3444d6f0aba5772318c77b26&svr_version=1.1×tamp=1465745136000&ts=1465745136&udid=a1761fdacd4633fdf16dfb77b84236d4"
// 2、发送请求
request(.GET, urlString: urlString, parameters: nil) { (result, error) in
WTLog("result:\(result)")
self.handleDictBlockWithKey("items", result, error, finished)
}
}
}
// MARK: - 登录
extension NetworkTools
{
func getLoginKey()
{
let urlString = "https://account.bilibili.com/api/login/get_key?_device=iphone&_hwid=a1761fdacd4633fd&_ulv=0&appkey=\(APP_KEY)&platform=ios&type=json&sign=\(WTBilibiliTool.encodeLoginKeySign(WTTimeInterval))"
request(.GET, urlString: urlString, parameters: nil) { (result, error) in
WTLog("result:\(result)")
// 2.1、错误检验
if error != nil
{
// finished(result: nil, error: error)
WTLog("error:\(error)")
return
}
// 2.2、将AnyObject转成字典
guard let resultDict = result else{
// finished(result: nil, error: NSError(domain: DOMAIN, code: -1011, userInfo: ["errorInfo": "将结果转成字典失败"]))
WTLog("将结果转成字典失败")
return
}
let loginKeyItem = WTLoginKeyItem(dict: resultDict as! [String : AnyObject])
let originPwd = "gJ19930304"
let key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCdScM09sZJqFPX7bvmB2y6i08J\nbHsa0v4THafPbJN9NoaZ9Djz1LmeLkVlmWx1DwgHVW+K7LVWT5FV3johacVRuV98\n37+RNntEK6SE82MPcl7fA++dmW2cLlAjsIIkrX+aIvvSGCuUfcWpWFy3YVDqhuHr\nNDjdNcaefJIQHMW+sQIDAQAB".stringByReplacingOccurrencesOfString("-----BEGIN PUBLIC KEY-----\n", withString: "").stringByReplacingOccurrencesOfString("\n-----END PUBLIC KEY-----\n", withString: "").stringByReplacingOccurrencesOfString("\n", withString: "")
WTLog("key:\(key)")
let view = UIView()
view.subviews
let pwd = RSAEncryptor.encryptString(originPwd, publicKey: key)
WTLog("pwd:\(pwd)")
let encodePwd = pwd.URLEncode()!
let userid = "耿大神"
let encodeUserid = userid.URLEncode()!
let urlString = "https://account.bilibili.com/api/login/v2?app_subid=1&appkey=\(APP_KEY)&appver=3430&permission=ALL&platform=ios&pwd=\(encodePwd)&type=json&userid=\(encodeUserid)&sign=\(WTBilibiliTool.encodeLoginSign(loginKeyItem.ts, userid: userid, pwd: pwd))"
WTLog("urlString:\(urlString)")
// self.request(.GET, urlString: urlString, parameters: nil) { (result, error) in
// WTLog("result:\(result)")
//
// }
}
}
} | apache-2.0 | 29316b0ca09a450211aac04f5f1820b4 | 38.787582 | 475 | 0.599556 | 3.869676 | false | false | false | false |
ashleybrgr/surfPlay | surfPlay/Pods/FaveButton/Source/FaveIcon.swift | 5 | 4791 | //
// FaveIcon.swift
// FaveButton
//
// Copyright © 2016 Jansel Valentin.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class FaveIcon: UIView {
var iconColor: UIColor = .gray
var iconImage: UIImage!
var iconLayer: CAShapeLayer!
var iconMask: CALayer!
var contentRegion: CGRect!
var tweenValues: [CGFloat]?
init(region: CGRect, icon: UIImage, color: UIColor) {
self.iconColor = color
self.iconImage = icon
self.contentRegion = region
super.init(frame: CGRect.zero)
applyInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: create
extension FaveIcon{
class func createFaveIcon(_ onView: UIView, icon: UIImage, color: UIColor) -> FaveIcon{
let faveIcon = Init(FaveIcon(region:onView.bounds, icon: icon, color: color)){
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .clear
}
onView.addSubview(faveIcon)
(faveIcon, onView) >>- [.centerX,.centerY]
faveIcon >>- [.width,.height]
return faveIcon
}
func applyInit(){
let maskRegion = contentRegion.size.scaleBy(0.7).rectCentered(at: contentRegion.center)
let shapeOrigin = CGPoint(x: -contentRegion.center.x, y: -contentRegion.center.y)
iconMask = Init(CALayer()){
$0.contents = iconImage.cgImage
$0.contentsScale = UIScreen.main.scale
$0.bounds = maskRegion
}
iconLayer = Init(CAShapeLayer()){
$0.fillColor = iconColor.cgColor
$0.path = UIBezierPath(rect: CGRect(origin: shapeOrigin, size: contentRegion.size)).cgPath
$0.mask = iconMask
}
self.layer.addSublayer(iconLayer)
}
}
// MARK : animation
extension FaveIcon{
func animateSelect(_ isSelected: Bool = false, fillColor: UIColor, duration: Double = 0.5, delay: Double = 0){
if nil == tweenValues{
tweenValues = generateTweenValues(from: 0, to: 1.0, duration: CGFloat(duration))
}
CATransaction.begin()
CATransaction.setDisableActions(true)
iconLayer.fillColor = fillColor.cgColor
CATransaction.commit()
let selectedDelay = isSelected ? delay : 0
if isSelected{
self.alpha = 0
UIView.animate(
withDuration: 0,
delay: selectedDelay,
options: .curveLinear,
animations: {
self.alpha = 1
}, completion: nil)
}
let scaleAnimation = Init(CAKeyframeAnimation(keyPath: "transform.scale")){
$0.values = tweenValues!
$0.duration = duration
$0.beginTime = CACurrentMediaTime()+selectedDelay
}
iconMask.add(scaleAnimation, forKey: nil)
}
func generateTweenValues(from: CGFloat, to: CGFloat, duration: CGFloat) -> [CGFloat]{
var values = [CGFloat]()
let fps = CGFloat(60.0)
let tpf = duration/fps
let c = to-from
let d = duration
var t = CGFloat(0.0)
let tweenFunction = Elastic.ExtendedEaseOut
while(t < d){
let scale = tweenFunction(t, from, c, d, c+0.001, 0.39988) // p=oscillations, c=amplitude(velocity)
values.append(scale)
t += tpf
}
return values
}
}
| apache-2.0 | 3f9821b040104be05fed0f278517b410 | 32.732394 | 114 | 0.595825 | 4.623552 | false | false | false | false |
kashesoft/kjob-apple | Sources/Command.swift | 1 | 4195 | /*
* Copyright (C) 2016 Andrey Kashaed
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
class Command : CustomStringConvertible {
enum Status {
case ready, launched, executing, succeeded, failed, suspended, canceled
}
private let id: Int64
private unowned let job: Job
private let worker: Worker
private let delay: Double?
private var block: (() -> ())!
private var task: DispatchWorkItem!
private var status: Status = .ready
private(set) var error: Error?
convenience init<O>(job: Job, worker: Worker, delay: Double?, action: Action<O>) {
let block = (O.self == Void.self) ? { [weak job] in
if let _ = job {
try action.act(())
}
} : { [weak job] in
if let _ = job {
for target in Shell.sharedInstance.getTargets() {
try action.act(target)
}
}
}
self.init(job: job, worker: worker, delay: delay, block: block)
}
convenience init<O>(job: Job, worker: Worker, delay: Double?, event: O) {
let block = { [weak job] in
if let _ = job {
for action in Shell.sharedInstance.getActions() {
try action.act(event)
}
}
}
self.init(job: job, worker: worker, delay: delay, block: block)
}
private init(job: Job, worker: Worker, delay: Double?, block: @escaping () throws -> Void) {
self.id = job.nextCommandId()
self.job = job
self.worker = worker
self.delay = delay
self.block = { [weak self] in
if let strongSelf = self {
objc_sync_enter(strongSelf)
defer {objc_sync_exit(strongSelf)}
if (strongSelf.status != .launched) {
return
}
strongSelf.error = nil
strongSelf.setStatus(.executing)
do {
try block()
strongSelf.setStatus(.succeeded)
} catch let error {
strongSelf.error = error
strongSelf.setStatus(.failed)
}
}
}
}
var description : String {
return "\(job).\(type(of: self)):\(id)"
}
func getStatus() -> Status {
objc_sync_enter(self)
defer {objc_sync_exit(self)}
return status
}
func getError() -> Error? {
return error
}
func launch() {
objc_sync_enter(self)
defer {objc_sync_exit(self)}
self.setStatus(.launched)
setUpTask()
worker.workUpTask(task, delay: delay)
}
func suspend() {
objc_sync_enter(self)
defer {objc_sync_exit(self)}
self.setStatus(.suspended)
}
func cancel() {
objc_sync_enter(self)
defer {objc_sync_exit(self)}
self.setStatus(.canceled)
if task != nil {
task.cancel()
}
}
private func setStatus(_ status: Status) {
Logger.log("<\(self)> status: \("\(self.status)".uppercased()) --> \("\(status)".uppercased())")
self.status = status
}
private func setUpTask() {
self.task = DispatchWorkItem(
qos: DispatchQoS.unspecified,
flags: DispatchWorkItemFlags.inheritQoS,
block: self.block
)
self.task.notify(
queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive),
execute: { [weak job] in job?.shiftCommand() }
)
}
}
| apache-2.0 | e0211880503b64c27a936c5fc5a42b4a | 29.179856 | 104 | 0.540644 | 4.477054 | false | false | false | false |
JadenGeller/Racer | Racer/RacerTests/RacerTests.swift | 1 | 3093 | //
// RacerTests.swift
// RacerTests
//
// Created by Jaden Geller on 10/21/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import XCTest
@testable import Racer
class RacerTests: XCTestCase {
func testSemaphore() {
let semaphore = Semaphore(value: 0)
dispatch {
semaphore.signal()
semaphore.wait()
semaphore.signal()
}
semaphore.wait()
semaphore.signal()
semaphore.wait()
}
func testMutex() {
let mutex = Mutex()
var array = [Int]()
dispatch {
mutex.acquire {
for i in 0...5 {
array.append(i)
usleep(5)
}
}
}
usleep(5)
dispatch {
mutex.acquire {
for i in 6...10 {
array.append(i)
}
}
}
// Let tests finish
sleep(1)
mutex.acquire {
XCTAssertEqual(Array(0...10), array)
}
}
func testRecursiveMutex() {
let mutex = RecursiveMutex()
func recursiveTester(x: Int) {
mutex.acquire {
if x > 0 { recursiveTester(x - 1) }
}
}
// Doesn't deadlock!
recursiveTester(10)
}
func testThreadLocal() {
let unique = ThreadLocal(defaultValue: 0)
dispatch {
unique.localValue = 1
dispatch {
unique.localValue = 2
XCTAssertEqual(2, unique.localValue)
}
usleep(20)
XCTAssertEqual(1, unique.localValue)
}
usleep(50)
XCTAssertEqual(0, unique.localValue)
}
func testCancelableSemaphore() {
let s = CancelableSemaphore(value: 1)
var count = 0
let expectedCount = 5
wait { dispatch in
for _ in 0..<5 {
dispatch {
do {
try s.wait()
print("Hooray")
}
catch {
print("Boo")
}
count++
}
}
usleep(50)
s.cancel()
}
XCTAssertEqual(expectedCount, count)
}
func testThreadSpecific() {
var threadIdentifier = ThreadSpecific { pthread_self() }
let savedCurrentThreadIdentifier = pthread_self()
var savedDisptchThreadIdentifier: pthread_t!
wait { dispatch in
dispatch {
savedDisptchThreadIdentifier = threadIdentifier.value
}
}
XCTAssertEqual(savedCurrentThreadIdentifier, threadIdentifier.value)
XCTAssertNotEqual(savedDisptchThreadIdentifier, threadIdentifier.value)
}
}
| mit | faa688fef29120ccabb16c26c946d73d | 21.903704 | 79 | 0.440815 | 5.358752 | false | true | false | false |
digipost/ios | Digipost-Test-Dpost Tests/XCTestCase+Convenience.swift | 1 | 1798 | //
// Copyright (C) Posten Norge AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import XCTest
extension XCTestCase {
class func jsonDictionaryFromFile(filename: String) -> Dictionary<String, AnyObject> {
let testBundle = NSBundle(forClass: OAuthTests.self)
let path = testBundle.pathForResource(filename, ofType: nil)
XCTAssertNotNil(path, "wrong filename")
let data = NSData(contentsOfFile: path!)
XCTAssertNotNil(data, "wrong filename")
var error : NSError?
let jsonDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments, error: &error) as Dictionary<String,AnyObject>
XCTAssertNil(error, "could not read json")
return jsonDictionary
}
class func mockTokenWithScope(scope: String) -> OAuthToken {
var oAuthDictionary: Dictionary <String,AnyObject>!
if scope == kOauth2ScopeFull {
oAuthDictionary = XCTestCase.jsonDictionaryFromFile("ValidOAuthToken.json")
} else {
oAuthDictionary = XCTestCase.jsonDictionaryFromFile("ValidOAuthTokenHigherSecurity.json")
}
let token = OAuthToken(attributes: oAuthDictionary, scope: scope)
return token!
}
}
| apache-2.0 | bc60a4e77aac235eee66ab76609ac7de | 39.863636 | 167 | 0.70634 | 4.794667 | false | true | false | false |
miktap/pepe-p06 | PePeP06/PePeP06Tests/TasoClientTests.swift | 1 | 4612 | //
// TasoClientTests.swift
// PePeP06Tests
//
// Created by Mikko Tapaninen on 24/12/2017.
//
import Quick
import Nimble
import ObjectMapper
import SwiftyBeaver
@testable import PePeP06
class TasoClientTests: QuickSpec {
override func spec() {
describe("Taso") {
var tasoClient: TasoClient!
beforeEach {
tasoClient = TasoClient()
tasoClient.initialize()
sleep(1)
}
describe("getTeam") {
it("gets PePe team") {
var teamListing: TasoTeamListing?
tasoClient.getTeam(team_id: "141460", competition_id: "lsfs1718", category_id: "FP12")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
teamListing = TasoTeamListing(JSONString: message!)
}
expect(teamListing?.team.team_name).toEventually(equal("PePe"), timeout: 3)
}
}
describe("getCompetitions") {
it("gets lsfs1718 competition") {
var competitionListing: TasoCompetitionListing?
tasoClient.getCompetitions()!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
competitionListing = TasoCompetitionListing(JSONString: message!)
}
expect(competitionListing?.competitions!).toEventually(containElementSatisfying({$0.competition_id == "lsfs1718"}), timeout: 3)
}
}
describe("getCategories") {
it("gets category FP12") {
var categoryListing: TasoCategoryListing?
tasoClient.getCategories(competition_id: "lsfs1718")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
categoryListing = TasoCategoryListing(JSONString: message!)
}
expect(categoryListing?.categories).toEventually(containElementSatisfying({$0.category_id == "FP12"}), timeout: 3)
}
}
describe("getClub") {
it("gets club 3077") {
var clubListing: TasoClubListing?
tasoClient.getClub()!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
clubListing = TasoClubListing(JSONString: message!)
}
expect(clubListing?.club?.club_id).toEventually(equal("3077"), timeout: 3)
}
}
describe("getPlayer") {
it("gets player Jimi") {
var playerListing: TasoPlayerListing?
tasoClient.getPlayer(player_id: "290384")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
playerListing = TasoPlayerListing(JSONString: message!)
}
expect(playerListing?.player?.first_name).toEventually(equal("Jimi"), timeout: 3)
}
}
describe("getGroup") {
it("gets group with team standings") {
var groupListing: TasoGroupListing?
tasoClient.getGroup(competition_id: "lsfs1718", category_id: "FP12", group_id: "1")!
.then { response -> Void in
let message = String(data: response.data!, encoding: .utf8)
log.debug(message!)
groupListing = TasoGroupListing(JSONString: message!)
}
expect(groupListing?.group?.teams).toNotEventually(beNil(), timeout: 3)
}
}
}
}
}
| mit | aa14940fef9b79b6284085f411332f38 | 40.927273 | 147 | 0.460104 | 5.464455 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCIRemoteNameRequestComplete.swift | 1 | 1151 | //
// HCIRemoteNameRequestComplete.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// HCI Remote Name Request Complete Event
@frozen
public struct HCIRemoteNameRequestComplete: HCIEventParameter {
public static let event = HCIGeneralEvent.remoteNameRequestComplete
public static let length = 255
public var status: HCIStatus
public var address: BluetoothAddress
public var name: String
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let statusByte = data[0]
guard let status = HCIStatus(rawValue: statusByte)
else { return nil }
self.status = status
self.address = BluetoothAddress(littleEndian: BluetoothAddress(bytes: (data[1], data[2], data[3], data[4], data[5], data[6])))
guard let name = String(data: data.subdataNoCopy(in: 7 ..< type(of: self).length), encoding: .utf8)
else { return nil }
self.name = name
}
}
| mit | 74ecd3790ab5ecb20f2a0e285b56e1c3 | 27.75 | 134 | 0.626087 | 4.423077 | false | false | false | false |
seanwoodward/IBAnimatable | IBAnimatable/ActivityIndicatorAnimationBallGridBeat.swift | 1 | 2021 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallGridBeat: ActivityIndicatorAnimating {
// MARK: Properties
private let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
// MARK: ActivityIndicatorAnimating
public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize = (size.width - circleSpacing * 2) / 3
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let durations = [0.96, 0.93, 1.19, 1.13, 1.34, 0.94, 1.2, 0.82, 1.19]
let beginTime = CACurrentMediaTime()
let beginTimes = [0.36, 0.4, 0.68, 0.41, 0.71, -0.15, -0.12, 0.01, 0.32]
let animation = self.animation
// Draw circles
for i in 0 ..< 3 {
for j in 0 ..< 3 {
let circle = ActivityIndicatorShape.Circle.createLayerWith(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j),
y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
width: circleSize,
height: circleSize)
animation.duration = durations[3 * i + j]
animation.beginTime = beginTime + beginTimes[3 * i + j]
circle.frame = frame
circle.addAnimation(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallGridBeat {
var animation: CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "opacity")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.7, 1]
animation.repeatCount = .infinity
animation.removedOnCompletion = false
return animation
}
}
| mit | 3c01bdc5b7c74d592e6578524c210ad0 | 33.254237 | 133 | 0.650668 | 4.11609 | false | false | false | false |
wikimedia/wikipedia-ios | WMF Framework/UIFont+WMFDynamicType.swift | 1 | 7851 | import UIKit
@objc(WMFFontFamily) public enum FontFamily: Int {
case system
case georgia
}
@objc (WMFDynamicTextStyle) public class DynamicTextStyle: NSObject {
@objc public static let subheadline = DynamicTextStyle(.system, .subheadline)
@objc public static let semiboldSubheadline = DynamicTextStyle(.system, .subheadline, .semibold)
public static let mediumSubheadline = DynamicTextStyle(.system, .subheadline, .medium)
public static let boldSubheadline = DynamicTextStyle(.system, .subheadline, .bold)
public static let italicSubheadline = DynamicTextStyle(.system, .subheadline, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let headline = DynamicTextStyle(.system, .headline)
public static let mediumHeadline = DynamicTextStyle(.system, .headline, .medium)
public static let semiboldHeadline = DynamicTextStyle(.system, .headline, .semibold)
public static let boldHeadline = DynamicTextStyle(.system, .headline, .bold)
public static let heavyHeadline = DynamicTextStyle(.system, .headline, .heavy)
public static let footnote = DynamicTextStyle(.system, .footnote)
public static let mediumFootnote = DynamicTextStyle(.system, .footnote, .medium)
@objc public static let semiboldFootnote = DynamicTextStyle(.system, .footnote, .semibold)
public static let italicFootnote = DynamicTextStyle(.system, .footnote, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let boldFootnote = DynamicTextStyle(.system, .footnote, .bold)
public static let boldTitle1 = DynamicTextStyle(.system, .title1, .bold)
public static let mediumTitle1 = DynamicTextStyle(.system, .title1, .medium)
public static let heavyTitle1 = DynamicTextStyle(.system, .title1, .heavy)
public static let boldTitle2 = DynamicTextStyle(.system, .title2, .bold)
public static let semiboldTitle3 = DynamicTextStyle(.system, .title3, .bold)
public static let callout = DynamicTextStyle(.system, .callout)
public static let semiboldCallout = DynamicTextStyle(.system, .callout, .semibold)
public static let boldCallout = DynamicTextStyle(.system, .callout, .bold)
public static let italicCallout = DynamicTextStyle(.system, .callout, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let title2 = DynamicTextStyle(.system, .title2)
public static let title3 = DynamicTextStyle(.system, .title3)
public static let body = DynamicTextStyle(.system, .body)
@objc public static let semiboldBody = DynamicTextStyle(.system, .body, .semibold)
public static let mediumBody = DynamicTextStyle(.system, .body, .medium)
public static let italicBody = DynamicTextStyle(.system, .body, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let caption1 = DynamicTextStyle(.system, .caption1)
public static let mediumCaption1 = DynamicTextStyle(.system, .caption1, .medium)
public static let caption2 = DynamicTextStyle(.system, .caption2)
public static let semiboldCaption2 = DynamicTextStyle(.system, .caption2, .semibold)
public static let mediumCaption2 = DynamicTextStyle(.system, .caption2, .medium)
public static let italicCaption2 = DynamicTextStyle(.system, .caption2, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let italicCaption1 = DynamicTextStyle(.system, .caption1, .regular, [UIFontDescriptor.SymbolicTraits.traitItalic])
public static let georgiaTitle3 = DynamicTextStyle(.georgia, .title3)
let family: FontFamily
let style: UIFont.TextStyle
let weight: UIFont.Weight
let traits: UIFontDescriptor.SymbolicTraits
init(_ family: FontFamily = .system, _ style: UIFont.TextStyle, _ weight: UIFont.Weight = .regular, _ traits: UIFontDescriptor.SymbolicTraits = []) {
self.family = family
self.weight = weight
self.traits = traits
self.style = style
}
func with(weight: UIFont.Weight) -> DynamicTextStyle {
return DynamicTextStyle(family, style, weight, traits)
}
func with(traits: UIFontDescriptor.SymbolicTraits) -> DynamicTextStyle {
return DynamicTextStyle(family, style, weight, traits)
}
func with(weight: UIFont.Weight, traits: UIFontDescriptor.SymbolicTraits) -> DynamicTextStyle {
return DynamicTextStyle(family, style, weight, traits)
}
}
public extension UITraitCollection {
var wmf_preferredContentSizeCategory: UIContentSizeCategory {
return preferredContentSizeCategory
}
}
fileprivate var fontCache: [String: UIFont] = [:]
public extension UIFont {
@objc(wmf_fontForDynamicTextStyle:) class func wmf_font(_ dynamicTextStyle: DynamicTextStyle) -> UIFont {
return UIFont.wmf_font(dynamicTextStyle, compatibleWithTraitCollection: UITraitCollection(preferredContentSizeCategory: .large))
}
class func wmf_scaledSystemFont(forTextStyle style: UIFont.TextStyle, weight: UIFont.Weight, size: CGFloat) -> UIFont {
return UIFontMetrics(forTextStyle: style).scaledFont(for: UIFont.systemFont(ofSize: size, weight: weight))
}
class func wmf_scaledSystemFont(forTextStyle style: UIFont.TextStyle, weight: UIFont.Weight, size: CGFloat, maximumPointSize: CGFloat) -> UIFont {
return UIFontMetrics(forTextStyle: style).scaledFont(for: UIFont.systemFont(ofSize: size, weight: weight), maximumPointSize: maximumPointSize)
}
@objc(wmf_fontForDynamicTextStyle:compatibleWithTraitCollection:) class func wmf_font(_ dynamicTextStyle: DynamicTextStyle, compatibleWithTraitCollection traitCollection: UITraitCollection) -> UIFont {
let fontFamily = dynamicTextStyle.family
let weight = dynamicTextStyle.weight
let traits = dynamicTextStyle.traits
let style = dynamicTextStyle.style
guard fontFamily != .system || weight != .regular || traits != [] else {
return UIFont.preferredFont(forTextStyle: style, compatibleWith: traitCollection)
}
let cacheKey = "\(fontFamily.rawValue)-\(weight.rawValue)-\(traits.rawValue)-\(style.rawValue)-\(traitCollection.preferredContentSizeCategory.rawValue)"
if let font = fontCache[cacheKey] {
return font
}
let size: CGFloat = UIFont.preferredFont(forTextStyle: style, compatibleWith: traitCollection).pointSize
var font: UIFont
switch fontFamily {
case .georgia:
// using the standard .with(traits: doesn't seem to work for georgia
let isBold = weight > UIFont.Weight.regular
let isItalic = traits.contains(.traitItalic)
if isBold && isItalic {
font = UIFont(descriptor: UIFontDescriptor(name: "Georgia-BoldItalic", size: size), size: 0)
} else if isBold {
font = UIFont(descriptor: UIFontDescriptor(name: "Georgia-Bold", size: size), size: 0)
} else if isItalic {
font = UIFont(descriptor: UIFontDescriptor(name: "Georgia-Italic", size: size), size: 0)
} else {
font = UIFont(descriptor: UIFontDescriptor(name: "Georgia", size: size), size: 0)
}
case .system:
font = weight != .regular ? UIFont.systemFont(ofSize: size, weight: weight) : UIFont.preferredFont(forTextStyle: style, compatibleWith: traitCollection)
if traits != [] {
font = font.with(traits: traits)
}
}
fontCache[cacheKey] = font
return font
}
func with(traits: UIFontDescriptor.SymbolicTraits) -> UIFont {
guard let descriptor = self.fontDescriptor.withSymbolicTraits(traits) else {
return self
}
return UIFont(descriptor: descriptor, size: 0)
}
}
| mit | a9718f34dd2e69aa0964d16d7f7275d1 | 50.651316 | 205 | 0.709719 | 4.828413 | false | false | false | false |
riosprogramming/JSON-Demo | JSON/ViewController.swift | 1 | 1477 | //
// ViewController.swift
// JSON
//
// Created by Thomas Denney on 14/08/2015.
// Copyright (c) 2015 Programming Thomas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
//Standard library request to http://httpbin.org
let session = NSURLSession.sharedSession()
//Prepare the request
let url = NSURL(string: "http://httpbin.org/get")!
let request = NSURLRequest(URL: url)
//Prepare the data task
let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//Warning: this closure is not executed on the main thread, so don't update the UI in here!
let httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
println(json)
println(json["url"]!)
}
})
//Begin the task
task.resume()
}
}
| apache-2.0 | 3c8e8a9daf08d28bc5d34b87850fceef | 31.108696 | 140 | 0.624238 | 5.040956 | false | false | false | false |
muhlenXi/SwiftEx | projects/ConditionBx/ConditionBx/main.swift | 1 | 2706 | //
// main.swift
// ConditionBx
//
// Created by 席银军 on 2017/9/8.
// Copyright © 2017年 muhlenXi. All rights reserved.
//
import Foundation
print("Hello, World!")
let apples = 5
let oranges = 3
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
print(quotation)
extension Array where Element: Comparable {
// 方式1
// mutating func mergeSort(_ begin: Index, end: Index) {
// if end - begin > 1 {
// let mid = (begin + end) / 2
//
// mergeSort(begin, end: mid)
// mergeSort(mid, end: end)
//
// merge(begin, mid, end)
// }
// }
//
// private mutating func merge(_ begin: Index, _ mid: Index, _ end: Index) {
//
// var tmp: [Element] = []
//
// var i = begin
// var j = mid
//
// while i != mid && j != end {
// if self[i] < self[j] {
// tmp.append(self[i])
// i += 1
// } else {
// tmp.append(self[j])
// j += 1
// }
// }
//
// tmp.append(contentsOf: self[i ..< mid])
// tmp.append(contentsOf: self[j ..< end])
//
// replaceSubrange(begin..<end, with: tmp)
// }
// 方式2
// 通过捕获局部变量共享资源
mutating func mergeSort(_ begin: Index, _ end: Index) {
var tmp: [Element] = []
tmp.reserveCapacity(count)
func merge(_ begin: Index, _ mid: Index, _ end: Index) {
tmp.removeAll(keepingCapacity: true)
var i = begin
var j = mid
while i != mid && j != end {
if self[i] > self[j] {
tmp.append(self[i])
i += 1
} else {
tmp.append(self[j])
j += 1
}
}
tmp.append(contentsOf: self[i..<mid])
tmp.append(contentsOf: self[j..<end])
replaceSubrange(begin..<end, with: tmp)
}
if end - begin > 1 {
let mid = (begin + end) / 2
mergeSort(begin, mid)
mergeSort(mid, end)
merge(begin, mid, end)
}
}
}
var numbers = [9, 7, 5, 3, 1, 6, 4, 2]
numbers.mergeSort(numbers.startIndex, numbers.endIndex)
print(numbers)
| mit | 8c9fe0aafd907e8a53d6468d2c089cbe | 20.666667 | 79 | 0.436398 | 3.867925 | false | false | false | false |
zhaobin19918183/zhaobinCode | HTK/HTK/HomeViewController/HomeViewController.swift | 1 | 11571 | //
// HomeViewController.swift
// HTK
//
// Created by 赵斌 on 16/5/16.
// Copyright © 2016年 赵斌. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class HomeViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,CLLocationManagerDelegate{
let locationManager:CLLocationManager = CLLocationManager()
var currLocation:CLLocation = CLLocation()
weak var weatherEntity : WeatherEntity?
weak var dataDic = NSMutableDictionary()
@IBOutlet weak var _weather: WeatherView!
@IBOutlet weak var _traffic: TrafficView!
@IBOutlet weak var collectionView: UICollectionView!
var progressHUD : MBProgressHUD!
var imageArray = ["basketball","football","news","wifi.jpg","jiazhao.jpg"]
var lineString:String!
override func viewDidLoad()
{
super.viewDidLoad()
location()
weatherCoredata()
weatherMoreButtonAction()
trafficViewSearchButtonAction()
_traffic.pickerView = self.parentViewController!
collectionView.registerNib(UINib(nibName: "HomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CollectionCellID")
rxTextFieldCocoa()
}
//MARK:CollectionView
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 5
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 1;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
var cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellID", for: indexPath as IndexPath) as? HomeCollectionViewCell
if cell == nil
{
let nibArray : NSArray = NSBundle.mainBundle().loadNibNamed("HomeCollectionViewCell", owner:self, options:nil)
cell = nibArray.firstObject as? HomeCollectionViewCell
}
cell?.backgroundimagView.image = UIImage(named: imageArray[indexPath.row])
return cell!
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
print(indexPath.row)
}
//MARK:weatherMoreButtonAction
func weatherMoreButtonAction()
{
_weather.moreButton.addTarget(self, action:#selector(HomeViewController.moreWeather), forControlEvents: UIControlEvents.TouchDown)
}
//MARK:trafficViewSearchButtonAction
func trafficViewSearchButtonAction()
{
_traffic.searchButton.addTarget(self, action:#selector(HomeViewController.searchTraffic), forControlEvents: UIControlEvents.TouchDown)
}
//MARK:searchTraffic
func searchTraffic()
{
self.prpgressHud()
// DataLogicJudgment()
alamofireRequestData()
}
//MARK: 数据逻辑判断 回家在做 啦啦啦啦
func DataLogicJudgment()
{
//1.查询方式选择
//2.线路添加,换乘方案,站台.
//|| _traffic.lineTextField.text == nil
if _traffic.project == nil
{
self.progressHUD.hide(true, afterDelay:0)
//数据添加错误
}
else
{
print("判断 ===== \(_traffic.project)")
if _traffic.project == "1"
{
//线路
}
if _traffic.project == "2"
{
//车辆
}
if _traffic.project == "3"
{
//换乘
}
}
}
//MARK:bus申请数据
func alamofireRequestData()
{
if self.lineString == nil {
let okAction:UIAlertAction = UIAlertAction(title: Common_OK, style: UIAlertActionStyle.Default) {
(action: UIAlertAction!) -> Void in
self.progressHUD.hide(true, afterDelay:0.25)
}
AlertControllerAction(Common_Warning, message: "公交线路输入为空", firstAction:okAction, seccondAction: nil,thirdAction:nil)
self.progressHUD.hide(true, afterDelay:0)
}
else
{
// NetWorkManager.alamofireRequestData("大连", bus:self.lineString, url: Common_busUrl)
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.successAction), name: "alamofireSuccess", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.errorAction), name: "alamofireError", object: nil)
}
//MARK:error
func errorAction()
{
NSNotificationCenter.defaultCenter().removeObserver(self, name: "alamofireError", object: nil)
let errorAction:UIAlertAction = UIAlertAction(title: Common_OK, style: UIAlertActionStyle.Default) {
(action: UIAlertAction!) -> Void in
self.progressHUD.hide(true, afterDelay:0)
}
AlertControllerAction(Common_Warning, message: "公交线路输入错误", firstAction:errorAction, seccondAction: nil,thirdAction:nil)
}
//MARK:AlertControllerAction
func AlertControllerAction(title:String , message:String ,firstAction:UIAlertAction,seccondAction:UIAlertAction?,thirdAction:UIAlertAction?)
{
let alert = UIAlertController(title:title, message:message, preferredStyle:UIAlertControllerStyle.Alert)
alert.addAction(firstAction)
if seccondAction != nil
{
alert.addAction(seccondAction!)
}
if thirdAction != nil
{
alert.addAction(thirdAction!)
}
self.presentViewController(alert, animated:true, completion:nil)
}
//MARK:successAction
func successAction()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let target = storyboard.instantiateViewControllerWithIdentifier("busTableViewViewController")
as! BusTableViewController
self.progressHUD.hide(true, afterDelay:0.25)
self.navigationController?.pushViewController(target, animated:true)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "alamofireSuccess", object: nil)
}
//MARK:MBProgressHUD
func prpgressHud()
{
progressHUD = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
progressHUD.labelText = "正在申请数据......"
//背景渐变效果
progressHUD.dimBackground = true
}
//MARK:moreWeather
func moreWeather()
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let target = storyboard.instantiateViewControllerWithIdentifier("moreWeatherViewController")
self.navigationController?.pushViewController(target, animated:true)
}
//MARK:netWorkAlert
func netWorkAlert()
{
let alert = UIAlertController(title:"提示", message:"无网络连接", preferredStyle:UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "好的", style: UIAlertActionStyle.Default) {
(action: UIAlertAction!) -> Void in
exit(0)
}
alert.addAction(okAction)
self.presentViewController(alert, animated:true, completion:nil)
}
//MARK:weatherAlamofire
func weatherAlamofire()
{
self.prpgressHud()
// NetWorkManager.alamofireWeatherRequestData("大连", url: "http://op.juhe.cn/onebox/weather/query", key: "e527188bbf687ccccac5350acf9a151f", dtype: "json")
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.weatherData), name: "TimeOut", object: nil)
// NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.weatherData), name: "WeatherData", object: nil)
}
func weatherData(notification:NSNotification)
{
if (notification.object?.localizedDescription == "The request timed out.")
{
let errorAction:UIAlertAction = UIAlertAction(title: Common_OK, style: UIAlertActionStyle.Default) {
(action: UIAlertAction!) -> Void in
self.progressHUD.hide(true, afterDelay:0)
}
AlertControllerAction(Common_Warning, message: "网络申请超时,将使用本地数据!!!!", firstAction:errorAction, seccondAction: nil,thirdAction:nil)
}
self.dataFunc()
NSNotificationCenter.defaultCenter().removeObserver(self, name:"WeatherData", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name:"TimeOut", object: nil)
}
func weatherCoredata()
{
let status = Reach().connectionStatus()
if (!(NSUserDefaults.standardUserDefaults().boolForKey("everLaunched"))) {
NSUserDefaults.standardUserDefaults().setBool(true, forKey:"everLaunched")
if status.description == "Offline"
{
netWorkAlert()
}
else
{
weatherAlamofire()
}
}
else
{
if status.description == "Offline"
{
dataFunc()
}
else
{
weatherAlamofire()
}
}
}
func dataFunc()
{
self.progressHUD.hide(true, afterDelay:0)
let weatherModel = WeatherDAO.SearchWeatherModel()
let dictionary:NSDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(weatherModel.realtime! )! as! NSDictionary
_weather.weatherDic(dictionary)
}
//MARK: - 地图
func location()
{
//设置定位服务管理器代理
locationManager.delegate = self
//设置定位进度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//更新距离
locationManager.distanceFilter = 100
//发送授权申请
locationManager.requestAlwaysAuthorization()
if (CLLocationManager.locationServicesEnabled())
{
//允许使用定位服务的话,开启定位服务更新
locationManager.startUpdatingLocation()
print("定位开始")
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//获取最新的坐标
currLocation = locations.last!
print( "经度:\(currLocation.coordinate.longitude)")
print( "纬度:\(currLocation.coordinate.latitude)")
LonLatToCity()
}
///将经纬度转换为城市名
func LonLatToCity() {
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
if(error == nil)
{
let array = placemark! as NSArray
let mark = array.firstObject as! CLPlacemark
//城市
let city: String = (mark.addressDictionary! as NSDictionary).valueForKey("City") as! String
print((mark.addressDictionary! as NSDictionary).allKeys)
print(city)
}
else
{
print(error)
}
}
}
}
| gpl-3.0 | 5fe0e5427a75c6410db375814eeb1171 | 33.152439 | 161 | 0.6173 | 5.117405 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/push-dominoes.swift | 1 | 1214 | class Solution {
func pushDominoes(_ dominoes: String) -> String {
var op = [(Int, String)]()
op.append((-1, "L"))
for (index, c) in dominoes.enumerated() {
let text = String(c)
if text != "." {
op.append((index, text))
}
}
op.append((dominoes.count, "R"))
var result = Array(dominoes)
for index in stride(from: 1, to: op.count, by: 1) {
var (start, t1) = op[index - 1]
var (end, t2) = op[index]
if t1 == t2 {
for idx in stride(from: start + 1, to: end, by: 1) {
result[idx] = Character(t1)
}
} else if t1 + t2 == "RL" {
start += 1
end -= 1
while start <= end {
if start == end {
result[start] = Character(".")
} else {
result[start] = Character("R")
result[end] = Character("L")
}
start += 1
end -= 1
}
}
}
return String(result)
}
}
| mit | c6601ef64064e8d10ff1469f16509644 | 31.810811 | 68 | 0.365733 | 4.215278 | false | false | false | false |
hejunbinlan/Carlos | Tests/NSDateFormatterTransformerTests.swift | 2 | 1195 | import Foundation
import Quick
import Nimble
import Carlos
class NSDateFormatterTransformerTests: QuickSpec {
override func spec() {
describe("NSDateFormatter") {
var formatter: NSDateFormatter!
beforeEach {
formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
}
context("when used as a transformer") {
context("when transforming") {
let originDate = NSDate(timeIntervalSince1970: 1436644623)
var resultString: String!
beforeEach {
resultString = formatter.transform(originDate)
}
it("should return the expected string") {
expect(resultString).to(equal("2015-07-11"))
}
}
context("when inverse transforming") {
let originString = "2015-07-11"
var resultDate: NSDate!
beforeEach {
resultDate = formatter.inverseTransform(originString)
}
it("should return the expected date") {
expect(formatter.stringFromDate(resultDate)).to(equal(originString))
}
}
}
}
}
} | mit | d7609779bed02d8e7ed3bc2301f6bb35 | 25.577778 | 80 | 0.56569 | 5.358744 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Profile/UserProfileImageViewController.swift | 1 | 2310 | //
// UserProfileImageViewController.swift
// AllStars
//
// Created by Ricardo Hernan Herrera Valle on 8/10/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import Foundation
class UserProfileImageViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var btnBack : UIButton!
@IBOutlet weak var userImageView : UIImageView!
@IBOutlet weak var viewHeader : UIView!
// MARK: - Properties
var userImage: UIImage! {
didSet {
if self.isViewLoaded() {
self.userImageView.image = userImage
}
}
}
// MARK: - Initializaion
override func viewDidLoad() {
super.viewDidLoad()
setViewsStyle()
self.userImageView.image = userImage
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(UserProfileImageViewController.clickBtnBack(_:)))
self.userImageView.userInteractionEnabled = true
self.userImageView.addGestureRecognizer(tapGesture)
}
// MARK: - UI
func setViewsStyle() {
viewHeader.backgroundColor = UIColor.colorPrimary()
}
// MARK: - User interaction
@IBAction func clickBtnBack(sender: AnyObject) {
var newFrame = self.viewHeader.frame
newFrame.size.height = 114.0
UIView.animateWithDuration(0.5, delay: 0.0,
options: [], animations: {
self.userImageView.frame.size = CGSizeMake(120.0, 120.0)
self.userImageView.center = CGPointMake(self.view.center.x, 70.0)
self.viewHeader.frame = newFrame
}) { (success) in
self.userImageView.layer.cornerRadius = 60.0
self.dismissViewController()
}
}
// MARK: - Navigation
func dismissViewController() {
self.dismissViewControllerAnimated(false, completion: nil)
}
// MARK: - UIScrollViewDelegate
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.userImageView
}
}
| mit | 7f87dd189d1654fba7260c5789877bdc | 29.381579 | 129 | 0.566046 | 5.445755 | false | false | false | false |
Greenlite/ios-test-URL-inet | I OS Test/I OS Test/RegisterPageViewController.swift | 1 | 4882 | //
// RegisterPageViewController.swift
// I OS Test // swift 3.0
//
// Created by Sergey Matveev on 25/12/2016.
// Copyright © 2016 Greenlite.cg. All rights reserved.
//
import UIKit
class RegisterPageViewController: UIViewController {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var repeatPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerButtonTapped(_ sender: Any) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userRepeatPassword = repeatPasswordTextField.text;
// Check for empty fields
if userEmail!.isEmpty || userPassword!.isEmpty || userRepeatPassword!.isEmpty
{
//display alert message
displayMyAlertMessage(userMessege: "All field are required ");
return;
}
// Check if password match
if (userPassword != userRepeatPassword)
{
displayMyAlertMessage(userMessege: "passwords do not match");
return;
}
//Send user data to server side
let myUrl = NSURL(string: "htpp://yandec.ur/user-register/userRegister.php")
let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST";
let postString = "email=\(userEmail)&password=\(userPassword)";
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
let json = try! JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON ["status"] as? String
print ("result: \(resultValue)")
var isUserRegister:Bool = false;
if (resultValue == "Succes") {isUserRegister = true; }
var messegeToDisplay:String = parseJSON ["message"] as! String!;
if (!isUserRegister)
{
messegeToDisplay = parseJSON ["message"] as! String!;
}
DispatchQueue.main.async(execute: {
// display alert mesage with confirmation
let myAlert = UIAlertController(title:"Alert", message: messegeToDisplay, preferredStyle:UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title:"ok", style:UIAlertActionStyle.default){
action in self.dismiss(animated: true, completion:nil);
}
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
});
}
}
task.resume()
}
// displayMYAlertmessege func
func displayMyAlertMessage(userMessege:String)
{
let myAlert = UIAlertController(title:"Alert", message:userMessege, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
/*
// 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.
}
*/
}
| mit | 6758a4012ae0ec755eaeffb203104a89 | 27.377907 | 138 | 0.516902 | 6.124216 | false | false | false | false |
team-pie/DDDKit | DDDKit/Classes/DDDShaderProgram.swift | 1 | 5423 | //
// DDDShaderProgram.swift
// DDDKit
//
// Created by Guillaume Sabran on 9/27/16.
// Copyright © 2016 Guillaume Sabran. All rights reserved.
//
import UIKit
/**
A shader program that describes how object should look like.
It's made of a vertex and fragment shaders
*/
public class DDDShaderProgram: DDDObject {
enum Uniforms {
case projection
case modelView
}
private var uniformLocations = [String: GLint]()
private var attributeLocations = [String: GLuint]()
private var attributes: NSMutableArray
private var uniforms: NSMutableArray
private(set) var vertex: DDDVertexShader?
private(set) var fragment: DDDFragmentShader?
private var program: GLuint
var programReference: GLuint {
return program
}
let shaderModifiers: [DDDShaderEntryPoint: String]?
/// The original code for the vertex shader, before optional shader modifiers are applied
public private(set) var originalVertexShader: String
/// The original code for the fragment shader, before optional shader modifiers are applied
public private(set) var originalFragmentShader: String
private static func addShaderModifier(to shader: DDDShader, modifier: String) {
var shaderCode = String(shader.originalCode)
var parts = modifier.components(separatedBy: "#pragma body")
var bodyModifier = parts.popLast() ?? ""
var headerModifier = parts.popLast() ?? ""
let lines = bodyModifier.components(separatedBy: "\n")
lines.forEach { line in
if line.contains("uniform") {
headerModifier.append(line + "\n")
}
}
bodyModifier = lines.filter { return !$0.contains("uniform") }.joined(separator: "\n")
shaderCode = shaderCode.replacingOccurrences(of: "// body modifier here", with: bodyModifier)
shaderCode = shaderCode.replacingOccurrences(of: "// header modifier here", with: headerModifier)
shader.code = NSString(string: shaderCode)
}
/**
Create a shader program
- Parameter vShader: the vertex shader, defaulting to a simple one
- Parameter fShader: the vertex shader, defaulting to a red one
- Parameter shaderModifiers: (optional) a set of modifications to be applied to the shaders. See the DDDShaderEntryPoint description
*/
public init(
vertex vShader: DDDVertexShader? = nil,
fragment fShader: DDDFragmentShader? = nil,
shaderModifiers: [DDDShaderEntryPoint: String]? = nil
) throws {
self.shaderModifiers = shaderModifiers
let vertex = vShader ?? DDDDefaultVertexShader()
self.vertex = vertex
let fragment = fShader ?? DDDDefaultFragmentShader()
self.fragment = fragment
self.originalVertexShader = String(vertex.originalCode)
self.originalFragmentShader = String(fragment.originalCode)
let vModifier = shaderModifiers?[.geometry] ?? ""
DDDShaderProgram.addShaderModifier(to: vertex, modifier: vModifier)
let fModifier = shaderModifiers?[.fragment] ?? ""
DDDShaderProgram.addShaderModifier(to: fragment, modifier: fModifier)
try vertex.compile()
try fragment.compile()
self.attributes = []
self.uniforms = []
self.program = glCreateProgram()
super.init()
glAttachShader(program, vertex.shaderReference)
glAttachShader(program, fragment.shaderReference)
glEnable(GLenum(GL_CULL_FACE))
// those attributes should always be here
addAttribute(named: "position")
addAttribute(named: "texCoord")
try setUp()
}
deinit {
if program != 0 {
glDeleteProgram(program);
program = 0;
}
}
func addAttribute(named name: String) {
if !attributes.contains(name) {
self.attributes.add(name)
glBindAttribLocation(program, GLuint(attributes.index(of: name)), NSString(string: name).utf8String)
}
}
func indexFor(attributeNamed name: String) -> GLuint {
guard let cachedIdx = attributeLocations[name] else {
let idx = GLuint(attributes.index(of: name))
attributeLocations[name] = idx
return idx
}
return cachedIdx
}
func indexFor(uniformNamed name: String) -> GLint {
guard let cachedIdx = uniformLocations[name] else {
let idx = GLint(glGetUniformLocation(program, NSString(string: name).utf8String))
uniformLocations[name] = idx
return idx
}
return cachedIdx
}
private func setUp() throws {
glLinkProgram(program)
var success = GLint()
glGetProgramiv(program, GLenum(GL_LINK_STATUS), &success)
if success == GL_FALSE {
throw DDDError.programFailedToLink
}
vertex = nil
fragment = nil
}
func use() {
glUseProgram(program)
}
}
/**
Shader modifiers alter the code of a shader. They make it easy to reuse generic shader logic.
Each modifier can contains two parts that will be inserted in different places:
- a body part that should inserted in the _main_ function. It's used to change computation.
- a pre-body part that should be inserted before the _main_ function. It's used to declare variables.
The exact place they are inserted is at the commented lines _"// header modifier here"_ and _"// body modifier here"_ that should be part of the code of the shader that should support modifiers. In the absence of such lines, the modifiers will be ignores.
The modifier is passed as a simple string of code. The pre-body will correspond to the _uniform_ variables, and optinally everything put before a line _#pragma body_ The body part is everything else.
*/
public enum DDDShaderEntryPoint {
/// A modification to be applied in the geometry computation
case geometry
/// A modification to be applied in the pixel computation
case fragment
}
| mit | 0e0030fad50967922b8e1020b72cee7e | 30.523256 | 255 | 0.743268 | 3.861823 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Camera/CameraController.swift | 1 | 10695 | ////
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireSystem
import UIKit
import AVFoundation
private let zmLog = ZMSLog(tag: "UI")
final class CameraController {
private(set) var currentCamera: SettingsCamera
var previewLayer: AVCaptureVideoPreviewLayer!
private enum SetupResult { case success, notAuthorized, failed }
private var setupResult: SetupResult = .success
private var session = AVCaptureSession()
private let sessionQueue = DispatchQueue(label: "com.wire.camera_controller_session")
private var frontCameraDeviceInput: AVCaptureDeviceInput?
private var backCameraDeviceInput: AVCaptureDeviceInput?
private var isSwitching = false
private var canSwitchInputs: Bool = false
private let photoOutput = AVCapturePhotoOutput()
private var captureDelegates = [Int64: PhotoCaptureDelegate]()
init?(camera: SettingsCamera) {
guard !UIDevice.isSimulator else { return nil }
currentCamera = camera
setupSession()
previewLayer = AVCaptureVideoPreviewLayer(session: session)
}
// MARK: - Session Management
private func requestAccess() {
sessionQueue.suspend()
AVCaptureDevice.requestAccess(for: .video) { granted in
self.setupResult = granted ? .success : .notAuthorized
self.sessionQueue.resume()
}
}
private func setupSession() {
switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized: break
case .notDetermined: requestAccess()
default: setupResult = .notAuthorized
}
sessionQueue.async(execute: configureSession)
}
private func configureSession() {
guard setupResult == .success else { return }
session.beginConfiguration()
defer { session.commitConfiguration() }
session.sessionPreset = .photo
// SETUP INPUTS
let availableInputs = [AVCaptureDevice.Position.front, .back]
.compactMap { cameraDevice(for: $0) }
.compactMap { try? AVCaptureDeviceInput(device: $0) }
.filter { session.canAddInput($0) }
switch availableInputs.count {
case 1:
let input = availableInputs.first!
if input.device.position == .front {
currentCamera = .front
frontCameraDeviceInput = input
} else {
currentCamera = .back
backCameraDeviceInput = input
}
case 2:
frontCameraDeviceInput = availableInputs.first!
backCameraDeviceInput = availableInputs.last!
canSwitchInputs = true
default:
zmLog.error("CameraController could not add any inputs.")
setupResult = .failed
return
}
connectInput(for: currentCamera)
// SETUP OUTPUTS
guard session.canAddOutput(photoOutput) else {
zmLog.error("CameraController could not add photo capture output.")
setupResult = .failed
return
}
session.addOutput(photoOutput)
}
func startRunning() {
sessionQueue.async { self.session.startRunning() }
}
func stopRunning() {
sessionQueue.async { self.session.stopRunning() }
}
// MARK: - Device Management
/**
* The capture device for the given camera position, if available.
*/
private func cameraDevice(for position: AVCaptureDevice.Position) -> AVCaptureDevice? {
return AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position)
}
/**
* The device input for the given camera, if available.
*/
private func input(for camera: SettingsCamera) -> AVCaptureDeviceInput? {
switch camera {
case .front: return frontCameraDeviceInput
case .back: return backCameraDeviceInput
}
}
/**
* Connects the input for the given camera, if it is available.
*/
private func connectInput(for camera: SettingsCamera) {
guard
let input = input(for: camera),
session.canAddInput(input)
else { return }
sessionQueue.async {
self.session.beginConfiguration()
self.session.addInput(input)
self.currentCamera = camera
self.session.commitConfiguration()
}
}
/**
* Disconnects the current camera and connects the given camera, but only
* if both camera inputs are available. The completion callback is passed
* a boolean value indicating whether the change was successful.
*/
func switchCamera(completion: @escaping (_ currentCamera: SettingsCamera) -> Void) {
let newCamera = currentCamera == .front ? SettingsCamera.back : .front
guard
!isSwitching, canSwitchInputs,
let toRemove = input(for: currentCamera),
let toAdd = input(for: newCamera)
else { return completion(currentCamera) }
isSwitching = true
sessionQueue.async {
self.session.beginConfiguration()
self.session.removeInput(toRemove)
self.session.addInput(toAdd)
self.currentCamera = newCamera
self.session.commitConfiguration()
DispatchQueue.main.async {
completion(newCamera)
self.isSwitching = false
}
}
}
/**
* Updates the orientation of the video preview layer to best fit the
* device/ui orientation.
*/
func updatePreviewOrientation() {
guard
let connection = previewLayer.connection,
connection.isVideoOrientationSupported
else { return }
connection.videoOrientation = AVCaptureVideoOrientation.current
}
// MARK: - Image Capture
typealias PhotoResult = (data: Data?, error: Error?)
/**
* Asynchronously attempts to capture a photo within the currently
* configured session. The result is passed into the given handler
* callback.
*/
func capturePhoto(_ handler: @escaping (PhotoResult) -> Void) {
// For iPad split/slide over mode, the session is not running.
guard session.isRunning else { return }
let currentOrientation = AVCaptureVideoOrientation.current
sessionQueue.async {
guard let connection = self.photoOutput.connection(with: .video) else { return }
connection.videoOrientation = currentOrientation
connection.automaticallyAdjustsVideoMirroring = false
connection.isVideoMirrored = false
let jpegType = AVVideoCodecType.jpeg
let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: jpegType,
AVVideoCompressionPropertiesKey: [AVVideoQualityKey: 0.9]])
let delegate = PhotoCaptureDelegate(settings: settings, handler: handler) {
self.sessionQueue.async { self.captureDelegates[settings.uniqueID] = nil }
}
self.captureDelegates[settings.uniqueID] = delegate
self.photoOutput.capturePhoto(with: settings, delegate: delegate)
}
}
/**
* A PhotoCaptureDelegate is responsible for processing the photo buffers
* returned from `AVCapturePhotoOutput`. For each photo captured, there is
* one unique delegate object responsible.
*/
private class PhotoCaptureDelegate: NSObject, AVCapturePhotoCaptureDelegate {
private let settings: AVCapturePhotoSettings
private let handler: (PhotoResult) -> Void
private let completion: () -> Void
init(settings: AVCapturePhotoSettings,
handler: @escaping (PhotoResult) -> Void,
completion: @escaping () -> Void) {
self.settings = settings
self.handler = handler
self.completion = completion
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
defer { completion() }
if let error = error {
zmLog.error("PhotoCaptureDelegate encountered error while processing photo:\(error.localizedDescription)")
handler(PhotoResult(nil, error))
return
}
let imageData = photo.fileDataRepresentation()
handler(PhotoResult(imageData, nil))
}
}
}
private extension AVCaptureVideoOrientation {
/// The video orientation matches against first the device orientation,
/// then the interface orientation. Must be called on the main thread.
static var current: AVCaptureVideoOrientation {
let device = UIDevice.current.orientation
let ui = UIWindow.interfaceOrientation ?? .unknown
let deviceOrientation = self.init(deviceOrientation: device)
let uiOrientation = self.init(uiOrientation: ui)
return uiOrientation ?? deviceOrientation ?? .portrait
}
/// convert UIDeviceOrientation to AVCaptureVideoOrientation except face up/down
///
/// - Parameter deviceOrientation: a UIDeviceOrientation
init?(deviceOrientation: UIDeviceOrientation) {
switch deviceOrientation {
case .landscapeLeft: self = .landscapeRight
case .portrait: self = .portrait
case .landscapeRight: self = .landscapeLeft
case .portraitUpsideDown: self = .portraitUpsideDown
default: return nil
}
}
init?(uiOrientation: UIInterfaceOrientation) {
switch uiOrientation {
case .landscapeLeft: self = .landscapeLeft
case .portrait: self = .portrait
case .landscapeRight: self = .landscapeRight
case .portraitUpsideDown: self = .portraitUpsideDown
default: return nil
}
}
}
| gpl-3.0 | f54aba6d310150f82418ce2172ee22c7 | 32.952381 | 122 | 0.636653 | 5.481804 | false | false | false | false |
babarqb/HackingWithSwift | project22/Project22/ViewController.swift | 25 | 2166 | //
// ViewController.swift
// Project22
//
// Created by Hudzilla on 16/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import CoreLocation
import UIKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var distanceReading: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
view.backgroundColor = UIColor.grayColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways {
if CLLocationManager.isMonitoringAvailableForClass(CLBeaconRegion.self) {
if CLLocationManager.isRangingAvailable() {
startScanning()
}
}
}
}
func startScanning() {
let uuid = NSUUID(UUIDString: "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5")!
let beaconRegion = CLBeaconRegion(proximityUUID: uuid, major: 123, minor: 456, identifier: "MyBeacon")
locationManager.startMonitoringForRegion(beaconRegion)
locationManager.startRangingBeaconsInRegion(beaconRegion)
}
func updateDistance(distance: CLProximity) {
UIView.animateWithDuration(0.8) { [unowned self] in
switch distance {
case .Unknown:
self.view.backgroundColor = UIColor.grayColor()
self.distanceReading.text = "UNKNOWN"
case .Far:
self.view.backgroundColor = UIColor.blueColor()
self.distanceReading.text = "FAR"
case .Near:
self.view.backgroundColor = UIColor.orangeColor()
self.distanceReading.text = "NEAR"
case .Immediate:
self.view.backgroundColor = UIColor.redColor()
self.distanceReading.text = "RIGHT HERE"
}
}
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
if beacons.count > 0 {
let beacon = beacons[0]
updateDistance(beacon.proximity)
} else {
updateDistance(.Unknown)
}
}
}
| unlicense | 48d38559cc67b498dda198d12643cf72 | 25.728395 | 121 | 0.74642 | 4.084906 | false | false | false | false |
hirooka/chukasa-ios | chukasa-ios/src/controller/ChukasaPhoneM4vViewController.swift | 1 | 1216 | import UIKit
import CoreData
class ChukasaPhoneM4vViewController: UIViewController, URLSessionDelegate, ChukasaCoreDataOperatorDelegate , ChukasaM4vDownloaderDelegate {
let M4V_FILE_API = "api/v1/m4v/"
let chukasaCoreDataOperator = ChukasaCoreDataOperator()
let m4vDownloader = ChukasaM4vDownloader()
var name = ""
override func viewDidLoad() {
super.viewDidLoad()
m4vDownloader.delegate = self
var chukasaServerDestination = ChukasaServerDestination()
let chukasaServerDestinationArray = chukasaCoreDataOperator.fetch("ChukasaServerDestination", key: "id", ascending: true)
if chukasaServerDestinationArray.count == 1 {
chukasaServerDestination = EntityConvertor.convertChukasaServerDestination(chukasaServerDestinationArray[0] as AnyObject)
}
m4vDownloader.download(chukasaServerDestination, name: name, type: M4vType.PHONE)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Delegate
func completeDownloading(_ url: URL) {
print("##### \(#file) - \(#function)")
print("\(url.absoluteString)")
}
}
| mit | 872417480d79318ff1e49b6bb8fa7882 | 32.777778 | 139 | 0.692434 | 4.342857 | false | false | false | false |
horizon-institute/babyface-ios | src/view controllers/DataViewController.swift | 1 | 6113 | //
// DataViewController.swift
// babyface
//
// Created by Kevin Glover on 16/04/2015.
// Copyright (c) 2015 Horizon. All rights reserved.
//
import Foundation
import UIKit
class DataViewController: PageViewController, UITextFieldDelegate
{
override func viewDidLoad()
{
super.viewDidLoad()
registerForKeyboardNotifications()
// if pageController?.babyData.weight != 0
// {
// weightField.text = "\(pageController!.babyData.weight)"
// }
// if pageController?.babyData.gender == "Girl"
// {
// genderSelect.selectedSegmentIndex = 0
// }
// else if pageController?.babyData.gender == "Boy"
// {
// genderSelect.selectedSegmentIndex = 1
// }
//
//
// if pageController?.babyData.ethnicity == "White"
// {
// ethnicitySelect.selectedSegmentIndex = 0
// }
// else if pageController?.babyData.ethnicity == "Asian"
// {
// ethnicitySelect.selectedSegmentIndex = 1
// }
// else if pageController?.babyData.ethnicity == "Black"
// {
// ethnicitySelect.selectedSegmentIndex = 2
// }
// else if pageController?.babyData.ethnicity == "Mixed"
// {
// ethnicitySelect.selectedSegmentIndex = 3
// }
// else if pageController?.babyData.ethnicity == "Other"
// {
// ethnicitySelect.selectedSegmentIndex = 4
// }
// ageSlider.value = Float(-(pageController!.babyData.age))
// dueSlider.value = Float(pageController!.babyData.due)
// birthChanged(ageSlider)
// dueDateChanged(dueSlider)
// weightField.delegate = self
update()
}
@IBAction func birthChanged(sender: AnyObject)
{
if let slider = sender as? UISlider
{
let value = Int(-slider.value)
// pageController?.babyData.age = value
if value == 0
{
// birthText.text = "Born today"
}
else if value == -1
{
// birthText.text = "Born 1 day ago"
}
else
{
// birthText.text = "Born \(value) days ago"
}
}
}
override func viewWillDisappear(animated: Bool)
{
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardDidShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillHideNotification,
object: nil)
}
func registerForKeyboardNotifications()
{
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(DataViewController.keyboardWillShow(_:)),
name: UIKeyboardWillShowNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: #selector(DataViewController.keyboardWillBeHidden(_:)),
name: UIKeyboardWillHideNotification,
object: nil)
}
func keyboardWillShow(notification: NSNotification)
{
if UIDevice.currentDevice().userInterfaceIdiom == .Pad
{
// var info = notification.userInfo!
// let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
UIView.animateWithDuration(0.1, animations: { () -> Void in
// self.bottomConstraint.constant = keyboardFrame.size.height + 16
})
}
}
func keyboardWillBeHidden(notification: NSNotification)
{
//var info = notification.userInfo!
//var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
UIView.animateWithDuration(0.1, animations: { () -> Void in
// self.bottomConstraint.constant = 16
})
}
@IBAction func weightChanged(sender: AnyObject)
{
// let formatter = NSNumberFormatter()
// if let weight = formatter.numberFromString(weightField.text!)?.floatValue
// {
// pageController?.babyData.weight = weight
// }
update()
}
@IBAction func dueDateChanged(sender: AnyObject)
{
if let slider = sender as? UISlider
{
let value = Int(slider.value)
// pageController?.babyData.due = value
if value == -1
{
// dueText.text = "Born 1 day early"
}
else if value == 1
{
// dueText.text = "Born 1 day late"
}
else if value == 0
{
// dueText.text = "Born on due date"
}
else if value < 0
{
// dueText.text = "Born \(-value) days early"
}
else
{
// dueText.text = "Born \(value) days late"
}
}
}
@IBAction func genderChanged(sender: AnyObject)
{
// if let segment = sender as? UISegmentedControl
// {
// pageController?.babyData.gender = segment.titleForSegmentAtIndex(segment.selectedSegmentIndex)!
// }
update()
}
@IBAction func ethnicityChanged(sender: AnyObject)
{
// if let segment = sender as? UISegmentedControl
// {
// pageController?.babyData.ethnicity = segment.titleForSegmentAtIndex(segment.selectedSegmentIndex)!
// }
update()
}
func endEditingNow()
{
// let formatter = NSNumberFormatter()
// if let weight = formatter.numberFromString(weightField.text!)?.floatValue
// {
// pageController?.babyData.weight = weight
// }
self.view.endEditing(true)
update()
}
func update()
{
// let enabled = pageController?.babyData.gender != nil && pageController?.babyData.weight != 0 && pageController?.babyData.ethnicity != nil
// if enabled != nextButton.enabled
// {
// nextButton.enabled = enabled
//pageController?.refresh(self)
//pageController?.refresh()
// }
}
// When clicking on the field, use this method.
func textFieldShouldBeginEditing(textField: UITextField) -> Bool
{
if UIDevice.currentDevice().userInterfaceIdiom != .Pad
{
// Create a button bar for the number pad
let keyboardDoneButtonView = UIToolbar()
keyboardDoneButtonView.sizeToFit()
// Setup the buttons to be put in the system.
let flexibleItem = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let item = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: #selector(DataViewController.endEditingNow) )
let toolbarButtons = [flexibleItem, item]
//Put the buttons into the ToolBar and display the tool bar
keyboardDoneButtonView.setItems(toolbarButtons, animated: false)
textField.inputAccessoryView = keyboardDoneButtonView
}
return true
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
//delegate method
textField.resignFirstResponder()
return true
}
} | gpl-3.0 | 3219318fb4c861a3c60a837619d7b62c | 24.057377 | 146 | 0.693277 | 3.525375 | false | false | false | false |
chris-wood/reveiller | reveiller/Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsSingleViewLayer.swift | 6 | 1390 | //
// ChartPointsSingleViewLayer.swift
// swift_charts
//
// Created by ischuetz on 19/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
// Layer that shows only one view at a time
public class ChartPointsSingleViewLayer<T: ChartPoint, U: UIView>: ChartPointsViewsLayer<T, U> {
private var addedViews: [UIView] = []
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, chartPoints: [T], viewGenerator: ChartPointViewGenerator) {
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: viewGenerator)
}
override func display(chart chart: Chart) {
// skip adding views - this layer manages its own list
}
public func showView(chartPoint chartPoint: T, chart: Chart) {
for view in self.addedViews {
view.removeFromSuperview()
}
let screenLoc = self.chartPointScreenLoc(chartPoint)
let index = self.chartPointsModels.map{$0.chartPoint}.indexOf(chartPoint)!
let model: ChartPointLayerModel = ChartPointLayerModel(chartPoint: chartPoint, index: index, screenLoc: screenLoc)
if let view = self.viewGenerator(chartPointModel: model, layer: self, chart: chart) {
self.addedViews.append(view)
chart.addSubview(view)
}
}
}
| mit | 2af364af990efdb7a3ceb8c1c42dda35 | 35.578947 | 141 | 0.679137 | 4.557377 | false | false | false | false |
nzaghini/mastering-reuse-viper | WeatherTests/Mocks/UserLocationsServiceMock.swift | 2 | 635 | import Foundation
@testable import Weather
class LocationStoreServiceMock: LocationStoreService {
var locationsList = [Location]()
var locationStored: Location?
var storeLocationCalled = false
var allLocationsCalled = false
var deleteAllLocationsCalled = false
func addLocation(_ location: Location) {
self.storeLocationCalled = true
self.locationStored = location
}
func locations() -> [Location] {
self.allLocationsCalled = true
return self.locationsList
}
func deleteLocations() {
self.deleteAllLocationsCalled = true
}
}
| mit | 55d8cc0c899add176b8cbc22747075b4 | 23.423077 | 54 | 0.669291 | 5.08 | false | false | false | false |
kdawgwilk/vapor | Sources/Vapor/Cookie/Response+Cookies.swift | 1 | 567 | extension Response {
public var cookies: Cookies {
get {
if let cookies = storage["Set-Cookie"] as? Cookies {
return cookies
} else if let cookieString = headers["Set-Cookie"] {
let cookie = Cookies(cookieString)
storage["Set-Cookie"] = cookie
return cookie
} else {
return []
}
}
set(cookie) {
storage["Set-Cookie"] = cookie
headers["Set-Cookie"] = cookie.serialize()
}
}
}
| mit | b728df8fbdcb5785af7518e78f88e4aa | 28.842105 | 64 | 0.465608 | 5.108108 | false | false | false | false |
goRestart/restart-backend-app | Sources/API/Application/HTTP/Controller/UserController.swift | 1 | 1265 | import HTTP
import Restart
import Domain
private struct UserParameters {
static let username = "username"
static let password = "password"
static let email = "email"
}
public struct UserController {
private let addUser: AddUser
init(addUser: AddUser) {
self.addUser = addUser
}
func post(_ request: Request) throws -> ResponseRepresentable {
guard let username = request.data[UserParameters.username]?.string,
let email = request.data[UserParameters.email]?.string,
let password = request.data[UserParameters.password]?.string else
{
return MissingParameters.error
}
let request = AddUserRequest(
username: username,
password: password,
email: email
)
do {
try addUser.add(with: request)
} catch AddUserError.userNameIsAlreadyInUse {
return UserNameIsAlreadyInUse.error
} catch AddUserError.emailIsAlreadyInUse {
return EmailIsAlreadyInUse.error
} catch AddUserError.invalidEmail {
return InvalidEmail.error
} catch {
return ServerError.error
}
return SuccessfullyCreated.response
}
}
| gpl-3.0 | c753672c6fb7b498d1493d001442170d | 25.914894 | 79 | 0.623715 | 5.100806 | false | false | false | false |
honghaoz/AutoKeyboardScrollView | Example/ProgrammaticExample/ProgrammaticExample/ViewController.swift | 2 | 3655 | //
// ViewController.swift
// ProgrammaticExample
//
// Created by Honghao Zhang on 2015-09-10.
// Copyright (c) 2015 Honghao Zhang. All rights reserved.
//
import UIKit
import AutoKeyboardScrollView
class ViewController: UIViewController {
let scrollView = AutoKeyboardScrollView()
var views = [String: UIView]()
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupConstraints()
}
private func setupViews() {
views["scrollView"] = scrollView
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.backgroundColor = UIColor(red:0.31, green:0.66, blue:0.42, alpha:1)
scrollView.isUserInteractionEnabled = true
scrollView.bounces = true
scrollView.isScrollEnabled = true
scrollView.textFieldMargin = 18
view.addSubview(scrollView)
// NOTE: Add subview on contentView!
for i in 0 ..< 8 {
scrollView.contentView.addSubview(newTextField(id: i))
}
// A text field on a subview
let dummyView = UIView()
dummyView.backgroundColor = UIColor(white: 1.0, alpha: 0.4)
dummyView.translatesAutoresizingMaskIntoConstraints = false
views["dummyView"] = dummyView
let textField8 = newTextField(id: 8)
textField8.placeholder = "Text filed on a deeper subview"
dummyView.addSubview(textField8)
scrollView.contentView.addSubview(dummyView)
scrollView.setTextMargin(100, forTextField: textField8)
}
private func setupConstraints() {
var constraints = [NSLayoutConstraint]()
// Constraints for scorllView
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: views)
// Center width constraints for text fields
for i in 0 ..< 8 {
addWidthCenterXConstraintsForView(view: views["textField\(i)"]!, width: 200)
}
// Constraints for dummy subview and textfield
addWidthCenterXConstraintsForView(view: views["dummyView"]!, width: 280)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField8]-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[textField8]-|", options: [], metrics: nil, views: views)
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(100)-[textField0(30)]-(20)-[textField1(30)]-(20)-[textField2(30)]-(20)-[textField3(30)]-(20)-[textField4(30)]-(20)-[textField5(30)]-(20)-[textField6(30)]-(20)-[textField7(30)]-(20)-[dummyView(50)]-(150)-|", options: [], metrics: nil, views: views)
NSLayoutConstraint.activate(constraints)
}
// MARK: - Helpers
private func newTextField(id: Int) -> UITextField {
let textField = UITextField()
textField.translatesAutoresizingMaskIntoConstraints = false
textField.placeholder = "Type here..."
textField.textAlignment = NSTextAlignment.center
textField.backgroundColor = .white
views["textField\(id)"] = textField
return textField
}
private func addWidthCenterXConstraintsForView(view: UIView, width: CGFloat) {
view.addConstraint(NSLayoutConstraint(item: view, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 0, constant: width))
view.superview!.addConstraint(NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: view.superview!, attribute: .centerX, multiplier: 1, constant: 0))
}
}
| mit | 4f98d6eb97832ecb251c8fca1054d592 | 35.55 | 325 | 0.712996 | 4.382494 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/PeerMediaDateItem.swift | 1 | 4774 | //
// PeerMediaDateItem.swift
// Telegram
//
// Created by keepcoder on 27/11/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
class PeerMediaDateItem: TableStickItem {
private let _stableId: AnyHashable
private let messageIndex: MessageIndex
fileprivate let textLayout: TextViewLayout
let viewType: GeneralViewType
let inset: NSEdgeInsets
init(_ initialSize: NSSize, index: MessageIndex, stableId: AnyHashable) {
self.messageIndex = index
self._stableId = stableId
self.viewType = .modern(position: .single, insets: NSEdgeInsetsMake(3, 0, 3, 0))
self.inset = NSEdgeInsets(left: 0, right: 0)
let timestamp = index.timestamp
let nowTimestamp = Int32(CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970)
var t: time_t = time_t(timestamp)
var timeinfo: tm = tm()
localtime_r(&t, &timeinfo)
var now: time_t = time_t(nowTimestamp)
var timeinfoNow: tm = tm()
localtime_r(&now, &timeinfoNow)
let text: String
let dateFormatter = makeNewDateFormatter()
dateFormatter.timeZone = NSTimeZone.local
dateFormatter.dateFormat = "MMMM yyyy";
text = dateFormatter.string(from: Date(timeIntervalSince1970: TimeInterval(timestamp))).uppercased()
textLayout = TextViewLayout(.initialize(string: text, color: theme.colors.listGrayText, font: .normal(.short)))
super.init(initialSize)
_ = makeSize(initialSize.width, oldWidth: 0)
}
required init(_ initialSize: NSSize) {
self._stableId = AnyHashable(0)
self.messageIndex = MessageIndex.absoluteLowerBound()
self.textLayout = TextViewLayout(.initialize(string: ""))
self.viewType = .separator
self.inset = NSEdgeInsets(left: 30, right: 30)
super.init(initialSize)
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
let success = super.makeSize(width, oldWidth: oldWidth)
textLayout.measure(width: width - 60)
return success
}
override var stableId: AnyHashable {
return _stableId
}
override var height: CGFloat {
return textLayout.layoutSize.height + viewType.innerInset.top + viewType.innerInset.bottom + 9
}
override func viewClass() -> AnyClass {
return PeerMediaDateView.self
}
}
fileprivate class PeerMediaDateView : TableStickView {
private let containerView = GeneralRowContainerView(frame: NSZeroRect)
private let textView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(self.containerView)
containerView.addSubview(self.textView)
self.textView.disableBackgroundDrawing = true
self.textView.isSelectable = false
self.textView.userInteractionEnabled = false
}
override var header: Bool {
didSet {
updateColors()
}
}
override func updateIsVisible(_ visible: Bool, animated: Bool) {
containerView.change(opacity: visible ? 1 : 0, animated: animated)
}
override var backdorColor: NSColor {
return theme.colors.listBackground.withAlphaComponent(0.8)
}
override func updateColors() {
guard let item = item as? PeerMediaDateItem else {
return
}
self.backgroundColor = item.viewType.rowBackground
self.containerView.backgroundColor = backdorColor
}
override func layout() {
super.layout()
guard let item = item as? PeerMediaDateItem else {
return
}
let blockWidth = min(600, frame.width - item.inset.left - item.inset.right)
self.containerView.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - blockWidth) / 2), item.inset.top, blockWidth, frame.height - item.inset.bottom - item.inset.top)
self.containerView.setCorners([])
textView.centerY(x: item.viewType.innerInset.left + 12)
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? PeerMediaDateItem else {
return
}
self.textView.update(item.textLayout)
needsLayout = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | 2e36a48548d72e28b1f91e4dc43ad7bb | 33.092857 | 200 | 0.620574 | 4.875383 | false | false | false | false |
brentsimmons/Evergreen | iOS/SceneCoordinator.swift | 1 | 76546 | //
// NavigationModelController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 4/21/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import UserNotifications
import Account
import Articles
import RSCore
import RSTree
import SafariServices
enum PanelMode {
case unset
case three
case standard
}
enum SearchScope: Int {
case timeline = 0
case global = 1
}
enum ShowFeedName {
case none
case byline
case feed
}
struct FeedNode: Hashable {
var node: Node
var feedID: FeedIdentifier
init(_ node: Node) {
self.node = node
self.feedID = (node.representedObject as! Feed).feedID!
}
func hash(into hasher: inout Hasher) {
hasher.combine(feedID)
}
}
class SceneCoordinator: NSObject, UndoableCommandRunner {
var undoableCommands = [UndoableCommand]()
var undoManager: UndoManager? {
return rootSplitViewController.undoManager
}
lazy var webViewProvider = WebViewProvider(coordinator: self)
private var panelMode: PanelMode = .unset
private var activityManager = ActivityManager()
private var rootSplitViewController: RootSplitViewController!
private var masterNavigationController: UINavigationController!
private var masterFeedViewController: MasterFeedViewController!
private var masterTimelineViewController: MasterTimelineViewController?
private var subSplitViewController: UISplitViewController?
private var articleViewController: ArticleViewController? {
if let detail = masterNavigationController.viewControllers.last as? ArticleViewController {
return detail
}
if let subSplit = subSplitViewController {
if let navController = subSplit.viewControllers.last as? UINavigationController {
return navController.topViewController as? ArticleViewController
}
} else {
if let navController = rootSplitViewController.viewControllers.last as? UINavigationController {
return navController.topViewController as? ArticleViewController
}
}
return nil
}
private var wasRootSplitViewControllerCollapsed = false
private let fetchAndMergeArticlesQueue = CoalescingQueue(name: "Fetch and Merge Articles", interval: 0.5)
private let rebuildBackingStoresQueue = CoalescingQueue(name: "Rebuild The Backing Stores", interval: 0.5)
private var fetchSerialNumber = 0
private let fetchRequestQueue = FetchRequestQueue()
// Which Containers are expanded
private var expandedTable = Set<ContainerIdentifier>()
// Which Containers used to be expanded. Reset by rebuilding the Shadow Table.
private var lastExpandedTable = Set<ContainerIdentifier>()
// Which Feeds have the Read Articles Filter enabled
private var readFilterEnabledTable = [FeedIdentifier: Bool]()
// Flattened tree structure for the Sidebar
private var shadowTable = [(sectionID: String, feedNodes: [FeedNode])]()
private(set) var preSearchTimelineFeed: Feed?
private var lastSearchString = ""
private var lastSearchScope: SearchScope? = nil
private var isSearching: Bool = false
private var savedSearchArticles: ArticleArray? = nil
private var savedSearchArticleIds: Set<String>? = nil
var isTimelineViewControllerPending = false
var isArticleViewControllerPending = false
private(set) var sortDirection = AppDefaults.shared.timelineSortDirection {
didSet {
if sortDirection != oldValue {
sortParametersDidChange()
}
}
}
private(set) var groupByFeed = AppDefaults.shared.timelineGroupByFeed {
didSet {
if groupByFeed != oldValue {
sortParametersDidChange()
}
}
}
var prefersStatusBarHidden = false
private let treeControllerDelegate = WebFeedTreeControllerDelegate()
private let treeController: TreeController
var stateRestorationActivity: NSUserActivity {
let activity = activityManager.stateRestorationActivity
var userInfo = activity.userInfo ?? [AnyHashable: Any]()
userInfo[UserInfoKey.windowState] = windowState()
let articleState = articleViewController?.currentState
userInfo[UserInfoKey.isShowingExtractedArticle] = articleState?.isShowingExtractedArticle ?? false
userInfo[UserInfoKey.articleWindowScrollY] = articleState?.windowScrollY ?? 0
activity.userInfo = userInfo
return activity
}
var isRootSplitCollapsed: Bool {
return rootSplitViewController.isCollapsed
}
var isThreePanelMode: Bool {
return panelMode == .three
}
var isReadFeedsFiltered: Bool {
return treeControllerDelegate.isReadFiltered
}
var isReadArticlesFiltered: Bool {
if let feedID = timelineFeed?.feedID, let readFilterEnabled = readFilterEnabledTable[feedID] {
return readFilterEnabled
} else {
return timelineDefaultReadFilterType != .none
}
}
var timelineDefaultReadFilterType: ReadFilterType {
return timelineFeed?.defaultReadFilterType ?? .none
}
var rootNode: Node {
return treeController.rootNode
}
// At some point we should refactor the current Feed IndexPath out and only use the timeline feed
private(set) var currentFeedIndexPath: IndexPath?
var timelineIconImage: IconImage? {
guard let timelineFeed = timelineFeed else {
return nil
}
return IconImageCache.shared.imageForFeed(timelineFeed)
}
private var exceptionArticleFetcher: ArticleFetcher?
private(set) var timelineFeed: Feed?
var timelineMiddleIndexPath: IndexPath?
private(set) var showFeedNames = ShowFeedName.none
private(set) var showIcons = false
var prevFeedIndexPath: IndexPath? {
guard let indexPath = currentFeedIndexPath else {
return nil
}
let prevIndexPath: IndexPath? = {
if indexPath.row - 1 < 0 {
for i in (0..<indexPath.section).reversed() {
if shadowTable[i].feedNodes.count > 0 {
return IndexPath(row: shadowTable[i].feedNodes.count - 1, section: i)
}
}
return nil
} else {
return IndexPath(row: indexPath.row - 1, section: indexPath.section)
}
}()
return prevIndexPath
}
var nextFeedIndexPath: IndexPath? {
guard let indexPath = currentFeedIndexPath else {
return nil
}
let nextIndexPath: IndexPath? = {
if indexPath.row + 1 >= shadowTable[indexPath.section].feedNodes.count {
for i in indexPath.section + 1..<shadowTable.count {
if shadowTable[i].feedNodes.count > 0 {
return IndexPath(row: 0, section: i)
}
}
return nil
} else {
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
}()
return nextIndexPath
}
var isPrevArticleAvailable: Bool {
guard let articleRow = currentArticleRow else {
return false
}
return articleRow > 0
}
var isNextArticleAvailable: Bool {
guard let articleRow = currentArticleRow else {
return false
}
return articleRow + 1 < articles.count
}
var prevArticle: Article? {
guard isPrevArticleAvailable, let articleRow = currentArticleRow else {
return nil
}
return articles[articleRow - 1]
}
var nextArticle: Article? {
guard isNextArticleAvailable, let articleRow = currentArticleRow else {
return nil
}
return articles[articleRow + 1]
}
var firstUnreadArticleIndexPath: IndexPath? {
for (row, article) in articles.enumerated() {
if !article.status.read {
return IndexPath(row: row, section: 0)
}
}
return nil
}
var currentArticle: Article?
private(set) var articles = ArticleArray() {
didSet {
timelineMiddleIndexPath = nil
articleDictionaryNeedsUpdate = true
}
}
private var articleDictionaryNeedsUpdate = true
private var _idToArticleDictionary = [String: Article]()
private var idToAticleDictionary: [String: Article] {
if articleDictionaryNeedsUpdate {
rebuildArticleDictionaries()
}
return _idToArticleDictionary
}
private var currentArticleRow: Int? {
guard let article = currentArticle else { return nil }
return articles.firstIndex(of: article)
}
var isTimelineUnreadAvailable: Bool {
return timelineUnreadCount > 0
}
var isAnyUnreadAvailable: Bool {
return appDelegate.unreadCount > 0
}
var timelineUnreadCount: Int = 0
override init() {
treeController = TreeController(delegate: treeControllerDelegate)
super.init()
for sectionNode in treeController.rootNode.childNodes {
markExpanded(sectionNode)
shadowTable.append((sectionID: "", feedNodes: [FeedNode]()))
}
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidInitialize(_:)), name: .UnreadCountDidInitialize, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(statusesDidChange(_:)), name: .StatusesDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(containerChildrenDidChange(_:)), name: .ChildrenDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(batchUpdateDidPerform(_:)), name: .BatchUpdateDidPerform, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountStateDidChange(_:)), name: .AccountStateDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidAddAccount(_:)), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidDeleteAccount(_:)), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDidAddFeed(_:)), name: .UserDidAddFeed, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange(_:)), name: UserDefaults.didChangeNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountDidDownloadArticles(_:)), name: .AccountDidDownloadArticles, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(importDownloadedTheme(_:)), name: .didEndDownloadingTheme, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(themeDownloadDidFail(_:)), name: .didFailToImportThemeWithError, object: nil)
}
func start(for size: CGSize) -> UIViewController {
rootSplitViewController = RootSplitViewController()
rootSplitViewController.coordinator = self
rootSplitViewController.preferredDisplayMode = .allVisible
rootSplitViewController.viewControllers = [InteractiveNavigationController.template()]
rootSplitViewController.delegate = self
masterNavigationController = (rootSplitViewController.viewControllers.first as! UINavigationController)
masterNavigationController.delegate = self
masterFeedViewController = UIStoryboard.main.instantiateController(ofType: MasterFeedViewController.self)
masterFeedViewController.coordinator = self
masterNavigationController.pushViewController(masterFeedViewController, animated: false)
let articleViewController = UIStoryboard.main.instantiateController(ofType: ArticleViewController.self)
articleViewController.coordinator = self
let detailNavigationController = addNavControllerIfNecessary(articleViewController, showButton: true)
rootSplitViewController.showDetailViewController(detailNavigationController, sender: self)
configurePanelMode(for: size)
return rootSplitViewController
}
func restoreWindowState(_ activity: NSUserActivity?) {
if let activity = activity, let windowState = activity.userInfo?[UserInfoKey.windowState] as? [AnyHashable: Any] {
if let containerExpandedWindowState = windowState[UserInfoKey.containerExpandedWindowState] as? [[AnyHashable: AnyHashable]] {
let containerIdentifers = containerExpandedWindowState.compactMap( { ContainerIdentifier(userInfo: $0) })
expandedTable = Set(containerIdentifers)
}
if let readArticlesFilterState = windowState[UserInfoKey.readArticlesFilterState] as? [[AnyHashable: AnyHashable]: Bool] {
for key in readArticlesFilterState.keys {
if let feedIdentifier = FeedIdentifier(userInfo: key) {
readFilterEnabledTable[feedIdentifier] = readArticlesFilterState[key]
}
}
}
rebuildBackingStores(initialLoad: true)
// You can't assign the Feeds Read Filter until we've built the backing stores at least once or there is nothing
// for state restoration to work with while we are waiting for the unread counts to initialize.
if let readFeedsFilterState = windowState[UserInfoKey.readFeedsFilterState] as? Bool {
treeControllerDelegate.isReadFiltered = readFeedsFilterState
}
} else {
rebuildBackingStores(initialLoad: true)
}
}
func handle(_ activity: NSUserActivity) {
selectFeed(indexPath: nil) {
guard let activityType = ActivityType(rawValue: activity.activityType) else { return }
switch activityType {
case .restoration:
break
case .selectFeed:
self.handleSelectFeed(activity.userInfo)
case .nextUnread:
self.selectFirstUnreadInAllUnread()
case .readArticle:
self.handleReadArticle(activity.userInfo)
case .addFeedIntent:
self.showAddWebFeed()
}
}
}
func handle(_ response: UNNotificationResponse) {
let userInfo = response.notification.request.content.userInfo
handleReadArticle(userInfo)
}
func configurePanelMode(for size: CGSize) {
guard rootSplitViewController.traitCollection.userInterfaceIdiom == .pad else {
return
}
if (size.width / size.height) > 1.2 {
if panelMode == .unset || panelMode == .standard {
panelMode = .three
configureThreePanelMode()
}
} else {
if panelMode == .unset || panelMode == .three {
panelMode = .standard
configureStandardPanelMode()
}
}
wasRootSplitViewControllerCollapsed = rootSplitViewController.isCollapsed
}
func resetFocus() {
if currentArticle != nil {
masterTimelineViewController?.focus()
} else {
masterFeedViewController?.focus()
}
}
func selectFirstUnreadInAllUnread() {
markExpanded(SmartFeedsController.shared)
self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.unreadFeed) {
self.selectFeed(SmartFeedsController.shared.unreadFeed) {
self.selectFirstUnreadArticleInTimeline()
}
}
}
func showSearch() {
selectFeed(indexPath: nil) {
self.installTimelineControllerIfNecessary(animated: false)
DispatchQueue.main.asyncAfter(deadline: .now()) {
self.masterTimelineViewController!.showSearchAll()
}
}
}
// MARK: Notifications
@objc func unreadCountDidInitialize(_ notification: Notification) {
guard notification.object is AccountManager else {
return
}
if isReadFeedsFiltered {
rebuildBackingStores()
}
}
@objc func unreadCountDidChange(_ note: Notification) {
// We will handle the filtering of unread feeds in unreadCountDidInitialize after they have all be calculated
guard AccountManager.shared.isUnreadCountsInitialized else {
return
}
queueRebuildBackingStores()
}
@objc func statusesDidChange(_ note: Notification) {
updateUnreadCount()
}
@objc func containerChildrenDidChange(_ note: Notification) {
if timelineFetcherContainsAnyPseudoFeed() || timelineFetcherContainsAnyFolder() {
fetchAndMergeArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: false)
self.rebuildBackingStores()
}
} else {
rebuildBackingStores()
}
}
@objc func batchUpdateDidPerform(_ notification: Notification) {
rebuildBackingStores()
}
@objc func displayNameDidChange(_ note: Notification) {
rebuildBackingStores()
}
@objc func accountStateDidChange(_ note: Notification) {
if timelineFetcherContainsAnyPseudoFeed() {
fetchAndMergeArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: false)
self.rebuildBackingStores()
}
} else {
self.rebuildBackingStores()
}
}
@objc func userDidAddAccount(_ note: Notification) {
let expandNewAccount = {
if let account = note.userInfo?[Account.UserInfoKey.account] as? Account,
let node = self.treeController.rootNode.childNodeRepresentingObject(account) {
self.markExpanded(node)
}
}
if timelineFetcherContainsAnyPseudoFeed() {
fetchAndMergeArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: false)
self.rebuildBackingStores(updateExpandedNodes: expandNewAccount)
}
} else {
self.rebuildBackingStores(updateExpandedNodes: expandNewAccount)
}
}
@objc func userDidDeleteAccount(_ note: Notification) {
let cleanupAccount = {
if let account = note.userInfo?[Account.UserInfoKey.account] as? Account,
let node = self.treeController.rootNode.childNodeRepresentingObject(account) {
self.unmarkExpanded(node)
}
}
if timelineFetcherContainsAnyPseudoFeed() {
fetchAndMergeArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: false)
self.rebuildBackingStores(updateExpandedNodes: cleanupAccount)
}
} else {
self.rebuildBackingStores(updateExpandedNodes: cleanupAccount)
}
}
@objc func userDidAddFeed(_ notification: Notification) {
guard let webFeed = notification.userInfo?[UserInfoKey.webFeed] as? WebFeed else {
return
}
discloseWebFeed(webFeed, animations: [.scroll, .navigation])
}
@objc func userDefaultsDidChange(_ note: Notification) {
self.sortDirection = AppDefaults.shared.timelineSortDirection
self.groupByFeed = AppDefaults.shared.timelineGroupByFeed
}
@objc func accountDidDownloadArticles(_ note: Notification) {
guard let feeds = note.userInfo?[Account.UserInfoKey.webFeeds] as? Set<WebFeed> else {
return
}
let shouldFetchAndMergeArticles = timelineFetcherContainsAnyFeed(feeds) || timelineFetcherContainsAnyPseudoFeed()
if shouldFetchAndMergeArticles {
queueFetchAndMergeArticles()
}
}
@objc func willEnterForeground(_ note: Notification) {
// Don't interfere with any fetch requests that we may have initiated before the app was returned to the foreground.
// For example if you select Next Unread from the Home Screen Quick actions, you can start a request before we are
// in the foreground.
if !fetchRequestQueue.isAnyCurrentRequest {
queueFetchAndMergeArticles()
}
}
@objc func importDownloadedTheme(_ note: Notification) {
guard let userInfo = note.userInfo,
let url = userInfo["url"] as? URL else {
return
}
DispatchQueue.main.async {
self.importTheme(filename: url.path)
}
}
@objc func themeDownloadDidFail(_ note: Notification) {
guard let userInfo = note.userInfo,
let error = userInfo["error"] as? Error else {
return
}
DispatchQueue.main.async {
self.rootSplitViewController.presentError(error, dismiss: nil)
}
}
// MARK: API
func suspend() {
fetchAndMergeArticlesQueue.performCallsImmediately()
rebuildBackingStoresQueue.performCallsImmediately()
fetchRequestQueue.cancelAllRequests()
}
func cleanUp(conditional: Bool) {
if isReadFeedsFiltered {
rebuildBackingStores()
}
if isReadArticlesFiltered && (AppDefaults.shared.refreshClearsReadArticles || !conditional) {
refreshTimeline(resetScroll: false)
}
}
func toggleReadFeedsFilter() {
if isReadFeedsFiltered {
treeControllerDelegate.isReadFiltered = false
} else {
treeControllerDelegate.isReadFiltered = true
}
rebuildBackingStores()
masterFeedViewController?.updateUI()
}
func toggleReadArticlesFilter() {
guard let feedID = timelineFeed?.feedID else {
return
}
if isReadArticlesFiltered {
readFilterEnabledTable[feedID] = false
} else {
readFilterEnabledTable[feedID] = true
}
refreshTimeline(resetScroll: false)
}
func nodeFor(feedID: FeedIdentifier) -> Node? {
return treeController.rootNode.descendantNode(where: { node in
if let feed = node.representedObject as? Feed {
return feed.feedID == feedID
} else {
return false
}
})
}
func numberOfSections() -> Int {
return shadowTable.count
}
func numberOfRows(in section: Int) -> Int {
return shadowTable[section].feedNodes.count
}
func nodeFor(_ indexPath: IndexPath) -> Node? {
guard indexPath.section < shadowTable.count && indexPath.row < shadowTable[indexPath.section].feedNodes.count else {
return nil
}
return shadowTable[indexPath.section].feedNodes[indexPath.row].node
}
func indexPathFor(_ node: Node) -> IndexPath? {
for i in 0..<shadowTable.count {
if let row = shadowTable[i].feedNodes.firstIndex(of: FeedNode(node)) {
return IndexPath(row: row, section: i)
}
}
return nil
}
func articleFor(_ articleID: String) -> Article? {
return idToAticleDictionary[articleID]
}
func cappedIndexPath(_ indexPath: IndexPath) -> IndexPath {
guard indexPath.section < shadowTable.count && indexPath.row < shadowTable[indexPath.section].feedNodes.count else {
return IndexPath(row: shadowTable[shadowTable.count - 1].feedNodes.count - 1, section: shadowTable.count - 1)
}
return indexPath
}
func unreadCountFor(_ node: Node) -> Int {
// The coordinator supplies the unread count for the currently selected feed
if node.representedObject === timelineFeed as AnyObject {
return timelineUnreadCount
}
if let unreadCountProvider = node.representedObject as? UnreadCountProvider {
return unreadCountProvider.unreadCount
}
assertionFailure("This method should only be called for nodes that have an UnreadCountProvider as the represented object.")
return 0
}
func refreshTimeline(resetScroll: Bool) {
if let article = self.currentArticle, let account = article.account {
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: article.articleID)
}
fetchAndReplaceArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: resetScroll)
}
}
func isExpanded(_ containerID: ContainerIdentifier) -> Bool {
return expandedTable.contains(containerID)
}
func isExpanded(_ containerIdentifiable: ContainerIdentifiable) -> Bool {
if let containerID = containerIdentifiable.containerID {
return isExpanded(containerID)
}
return false
}
func isExpanded(_ node: Node) -> Bool {
if let containerIdentifiable = node.representedObject as? ContainerIdentifiable {
return isExpanded(containerIdentifiable)
}
return false
}
func expand(_ containerID: ContainerIdentifier) {
markExpanded(containerID)
rebuildBackingStores()
}
/// This is a special function that expects the caller to change the disclosure arrow state outside this function.
/// Failure to do so will get the Sidebar into an invalid state.
func expand(_ node: Node) {
guard let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { return }
lastExpandedTable.insert(containerID)
expand(containerID)
}
func expandAllSectionsAndFolders() {
for sectionNode in treeController.rootNode.childNodes {
markExpanded(sectionNode)
for topLevelNode in sectionNode.childNodes {
if topLevelNode.representedObject is Folder {
markExpanded(topLevelNode)
}
}
}
rebuildBackingStores()
}
func collapse(_ containerID: ContainerIdentifier) {
unmarkExpanded(containerID)
rebuildBackingStores()
clearTimelineIfNoLongerAvailable()
}
/// This is a special function that expects the caller to change the disclosure arrow state outside this function.
/// Failure to do so will get the Sidebar into an invalid state.
func collapse(_ node: Node) {
guard let containerID = (node.representedObject as? ContainerIdentifiable)?.containerID else { return }
lastExpandedTable.remove(containerID)
collapse(containerID)
}
func collapseAllFolders() {
for sectionNode in treeController.rootNode.childNodes {
for topLevelNode in sectionNode.childNodes {
if topLevelNode.representedObject is Folder {
unmarkExpanded(topLevelNode)
}
}
}
rebuildBackingStores()
clearTimelineIfNoLongerAvailable()
}
func masterFeedIndexPathForCurrentTimeline() -> IndexPath? {
guard let node = treeController.rootNode.descendantNodeRepresentingObject(timelineFeed as AnyObject) else {
return nil
}
return indexPathFor(node)
}
func selectFeed(_ feed: Feed?, animations: Animations = [], deselectArticle: Bool = true, completion: (() -> Void)? = nil) {
let indexPath: IndexPath? = {
if let feed = feed, let indexPath = indexPathFor(feed as AnyObject) {
return indexPath
} else {
return nil
}
}()
selectFeed(indexPath: indexPath, animations: animations, deselectArticle: deselectArticle, completion: completion)
}
func selectFeed(indexPath: IndexPath?, animations: Animations = [], deselectArticle: Bool = true, completion: (() -> Void)? = nil) {
guard indexPath != currentFeedIndexPath else {
completion?()
return
}
currentFeedIndexPath = indexPath
masterFeedViewController.updateFeedSelection(animations: animations)
if deselectArticle {
selectArticle(nil)
}
if let ip = indexPath, let node = nodeFor(ip), let feed = node.representedObject as? Feed {
self.activityManager.selecting(feed: feed)
self.installTimelineControllerIfNecessary(animated: animations.contains(.navigation))
setTimelineFeed(feed, animated: false) {
if self.isReadFeedsFiltered {
self.rebuildBackingStores()
}
completion?()
}
} else {
setTimelineFeed(nil, animated: false) {
if self.isReadFeedsFiltered {
self.rebuildBackingStores()
}
self.activityManager.invalidateSelecting()
if self.rootSplitViewController.isCollapsed && self.navControllerForTimeline().viewControllers.last is MasterTimelineViewController {
self.navControllerForTimeline().popViewController(animated: animations.contains(.navigation))
}
completion?()
}
}
}
func selectPrevFeed() {
if let indexPath = prevFeedIndexPath {
selectFeed(indexPath: indexPath, animations: [.navigation, .scroll])
}
}
func selectNextFeed() {
if let indexPath = nextFeedIndexPath {
selectFeed(indexPath: indexPath, animations: [.navigation, .scroll])
}
}
func selectTodayFeed(completion: (() -> Void)? = nil) {
markExpanded(SmartFeedsController.shared)
self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.todayFeed) {
self.selectFeed(SmartFeedsController.shared.todayFeed, animations: [.navigation, .scroll], completion: completion)
}
}
func selectAllUnreadFeed(completion: (() -> Void)? = nil) {
markExpanded(SmartFeedsController.shared)
self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.unreadFeed) {
self.selectFeed(SmartFeedsController.shared.unreadFeed, animations: [.navigation, .scroll], completion: completion)
}
}
func selectStarredFeed(completion: (() -> Void)? = nil) {
markExpanded(SmartFeedsController.shared)
self.ensureFeedIsAvailableToSelect(SmartFeedsController.shared.starredFeed) {
self.selectFeed(SmartFeedsController.shared.starredFeed, animations: [.navigation, .scroll], completion: completion)
}
}
func selectArticle(_ article: Article?, animations: Animations = [], isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) {
guard article != currentArticle else { return }
currentArticle = article
activityManager.reading(feed: timelineFeed, article: article)
if article == nil {
if rootSplitViewController.isCollapsed {
if masterNavigationController.children.last is ArticleViewController {
masterNavigationController.popViewController(animated: animations.contains(.navigation))
}
} else {
articleViewController?.article = nil
}
masterTimelineViewController?.updateArticleSelection(animations: animations)
return
}
let currentArticleViewController: ArticleViewController
if articleViewController == nil {
currentArticleViewController = installArticleController(animated: animations.contains(.navigation))
} else {
currentArticleViewController = articleViewController!
}
// Mark article as read before navigating to it, so the read status does not flash unread/read on display
markArticles(Set([article!]), statusKey: .read, flag: true)
masterTimelineViewController?.updateArticleSelection(animations: animations)
currentArticleViewController.article = article
if let isShowingExtractedArticle = isShowingExtractedArticle, let articleWindowScrollY = articleWindowScrollY {
currentArticleViewController.restoreScrollPosition = (isShowingExtractedArticle, articleWindowScrollY)
}
}
func beginSearching() {
isSearching = true
preSearchTimelineFeed = timelineFeed
savedSearchArticles = articles
savedSearchArticleIds = Set(articles.map { $0.articleID })
setTimelineFeed(nil, animated: true)
selectArticle(nil)
}
func endSearching() {
if let oldTimelineFeed = preSearchTimelineFeed {
emptyTheTimeline()
timelineFeed = oldTimelineFeed
masterTimelineViewController?.reinitializeArticles(resetScroll: true)
replaceArticles(with: savedSearchArticles!, animated: true)
} else {
setTimelineFeed(nil, animated: true)
}
lastSearchString = ""
lastSearchScope = nil
preSearchTimelineFeed = nil
savedSearchArticleIds = nil
savedSearchArticles = nil
isSearching = false
selectArticle(nil)
masterTimelineViewController?.focus()
}
func searchArticles(_ searchString: String, _ searchScope: SearchScope) {
guard isSearching else { return }
if searchString.count < 3 {
setTimelineFeed(nil, animated: true)
return
}
if searchString != lastSearchString || searchScope != lastSearchScope {
switch searchScope {
case .global:
setTimelineFeed(SmartFeed(delegate: SearchFeedDelegate(searchString: searchString)), animated: true)
case .timeline:
setTimelineFeed(SmartFeed(delegate: SearchTimelineFeedDelegate(searchString: searchString, articleIDs: savedSearchArticleIds!)), animated: true)
}
lastSearchString = searchString
lastSearchScope = searchScope
}
}
func findPrevArticle(_ article: Article) -> Article? {
guard let index = articles.firstIndex(of: article), index > 0 else {
return nil
}
return articles[index - 1]
}
func findNextArticle(_ article: Article) -> Article? {
guard let index = articles.firstIndex(of: article), index + 1 != articles.count else {
return nil
}
return articles[index + 1]
}
func selectPrevArticle() {
if let article = prevArticle {
selectArticle(article, animations: [.navigation, .scroll])
}
}
func selectNextArticle() {
if let article = nextArticle {
selectArticle(article, animations: [.navigation, .scroll])
}
}
func selectFirstUnread() {
if selectFirstUnreadArticleInTimeline() {
activityManager.selectingNextUnread()
}
}
func selectPrevUnread() {
// This should never happen, but I don't want to risk throwing us
// into an infinate loop searching for an unread that isn't there.
if appDelegate.unreadCount < 1 {
return
}
if selectPrevUnreadArticleInTimeline() {
return
}
selectPrevUnreadFeedFetcher()
selectPrevUnreadArticleInTimeline()
}
func selectNextUnread() {
// This should never happen, but I don't want to risk throwing us
// into an infinate loop searching for an unread that isn't there.
if appDelegate.unreadCount < 1 {
return
}
if selectNextUnreadArticleInTimeline() {
return
}
if self.isSearching {
self.masterTimelineViewController?.hideSearch()
}
selectNextUnreadFeed() {
self.selectNextUnreadArticleInTimeline()
}
}
func scrollOrGoToNextUnread() {
if articleViewController?.canScrollDown() ?? false {
articleViewController?.scrollPageDown()
} else {
selectNextUnread()
}
}
func scrollUp() {
if articleViewController?.canScrollUp() ?? false {
articleViewController?.scrollPageUp()
}
}
func markAllAsRead(_ articles: [Article], completion: (() -> Void)? = nil) {
markArticlesWithUndo(articles, statusKey: .read, flag: true, completion: completion)
}
func markAllAsReadInTimeline(completion: (() -> Void)? = nil) {
markAllAsRead(articles) {
self.masterNavigationController.popViewController(animated: true)
completion?()
}
}
func canMarkAboveAsRead(for article: Article) -> Bool {
let articlesAboveArray = articles.articlesAbove(article: article)
return articlesAboveArray.canMarkAllAsRead()
}
func markAboveAsRead() {
guard let currentArticle = currentArticle else {
return
}
markAboveAsRead(currentArticle)
}
func markAboveAsRead(_ article: Article) {
let articlesAboveArray = articles.articlesAbove(article: article)
markAllAsRead(articlesAboveArray)
}
func canMarkBelowAsRead(for article: Article) -> Bool {
let articleBelowArray = articles.articlesBelow(article: article)
return articleBelowArray.canMarkAllAsRead()
}
func markBelowAsRead() {
guard let currentArticle = currentArticle else {
return
}
markBelowAsRead(currentArticle)
}
func markBelowAsRead(_ article: Article) {
let articleBelowArray = articles.articlesBelow(article: article)
markAllAsRead(articleBelowArray)
}
func markAsReadForCurrentArticle() {
if let article = currentArticle {
markArticlesWithUndo([article], statusKey: .read, flag: true)
}
}
func markAsUnreadForCurrentArticle() {
if let article = currentArticle {
markArticlesWithUndo([article], statusKey: .read, flag: false)
}
}
func toggleReadForCurrentArticle() {
if let article = currentArticle {
toggleRead(article)
}
}
func toggleRead(_ article: Article) {
guard !article.status.read || article.isAvailableToMarkUnread else { return }
markArticlesWithUndo([article], statusKey: .read, flag: !article.status.read)
}
func toggleStarredForCurrentArticle() {
if let article = currentArticle {
toggleStar(article)
}
}
func toggleStar(_ article: Article) {
markArticlesWithUndo([article], statusKey: .starred, flag: !article.status.starred)
}
func timelineFeedIsEqualTo(_ feed: WebFeed) -> Bool {
guard let timelineFeed = timelineFeed as? WebFeed else {
return false
}
return timelineFeed == feed
}
func discloseWebFeed(_ webFeed: WebFeed, initialLoad: Bool = false, animations: Animations = [], completion: (() -> Void)? = nil) {
if isSearching {
masterTimelineViewController?.hideSearch()
}
guard let account = webFeed.account else {
completion?()
return
}
let parentFolder = account.sortedFolders?.first(where: { $0.objectIsChild(webFeed) })
markExpanded(account)
if let parentFolder = parentFolder {
markExpanded(parentFolder)
}
if let webFeedFeedID = webFeed.feedID {
self.treeControllerDelegate.addFilterException(webFeedFeedID)
}
if let parentFolderFeedID = parentFolder?.feedID {
self.treeControllerDelegate.addFilterException(parentFolderFeedID)
}
rebuildBackingStores(initialLoad: initialLoad, completion: {
self.treeControllerDelegate.resetFilterExceptions()
self.selectFeed(nil) {
self.selectFeed(webFeed, animations: animations, completion: completion)
}
})
}
func showStatusBar() {
prefersStatusBarHidden = false
UIView.animate(withDuration: 0.15) {
self.rootSplitViewController.setNeedsStatusBarAppearanceUpdate()
}
}
func hideStatusBar() {
prefersStatusBarHidden = true
UIView.animate(withDuration: 0.15) {
self.rootSplitViewController.setNeedsStatusBarAppearanceUpdate()
}
}
func showSettings(scrollToArticlesSection: Bool = false) {
let settingsNavController = UIStoryboard.settings.instantiateInitialViewController() as! UINavigationController
let settingsViewController = settingsNavController.topViewController as! SettingsViewController
settingsViewController.scrollToArticlesSection = scrollToArticlesSection
settingsNavController.modalPresentationStyle = .formSheet
settingsViewController.presentingParentController = rootSplitViewController
rootSplitViewController.present(settingsNavController, animated: true)
}
func showAccountInspector(for account: Account) {
let accountInspectorNavController =
UIStoryboard.inspector.instantiateViewController(identifier: "AccountInspectorNavigationViewController") as! UINavigationController
let accountInspectorController = accountInspectorNavController.topViewController as! AccountInspectorViewController
accountInspectorNavController.modalPresentationStyle = .formSheet
accountInspectorNavController.preferredContentSize = AccountInspectorViewController.preferredContentSizeForFormSheetDisplay
accountInspectorController.isModal = true
accountInspectorController.account = account
rootSplitViewController.present(accountInspectorNavController, animated: true)
}
func showFeedInspector() {
let timelineWebFeed = timelineFeed as? WebFeed
let articleFeed = currentArticle?.webFeed
guard let feed = timelineWebFeed ?? articleFeed else {
return
}
showFeedInspector(for: feed)
}
func showFeedInspector(for feed: WebFeed) {
let feedInspectorNavController =
UIStoryboard.inspector.instantiateViewController(identifier: "FeedInspectorNavigationViewController") as! UINavigationController
let feedInspectorController = feedInspectorNavController.topViewController as! WebFeedInspectorViewController
feedInspectorNavController.modalPresentationStyle = .formSheet
feedInspectorNavController.preferredContentSize = WebFeedInspectorViewController.preferredContentSizeForFormSheetDisplay
feedInspectorController.webFeed = feed
rootSplitViewController.present(feedInspectorNavController, animated: true)
}
func showAddWebFeed(initialFeed: String? = nil, initialFeedName: String? = nil) {
// Since Add Feed can be opened from anywhere with a keyboard shortcut, we have to deselect any currently selected feeds
selectFeed(nil)
let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddWebFeedViewControllerNav") as! UINavigationController
let addViewController = addNavViewController.topViewController as! AddFeedViewController
addViewController.initialFeed = initialFeed
addViewController.initialFeedName = initialFeedName
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay
masterFeedViewController.present(addNavViewController, animated: true)
}
func showAddRedditFeed() {
let addNavViewController = UIStoryboard.redditAdd.instantiateInitialViewController() as! UINavigationController
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay
masterFeedViewController.present(addNavViewController, animated: true)
}
func showAddTwitterFeed() {
let addNavViewController = UIStoryboard.twitterAdd.instantiateInitialViewController() as! UINavigationController
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFeedViewController.preferredContentSizeForFormSheetDisplay
masterFeedViewController.present(addNavViewController, animated: true)
}
func showAddFolder() {
let addNavViewController = UIStoryboard.add.instantiateViewController(withIdentifier: "AddFolderViewControllerNav") as! UINavigationController
addNavViewController.modalPresentationStyle = .formSheet
addNavViewController.preferredContentSize = AddFolderViewController.preferredContentSizeForFormSheetDisplay
masterFeedViewController.present(addNavViewController, animated: true)
}
func showFullScreenImage(image: UIImage, imageTitle: String?, transitioningDelegate: UIViewControllerTransitioningDelegate) {
let imageVC = UIStoryboard.main.instantiateController(ofType: ImageViewController.self)
imageVC.image = image
imageVC.imageTitle = imageTitle
imageVC.modalPresentationStyle = .currentContext
imageVC.transitioningDelegate = transitioningDelegate
rootSplitViewController.present(imageVC, animated: true)
}
func homePageURLForFeed(_ indexPath: IndexPath) -> URL? {
guard let node = nodeFor(indexPath),
let feed = node.representedObject as? WebFeed,
let homePageURL = feed.homePageURL,
let url = URL(string: homePageURL) else {
return nil
}
return url
}
func showBrowserForFeed(_ indexPath: IndexPath) {
if let url = homePageURLForFeed(indexPath) {
UIApplication.shared.open(url, options: [:])
}
}
func showBrowserForCurrentFeed() {
if let ip = currentFeedIndexPath, let url = homePageURLForFeed(ip) {
UIApplication.shared.open(url, options: [:])
}
}
func showBrowserForArticle(_ article: Article) {
guard let url = article.preferredURL else { return }
UIApplication.shared.open(url, options: [:])
}
func showBrowserForCurrentArticle() {
guard let url = currentArticle?.preferredURL else { return }
UIApplication.shared.open(url, options: [:])
}
func showInAppBrowser() {
if currentArticle != nil {
articleViewController?.openInAppBrowser()
}
else {
masterFeedViewController.openInAppBrowser()
}
}
func navigateToFeeds() {
masterFeedViewController?.focus()
selectArticle(nil)
}
func navigateToTimeline() {
if currentArticle == nil && articles.count > 0 {
selectArticle(articles[0])
}
masterTimelineViewController?.focus()
}
func navigateToDetail() {
articleViewController?.focus()
}
func toggleSidebar() {
rootSplitViewController.preferredDisplayMode = rootSplitViewController.displayMode == .allVisible ? .primaryHidden : .allVisible
}
func selectArticleInCurrentFeed(_ articleID: String, isShowingExtractedArticle: Bool? = nil, articleWindowScrollY: Int? = nil) {
if let article = self.articles.first(where: { $0.articleID == articleID }) {
self.selectArticle(article, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
}
}
func importTheme(filename: String) {
do {
try ArticleThemeImporter.importTheme(controller: rootSplitViewController, filename: filename)
} catch {
NotificationCenter.default.post(name: .didFailToImportThemeWithError, object: nil, userInfo: ["error" : error])
}
}
/// This will dismiss the foremost view controller if the user
/// has launched from an external action (i.e., a widget tap, or
/// selecting an article via a notification).
///
/// The dismiss is only applicable if the view controller is a
/// `SFSafariViewController` or `SettingsViewController`,
/// otherwise, this function does nothing.
func dismissIfLaunchingFromExternalAction() {
guard let presentedController = masterFeedViewController.presentedViewController else { return }
if presentedController.isKind(of: SFSafariViewController.self) {
presentedController.dismiss(animated: true, completion: nil)
}
guard let settings = presentedController.children.first as? SettingsViewController else { return }
settings.dismiss(animated: true, completion: nil)
}
}
// MARK: UISplitViewControllerDelegate
extension SceneCoordinator: UISplitViewControllerDelegate {
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
masterTimelineViewController?.updateUI()
guard !isThreePanelMode else {
return true
}
if let articleViewController = (secondaryViewController as? UINavigationController)?.topViewController as? ArticleViewController {
if currentArticle != nil {
masterNavigationController.pushViewController(articleViewController, animated: false)
}
}
return true
}
func splitViewController(_ splitViewController: UISplitViewController, separateSecondaryFrom primaryViewController: UIViewController) -> UIViewController? {
masterTimelineViewController?.updateUI()
guard !isThreePanelMode else {
return subSplitViewController
}
if let articleViewController = masterNavigationController.viewControllers.last as? ArticleViewController {
articleViewController.showBars(self)
masterNavigationController.popViewController(animated: false)
let controller = addNavControllerIfNecessary(articleViewController, showButton: true)
return controller
}
if currentArticle == nil {
let articleViewController = UIStoryboard.main.instantiateController(ofType: ArticleViewController.self)
articleViewController.coordinator = self
let controller = addNavControllerIfNecessary(articleViewController, showButton: true)
return controller
}
return nil
}
}
// MARK: UINavigationControllerDelegate
extension SceneCoordinator: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
if UIApplication.shared.applicationState == .background {
return
}
// If we are showing the Feeds and only the feeds start clearing stuff
if viewController === masterFeedViewController && !isThreePanelMode && !isTimelineViewControllerPending {
activityManager.invalidateCurrentActivities()
selectFeed(nil, animations: [.scroll, .select, .navigation])
return
}
// If we are using a phone and navigate away from the detail, clear up the article resources (including activity).
// Don't clear it if we have pushed an ArticleViewController, but don't yet see it on the navigation stack.
// This happens when we are going to the next unread and we need to grab another timeline to continue. The
// ArticleViewController will be pushed, but we will briefly show the Timeline. Don't clear things out when that happens.
if viewController === masterTimelineViewController && !isThreePanelMode && rootSplitViewController.isCollapsed && !isArticleViewControllerPending {
currentArticle = nil
masterTimelineViewController?.updateArticleSelection(animations: [.scroll, .select, .navigation])
activityManager.invalidateReading()
// Restore any bars hidden by the article controller
showStatusBar()
navigationController.setNavigationBarHidden(false, animated: true)
navigationController.setToolbarHidden(false, animated: true)
return
}
}
}
// MARK: Private
private extension SceneCoordinator {
func markArticlesWithUndo(_ articles: [Article], statusKey: ArticleStatus.Key, flag: Bool, completion: (() -> Void)? = nil) {
guard let undoManager = undoManager,
let markReadCommand = MarkStatusCommand(initialArticles: articles, statusKey: statusKey, flag: flag, undoManager: undoManager, completion: completion) else {
completion?()
return
}
runCommand(markReadCommand)
}
func updateUnreadCount() {
var count = 0
for article in articles {
if !article.status.read {
count += 1
}
}
timelineUnreadCount = count
}
func rebuildArticleDictionaries() {
var idDictionary = [String: Article]()
articles.forEach { article in
idDictionary[article.articleID] = article
}
_idToArticleDictionary = idDictionary
articleDictionaryNeedsUpdate = false
}
func ensureFeedIsAvailableToSelect(_ feed: Feed, completion: @escaping () -> Void) {
addToFilterExeptionsIfNecessary(feed)
addShadowTableToFilterExceptions()
rebuildBackingStores(completion: {
self.treeControllerDelegate.resetFilterExceptions()
completion()
})
}
func addToFilterExeptionsIfNecessary(_ feed: Feed?) {
if isReadFeedsFiltered, let feedID = feed?.feedID {
if feed is SmartFeed {
treeControllerDelegate.addFilterException(feedID)
} else if let folderFeed = feed as? Folder {
if folderFeed.account?.existingFolder(withID: folderFeed.folderID) != nil {
treeControllerDelegate.addFilterException(feedID)
}
} else if let webFeed = feed as? WebFeed {
if webFeed.account?.existingWebFeed(withWebFeedID: webFeed.webFeedID) != nil {
treeControllerDelegate.addFilterException(feedID)
addParentFolderToFilterExceptions(webFeed)
}
}
}
}
func addParentFolderToFilterExceptions(_ feed: Feed) {
guard let node = treeController.rootNode.descendantNodeRepresentingObject(feed as AnyObject),
let folder = node.parent?.representedObject as? Folder,
let folderFeedID = folder.feedID else {
return
}
treeControllerDelegate.addFilterException(folderFeedID)
}
func addShadowTableToFilterExceptions() {
for section in shadowTable {
for feedNode in section.feedNodes {
if let feed = feedNode.node.representedObject as? Feed, let feedID = feed.feedID {
treeControllerDelegate.addFilterException(feedID)
}
}
}
}
func queueRebuildBackingStores() {
rebuildBackingStoresQueue.add(self, #selector(rebuildBackingStoresWithDefaults))
}
@objc func rebuildBackingStoresWithDefaults() {
rebuildBackingStores()
}
func rebuildBackingStores(initialLoad: Bool = false, updateExpandedNodes: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
if !BatchUpdate.shared.isPerforming {
addToFilterExeptionsIfNecessary(timelineFeed)
treeController.rebuild()
treeControllerDelegate.resetFilterExceptions()
updateExpandedNodes?()
let changes = rebuildShadowTable()
masterFeedViewController.reloadFeeds(initialLoad: initialLoad, changes: changes, completion: completion)
}
}
func rebuildShadowTable() -> ShadowTableChanges {
var newShadowTable = [(sectionID: String, feedNodes: [FeedNode])]()
for i in 0..<treeController.rootNode.numberOfChildNodes {
var feedNodes = [FeedNode]()
let sectionNode = treeController.rootNode.childAtIndex(i)!
if isExpanded(sectionNode) {
for node in sectionNode.childNodes {
feedNodes.append(FeedNode(node))
if isExpanded(node) {
for child in node.childNodes {
feedNodes.append(FeedNode(child))
}
}
}
}
let sectionID = (sectionNode.representedObject as? Account)?.accountID ?? ""
newShadowTable.append((sectionID: sectionID, feedNodes: feedNodes))
}
// If we have a current Feed IndexPath it is no longer valid and needs reset.
if currentFeedIndexPath != nil {
currentFeedIndexPath = indexPathFor(timelineFeed as AnyObject)
}
// Compute the differences in the shadow table rows and the expanded table entries
var changes = [ShadowTableChanges.RowChanges]()
let expandedTableDifference = lastExpandedTable.symmetricDifference(expandedTable)
for (section, newSectionRows) in newShadowTable.enumerated() {
var moves = Set<ShadowTableChanges.Move>()
var inserts = Set<Int>()
var deletes = Set<Int>()
let oldFeedNodes = shadowTable.first(where: { $0.sectionID == newSectionRows.sectionID })?.feedNodes ?? [FeedNode]()
let diff = newSectionRows.feedNodes.difference(from: oldFeedNodes).inferringMoves()
for change in diff {
switch change {
case .insert(let offset, _, let associated):
if let associated = associated {
moves.insert(ShadowTableChanges.Move(associated, offset))
} else {
inserts.insert(offset)
}
case .remove(let offset, _, let associated):
if let associated = associated {
moves.insert(ShadowTableChanges.Move(offset, associated))
} else {
deletes.insert(offset)
}
}
}
// We need to reload the difference in expanded rows to get the disclosure arrows correct when programmatically changing their state
var reloads = Set<Int>()
for (index, newFeedNode) in newSectionRows.feedNodes.enumerated() {
if let newFeedNodeContainerID = (newFeedNode.node.representedObject as? Container)?.containerID {
if expandedTableDifference.contains(newFeedNodeContainerID) {
reloads.insert(index)
}
}
}
changes.append(ShadowTableChanges.RowChanges(section: section, deletes: deletes, inserts: inserts, reloads: reloads, moves: moves))
}
lastExpandedTable = expandedTable
// Compute the difference in the shadow table sections
var moves = Set<ShadowTableChanges.Move>()
var inserts = Set<Int>()
var deletes = Set<Int>()
let oldSections = shadowTable.map { $0.sectionID }
let newSections = newShadowTable.map { $0.sectionID }
let diff = newSections.difference(from: oldSections).inferringMoves()
for change in diff {
switch change {
case .insert(let offset, _, let associated):
if let associated = associated {
moves.insert(ShadowTableChanges.Move(associated, offset))
} else {
inserts.insert(offset)
}
case .remove(let offset, _, let associated):
if let associated = associated {
moves.insert(ShadowTableChanges.Move(offset, associated))
} else {
deletes.insert(offset)
}
}
}
shadowTable = newShadowTable
return ShadowTableChanges(deletes: deletes, inserts: inserts, moves: moves, rowChanges: changes)
}
func shadowTableContains(_ feed: Feed) -> Bool {
for section in shadowTable {
for feedNode in section.feedNodes {
if let nodeFeed = feedNode.node.representedObject as? Feed, nodeFeed.feedID == feed.feedID {
return true
}
}
}
return false
}
func clearTimelineIfNoLongerAvailable() {
if let feed = timelineFeed, !shadowTableContains(feed) {
selectFeed(nil, deselectArticle: true)
}
}
func indexPathFor(_ object: AnyObject) -> IndexPath? {
guard let node = treeController.rootNode.descendantNodeRepresentingObject(object) else {
return nil
}
return indexPathFor(node)
}
func setTimelineFeed(_ feed: Feed?, animated: Bool, completion: (() -> Void)? = nil) {
timelineFeed = feed
fetchAndReplaceArticlesAsync(animated: animated) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: true)
completion?()
}
}
func updateShowNamesAndIcons() {
if timelineFeed is WebFeed {
showFeedNames = {
for article in articles {
if !article.byline().isEmpty {
return .byline
}
}
return .none
}()
} else {
showFeedNames = .feed
}
if showFeedNames == .feed {
self.showIcons = true
return
}
if showFeedNames == .none {
self.showIcons = false
return
}
for article in articles {
if let authors = article.authors {
for author in authors {
if author.avatarURL != nil {
self.showIcons = true
return
}
}
}
}
self.showIcons = false
}
func markExpanded(_ containerID: ContainerIdentifier) {
expandedTable.insert(containerID)
}
func markExpanded(_ containerIdentifiable: ContainerIdentifiable) {
if let containerID = containerIdentifiable.containerID {
markExpanded(containerID)
}
}
func markExpanded(_ node: Node) {
if let containerIdentifiable = node.representedObject as? ContainerIdentifiable {
markExpanded(containerIdentifiable)
}
}
func unmarkExpanded(_ containerID: ContainerIdentifier) {
expandedTable.remove(containerID)
}
func unmarkExpanded(_ containerIdentifiable: ContainerIdentifiable) {
if let containerID = containerIdentifiable.containerID {
unmarkExpanded(containerID)
}
}
func unmarkExpanded(_ node: Node) {
if let containerIdentifiable = node.representedObject as? ContainerIdentifiable {
unmarkExpanded(containerIdentifiable)
}
}
// MARK: Select Prev Unread
@discardableResult
func selectPrevUnreadArticleInTimeline() -> Bool {
let startingRow: Int = {
if let articleRow = currentArticleRow {
return articleRow
} else {
return articles.count - 1
}
}()
return selectPrevArticleInTimeline(startingRow: startingRow)
}
func selectPrevArticleInTimeline(startingRow: Int) -> Bool {
guard startingRow >= 0 else {
return false
}
for i in (0...startingRow).reversed() {
let article = articles[i]
if !article.status.read {
selectArticle(article)
return true
}
}
return false
}
func selectPrevUnreadFeedFetcher() {
let indexPath: IndexPath = {
if currentFeedIndexPath == nil {
return IndexPath(row: 0, section: 0)
} else {
return currentFeedIndexPath!
}
}()
// Increment or wrap around the IndexPath
let nextIndexPath: IndexPath = {
if indexPath.row - 1 < 0 {
if indexPath.section - 1 < 0 {
return IndexPath(row: shadowTable[shadowTable.count - 1].feedNodes.count - 1, section: shadowTable.count - 1)
} else {
return IndexPath(row: shadowTable[indexPath.section - 1].feedNodes.count - 1, section: indexPath.section - 1)
}
} else {
return IndexPath(row: indexPath.row - 1, section: indexPath.section)
}
}()
if selectPrevUnreadFeedFetcher(startingWith: nextIndexPath) {
return
}
let maxIndexPath = IndexPath(row: shadowTable[shadowTable.count - 1].feedNodes.count - 1, section: shadowTable.count - 1)
selectPrevUnreadFeedFetcher(startingWith: maxIndexPath)
}
@discardableResult
func selectPrevUnreadFeedFetcher(startingWith indexPath: IndexPath) -> Bool {
for i in (0...indexPath.section).reversed() {
let startingRow: Int = {
if indexPath.section == i {
return indexPath.row
} else {
return shadowTable[i].feedNodes.count - 1
}
}()
for j in (0...startingRow).reversed() {
let prevIndexPath = IndexPath(row: j, section: i)
guard let node = nodeFor(prevIndexPath), let unreadCountProvider = node.representedObject as? UnreadCountProvider else {
assertionFailure()
return true
}
if isExpanded(node) {
continue
}
if unreadCountProvider.unreadCount > 0 {
selectFeed(indexPath: prevIndexPath, animations: [.scroll, .navigation])
return true
}
}
}
return false
}
// MARK: Select Next Unread
@discardableResult
func selectFirstUnreadArticleInTimeline() -> Bool {
return selectNextArticleInTimeline(startingRow: 0, animated: true)
}
@discardableResult
func selectNextUnreadArticleInTimeline() -> Bool {
let startingRow: Int = {
if let articleRow = currentArticleRow {
return articleRow + 1
} else {
return 0
}
}()
return selectNextArticleInTimeline(startingRow: startingRow, animated: false)
}
func selectNextArticleInTimeline(startingRow: Int, animated: Bool) -> Bool {
guard startingRow < articles.count else {
return false
}
for i in startingRow..<articles.count {
let article = articles[i]
if !article.status.read {
selectArticle(article, animations: [.scroll, .navigation])
return true
}
}
return false
}
func selectNextUnreadFeed(completion: @escaping () -> Void) {
let indexPath: IndexPath = {
if currentFeedIndexPath == nil {
return IndexPath(row: -1, section: 0)
} else {
return currentFeedIndexPath!
}
}()
// Increment or wrap around the IndexPath
let nextIndexPath: IndexPath = {
if indexPath.row + 1 >= shadowTable[indexPath.section].feedNodes.count {
if indexPath.section + 1 >= shadowTable.count {
return IndexPath(row: 0, section: 0)
} else {
return IndexPath(row: 0, section: indexPath.section + 1)
}
} else {
return IndexPath(row: indexPath.row + 1, section: indexPath.section)
}
}()
selectNextUnreadFeed(startingWith: nextIndexPath) { found in
if !found {
self.selectNextUnreadFeed(startingWith: IndexPath(row: 0, section: 0)) { _ in
completion()
}
} else {
completion()
}
}
}
func selectNextUnreadFeed(startingWith indexPath: IndexPath, completion: @escaping (Bool) -> Void) {
for i in indexPath.section..<shadowTable.count {
let startingRow: Int = {
if indexPath.section == i {
return indexPath.row
} else {
return 0
}
}()
for j in startingRow..<shadowTable[i].feedNodes.count {
let nextIndexPath = IndexPath(row: j, section: i)
guard let node = nodeFor(nextIndexPath), let unreadCountProvider = node.representedObject as? UnreadCountProvider else {
assertionFailure()
completion(false)
return
}
if isExpanded(node) {
continue
}
if unreadCountProvider.unreadCount > 0 {
selectFeed(indexPath: nextIndexPath, animations: [.scroll, .navigation], deselectArticle: false) {
self.currentArticle = nil
completion(true)
}
return
}
}
}
completion(false)
}
// MARK: Fetching Articles
func emptyTheTimeline() {
if !articles.isEmpty {
replaceArticles(with: Set<Article>(), animated: false)
}
}
func sortParametersDidChange() {
replaceArticles(with: Set(articles), animated: true)
}
func replaceArticles(with unsortedArticles: Set<Article>, animated: Bool) {
let sortedArticles = Array(unsortedArticles).sortedByDate(sortDirection, groupByFeed: groupByFeed)
replaceArticles(with: sortedArticles, animated: animated)
}
func replaceArticles(with sortedArticles: ArticleArray, animated: Bool) {
if articles != sortedArticles {
articles = sortedArticles
updateShowNamesAndIcons()
updateUnreadCount()
masterTimelineViewController?.reloadArticles(animated: animated)
}
}
func queueFetchAndMergeArticles() {
fetchAndMergeArticlesQueue.add(self, #selector(fetchAndMergeArticlesAsync))
}
@objc func fetchAndMergeArticlesAsync() {
fetchAndMergeArticlesAsync(animated: true) {
self.masterTimelineViewController?.reinitializeArticles(resetScroll: false)
self.masterTimelineViewController?.restoreSelectionIfNecessary(adjustScroll: false)
}
}
func fetchAndMergeArticlesAsync(animated: Bool = true, completion: (() -> Void)? = nil) {
guard let timelineFeed = timelineFeed else {
return
}
fetchUnsortedArticlesAsync(for: [timelineFeed]) { [weak self] (unsortedArticles) in
// Merge articles by articleID. For any unique articleID in current articles, add to unsortedArticles.
guard let strongSelf = self else {
return
}
let unsortedArticleIDs = unsortedArticles.articleIDs()
var updatedArticles = unsortedArticles
for article in strongSelf.articles {
if !unsortedArticleIDs.contains(article.articleID) {
updatedArticles.insert(article)
}
if article.account?.existingWebFeed(withWebFeedID: article.webFeedID) == nil {
updatedArticles.remove(article)
}
}
strongSelf.replaceArticles(with: updatedArticles, animated: animated)
completion?()
}
}
func cancelPendingAsyncFetches() {
fetchSerialNumber += 1
fetchRequestQueue.cancelAllRequests()
}
func fetchAndReplaceArticlesAsync(animated: Bool, completion: @escaping () -> Void) {
// To be called when we need to do an entire fetch, but an async delay is okay.
// Example: we have the Today feed selected, and the calendar day just changed.
cancelPendingAsyncFetches()
guard let timelineFeed = timelineFeed else {
emptyTheTimeline()
completion()
return
}
var fetchers = [ArticleFetcher]()
fetchers.append(timelineFeed)
if exceptionArticleFetcher != nil {
fetchers.append(exceptionArticleFetcher!)
exceptionArticleFetcher = nil
}
fetchUnsortedArticlesAsync(for: fetchers) { [weak self] (articles) in
self?.replaceArticles(with: articles, animated: animated)
completion()
}
}
func fetchUnsortedArticlesAsync(for representedObjects: [Any], completion: @escaping ArticleSetBlock) {
// The callback will *not* be called if the fetch is no longer relevant — that is,
// if it’s been superseded by a newer fetch, or the timeline was emptied, etc., it won’t get called.
precondition(Thread.isMainThread)
cancelPendingAsyncFetches()
let fetchers = representedObjects.compactMap { $0 as? ArticleFetcher }
let fetchOperation = FetchRequestOperation(id: fetchSerialNumber, readFilterEnabledTable: readFilterEnabledTable, fetchers: fetchers) { [weak self] (articles, operation) in
precondition(Thread.isMainThread)
guard !operation.isCanceled, let strongSelf = self, operation.id == strongSelf.fetchSerialNumber else {
return
}
completion(articles)
}
fetchRequestQueue.add(fetchOperation)
}
func timelineFetcherContainsAnyPseudoFeed() -> Bool {
if timelineFeed is PseudoFeed {
return true
}
return false
}
func timelineFetcherContainsAnyFolder() -> Bool {
if timelineFeed is Folder {
return true
}
return false
}
func timelineFetcherContainsAnyFeed(_ feeds: Set<WebFeed>) -> Bool {
// Return true if there’s a match or if a folder contains (recursively) one of feeds
if let feed = timelineFeed as? WebFeed {
for oneFeed in feeds {
if feed.webFeedID == oneFeed.webFeedID || feed.url == oneFeed.url {
return true
}
}
} else if let folder = timelineFeed as? Folder {
for oneFeed in feeds {
if folder.hasWebFeed(with: oneFeed.webFeedID) || folder.hasWebFeed(withURL: oneFeed.url) {
return true
}
}
}
return false
}
// MARK: Three Panel Mode
func installTimelineControllerIfNecessary(animated: Bool) {
if navControllerForTimeline().viewControllers.filter({ $0 is MasterTimelineViewController }).count < 1 {
isTimelineViewControllerPending = true
masterTimelineViewController = UIStoryboard.main.instantiateController(ofType: MasterTimelineViewController.self)
masterTimelineViewController!.coordinator = self
navControllerForTimeline().pushViewController(masterTimelineViewController!, animated: animated)
}
}
@discardableResult
func installArticleController(state: ArticleViewController.State? = nil, animated: Bool) -> ArticleViewController {
isArticleViewControllerPending = true
let articleController = UIStoryboard.main.instantiateController(ofType: ArticleViewController.self)
articleController.coordinator = self
articleController.article = currentArticle
articleController.restoreState = state
if let subSplit = subSplitViewController {
let controller = addNavControllerIfNecessary(articleController, showButton: false)
subSplit.showDetailViewController(controller, sender: self)
} else if rootSplitViewController.isCollapsed || wasRootSplitViewControllerCollapsed {
masterNavigationController.pushViewController(articleController, animated: animated)
} else {
let controller = addNavControllerIfNecessary(articleController, showButton: true)
rootSplitViewController.showDetailViewController(controller, sender: self)
}
return articleController
}
func addNavControllerIfNecessary(_ controller: UIViewController, showButton: Bool) -> UIViewController {
// You will sometimes get a compact horizontal size class while in three panel mode. Dunno why it lies.
if rootSplitViewController.traitCollection.horizontalSizeClass == .compact && !isThreePanelMode {
return controller
} else {
let navController = InteractiveNavigationController.template(rootViewController: controller)
navController.isToolbarHidden = false
if showButton {
controller.navigationItem.leftBarButtonItem = rootSplitViewController.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
} else {
controller.navigationItem.leftBarButtonItem = nil
controller.navigationItem.leftItemsSupplementBackButton = false
}
return navController
}
}
func installSubSplit() {
rootSplitViewController.preferredPrimaryColumnWidthFraction = 0.30
subSplitViewController = UISplitViewController()
subSplitViewController!.preferredDisplayMode = .allVisible
subSplitViewController!.viewControllers = [InteractiveNavigationController.template()]
subSplitViewController!.preferredPrimaryColumnWidthFraction = 0.4285
rootSplitViewController.showDetailViewController(subSplitViewController!, sender: self)
rootSplitViewController.setOverrideTraitCollection(UITraitCollection(horizontalSizeClass: .regular), forChild: subSplitViewController!)
}
func navControllerForTimeline() -> UINavigationController {
if let subSplit = subSplitViewController {
return subSplit.viewControllers.first as! UINavigationController
} else {
return masterNavigationController
}
}
func configureThreePanelMode() {
articleViewController?.stopArticleExtractorIfProcessing()
let articleViewControllerState = articleViewController?.currentState
defer {
masterNavigationController.viewControllers = [masterFeedViewController]
}
if rootSplitViewController.viewControllers.last is InteractiveNavigationController {
_ = rootSplitViewController.viewControllers.popLast()
}
installSubSplit()
installTimelineControllerIfNecessary(animated: false)
masterTimelineViewController?.navigationItem.leftBarButtonItem = rootSplitViewController.displayModeButtonItem
masterTimelineViewController?.navigationItem.leftItemsSupplementBackButton = true
installArticleController(state: articleViewControllerState, animated: false)
masterFeedViewController.restoreSelectionIfNecessary(adjustScroll: true)
masterTimelineViewController!.restoreSelectionIfNecessary(adjustScroll: false)
}
func configureStandardPanelMode() {
articleViewController?.stopArticleExtractorIfProcessing()
let articleViewControllerState = articleViewController?.currentState
rootSplitViewController.preferredPrimaryColumnWidthFraction = UISplitViewController.automaticDimension
// Set the is Pending flags early to prevent the navigation controller delegate from thinking that we
// swiping around in the user interface
isTimelineViewControllerPending = true
isArticleViewControllerPending = true
masterNavigationController.viewControllers = [masterFeedViewController]
if rootSplitViewController.viewControllers.last is UISplitViewController {
subSplitViewController = nil
_ = rootSplitViewController.viewControllers.popLast()
}
if currentFeedIndexPath != nil {
masterTimelineViewController = UIStoryboard.main.instantiateController(ofType: MasterTimelineViewController.self)
masterTimelineViewController!.coordinator = self
masterNavigationController.pushViewController(masterTimelineViewController!, animated: false)
}
installArticleController(state: articleViewControllerState, animated: false)
}
// MARK: NSUserActivity
func windowState() -> [AnyHashable: Any] {
let containerExpandedWindowState = expandedTable.map( { $0.userInfo })
var readArticlesFilterState = [[AnyHashable: AnyHashable]: Bool]()
for key in readFilterEnabledTable.keys {
readArticlesFilterState[key.userInfo] = readFilterEnabledTable[key]
}
return [
UserInfoKey.readFeedsFilterState: isReadFeedsFiltered,
UserInfoKey.containerExpandedWindowState: containerExpandedWindowState,
UserInfoKey.readArticlesFilterState: readArticlesFilterState
]
}
func handleSelectFeed(_ userInfo: [AnyHashable : Any]?) {
guard let userInfo = userInfo,
let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable],
let feedIdentifier = FeedIdentifier(userInfo: feedIdentifierUserInfo) else {
return
}
treeControllerDelegate.addFilterException(feedIdentifier)
switch feedIdentifier {
case .smartFeed:
guard let smartFeed = SmartFeedsController.shared.find(by: feedIdentifier) else { return }
markExpanded(SmartFeedsController.shared)
rebuildBackingStores(initialLoad: true, completion: {
self.treeControllerDelegate.resetFilterExceptions()
if let indexPath = self.indexPathFor(smartFeed) {
self.selectFeed(indexPath: indexPath) {
self.masterFeedViewController.focus()
}
}
})
case .script:
break
case .folder(let accountID, let folderName):
guard let accountNode = self.findAccountNode(accountID: accountID),
let account = accountNode.representedObject as? Account else {
return
}
markExpanded(account)
rebuildBackingStores(initialLoad: true, completion: {
self.treeControllerDelegate.resetFilterExceptions()
if let folderNode = self.findFolderNode(folderName: folderName, beginningAt: accountNode), let indexPath = self.indexPathFor(folderNode) {
self.selectFeed(indexPath: indexPath) {
self.masterFeedViewController.focus()
}
}
})
case .webFeed(let accountID, let webFeedID):
guard let accountNode = findAccountNode(accountID: accountID),
let account = accountNode.representedObject as? Account,
let webFeed = account.existingWebFeed(withWebFeedID: webFeedID) else {
return
}
self.discloseWebFeed(webFeed, initialLoad: true) {
self.masterFeedViewController.focus()
}
}
}
func handleReadArticle(_ userInfo: [AnyHashable : Any]?) {
guard let userInfo = userInfo else { return }
guard let articlePathUserInfo = userInfo[UserInfoKey.articlePath] as? [AnyHashable : Any],
let accountID = articlePathUserInfo[ArticlePathKey.accountID] as? String,
let accountName = articlePathUserInfo[ArticlePathKey.accountName] as? String,
let webFeedID = articlePathUserInfo[ArticlePathKey.webFeedID] as? String,
let articleID = articlePathUserInfo[ArticlePathKey.articleID] as? String,
let accountNode = findAccountNode(accountID: accountID, accountName: accountName),
let account = accountNode.representedObject as? Account else {
return
}
exceptionArticleFetcher = SingleArticleFetcher(account: account, articleID: articleID)
if restoreFeedSelection(userInfo, accountID: accountID, webFeedID: webFeedID, articleID: articleID) {
return
}
guard let webFeed = account.existingWebFeed(withWebFeedID: webFeedID) else {
return
}
discloseWebFeed(webFeed) {
self.selectArticleInCurrentFeed(articleID)
}
}
func restoreFeedSelection(_ userInfo: [AnyHashable : Any], accountID: String, webFeedID: String, articleID: String) -> Bool {
guard let feedIdentifierUserInfo = userInfo[UserInfoKey.feedIdentifier] as? [AnyHashable : AnyHashable],
let feedIdentifier = FeedIdentifier(userInfo: feedIdentifierUserInfo),
let isShowingExtractedArticle = userInfo[UserInfoKey.isShowingExtractedArticle] as? Bool,
let articleWindowScrollY = userInfo[UserInfoKey.articleWindowScrollY] as? Int else {
return false
}
switch feedIdentifier {
case .script:
return false
case .smartFeed, .folder:
let found = selectFeedAndArticle(feedIdentifier: feedIdentifier, articleID: articleID, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
if found {
treeControllerDelegate.addFilterException(feedIdentifier)
}
return found
case .webFeed:
let found = selectFeedAndArticle(feedIdentifier: feedIdentifier, articleID: articleID, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
if found {
treeControllerDelegate.addFilterException(feedIdentifier)
if let webFeedNode = nodeFor(feedID: feedIdentifier), let folder = webFeedNode.parent?.representedObject as? Folder, let folderFeedID = folder.feedID {
treeControllerDelegate.addFilterException(folderFeedID)
}
}
return found
}
}
func findAccountNode(accountID: String, accountName: String? = nil) -> Node? {
if let node = treeController.rootNode.descendantNode(where: { ($0.representedObject as? Account)?.accountID == accountID }) {
return node
}
if let accountName = accountName, let node = treeController.rootNode.descendantNode(where: { ($0.representedObject as? Account)?.nameForDisplay == accountName }) {
return node
}
return nil
}
func findFolderNode(folderName: String, beginningAt startingNode: Node) -> Node? {
if let node = startingNode.descendantNode(where: { ($0.representedObject as? Folder)?.nameForDisplay == folderName }) {
return node
}
return nil
}
func findWebFeedNode(webFeedID: String, beginningAt startingNode: Node) -> Node? {
if let node = startingNode.descendantNode(where: { ($0.representedObject as? WebFeed)?.webFeedID == webFeedID }) {
return node
}
return nil
}
func selectFeedAndArticle(feedIdentifier: FeedIdentifier, articleID: String, isShowingExtractedArticle: Bool, articleWindowScrollY: Int) -> Bool {
guard let feedNode = nodeFor(feedID: feedIdentifier), let feedIndexPath = indexPathFor(feedNode) else { return false }
selectFeed(indexPath: feedIndexPath) {
self.selectArticleInCurrentFeed(articleID, isShowingExtractedArticle: isShowingExtractedArticle, articleWindowScrollY: articleWindowScrollY)
}
return true
}
}
| mit | 375d26e1e83d88d960261735b1004675 | 30.771274 | 187 | 0.751754 | 4.225529 | false | false | false | false |
ProcedureKit/ProcedureKit | Sources/ProcedureKit/DispatchQueue+ProcedureKit.swift | 2 | 4445 | //
// ProcedureKit
//
// Copyright © 2015-2018 ProcedureKit. All rights reserved.
//
import Foundation
import Dispatch
// MARK: - Queue
public extension DispatchQueue {
static var isMainDispatchQueue: Bool {
return mainQueueScheduler.isOnScheduledQueue
}
var isMainDispatchQueue: Bool {
return mainQueueScheduler.isScheduledQueue(self)
}
static var `default`: DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.QoSClass.default)
}
static var initiated: DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated)
}
static var interactive: DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive)
}
static var utility: DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.QoSClass.utility)
}
static var background: DispatchQueue {
return DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
}
static func concurrent(label: String, qos: DispatchQoS = .default, autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency = .inherit, target: DispatchQueue? = nil) -> DispatchQueue {
return DispatchQueue(label: label, qos: qos, attributes: [.concurrent], autoreleaseFrequency: autoreleaseFrequency, target: target)
}
static func onMain<T>(execute work: () throws -> T) rethrows -> T {
guard isMainDispatchQueue else {
return try DispatchQueue.main.sync(execute: work)
}
return try work()
}
static var currentQoSClass: DispatchQoS.QoSClass {
return DispatchQoS.QoSClass(rawValue: qos_class_self()) ?? .unspecified
}
}
internal extension QualityOfService {
var qos: DispatchQoS {
switch self {
case .userInitiated: return DispatchQoS.userInitiated
case .userInteractive: return DispatchQoS.userInteractive
case .utility: return DispatchQoS.utility
case .background: return DispatchQoS.background
case .default: return DispatchQoS.default
@unknown default:
return DispatchQoS.default
}
}
var qosClass: DispatchQoS.QoSClass {
switch self {
case .userInitiated: return .userInitiated
case .userInteractive: return .userInteractive
case .utility: return .utility
case .background: return .background
case .default: return .default
@unknown default:
return .default
}
}
}
extension DispatchQoS.QoSClass: Comparable {
public static func < (lhs: DispatchQoS.QoSClass, rhs: DispatchQoS.QoSClass) -> Bool { // swiftlint:disable:this cyclomatic_complexity
switch lhs {
case .unspecified:
return rhs != .unspecified
case .background:
switch rhs {
case .unspecified, lhs: return false
default: return true
}
case .utility:
switch rhs {
case .default, .userInitiated, .userInteractive: return true
default: return false
}
case .default:
switch rhs {
case .userInitiated, .userInteractive: return true
default: return false
}
case .userInitiated:
return rhs == .userInteractive
case .userInteractive:
return false
@unknown default:
fatalError()
}
}
}
extension DispatchQoS: Comparable {
public static func < (lhs: DispatchQoS, rhs: DispatchQoS) -> Bool {
if lhs.qosClass < rhs.qosClass { return true }
else if lhs.qosClass > rhs.qosClass { return false }
else { // qosClass are equal
return lhs.relativePriority < rhs.relativePriority
}
}
}
internal final class Scheduler {
var key: DispatchSpecificKey<UInt8>
var value: UInt8 = 1
init(queue: DispatchQueue) {
key = DispatchSpecificKey()
queue.setSpecific(key: key, value: value)
}
var isOnScheduledQueue: Bool {
guard let retrieved = DispatchQueue.getSpecific(key: key) else { return false }
return value == retrieved
}
func isScheduledQueue(_ queue: DispatchQueue) -> Bool {
guard let retrieved = queue.getSpecific(key: key) else { return false }
return value == retrieved
}
}
internal let mainQueueScheduler = Scheduler(queue: DispatchQueue.main)
| mit | 2568011e731ab127b98bb2607ddb91cf | 29.231293 | 188 | 0.64784 | 5.137572 | false | false | false | false |
tattn/SPAJAM2017-Final | SPAJAM2017Final/Utility/Extension/UIImageView+.swift | 1 | 2039 | //
// UIImageView+.swift
// HackathonStarter
//
// Created by 田中 達也 on 2016/07/20.
// Copyright © 2016年 tattn. All rights reserved.
//
import UIKit
import Kingfisher
private let activityIndicatorViewTag = 2017
extension UIImageView {
func setWebImage(_ url: URL?) {
kf.setImage(with: url)
}
@nonobjc
func setWebImage(_ urlString: String) {
setWebImage(urlString.url)
}
func setWebImageWithIndicator(_ url: URL?, indicatorColor: UIColor = .white) {
addLoading()
kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil) { [weak self] _ in
self?.removeLoading()
}
}
@nonobjc
func setWebImageWithIndicator(_ urlString: String) {
setWebImageWithIndicator(urlString.url)
}
func cancelDownload() {
kf.cancelDownloadTask()
}
fileprivate func addLoading(_ indicatorColor: UIColor = .white) {
if let loading = viewWithTag(activityIndicatorViewTag) as? UIActivityIndicatorView {
loading.startAnimating()
} else {
let activityIndicatorView = UIActivityIndicatorView(frame: .init(x: 0, y: 0, width: 50, height: 50))
activityIndicatorView.center = center
activityIndicatorView.hidesWhenStopped = false
activityIndicatorView.activityIndicatorViewStyle = .white
activityIndicatorView.layer.opacity = 0.8
activityIndicatorView.color = indicatorColor
activityIndicatorView.tag = activityIndicatorViewTag
activityIndicatorView.startAnimating()
addSubview(activityIndicatorView)
activityIndicatorView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
fileprivate func removeLoading() {
if let activityIndicatorView = self.viewWithTag(activityIndicatorViewTag) as? UIActivityIndicatorView {
activityIndicatorView.stopAnimating()
activityIndicatorView.removeFromSuperview()
}
}
}
| mit | 11ac5820bb8dcc4b262ad772d090f7a8 | 30.169231 | 112 | 0.664857 | 5.289817 | false | false | false | false |
varpeti/Suli | Mobil/work/varpe8/homeworks/04/main.swift | 1 | 5230 | //*/// Cards
class Card
{
// A legtöbb kártyában van többértékűség (Ace, TheFool, Joker stb)
let value: (Int, Int)
// A legtöbb kártyában van rank és suit
let rank: String
let suit: String
init(suit: String, rank: String, value: (Int, Int))
{
self.value = value
self.rank = rank
self.suit = suit
}
init(rank: String, value: (Int, Int))
{
self.value = value
self.rank = rank
self.suit = ""
}
// Kiíráshoz
func p() -> String
{
return "[\(suit)\(rank)]"
}
// Összehasonlítás (a tuplesekkel jól megy)
static func ==(lhs: Card, rhs: Card) -> Bool
{
return lhs.value==rhs.value
}
static func <(lhs: Card, rhs: Card) -> Bool
{
return lhs.value<rhs.value
}
static func >(lhs: Card, rhs: Card) -> Bool
{
return lhs.value>rhs.value
}
static func <=(lhs: Card, rhs: Card) -> Bool
{
return lhs.value<=rhs.value
}
static func >=(lhs: Card, rhs: Card) -> Bool
{
return lhs.value>=rhs.value
}
}
//*/// Playing Cards
// "CaseIterable after the enumeration’s name and Swift exposes a collection of all the cases as an allCases property of the enumeration type."
enum Rank: Int, CaseIterable
{
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
// BlackJack értékek
func value() -> (Int, Int)
{
switch self
{
case .Ace : return (0, 11)
case .Jack, .Queen, .King : return (10, 10)
default : return (rawValue, rawValue)
}
}
func name() -> String
{
switch self
{
case .Ace : return " A"
case .Jack : return " J"
case .Queen : return " Q"
case .King : return " K"
case .Ten : return "10"
default : return " \(rawValue)"
}
}
}
enum Suit: String, CaseIterable
{
case Spade, Heart, Diamond, Club
func name() -> String
{
//I \u{2665} Unicode
switch self
{
case .Spade : return "\u{2660}"
case .Heart : return "\u{2665}"
case .Diamond : return "\u{2666}"
case .Club : return "\u{2663}"
}
}
}
class PlayingCard : Card
{
init(suit : Suit, rank : Rank)
{
super.init(suit: suit.name(),rank: rank.name(),value: rank.value())
}
}
//*/// Decks
class DeckOfPlayingCards
{
var deck : [PlayingCard] = []
init()
{
for s in Suit.allCases
{
for r in Rank.allCases
{
deck.append(PlayingCard(suit: s, rank: r))
}
}
}
func p(_ id : Int) -> String
{
return deck[id].p()
}
}
class MajorArcana
{
var deck: [Card] = []
init()
{
//Enum azoknak való akik nem tudják a szövegszerkeztőjüket használni :)
deck.append(Card(rank: "The Fool", value: (0,22)))
deck.append(Card(rank: "The Magician", value: (1,1)))
deck.append(Card(rank: "The High Priestess", value: (2,2)))
deck.append(Card(rank: "The Empress", value: (3,3)))
deck.append(Card(rank: "The Emperor", value: (4,4)))
deck.append(Card(rank: "The Hierophant", value: (5,5)))
deck.append(Card(rank: "The Lovers", value: (6,6)))
deck.append(Card(rank: "The Chariot", value: (7,7)))
deck.append(Card(rank: "Strength", value: (8,8)))
deck.append(Card(rank: "The Hermit", value: (9,9)))
deck.append(Card(rank: "Wheel of Fortune", value: (10,10)))
deck.append(Card(rank: "Justice", value: (11,11)))
deck.append(Card(rank: "The Hanged Man", value: (12,12)))
deck.append(Card(rank: "Death", value: (13,13)))
deck.append(Card(rank: "Temperance", value: (14,14)))
deck.append(Card(rank: "The Devil", value: (15,15)))
deck.append(Card(rank: "The Tower", value: (16,16)))
deck.append(Card(rank: "The Star", value: (17,17)))
deck.append(Card(rank: "The Moon", value: (18,18)))
deck.append(Card(rank: "The Sun", value: (19,19)))
deck.append(Card(rank: "Judgement", value: (20,20)))
deck.append(Card(rank: "The World", value: (21,21)))
}
func drawRandomCard() -> Card
{
let id = Int.random(in: 0..<deck.count)
let card = deck[id]
deck.remove(at: id)
return card
}
}
//*/// Test
let theFool = Card(rank: "The Fool", value: ( 0,22))
let theMoon = Card(rank: "The Moon", value: (18,18))
print(theFool.p(),theMoon.p())
print(theFool < theMoon)
print(theFool == theMoon)
print("\n")
let card1 = PlayingCard(suit: Suit.Heart, rank: Rank.Ace)
let card2 = PlayingCard(suit: Suit.Heart, rank: Rank.Two)
print(card1.p(), card2.p(), card2.value)
print(card1 >= card2)
print(card1 == card1)
print("\n")
for s in Suit.allCases
{
print(s,terminator:", ")
}
print("\n")
var deck = DeckOfPlayingCards()
for i in 0..<52
{
print(deck.p(i), terminator:", ")
}
print("\n")
// MiniJósda
var majorArcana = MajorArcana()
var sum = 0
var last = Card(rank: "",value: (0,0))
for _ in 0..<7
{
let card = majorArcana.drawRandomCard()
print(card.p(),terminator:", ")
if (last<card)
{
sum+=1
}
else
{
sum-=1
}
last=card
//print(sum, terminator:" ")
}
print("")
//Sokkal nagyobb a "szerencse" valószínűsége (1. húzás után 1-ről indulunk, és a 0 is "szerencse")
if (sum>=0)
{
print("Szerencséd lesz!")
}
else
{
print("Balszerencséd lesz!")
}
print("\n") | unlicense | 720d6d5bc03bb3f69a8496ed35a6121b | 21.183761 | 143 | 0.593256 | 2.82988 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Extensions/UIDevice-Extensions.swift | 1 | 5719 | //
// UIDevice-Extensions.swift
// Habitica
//
// Created by Phillip Thelen on 09.10.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
//https://stackoverflow.com/a/26962452
public extension UIDevice {
// swiftlint:disable all
static let 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, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
func mapToDevice(identifier: String) -> String {
#if os(iOS)
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 "iPhone9,1", "iPhone9,3": return "iPhone 7"
case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone10,1", "iPhone10,4": return "iPhone 8"
case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,3", "iPhone10,6": return "iPhone X"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4", "iPhone11,6": return "iPhone XS Max"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE (2nd generation)"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)"
case "iPad6,11", "iPad6,12": return "iPad (5th generation)"
case "iPad7,5", "iPad7,6": return "iPad (6th generation)"
case "iPad7,11", "iPad7,12": return "iPad (7th generation)"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad11,4", "iPad11,5": return "iPad Air (3rd generation)"
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 "iPad11,1", "iPad11,2": return "iPad mini (5th generation)"
case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)"
case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)"
case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)"
case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)"
case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)"
case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)"
case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)"
case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)"
case "AppleTV5,3": return "Apple TV"
case "AppleTV6,2": return "Apple TV 4K"
case "AudioAccessory1,1": return "HomePod"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))"
default: return identifier
}
#elseif os(tvOS)
switch identifier {
case "AppleTV5,3": return "Apple TV 4"
case "AppleTV6,2": return "Apple TV 4K"
case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))"
default: return identifier
}
#endif
}
// swiftlint:disable all
return mapToDevice(identifier: identifier)
}()
}
| gpl-3.0 | 090391424b8d3013272c3e6a6ff897a6 | 63.247191 | 171 | 0.464323 | 4.098925 | false | false | false | false |
slavapestov/swift | validation-test/Evolution/test_struct_add_property.swift | 1 | 2743 | // RUN: rm -rf %t && mkdir -p %t/before && mkdir -p %t/after
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_add_property.swift -o %t/before/struct_add_property.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D BEFORE -c %S/Inputs/struct_add_property.swift -o %t/before/struct_add_property.o
// RUN: %target-build-swift -emit-library -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_add_property.swift -o %t/after/struct_add_property.o
// RUN: %target-build-swift -emit-module -Xfrontend -enable-resilience -D AFTER -c %S/Inputs/struct_add_property.swift -o %t/after/struct_add_property.o
// RUN: %target-build-swift -D BEFORE -c %s -I %t/before -o %t/before/main.o
// RUN: %target-build-swift -D AFTER -c %s -I %t/after -o %t/after/main.o
// RUN: %target-build-swift %t/before/struct_add_property.o %t/before/main.o -o %t/before_before
// RUN: %target-build-swift %t/before/struct_add_property.o %t/after/main.o -o %t/before_after
// RUN: %target-build-swift %t/after/struct_add_property.o %t/before/main.o -o %t/after_before
// RUN: %target-build-swift %t/after/struct_add_property.o %t/after/main.o -o %t/after_after
// RUN: %target-run %t/before_before
// RUN: %target-run %t/before_after
// RUN: %target-run %t/after_before
// RUN: %target-run %t/after_after
// REQUIRES: executable_test
import StdlibUnittest
import struct_add_property
var StructAddPropertyTest = TestSuite("StructAddProperty")
StructAddPropertyTest.test("AddStoredProperty") {
var t1 = AddStoredProperty()
var t2 = AddStoredProperty()
do {
expectEqual(t1.forth, "Chuck Moore")
expectEqual(t2.forth, "Chuck Moore")
}
do {
t1.forth = "Elizabeth Rather"
expectEqual(t1.forth, "Elizabeth Rather")
expectEqual(t2.forth, "Chuck Moore")
}
do {
if getVersion() > 0 {
expectEqual(t1.languageDesigners, ["Elizabeth Rather",
"John McCarthy",
"Dennis Ritchie"])
expectEqual(t2.languageDesigners, ["Chuck Moore",
"John McCarthy",
"Dennis Ritchie"])
} else {
expectEqual(t1.languageDesigners, ["Elizabeth Rather"])
expectEqual(t2.languageDesigners, ["Chuck Moore"])
}
}
}
StructAddPropertyTest.test("ChangeEmptyToNonEmpty") {
var t = ChangeEmptyToNonEmpty()
do {
expectEqual(t.property, 0)
t.property += 1
expectEqual(t.property, 1)
}
do {
func increment(inout t: Int) {
t += 1
}
increment(&t.property)
expectEqual(t.property, 2)
}
do {
expectEqual(getProperty(t), 2)
}
}
runAllTests()
| apache-2.0 | 621851ff40728557ee3786dfd5bf2742 | 32.048193 | 155 | 0.646008 | 3.106455 | false | true | false | false |
jeanetienne/Bee | Bee/Appearance/PhraseTextField.swift | 1 | 1149 | //
// Bee
// Copyright © 2017 Jean-Étienne. All rights reserved.
//
import UIKit
class PhraseTextField: UITextField {
@IBInspectable var topPadding: CGFloat = 0
@IBInspectable var rightPadding: CGFloat = 0
@IBInspectable var bottomPadding: CGFloat = 0
@IBInspectable var leftPadding: CGFloat = 0
override func textRect(forBounds bounds: CGRect) -> CGRect {
return paddedRect(forBounds: bounds).offsetBy(dx: 0, dy: 0.5)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return paddedRect(forBounds: bounds)
}
private func paddedRect(forBounds bounds: CGRect) -> CGRect {
var newBounds = bounds
// Top Padding
newBounds.origin.y += topPadding
newBounds.size.height -= topPadding
// Right Padding
newBounds.size.width -= rightPadding
// Bottom Padding
newBounds.size.height -= bottomPadding
// Left Padding
newBounds.origin.x += leftPadding
newBounds.size.width -= leftPadding
return newBounds.integral
}
}
| mit | 8137b1bfe9dd0ab1d80080221e2d66ac | 23.934783 | 69 | 0.619006 | 5.166667 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Basics/Version+Extensions.swift | 2 | 941 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 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 struct TSCUtility.Version
extension Version {
/// Try a version from a git tag.
///
/// - Parameter tag: A version string possibly prepended with "v".
public init?(tag: String) {
if tag.first == "v" {
try? self.init(versionString: String(tag.dropFirst()), usesLenientParsing: true)
} else {
try? self.init(versionString: tag, usesLenientParsing: true)
}
}
}
| apache-2.0 | f7c7dc25d7bef46dc53da7e4f9f589d4 | 35.192308 | 92 | 0.551541 | 4.850515 | false | false | false | false |
hooman/swift | test/Constraints/result_builder_invalid_vars.swift | 11 | 1240 | // RUN: %target-typecheck-verify-swift
@resultBuilder
struct DummyBuilder { // expected-note 5 {{struct 'DummyBuilder' declared here}}
static func buildBlock<T>(_ t: T) -> T {
return t
}
}
func dummy<T>(@DummyBuilder _: () -> T) {}
dummy {
var computedVar: Int { return 123 } // expected-error {{cannot declare local computed variable in result builder}}
()
}
dummy {
lazy var lazyVar: Int = 123 // expected-error {{cannot declare local lazy variable in result builder}}
()
}
dummy {
var observedVar: Int = 123 { // expected-error {{cannot declare local observed variable in result builder}}
didSet {}
}
()
}
dummy {
var observedVar: Int = 123 { // expected-error {{cannot declare local observed variable in result builder}}
willSet {}
}
()
}
@propertyWrapper struct Wrapper {
var wrappedValue: Int
}
dummy {
@Wrapper var wrappedVar: Int = 123 // expected-error {{cannot declare local wrapped variable in result builder}}
()
}
dummy {
@resultBuilder var attributedVar: Int = 123 // expected-error {{@resultBuilder' attribute cannot be applied to this declaration}}
// expected-warning@-1 {{variable 'attributedVar' was never used; consider replacing with '_' or removing it}}
()
}
| apache-2.0 | c7f91e08fc3aee48a3d2f89e83189ef2 | 23.313725 | 131 | 0.683065 | 4 | false | false | false | false |
shkodnii/SwiftSpalah | HomeWork3.playground/Contents.swift | 1 | 1386 | //: Playground - noun: a place where people can play
import UIKit
//Arrays
let constArray = ["a", "b", "c", "d"]
var array = [String]()
if array.isEmpty {
print("array is empty")
}
array.append("e")
array += constArray
var array2 = array
array
array2
array2[0] = "1"
array
array2
array2.removeAtIndex(3)
array2
//Dictionary
let dictionary : [String:String] = ["чай" : "tea", "кофе" : "coffee"]
let dictionary2 : [Int:String] = [1 : "tea", 2 : "coffee"]
dictionary["кофе"]
dictionary2[1]
//Enum
enum Animals{
case cat(jump: Int, move: Int, voice: String, weight: Int)
case dog(jump: Int, move: Int, voice: String, weight: Int)
case cow(jump: Int, move: Int, voice: String, weight: Int)
case pig(jump: Int, move: Int, voice: String, weight: Int)
}
var animals = Animals.cat(jump: 3, move: 5, voice: "myau", weight: 3)
Animals.dog(jump: 4, move: 7, voice: "wow", weight: 8)
//For/While
for i in 1...5 {
print("\(i) times 5 is \(i * 5)")
}
var i = 1
while i < 20 {
do { i += 1
}
print(i)
}
//Class & Struct
class StudentClass {
var name: String? = nil
var age: Int? = nil
init(name: String, age: Int){
self.name = name
self.age = age
}
func StudentInfo() {
print(name,age)
}
}
struct StudentStruct {
var name : String
var age : Int
}
| apache-2.0 | 79479809d3311305df14af4d579548c6 | 14.804598 | 69 | 0.586182 | 2.906977 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Jobs/ZoomChartViewJob.swift | 13 | 2129 | //
// ZoomChartViewJob.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ZoomChartViewJob: ChartViewPortJob
{
internal var scaleX: CGFloat = 0.0
internal var scaleY: CGFloat = 0.0
internal var axisDependency: ChartYAxis.AxisDependency = ChartYAxis.AxisDependency.Left
public init(
viewPortHandler: ChartViewPortHandler,
scaleX: CGFloat,
scaleY: CGFloat,
xIndex: CGFloat,
yValue: Double,
transformer: ChartTransformer,
axis: ChartYAxis.AxisDependency,
view: ChartViewBase)
{
super.init(
viewPortHandler: viewPortHandler,
xIndex: xIndex,
yValue: yValue,
transformer: transformer,
view: view)
self.scaleX = scaleX
self.scaleY = scaleY
self.axisDependency = axis
}
public override func doJob()
{
guard let
viewPortHandler = viewPortHandler,
transformer = transformer,
view = view
else { return }
var matrix = viewPortHandler.setZoom(scaleX: scaleX, scaleY: scaleY)
viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
let valsInView = (view as! BarLineChartViewBase).getDeltaY(axisDependency) / viewPortHandler.scaleY
let xsInView = CGFloat((view as! BarLineChartViewBase).xAxis.values.count) / viewPortHandler.scaleX
var pt = CGPoint(
x: xIndex - xsInView / 2.0,
y: CGFloat(yValue) + valsInView / 2.0
)
transformer.pointValueToPixel(&pt)
matrix = viewPortHandler.translate(pt: pt)
viewPortHandler.refresh(newMatrix: matrix, chart: view, invalidate: false)
(view as! BarLineChartViewBase).calculateOffsets()
view.setNeedsDisplay()
}
} | apache-2.0 | 0a5c0111d5ff314f6762c138890cb9bf | 27.783784 | 107 | 0.621888 | 5.081146 | false | false | false | false |
ishanhanda/IHLoopingVideoPlayerView | LoopingVideoPlayerView/LoopingVideoPlayerView.swift | 1 | 11356 | //
// LoopingVideoPlayerView.swift
//
// Copyright © 2016 Ishan Handa. 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 AVFoundation
class LoopingVideoPlayerView: UIView {
fileprivate var OddPlayerStatusContext = "OddPlayerStatusContext"
fileprivate var EvenPlayerStatusContext = "EvenPlayerStatusContext"
fileprivate var PlayerStatusKey = "status"
fileprivate var PlayerItemKey = "currentItem"
/// Video player view responsible for playing odd index
fileprivate var oddVideoPlayerView = VideoPlayerView()
/// Video player view responsible for playing even index
fileprivate var evenVideoPlayerView = VideoPlayerView()
/// Index of the video to play
fileprivate var currentVideoIndex: Int?
/**
Specifies how the video is displayed within an LoopingVideoPlayerView’s bounds.
Options are AVLayerVideoGravityResizeAspect, AVLayerVideoGravityResizeAspectFill
and AVLayerVideoGravityResize. AVLayerVideoGravityResizeAspectFill is default.
See <AVFoundation/AVAnimation.h> for a description of these options.
*/
public var videoGravity: String {
set {
(self.oddVideoPlayerView.layer as! AVPlayerLayer).videoGravity = newValue
(self.evenVideoPlayerView.layer as! AVPlayerLayer).videoGravity = newValue
}
get {
return (self.evenVideoPlayerView.layer as! AVPlayerLayer).videoGravity
}
}
/**
Gives the index of the next video to be played.
*/
fileprivate var nextVideoIndex: Int? {
get {
if let currentVideoIndex = self.currentVideoIndex ,let uRls = self.videoURLs, uRls.count > 0 {
let newIndex = currentVideoIndex + 1
return newIndex < uRls.count ? newIndex : 0
} else {
return nil
}
}
}
/// Helper to check if current index is even.
fileprivate var isCurrentEven: Bool {
get {
guard let currentIndex = self.currentVideoIndex else { return false }
return currentIndex % 2 == 0
}
}
/// The duration for which the current video will be played before fading in the next loop.
fileprivate var currentVideoPlayDuration: Double!
/// Transion to to fade into next video.
fileprivate var fadeTime: Double = 5.0
/// stores copies of urls to be played back to back.
fileprivate var videoURLs: [URL]?
/// The url for the video to be played infinitely.
public var videoURL: URL? {
get {
return self.videoURLs?.first ?? nil
}
set {
if let newValue = newValue {
self.videoURLs = [newValue, newValue]
} else {
self.videoURLs = nil
}
}
}
// MARK: - Initalizers
public override init(frame : CGRect) {
super.init(frame : frame)
self.commonInit()
}
public convenience init(videoURL: URL) {
self.init(frame:CGRect.zero)
self.videoURLs = [videoURL, videoURL]
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
// Initialize Players
self.oddVideoPlayerView.player = AVPlayer()
self.oddVideoPlayerView.translatesAutoresizingMaskIntoConstraints = false
self.evenVideoPlayerView.player = AVPlayer()
self.evenVideoPlayerView.translatesAutoresizingMaskIntoConstraints = false
// Create View Layout
self.addSubview(self.oddVideoPlayerView)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[oddVideoPlayerView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["oddVideoPlayerView": self.oddVideoPlayerView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[oddVideoPlayerView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["oddVideoPlayerView": self.oddVideoPlayerView]))
self.addSubview(self.evenVideoPlayerView)
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[evenVideoPlayerView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["evenVideoPlayerView": self.evenVideoPlayerView]))
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[evenVideoPlayerView]|", options: NSLayoutFormatOptions.init(rawValue: 0), metrics: nil, views: ["evenVideoPlayerView": self.evenVideoPlayerView]))
}
deinit {
self.oddVideoPlayerView.player.currentItem?.removeObserver(self, forKeyPath: self.PlayerStatusKey, context: &self.OddPlayerStatusContext)
self.evenVideoPlayerView.player.currentItem?.removeObserver(self, forKeyPath: self.PlayerStatusKey, context: &self.EvenPlayerStatusContext)
}
}
// MARK: - LoopingVideoPlayerView Playback Control
extension LoopingVideoPlayerView {
/// Call this function to start playng the video.
public func beginPlayBack() {
guard let urls = self.videoURLs, urls.count > 0 else {
return
}
// Setting up even and odd players to play the first two items in urls
self.currentVideoIndex = 0
let playerItem = AVPlayerItem(url: urls[0])
playerItem.addObserver(self, forKeyPath: PlayerStatusKey, options: [.new, .old], context: &self.EvenPlayerStatusContext)
self.evenVideoPlayerView.player.replaceCurrentItem(with: playerItem)
let nextPlayerItem = AVPlayerItem(url: urls[1])
nextPlayerItem.addObserver(self, forKeyPath: PlayerStatusKey, options: [.new, .old], context: &self.OddPlayerStatusContext)
self.oddVideoPlayerView.player.replaceCurrentItem(with: nextPlayerItem)
}
/**
This function is called once the status for each AVPlayer changes to Ready to Play.
it fades in the odd or even player based on odd or even index and stops playeing the other player.
This is repeated infinitely so that the looping video appears to be one continuous video.
*/
fileprivate func startPlaying() {
if self.isCurrentEven {
self.bringSubview(toFront: self.evenVideoPlayerView)
self.evenVideoPlayerView.player.play()
UIView.animate(withDuration: self.fadeTime, animations: {
self.evenVideoPlayerView.alpha = 1
}, completion: { (finished) in
if finished {
self.oddVideoPlayerView.alpha = 0
}
})
// Set up to play the odd video after current play duration.
delay(self.currentVideoPlayDuration) {
self.currentVideoIndex = self.nextVideoIndex
self.oddVideoPlayerView.player.currentItem?.removeObserver(self, forKeyPath: self.PlayerStatusKey, context: &self.OddPlayerStatusContext)
let playerItem = AVPlayerItem(url: self.videoURLs![self.currentVideoIndex!])
playerItem.addObserver(self, forKeyPath: self.PlayerStatusKey, options: [.new, .old], context: &self.OddPlayerStatusContext)
self.oddVideoPlayerView.player.replaceCurrentItem(with: playerItem)
}
} else {
self.bringSubview(toFront: self.oddVideoPlayerView)
self.oddVideoPlayerView.player.play()
UIView.animate(withDuration: self.fadeTime, animations: {
self.oddVideoPlayerView.alpha = 1
}, completion: { (finished) in
if finished {
self.evenVideoPlayerView.alpha = 0
}
})
// Set up to play the even video after current play duration.
delay(self.currentVideoPlayDuration) {
self.currentVideoIndex = self.nextVideoIndex
self.evenVideoPlayerView.player.currentItem?.removeObserver(self, forKeyPath: self.PlayerStatusKey, context: &self.EvenPlayerStatusContext)
let playerItem = AVPlayerItem(url: self.videoURLs![self.currentVideoIndex!])
playerItem.addObserver(self, forKeyPath: self.PlayerStatusKey, options: [.new, .old], context: &self.EvenPlayerStatusContext)
self.evenVideoPlayerView.player.replaceCurrentItem(with: playerItem)
}
}
}
}
/// utiltiy function to execute after time delay.
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
// MARK: - LoopingVideoPlayerView AVPlayer Observers
extension LoopingVideoPlayerView {
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
switch context! {
case &self.OddPlayerStatusContext where !self.isCurrentEven:
if self.oddVideoPlayerView.player.currentItem!.status == .readyToPlay {
// Calculate the duration for which the next item is to played.
self.currentVideoPlayDuration = self.playerDurationForPlayerItem(self.oddVideoPlayerView.player.currentItem!)
self.startPlaying()
}
case &self.EvenPlayerStatusContext where self.isCurrentEven:
if self.evenVideoPlayerView.player.currentItem!.status == .readyToPlay {
// Calculate the duration for which the next item is to played.
self.currentVideoPlayDuration = self.playerDurationForPlayerItem(self.evenVideoPlayerView.player.currentItem!)
self.startPlaying()
}
default:
break
}
}
/**
The duration for which an item should be played.
Calculated by subtracting the fadeTime from the duration of the playerItem.
*/
func playerDurationForPlayerItem(_ playerItem: AVPlayerItem) -> Double {
return CMTimeGetSeconds(playerItem.duration) - self.fadeTime - 1
}
}
| mit | 8a54ee5609c5111fa6bc5d67bca38918 | 43.347656 | 228 | 0.668986 | 4.985946 | false | false | false | false |
Limon-O-O/Lego | Modules/Door/Door/Targets/Target_Door.swift | 1 | 2904 | //
// Target_Door.swift
// Door
//
// Created by Limon.F on 19/2/2017.
// Copyright © 2017 Limon.F. All rights reserved.
//
import UIKit
@objc(Target_Door)
class Target_Door: NSObject {}
// MARK: - Controllers
extension Target_Door {
func Action_WelcomeViewController(params: [String: Any]) -> UIViewController? {
let navigationController = Storyboard.door.navigationController(with: "DoorNavigationController") as? DoorNavigationController
navigationController?.innateParams = params
return navigationController
}
func Action_PresentWelcomeViewController(params: [String: Any]) {
if DoorUserDefaults.didLogin { // 已将登录了,不需要再 present Door
(params["callbackAction"] as? ([String: Any]) -> Void)?(["result": true])
} else {
guard let navigationController = Storyboard.door.navigationController(with: "DoorNavigationController") as? DoorNavigationController else { return }
let action: ([String: Any]) -> Void = { [weak navigationController] info in
navigationController?.dismiss(animated: true, completion: nil)
(params["callbackAction"] as? ([String: Any]) -> Void)?(info)
}
var paramsBuffer = params
paramsBuffer["callbackAction"] = action
navigationController.innateParams = paramsBuffer
UIApplication.shared.keyWindow?.rootViewController?.present(navigationController, animated: true, completion: nil)
}
}
func Action_LoginViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.login.viewController(of: LoginViewController.self)
viewController.innateParams = params
return viewController
}
func Action_PhoneNumberPickerViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.register.viewController(of: PhoneNumberPickerViewController.self)
viewController.innateParams = params
return viewController
}
func Action_ProfilePickerViewController(params: [String: Any]) -> UIViewController {
let viewController = Storyboard.register.viewController(of: ProfilePickerViewController.self)
viewController.innateParams = params
return viewController
}
}
// MARK: - Properties
extension Target_Door {
func Action_AccessToken() -> [String: Any]? {
return DoorUserDefaults.accessToken.flatMap { accessToken -> [String: Any] in
return ["result": accessToken]
}
}
func Action_UserID() -> [String: Any]? {
return DoorUserDefaults.userID.flatMap { accessToken -> [String: Any] in
return ["result": accessToken]
}
}
}
// MARK: - Methods
extension Target_Door {
func Action_ClearUserDefaults() {
DoorUserDefaults.clear()
}
}
| mit | 30389016e11beeff05ee8d90d14ea1ec | 31.761364 | 161 | 0.671523 | 4.97069 | false | false | false | false |
between40and2/XALG | frameworks/Framework-XALG/Graph/Rep/XALG_Rep_Graph.swift | 1 | 2566 | //
// XALG_Rep_Graph.swift
// XALG
//
// Created by Juguang Xiao on 1/7/15 (oringally).
//
import Swift
class XALG_Rep_Graph<VertexIdentifier : Hashable> : XALG_ADT_Graph {
func edge_(on v: XALG_DS_GraphVertex<VertexIdentifier>) -> [XALG_DS_GraphEdge<VertexType>] {
store_edge.edge_(on: v)
}
internal let store_edge = XALG_StoreImpl_GraphEdge<VertexIdentifier>()
internal let store_vertex = XALG_StoreImpl_GraphVertex<VertexIdentifier>()
// typealias VertexIdentifierType = VertexIdentifier
typealias VertexType = XALG_DS_GraphVertex<VertexIdentifier>
typealias EdgeType = XALG_DS_GraphEdge<VertexType>
// typealias VertexIdentifier = String
var allows_addingEdge_samePairOfVertex = true {
didSet {
store_edge.allows_samePairOfVertex = allows_addingEdge_samePairOfVertex
}
}
func addEdge(between v0: VertexType, and v1: VertexType) throws -> EdgeType? {
let e = EdgeType(v0, v1)
// e.vertex_ = [v0, v1]
try store_edge.installEdge(e)
// edge_.append(e)
return e
}
func addEdge(from v0: VertexType, to v1: VertexType) throws -> EdgeType? {
let e = EdgeType(v0, v1)
try store_edge.installEdge(e)
return e
}
var edge_ : [EdgeType] { store_edge.edge_ }
func addVertex(identifier ident: VertexIdentifier) throws -> VertexType {
return try store_vertex.createVertex(identifier: ident)
//
// let v = XALG_DS_GraphVertex<VertexIdentifierType>(ident)
// // v.identifier = ident
//
// if set_vertexIdentifier.contains(ident) {
// throw XALG_Error_Graph.addVertexWithDeplicateIdentifier
// }
//
// set_vertexIdentifier.insert(ident)
//
// vertex_.append(v)
// // set_vertex.insert(v)
//
// vertexIdent_vertex_[ident] = v
//
// return v
}
var vertex_: [VertexType] { store_vertex.vertex_ }
func vertex(identifier ident: VertexIdentifier) -> XALG_DS_GraphVertex<VertexIdentifier>? {
store_vertex.vertex(identifier: ident)
}
private var _directed : Bool
required init(directed: Bool = false ) {
_directed = directed
// vertex_ = [VertexType]()
// edge_ = [EdgeType]()
}
var directed: Bool { return _directed }
// var rootVertex_: [XALG_Rep_Vertex<VertexIdentifier>] {
// return []
// }
}
| mit | 5566617cdcac3e495c6f0286eb61bcc1 | 25.453608 | 96 | 0.591582 | 3.858647 | false | false | false | false |
visenze/visearch-sdk-swift | ViSearchSDK/ViSearchSDK/Classes/Request/ViImageSettings.swift | 1 | 885 | import Foundation
/// Set quality if image upload
/// image will be resized before uploadling to server
public class ViImageSettings {
/// Default and high quality settings for image upload
public enum Options {case defaultSetting, highQualitySetting}
public var quality: Float
public var maxWidth: Float
public init(setting: Options){
// default setting
quality = 0.97;
maxWidth = 512;
// high quality
if(setting == .highQualitySetting){
quality = 0.985;
maxWidth = 1024;
}
}
public convenience init(){
self.init(setting: Options.defaultSetting)
}
public init(size: CGSize, quality: Float) {
self.quality = quality
self.maxWidth = Float( (size.height > size.width) ? size.height : size.width);
}
}
| mit | 64c606ad95290b1e66b84ac38dceba27 | 23.583333 | 86 | 0.59661 | 4.758065 | false | false | false | false |
georgievtodor/ios | TV Show Calendar/TV Show Calendar/AppDelegate.swift | 1 | 1182 | import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillTerminate(_ application: UIApplication) {
self.saveContext()
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "TV_Show_Calendar")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | cde03357964135564fe8d9b730541b8c | 27.829268 | 144 | 0.605753 | 6.124352 | false | false | false | false |
SanctionCo/pilot-ios | Pods/Gallery/Sources/Camera/CameraMan.swift | 1 | 5773 | import Foundation
import AVFoundation
import PhotosUI
import Photos
protocol CameraManDelegate: class {
func cameraManNotAvailable(_ cameraMan: CameraMan)
func cameraManDidStart(_ cameraMan: CameraMan)
func cameraMan(_ cameraMan: CameraMan, didChangeInput input: AVCaptureDeviceInput)
}
class CameraMan {
weak var delegate: CameraManDelegate?
let session = AVCaptureSession()
let queue = DispatchQueue(label: "no.hyper.Gallery.Camera.SessionQueue", qos: .background)
let savingQueue = DispatchQueue(label: "no.hyper.Gallery.Camera.SavingQueue", qos: .background)
var backCamera: AVCaptureDeviceInput?
var frontCamera: AVCaptureDeviceInput?
var stillImageOutput: AVCaptureStillImageOutput?
deinit {
stop()
}
// MARK: - Setup
func setup() {
if Permission.Camera.status == .authorized {
self.start()
} else {
self.delegate?.cameraManNotAvailable(self)
}
}
func setupDevices() {
// Input
AVCaptureDevice
.devices()
.filter {
return $0.hasMediaType(.video)
}.forEach {
switch $0.position {
case .front:
self.frontCamera = try? AVCaptureDeviceInput(device: $0)
case .back:
self.backCamera = try? AVCaptureDeviceInput(device: $0)
default:
break
}
}
// Output
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
}
func addInput(_ input: AVCaptureDeviceInput) {
configurePreset(input)
if session.canAddInput(input) {
session.addInput(input)
DispatchQueue.main.async {
self.delegate?.cameraMan(self, didChangeInput: input)
}
}
}
// MARK: - Session
var currentInput: AVCaptureDeviceInput? {
return session.inputs.first as? AVCaptureDeviceInput
}
fileprivate func start() {
// Devices
setupDevices()
guard let input = backCamera, let output = stillImageOutput else { return }
addInput(input)
if session.canAddOutput(output) {
session.addOutput(output)
}
queue.async {
self.session.startRunning()
DispatchQueue.main.async {
self.delegate?.cameraManDidStart(self)
}
}
}
func stop() {
self.session.stopRunning()
}
func switchCamera(_ completion: (() -> Void)? = nil) {
guard let currentInput = currentInput
else {
completion?()
return
}
queue.async {
guard let input = (currentInput == self.backCamera) ? self.frontCamera : self.backCamera
else {
DispatchQueue.main.async {
completion?()
}
return
}
self.configure {
self.session.removeInput(currentInput)
self.addInput(input)
}
DispatchQueue.main.async {
completion?()
}
}
}
func takePhoto(_ previewLayer: AVCaptureVideoPreviewLayer, location: CLLocation?, completion: @escaping ((PHAsset?) -> Void)) {
guard let connection = stillImageOutput?.connection(with: .video) else { return }
connection.videoOrientation = Utils.videoOrientation()
queue.async {
self.stillImageOutput?.captureStillImageAsynchronously(from: connection) {
buffer, error in
guard error == nil, let buffer = buffer, CMSampleBufferIsValid(buffer),
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer),
let image = UIImage(data: imageData)
else {
DispatchQueue.main.async {
completion(nil)
}
return
}
self.savePhoto(image, location: location, completion: completion)
}
}
}
func savePhoto(_ image: UIImage, location: CLLocation?, completion: @escaping ((PHAsset?) -> Void)) {
var localIdentifier: String?
savingQueue.async {
do {
try PHPhotoLibrary.shared().performChangesAndWait {
let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
localIdentifier = request.placeholderForCreatedAsset?.localIdentifier
request.creationDate = Date()
request.location = location
}
DispatchQueue.main.async {
if let localIdentifier = localIdentifier {
completion(Fetcher.fetchAsset(localIdentifier))
} else {
completion(nil)
}
}
} catch {
DispatchQueue.main.async {
completion(nil)
}
}
}
}
func flash(_ mode: AVCaptureDevice.FlashMode) {
guard let device = currentInput?.device , device.isFlashModeSupported(mode) else { return }
queue.async {
self.lock {
device.flashMode = mode
}
}
}
func focus(_ point: CGPoint) {
guard let device = currentInput?.device , device.isFocusModeSupported(AVCaptureDevice.FocusMode.locked) else { return }
queue.async {
self.lock {
device.focusPointOfInterest = point
}
}
}
// MARK: - Lock
func lock(_ block: () -> Void) {
if let device = currentInput?.device , (try? device.lockForConfiguration()) != nil {
block()
device.unlockForConfiguration()
}
}
// MARK: - Configure
func configure(_ block: () -> Void) {
session.beginConfiguration()
block()
session.commitConfiguration()
}
// MARK: - Preset
func configurePreset(_ input: AVCaptureDeviceInput) {
for asset in preferredPresets() {
if input.device.supportsSessionPreset(asset) && self.session.canSetSessionPreset(asset) {
self.session.sessionPreset = asset
return
}
}
}
func preferredPresets() -> [AVCaptureSession.Preset] {
return [
.high,
.medium,
.low
]
}
}
| mit | 8869156599f5213b41a9f733c60f2519 | 23.565957 | 129 | 0.633466 | 4.830962 | false | false | false | false |
codemonkey85/XCode-Playgrounds | ClassPlayground.playground/section-1.swift | 1 | 590 | // Playground - noun: a place where people can play
import UIKit
class Person
{
var FirstName = ""
var LastName = ""
}
var person:Person = Person()
person.FirstName = "Michael"
person.LastName = "Bond"
person
var personinstance = person
personinstance.LastName = "Kent"
person
enum Numbers : Int
{
case one = 1
case two = 2
case three = 3
}
Numbers.one.rawValue
let possNumber = Numbers(rawValue: 3)
possNumber
possNumber == Numbers.one
possNumber == Numbers.two
possNumber == Numbers.three
// var shannan = Person(FirstName: "Shannan", LastName: "Bond")
| unlicense | 8c1d748b1d99686a6bd6d3494b23f793 | 13.047619 | 63 | 0.691525 | 3.241758 | false | false | false | false |
oacastefanita/PollsFramework | PollsFramework/Classes/Utils/Constans.swift | 1 | 8909 | //let PERSISTENT_CONTAINER = (DatabaseManager.sharedInstance).persistentContainer
let POLLS_FRAMEWORK = PollsFrameworkController.sharedInstance
let API_CLIENT = APIClient.sharedInstance
let DATA_CONTROLLER = DataController.sharedInstance
#if os(iOS) || os(watchOS)
let WATCH_CONTROLLER = WatchKitController.sharedInstance
#endif
/// Server date format
let dateFormatForServer = "yyyy-MM-dd HH:mm:ss"
//MARK: request paths
let kRegister = "/Polls/Registration"
let kLogin = "/Polls/Login"
let kLogout = "/Polls/LogOut"
let kResetPassword = "/Polls/ResetPasswordRequest"
let kViewProfile = "/Polls/ViewProfile"
let kGetMyAllPolls = "/Polls/GetMyAllPolls"
let kGetBallance = "/Polls/GetBalance"
let kDeleteUser = "/Polls/DeleteUser"
let kPostAuthentication = "/Polls/PostAuth"
let kReSendVerifyEmail = "/Polls/ReSendVerifyEmail"
let kVerifyPhone = "/Polls/VerifyPhone"
let kResendVerifyCode = "/Polls/ResendVerifyCode"
let kGetPollCounters = "/Polls/GetPollCounters"
let kGetPollById = "/Polls/GetPollById"
let kGetPollResult = "/Polls/GetPollResult"
let kCreateTextPoll = "/Polls/CreateTextPoll"
let kGetEmployeeFilterCount = "/Polls/GetEmployeeFilterCount"
let kCreateBestTextPoll = "/Polls/CreateBestTextPoll"
let kCreateSingleImagePoll = "/Polls/CreateSingleImagePoll"
let kBestImagePoll = "/Polls/BestImagePoll"
let kDeleteDraftPoll = "/Polls/DeleteDraftPoll"
let kGetWorkerDetails = "/Polls/GetWorkerDetails"
let kChangePassword = "/Polls/ChangePassword"
let kGetListPublicProfile = "/Polls/GetListPublicProfile"
let kDeleteProfilePic = "/Polls/DeleteProfilePic?fileUniqueId="
let kUpdateProfile = "/Polls/UpdateProfile"
let kThumbsUpDown = "/Polls/ThumbsUpDown"
let kGetFileDetails = "/Polls/GetFileDetails"
let kExtendExpireTime = "/Polls/ExtendExpireTime"
let kExpirePoll = "/Polls/ExpirePoll"
let kUpdatePublishedPoll = "/Polls/UpdatePublishedPoll"
let kDeletePoll = "/Polls/DeletePoll"
let kGetPollStatus = "/Polls/GetPollStatus"
let kGetAllFilters = "/Polls/GetAllFilters"
let kUploadFile = "/Polls/UploadFile?accessKey="
let kGetPaymentPlans = "/Polls/GetPaymentPlans"
let kGetAllFilterCategories = "/Polls/GetAllFilterCategories"
let kGetQuestions = "/Polls/GetQuestions"
let kGetCategories = "/Polls/GetCategories"
let kGetFilterOptions = "/Polls/GetFilterOptions"
let kGetFilterOptionsList = "/Polls/GetFilterOptionsList"
let kGetFilterDataCount = "/Polls/GetFilterDataCount"
let kFullFilterViewByPollId = "/Polls/FullFilterViewByPollId"
let kFilterViewByPollId = "/Polls/FilterViewByPollId"
let kGetAllDepartment = "/Polls/GetAllDepartment"
let kGetPublicPollByQuery = "/Polls/GetPublicPollByQuery"
let kGetEducations = "/Polls/GetEducations"
let kSaveBillingAgreement = "/Polls/SaveBillingAgreement"
let kCancelBillingAgreement = "/Polls/CancelBillingAgreement"
let kGetMyBillingAgreement = "/Polls/GetMyBillingAgreement"
let kGetDemographicStats = "/Polls/GetDemographicStats"
let kGetUserFullContact = "/Polls/GetUserFullContact"
let kGetLoginHistory = "/Polls/GetLoginHistory"
let kViewNotificationsPreference = "/Polls/ViewNotificationsPreference"
let kRegisterNotifications = "/Polls/RegisterNotifications"
let kVerifyPhoneCall = "/Polls/VerifyPhoneCall"
let kListPartnerPoll = "/Polls/ListPartnerPoll"
let kCountries = "/Polls/Countries"
let kStatesByCountry = "/Polls/StatesByCountry"
let kCitiesByState = "/Polls/CitiesByState"
let kSaveRemoteImage = "/Polls/SaveRemoteImage"
let kVerifyEmail = "/Polls/VerifyEmail"
let kMakeCall = "/Polls/MakeCall"
let kGetMyPolls = "/Polls/GetMyPolls"
let kViewPublicProfile = "/Polls/ViewPublicProfile"
//Bussiness
let kAddNewEmployee = "/Business/AddNewEmployee"
let kRemoveEmployee = "/Business/RemoveEmployee"
let kCreateCompany = "/Business/CreateCompany"
let kRequestBusinessAccount = "/Business/RequestBusinessAccount"
let kPostPollAnswer = "/Business/PostPollAnswer"
let kResponseInvitation = "/Business/ResponseInvitation"
let kGetBusinessPollCounters = "/Business/GetPollCounters?userId="
let kCompanyEmployees = "/Business/CompanyEmployees"
let kViewEmployee = "/Business/ViewEmployee"
let kUpdateEmployee = "/Business/UpdateEmployee"
let kBusinessGetPollCounters = "/Business/GetPollCounters?userId="
//Pay
let kBillingHistory = "/Pay/BillingHistory"
let kBillingInvoice = "/Pay/BillingInvoice"
let kChargePayment = "/Pay/ChargePayment"
let kBuyingHistory = "/Pay/BuyingHistory"
let kVerifyPayment = "/Pay/VerifyPayment"
let kGetAccessToken = "/Pay/GetAccessToken"
let kGetPayPalPayments = "/Pay/GetPayPalPayments"
//Push
let kListNotificationAlerts = "/Push/ListNotificationAlerts"
let kRegisterSnsDevice = "/Push/RegisterSnsDevice"
let kSendWebPushNotificationsTest = "/Push/SendWebPushNotificationsTest"
//Checkin
let kPostLocation = "/CheckIn/PostLocation"
let kCheckinLocation = "/CheckIn/CheckinLocation"
let kGetLocationDetails = "/CheckIn/GetNearByLocations"
//Public
let kGetPublic = "/PublicPoll/GetPublic"
let kViewPublicProfilePublic = "/PublicPoll/ViewPublicProfile"
let kListPublicUsersPublic = "/PublicPoll/ListPublicUsers"
let kGetPollResultPublic = "/PublicPoll/GetPollResult"
//MARK: notifications
let kTakeUserOutNotification = "takeUserOutNotification"
//MARK: Enums
public let enumTypes = ["phoneType":PhoneTypes.allValues,"userType":UserType.allValues,"verificationMethod":VerificationMethod.allValues,"pollTypeId":PollTypes.allValues] as [String : [String]]
public enum PhoneTypes : Int {
case mobile = 0
case landline = 1
case voip = 2
static let allValues:[String] = ["\(mobile)", "\(landline)", "\(voip)"]
}
public enum UserType : Int {
case normal = 0
case admin = 1
case business = 2
case member = 3
case partner = 4
case celebrity = 5
case worker = 6
static let allValues = ["\(normal)", "\(admin)", "\(business)", "\(member)", "\(partner)", "\(celebrity)", "\(worker)"]
}
public enum VerificationMethod : Int {
case email = 0
case sms = 1
case phone = 2
case none = 3
static let allValues = ["\(email)", "\(sms)", "\(phone)", "\(none)"]
}
public enum VerificationMethodString : String {
case email = "EMAIL"
case sms = "SMS"
case phone = "PHONE"
case none = "NONE"
static let allValues = ["\(email)", "\(sms)", "\(phone)", "\(none)"]
}
public enum PollTypes : Int64 {
case singleText = 1
case bestText = 2
case singleImage = 3
case bestImage = 4
static let allValues = ["","\(singleText)", "\(bestText)", "\(singleImage)", "\(bestImage)"]
}
public enum PollStatus : Int64 {
case completed = 1
case pending = 2
case inProgress = 3
case expired = 4
case suspended = 5
case draft = 6
static let allValues = ["","\(completed)", "\(pending)", "\(inProgress)", "\(expired)", "\(suspended)", "\(draft)"]
}
public enum SortDirection : Int64 {
case ascending = 1
case descending = 2
static let allValues = ["","\(ascending)", "\(descending)"]
}
/// All the objects in the Framework with their name as a string
public enum ObjectTypes: String {
case ballance = "Ballance"
case bill = "Bill"
case billingAgreement = "BillingAgreement"
case chargePayment = "ChargePayment"
case city = "City"
case contact = "Contact"
case country = "Country"
case department = "Department"
case device = "Device"
case education = "Education"
case employee = "Employee"
case fileDetails = "FileDetails"
case filter = "Filter"
case filterCategory = "FilterCategory"
case filterNameValue = "FilterNameValue"
case filterValue = "FilterValue"
case getFilters = "GetFilters"
case getPolls = "GetPolls"
case invoice = "Invoice"
case location = "Location"
case locationDetails = "LocationDetails"
case login = "Login"
case paymentPlan = "PaymentPlan"
case pollAnswer = "PollAnswer"
case poll = "Poll"
case pollCategory = "PollCategory"
case pollCounters = "PollCounters"
case pollDemographicStatus = "PollDemographicStatus"
case pollsNotification = "PollsNotification"
case pollsNotificationPreference = "PollsNotificationPreference"
case postAuth = "PostAuth"
case question = "Question"
case register = "Register"
case remoteImage = "RemoteImage"
case result = "Result"
case responseInvitation = "ResponseInvitation"
case sNSDevice = "SNSDevice"
case state = "State"
case thumbs = "Thumbs"
case user = "User"
case userInvitation = "UserInvitation"
case verifyPayment = "VerifyPayment"
case verifyPhone = "VerifyPhone"
case worker = "Worker"
case getCompanyEmployees = "getCompanyEmployees"
case viewEmployee = "viewEmployee"
case billingHistory = "billingHistory"
case notificationAlerts = "notificationAlerts"
case billingInvoice = "billingInvoice"
case buyingHistory = "buyingHistory"
case checkinLocations = "checkinLocations"
}
| mit | 413012af3fcc5111588f2ac0d1d6ae6d | 35.363265 | 193 | 0.744416 | 3.765427 | false | false | false | false |
tootbot/tootbot | Tootbot/Source/Client/DataImporter.swift | 1 | 2525 | //
// Copyright (C) 2017 Tootbot Contributors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import CoreData
import ReactiveSwift
enum DataImporterError: Error {
case coreData(Error)
}
struct DataImporter<ManagedObject> where ManagedObject: APIImportable, ManagedObject.T == ManagedObject {
let dataController: DataController
let beforeSaveHandler: ([ManagedObject]) -> Void
init(dataController: DataController, beforeSaveHandler: @escaping ([ManagedObject]) -> Void = { _ in }) {
self.beforeSaveHandler = beforeSaveHandler
self.dataController = dataController
}
func importModels(collection: JSONCollection<ManagedObject.JSONModel>) -> SignalProducer<[ManagedObject], DataImporterError> {
return SignalProducer { observer, disposable in
self.dataController.performWrite(backgroundTask: { context in
guard !disposable.isDisposed else { return }
let managedObjects = collection.elements.map { model in ManagedObject.upsert(model: model, in: context) }
self.beforeSaveHandler(managedObjects)
do {
context.mergePolicy = NSMergePolicy.overwrite
try context.save()
} catch {
observer.send(error: .coreData(error))
return
}
let managedObjectIDs = managedObjects.map { $0.objectID }
DispatchQueue.main.async {
guard !disposable.isDisposed else { return }
let viewContext = self.dataController.viewContext
let managedObjects = managedObjectIDs.map { objectID in viewContext.object(with: objectID) as! ManagedObject }
observer.send(value: managedObjects)
observer.sendCompleted()
}
})
}
}
}
| agpl-3.0 | 40dcb953acc658b0f8b0d73f9f2f435c | 39.725806 | 130 | 0.654257 | 5.17418 | false | false | false | false |
lovefantasy/SoundCamera | SoundCamera/SoundCamera/ViewController.swift | 1 | 4068 | //
// ViewController.swift
// SoundCamera
//
// Created by Chih-Kuang Chang on 2017/8/2.
// Copyright © 2017年 Cytus Chang. All rights reserved.
//
import UIKit
import AudioKit
import GPUImage
class ViewController: UIViewController, CameraDelegate {
@IBOutlet var cameraContainerView: RenderView!
@IBOutlet var waveContainerView: UIView!
// GPUImage components
let videoCamera: Camera?
let swirlFilter = SwirlDistortion()
// AudioKit components
var mic: AKMicrophone
var fft: CustomFFT
// var tracker: AKFrequencyTracker!
// var silence: AKBooster!
var accel: Float = 0.0
required init(coder aDecoder: NSCoder)
{
do {
videoCamera = try Camera(sessionPreset:AVCaptureSessionPreset640x480, location:.frontFacing)
} catch {
videoCamera = nil
print("Couldn't initialize camera with error: \(error)")
}
AKSettings.audioInputEnabled = true
mic = AKMicrophone()
fft = CustomFFT.init(mic)
// tracker = AKFrequencyTracker(mic)
// silence = AKBooster(tracker, gain: 0)
super.init(coder: aDecoder)!
guard videoCamera != nil else {
return
}
videoCamera!.delegate = self
}
func startCamera() {
guard let videoCamera = videoCamera else {
let errorAlertController = UIAlertController(title: NSLocalizedString("Error", comment: "Error"), message: "Couldn't initialize camera", preferredStyle: .alert)
errorAlertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "OK"), style: .default, handler: nil))
self.present(errorAlertController, animated: true, completion: nil)
return
}
let rotationFilter = TransformOperation()
let flipTransform = CATransform3DMakeRotation(CGFloat(Float.pi), 1, 0, 0)
rotationFilter.transform = Matrix4x4(flipTransform)
videoCamera --> rotationFilter --> swirlFilter --> cameraContainerView
videoCamera.startCapture()
}
override func viewDidLoad() {
super.viewDidLoad()
self.startCamera()
AudioKit.output = mic
AudioKit.start()
// let plot = AKNodeOutputPlot(mic, frame: waveContainerView.bounds)
// plot.plotType = .rolling
// plot.shouldFill = true
// plot.shouldMirror = true
// plot.color = UIColor.blue
// waveContainerView.addSubview(plot)
swirlFilter.angle = 0
swirlFilter.radius = 0.75
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillDisappear(_ animated: Bool) {
if let videoCamera = videoCamera {
videoCamera.stopCapture()
videoCamera.removeAllTargets()
}
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didCaptureBuffer(_ sampleBuffer: CMSampleBuffer) {
// NSLog("Freq: %.1f, Amp: %.3f", tracker.frequency, tracker.amplitude)
// let power = Float(tracker.frequency / 4000.0 + tracker.amplitude / 5)
// updateSwirlFilter(freq: power > 0.06 ? power : 0)
for i in 0..<256 {
NSLog("%d Hz: %f", i, fft.fftData[i])
}
}
func updateSwirlFilter(freq: Float) {
let diff = freq - swirlFilter.angle
if (diff >= 0 && accel < diff) || (diff < 0 && swirlFilter.angle + accel < 0) {
accel += fabsf (diff / 10.0)
} else {
accel -= fabsf (diff / 10.0)
}
swirlFilter.angle += accel
if swirlFilter.angle < 0 {
swirlFilter.angle = 0
accel = 0
} else if swirlFilter.angle > 2 {
swirlFilter.angle = 2
accel = 0
}
//NSLog("Angle: %.3f", swirlFilter.angle)
}
}
| apache-2.0 | 113a10d2bdb7a20d2fe6dc5f4505d682 | 31.007874 | 172 | 0.600492 | 4.491713 | false | false | false | false |
SoufianeLasri/Sisley | Sisley/CustomTitle.swift | 1 | 909 | //
// CustomTitle.swift
// Sisley
//
// Created by Soufiane Lasri on 01/12/2015.
// Copyright © 2015 Soufiane Lasri. All rights reserved.
//
import UIKit
class CustomTitle: UILabel {
init( frame: CGRect, color: UIColor) {
super.init( frame: frame )
let color = color
let linePath = UIBezierPath()
linePath.moveToPoint( CGPoint( x: self.frame.width / 2 - 35, y: self.frame.height + 15 ) )
linePath.addLineToPoint( CGPoint( x: self.frame.width / 2 + 35, y: self.frame.height + 15 ) )
let line = CAShapeLayer()
line.path = linePath.CGPath
line.lineWidth = 1.0
line.lineCap = kCALineJoinRound
line.strokeColor = color.CGColor
self.layer.addSublayer( line )
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 07da76072abe6e3c4205a417f6b0ccf4 | 26.515152 | 101 | 0.601322 | 3.930736 | false | false | false | false |
freshOS/Komponents | Source/Field.swift | 1 | 3703 | //
// Field.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 12/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
public struct Field: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public var children = [IsNode]()
let props: FieldProps
public var layout: Layout
public let ref: UnsafeMutablePointer<UITextField>?
var registerTextChanged: ((UITextField) -> Void)?
public init(_ placeholder: String = "",
text: String = "",
textChanged: ((String) -> Void)? = nil,
props:((inout FieldProps) -> Void)? = nil,
layout: Layout? = nil,
ref: UnsafeMutablePointer<UITextField>? = nil) {
var defaultProps = FieldProps()
defaultProps.placeholder = placeholder
defaultProps.text = text
if let p = props {
var prop = defaultProps
p(&prop)
self.props = prop
} else {
self.props = defaultProps
}
self.layout = layout ?? Layout()
self.ref = ref
registerTextChanged = { field in
if let field = field as? BlockBasedUITextField, let textChanged = textChanged {
field.setCallback(textChanged)
}
}
}
// public init<T:HasState>(_ placeholder: String = "",
// target:T,
// property:() -> String ,
// updateCallback: @escaping (T.State) -> UnsafeMutablePointer<String>,
// props:((inout FieldProps) -> Void)? = nil,
// layout: Layout? = nil,
// ref: UnsafeMutablePointer<UITextField>? = nil) {
//
// var defaultProps = FieldProps()
// defaultProps.placeholder = placeholder
//// defaultProps.text = text
//
//
//
// defaultProps.text = property()
//
//
//
//
// if let p = props {
// var prop = defaultProps
// p(&prop)
// self.props = prop
// } else {
// self.props = defaultProps
// }
//
// self.layout = layout ?? Layout()
// self.ref = ref
//
// registerTextChanged = { field in
// if let field = field as? BlockBasedUITextField {
// field.setCallback { newtext in
// target.updateState { state in
//
// let propertyPointer = updateCallback(state)
// propertyPointer.pointee = newtext
// }
// }
// }
// }
//
//
// }
}
public func == (lhs: Field, rhs: Field) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public struct FieldProps: HasViewProps, Equatable, Hashable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public var placeholder: String = ""
public var text: String = ""
public var hashValue: Int {
return viewPropsHash
^ placeholder.hashValue
^ text.hashValue
}
}
public func == (lhs: FieldProps, rhs: FieldProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
| mit | 9ff99958873498bee3dd571ba5509c14 | 28.616 | 97 | 0.524041 | 4.692015 | false | false | false | false |
freshOS/Komponents | Source/View.swift | 1 | 3166 | //
// View.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 11/05/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import Foundation
public struct View: Node, Equatable {
public var uniqueIdentifier: Int = generateUniqueId()
public var propsHash: Int { return props.hashValue }
public var children = [IsNode]()
public let props: ViewProps
public var layout: Layout
public var ref: UnsafeMutablePointer<UIView>?
public init(
color: UIColor? = nil,
props:((inout ViewProps) -> Void)? = nil,
layout: Layout? = nil,
ref: UnsafeMutablePointer<UIView>? = nil,
_ children: [IsNode]) {
var prop = ViewProps()
if let color = color {
prop.backgroundColor = color
}
if let p = props {
p(&prop)
}
self.props = prop
self.layout = layout ?? Layout()
self.ref = ref
self.children = children
}
// No children init
public init(
color: UIColor? = nil,
props: ((inout ViewProps) -> Void)? = nil,
layout: Layout? = nil,
ref: UnsafeMutablePointer<UIView>? = nil) {
var prop = ViewProps()
if let color = color {
prop.backgroundColor = color
}
if let p = props {
p(&prop)
}
self.props = prop
self.layout = layout ?? Layout()
self.ref = ref
self.children = [IsNode]()
}
}
public func == (lhs: View, rhs: View) -> Bool {
return lhs.props == rhs.props
&& lhs.layout == rhs.layout
}
public protocol HasViewProps {
var backgroundColor: UIColor { get }
var borderColor: UIColor { get }
var borderWidth: CGFloat { get }
var cornerRadius: CGFloat { get }
var isHidden: Bool { get }
var alpha: CGFloat { get }
var clipsToBounds: Bool { get }
var isUserInteractionEnabled: Bool { get }
}
extension HasViewProps {
var viewPropsHash: Int {
return backgroundColor.hashValue
^ borderColor.hashValue
^ borderWidth.hashValue
^ cornerRadius.hashValue
^ isHidden.hashValue
^ alpha.hashValue
^ clipsToBounds.hashValue
^ isUserInteractionEnabled.hashValue
}
}
public struct ViewProps: HasViewProps, Equatable, Hashable {
// HasViewProps
public var backgroundColor = UIColor.white
public var borderColor = UIColor.clear
public var borderWidth: CGFloat = 0
public var cornerRadius: CGFloat = 0
public var isHidden = false
public var alpha: CGFloat = 1
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public var anchorPoint = CGPoint(x: 0.5, y: 0.5)
public var hashValue: Int {
return viewPropsHash
^ anchorPoint.x.hashValue
^ anchorPoint.y.hashValue
}
}
public func == (lhs: ViewProps, rhs: ViewProps) -> Bool {
return lhs.hashValue == rhs.hashValue
}
public func hashFor<T: Hashable>(_ obj: T?) -> Int {
if let t = obj {
return t.hashValue
}
return 0
}
| mit | efffb7b27553943692b0fb823f5fe184 | 24.731707 | 60 | 0.591469 | 4.43899 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/ViewControllers/Search/SearchNavigationController.swift | 1 | 4333 | /**
*
* SearchNavigationController.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/07/23.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import Material
import ARNTransitionAnimator
class SearchNavigationController: NavigationController, UINavigationControllerDelegate {
// MARK: - Private instance fileds
private var statusBarView: Material.View!
private var statusBarHidden: Bool = true
// MARK: - Initialization
private init() {
super.init(nibName: nil, bundle: nil)
}
override init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View initialization
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = self
// Hide navigation bar
self.navigationBar.backgroundColor = Material.Color.white
self.navigationBar.isTranslucent = true
self.navigationBar.isHidden = true
// Set status bar
statusBarView = Material.View()
statusBarView.zPosition = 3000
statusBarView.restorationIdentifier = "StatusBarView"
statusBarView.backgroundColor = Material.Color.black.withAlphaComponent(0.12)
self.view.layout(statusBarView).top(0).horizontally().height(20)
}
// MARK: - Memory/resource management
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Layout methods
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
statusBarView.isHidden = statusBarHidden || Material.Application.isLandscape && !Material.Device.identifier.hasPrefix("iPad")
}
// MARK: - Navigation
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
switch operation {
case .push:
self.navigationBar.backgroundColor = Material.Color.white
self.navigationBar.isHidden = false
self.statusBarHidden = false
let animation = ShowDetailTransition(fromVC: fromVC, toVC: toVC)
let animator = ARNTransitionAnimator(duration: 0.4, animation: animation)
return animator.animationController(forPresented: self, presenting: toVC, source: fromVC)
case .pop:
self.navigationBar.isHidden = true
self.statusBarHidden = true
let animation = ShowDetailTransition(fromVC: toVC, toVC: fromVC)
let animator = ARNTransitionAnimator(duration: 0.4, animation: animation)
return animator.animationController(forDismissed: self)
case .none:
return nil
}
}
}
| bsd-3-clause | 3e99dea87d9206a1c4f00bf10e5d56f5 | 33.943548 | 127 | 0.756751 | 4.490155 | false | false | false | false |
github/Nimble | Nimble/Matchers/BeNil.swift | 77 | 647 | import Foundation
public func beNil<T>() -> MatcherFunc<T> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be nil"
let actualValue = actualExpression.evaluate()
return actualValue == nil
}
}
extension NMBObjCMatcher {
public class func beNilMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualBlock, failureMessage, location in
let block = ({ actualBlock() as NSObject? })
let expr = Expression(expression: block, location: location)
return beNil().matches(expr, failureMessage: failureMessage)
}
}
}
| apache-2.0 | 458e848f6c62522a1011f73b3edcd2c2 | 33.052632 | 72 | 0.664606 | 5.436975 | false | false | false | false |
russellladd/Wolverine | WolverineTests/WolverineTests.swift | 1 | 2091 | //
// WolverineTests.swift
// WolverineTests
//
// Created by Russell Ladd on 8/5/14.
// Copyright (c) 2014 GRL5. All rights reserved.
//
import Wolverine
import XCTest
class WolverineTests: XCTestCase {
class ServiceManagerTestDelegate: ServiceManagerDelegate {
var serviceManagerDidChangeStatusHandler: (ServiceManager.Status -> ())?
func serviceManager(serviceManager: ServiceManager, didChangeStatus status: ServiceManager.Status) {
serviceManagerDidChangeStatusHandler?(status)
}
}
func testServiceManager() {
let serviceManager = ServiceManager(credential: Credential(key: "Wijw6wNYqffL0_ZnLOW9HemfEf8a", secret: "hjUuNq2CqsjchshuVsGnJs5Kenca"))
let delegate = ServiceManagerTestDelegate()
serviceManager.delegate = delegate
let connectionExpectation = expectationWithDescription("Connect service manager")
delegate.serviceManagerDidChangeStatusHandler = { status in
connectionExpectation.fulfill()
}
waitForExpectationsWithTimeout(10.0) { error in
switch serviceManager.status {
case .Connected(let service):
let personExpectation = self.expectationWithDescription("Ger person")
service.getPersonWithUniqname("grladd") { result in
personExpectation.fulfill()
switch result {
case .Success(let person):
()
case .Error(let error):
XCTFail("Service did not get person (Error: \(error))")
}
}
self.waitForExpectationsWithTimeout(10.0, nil)
default:
XCTFail("Service manager did not connect (Status: \(serviceManager.status))")
}
}
}
}
| mit | ba6e7e010881876066c516b164831b08 | 31.169231 | 144 | 0.552367 | 5.502632 | false | true | false | false |
Nana-Muthuswamy/AadhuEats | AadhuEats/Common/Constants.swift | 1 | 1139 | //
// Constants.swift
// AadhuEats
//
// Created by Nana on 10/27/17.
// Copyright © 2017 Nana. All rights reserved.
//
// Model attribute names
let kDate = "date"
let kType = "type"
let kMilkType = "milkType"
let kBreastOrientation = "breastOrientation"
let kVolume = "volume"
let kDuration = "duration"
let kLogs = "logs"
let kDisplayDate = "displayDate"
let kTotalFeedVolume = "totalFeedVolume"
let kTotalBreastFeedVolume = "totalBreastFeedVolume"
let kTotalBreastPumpVolume = "totalBreastPumpVolume"
let kTotalDurationMinutes = "totalDurationMinutes"
let kDisplayTotalFeedVolume = "displayTotalFeedVolume"
let kDisplayTotalBreastFeedVolume = "displayTotalBreastFeedVolume"
let kDisplayTotalBreastPumpVolume = "displayTotalBreastPumpVolume"
let kDisplayTotalDurationMinutes = "displayTotalDurationMinutes"
// Other constants
let kSavedLogHistory = "history"
// UI View constants
let kSummaryCellIdentifier = "Summary"
let kPumpLogCellIdentifier = "PumpLog"
let kBottleFeedLogCellIdentifier = "BottleFeedLog"
let kBreastFeedLogCellIdentifier = "BreastFeedLog"
// Segue Identifier constants
let kLogDetailsSegue = "LogDetails"
| mit | 76d00ce01e6850db296515eff1fecc38 | 28.179487 | 66 | 0.79877 | 3.512346 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Data/RoomList/CoreData/MXCoreDataRoomListDataFetcher.swift | 1 | 18962 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import CoreData
private let kPropertyNameDataTypesInt: String = "s_dataTypesInt"
private let kPropertyNameSentStatusInt: String = "s_sentStatusInt"
private let kPropertyNameNotificationCount: String = "s_notificationCount"
private let kPropertyNameHighlightCount: String = "s_highlightCount"
internal typealias MXRoomSummaryCoreDataContextableStore = MXRoomSummaryStore & CoreDataContextable
@objcMembers
internal class MXCoreDataRoomListDataFetcher: NSObject, MXRoomListDataFetcher {
private let multicastDelegate: MXMulticastDelegate<MXRoomListDataFetcherDelegate> = MXMulticastDelegate()
internal let fetchOptions: MXRoomListDataFetchOptions
private lazy var dataUpdateThrottler: MXThrottler = {
return MXThrottler(minimumDelay: 0.1, queue: .main)
}()
internal private(set) var data: MXRoomListData? {
didSet {
guard let data = data else {
// do not notify when stopped
return
}
if data != oldValue {
let totalCountsChanged: Bool
if fetchOptions.paginationOptions == .none {
// pagination disabled, we don't need to track number of rooms in this case
totalCountsChanged = true
} else {
totalCountsChanged = oldValue?.counts.total?.numberOfRooms != data.counts.total?.numberOfRooms
}
notifyDataChange(totalCountsChanged: totalCountsChanged)
}
}
}
private let store: MXRoomSummaryCoreDataContextableStore
private lazy var fetchedResultsController: NSFetchedResultsController<MXRoomSummaryMO> = {
let request = MXRoomSummaryMO.typedFetchRequest()
request.predicate = filterPredicate(for: filterOptions)
request.sortDescriptors = sortDescriptors(for: sortOptions)
request.fetchLimit = fetchOptions.paginationOptions.rawValue
return NSFetchedResultsController(fetchRequest: request,
managedObjectContext: store.mainManagedObjectContext,
sectionNameKeyPath: nil,
cacheName: nil)
}()
private var totalRoomsCount: Int {
let request = MXRoomSummaryMO.typedFetchRequest()
request.predicate = filterPredicate(for: filterOptions)
request.resultType = .countResultType
do {
return try store.mainManagedObjectContext.count(for: request)
} catch let error {
MXLog.error("[MXCoreDataRoomListDataFetcher] failed to count rooms", context: error)
return 0
}
}
private var totalCounts: MXRoomListDataCounts? {
guard fetchOptions.paginationOptions != .none else {
return nil
}
let request = MXRoomSummaryMO.genericFetchRequest()
request.predicate = filterPredicate(for: filterOptions)
let propertyNames: [String] = [
kPropertyNameDataTypesInt,
kPropertyNameSentStatusInt,
kPropertyNameNotificationCount,
kPropertyNameHighlightCount
]
var properties: [NSPropertyDescription] = []
for propertyName in propertyNames {
guard let property = MXRoomSummaryMO.entity().propertiesByName[propertyName] else {
fatalError("[MXCoreDataRoomSummaryStore] Couldn't find \(propertyName) on entity \(String(describing: MXRoomSummaryMO.self)), probably property name changed")
}
properties.append(property)
}
request.propertiesToFetch = properties
// when specific properties set, use dictionary result type for issues seen mostly on iOS 12 devices
request.resultType = .dictionaryResultType
var result: MXRoomListDataCounts? = nil
do {
if let dictionaries = try store.mainManagedObjectContext.fetch(request) as? [[String: Any]] {
let summaries = dictionaries.map { RoomSummaryForTotalCounts(withDictionary: $0) }
result = MXStoreRoomListDataCounts(withRooms: summaries,
total: nil)
}
} catch let error {
MXLog.error("[MXCoreDataRoomListDataFetcher] failed to calculate total counts", context: error)
}
return result
}
internal init(fetchOptions: MXRoomListDataFetchOptions,
store: MXRoomSummaryCoreDataContextableStore) {
self.fetchOptions = fetchOptions
self.store = store
super.init()
self.fetchOptions.fetcher = self
self.fetchedResultsController.delegate = self
}
// MARK: - Delegate
internal func addDelegate(_ delegate: MXRoomListDataFetcherDelegate) {
multicastDelegate.addDelegate(delegate)
}
internal func removeDelegate(_ delegate: MXRoomListDataFetcherDelegate) {
multicastDelegate.removeDelegate(delegate)
}
internal func removeAllDelegates() {
multicastDelegate.removeAllDelegates()
}
// MARK: - Data
func paginate() {
guard let oldData = data else {
// load first page
performFetch()
return
}
guard oldData.hasMoreRooms else {
// no more rooms
return
}
removeCacheIfRequired()
let numberOfItems = (oldData.currentPage + 2) * oldData.paginationOptions.rawValue
fetchedResultsController.fetchRequest.fetchLimit = numberOfItems > 0 ? numberOfItems : 0
performFetch()
}
func resetPagination() {
removeCacheIfRequired()
let numberOfItems = fetchOptions.paginationOptions.rawValue
fetchedResultsController.fetchRequest.fetchLimit = numberOfItems > 0 ? numberOfItems : 0
performFetch()
}
func refresh() {
guard let oldData = data else {
// data will still be nil if the fetchRequest properties have changed before fetching the first page.
// In this instance, update the fetchRequest so it is correctly configured for the first page fetch.
fetchedResultsController.fetchRequest.predicate = filterPredicate(for: filterOptions)
fetchedResultsController.fetchRequest.sortDescriptors = sortDescriptors(for: sortOptions)
fetchedResultsController.fetchRequest.fetchLimit = fetchOptions.paginationOptions.rawValue
return
}
data = nil
recomputeData(using: oldData)
}
func stop() {
fetchedResultsController.delegate = nil
removeCacheIfRequired()
}
deinit {
stop()
}
// MARK: - Private
private func removeCacheIfRequired() {
if let cacheName = fetchedResultsController.cacheName {
NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: cacheName)
}
}
private func performFetch() {
do {
try fetchedResultsController.performFetch()
computeData()
} catch let error {
MXLog.error("[MXCoreDataRoomListDataFetcher] failed to perform fetch", context: error)
}
}
private func notifyDataChange(totalCountsChanged: Bool) {
multicastDelegate.invoke({ $0.fetcherDidChangeData(self,
totalCountsChanged: totalCountsChanged) })
}
/// Recompute data with the same number of rooms of the given `data`
private func recomputeData(using data: MXRoomListData) {
removeCacheIfRequired()
let numberOfItems = (data.currentPage + 1) * data.paginationOptions.rawValue
fetchedResultsController.fetchRequest.predicate = filterPredicate(for: filterOptions)
fetchedResultsController.fetchRequest.sortDescriptors = sortDescriptors(for: sortOptions)
fetchedResultsController.fetchRequest.fetchLimit = numberOfItems > 0 ? numberOfItems : 0
performFetch()
}
private func computeData() {
guard let summaries = fetchedResultsController.fetchedObjects else {
data = nil
return
}
let fetchLimit = fetchedResultsController.fetchRequest.fetchLimit
let mapped: [MXRoomSummary]
if fetchLimit > 0 && summaries.count > fetchLimit {
data = nil
mapped = summaries[0..<fetchLimit].compactMap { MXRoomSummary(summaryModel: $0) }
} else {
mapped = summaries.compactMap { MXRoomSummary(summaryModel: $0) }
}
let counts = MXStoreRoomListDataCounts(withRooms: mapped,
total: totalCounts)
data = MXRoomListData(rooms: mapped,
counts: counts,
paginationOptions: fetchOptions.paginationOptions)
fetchedResultsController.delegate = self
}
}
// MARK: MXRoomListDataSortable
extension MXCoreDataRoomListDataFetcher: MXRoomListDataSortable {
var sortOptions: MXRoomListDataSortOptions {
return fetchOptions.sortOptions
}
func sortDescriptors(for sortOptions: MXRoomListDataSortOptions) -> [NSSortDescriptor] {
var result: [NSSortDescriptor] = []
if sortOptions.alphabetical {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_displayName, ascending: true))
}
if sortOptions.invitesFirst {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_membershipInt, ascending: true))
}
if sortOptions.sentStatus {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_sentStatusInt, ascending: false))
}
if sortOptions.missedNotificationsFirst {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_hasAnyHighlight, ascending: false))
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_hasAnyNotification, ascending: false))
}
if sortOptions.unreadMessagesFirst {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_hasAnyUnread, ascending: false))
}
if sortOptions.lastEventDate {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_lastMessage?.s_originServerTs, ascending: false))
}
if sortOptions.favoriteTag {
result.append(NSSortDescriptor(keyPath: \MXRoomSummaryMO.s_favoriteTagOrder, ascending: false))
}
return result
}
}
// MARK: MXRoomListDataFilterable
extension MXCoreDataRoomListDataFetcher: MXRoomListDataFilterable {
var filterOptions: MXRoomListDataFilterOptions {
return fetchOptions.filterOptions
}
func filterPredicate(for filterOptions: MXRoomListDataFilterOptions) -> NSPredicate? {
var predicates: [NSPredicate] = []
if !filterOptions.onlySuggested {
if filterOptions.hideUnknownMembershipRooms {
let memberPredicate = NSPredicate(format: "%K != %d",
#keyPath(MXRoomSummaryMO.s_membershipInt),
MXMembership.unknown.rawValue)
predicates.append(memberPredicate)
}
// data types
if !filterOptions.dataTypes.isEmpty {
let predicate: NSPredicate
if filterOptions.strictMatches {
predicate = NSPredicate(format: "(%K & %d) == %d",
#keyPath(MXRoomSummaryMO.s_dataTypesInt),
filterOptions.dataTypes.rawValue,
filterOptions.dataTypes.rawValue)
} else {
predicate = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryMO.s_dataTypesInt),
filterOptions.dataTypes.rawValue)
}
predicates.append(predicate)
}
// not data types
if !filterOptions.notDataTypes.isEmpty {
let predicate = NSPredicate(format: "(%K & %d) == 0",
#keyPath(MXRoomSummaryMO.s_dataTypesInt),
filterOptions.notDataTypes.rawValue)
predicates.append(predicate)
}
// space
if let space = filterOptions.space {
// specific space
let predicate = NSPredicate(format: "%K CONTAINS[c] %@",
#keyPath(MXRoomSummaryMO.s_parentSpaceIds),
space.spaceId)
predicates.append(predicate)
} else {
// home space
// In case of home space we show a room if one of the following conditions is true:
// - Show All Rooms is enabled
// - It's a direct room
// - The room is a favourite
// - The room is orphaned
let predicate1 = NSPredicate(value: filterOptions.showAllRoomsInHomeSpace)
let directDataTypes: MXRoomSummaryDataTypes = .direct
let predicate2 = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryMO.s_dataTypesInt),
directDataTypes.rawValue)
let favoritedDataTypes: MXRoomSummaryDataTypes = .favorited
let predicate3 = NSPredicate(format: "(%K & %d) != 0",
#keyPath(MXRoomSummaryMO.s_dataTypesInt),
favoritedDataTypes.rawValue)
let predicate4 = NSPredicate(format: "%K MATCHES %@",
#keyPath(MXRoomSummaryMO.s_parentSpaceIds),
"^$")
let predicate = NSCompoundPredicate(type: .or,
subpredicates: [predicate1, predicate2, predicate3, predicate4])
predicates.append(predicate)
}
}
// query
if let query = filterOptions.query, !query.isEmpty {
let predicate = NSPredicate(format: "%K CONTAINS[cd] %@",
#keyPath(MXRoomSummaryMO.s_displayName),
query)
predicates.append(predicate)
}
guard !predicates.isEmpty else {
return nil
}
if predicates.count == 1 {
return predicates.first
}
return NSCompoundPredicate(type: .and,
subpredicates: predicates)
}
}
// MARK: - NSFetchedResultsControllerDelegate
extension MXCoreDataRoomListDataFetcher: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
dataUpdateThrottler.throttle {
self.computeData()
}
}
}
// MARK: - RoomSummaryForTotalCounts
/// Room summary implementation specific to total counts calculation.
private class RoomSummaryForTotalCounts: NSObject, MXRoomSummaryProtocol {
var roomId: String = ""
var roomTypeString: String?
var roomType: MXRoomType = .room
var avatar: String?
var displayname: String?
var topic: String?
var creatorUserId: String = ""
var aliases: [String] = []
var historyVisibility: String? = nil
var joinRule: String? = kMXRoomJoinRuleInvite
var membership: MXMembership = .unknown
var membershipTransitionState: MXMembershipTransitionState = .unknown
var membersCount: MXRoomMembersCount = MXRoomMembersCount(members: 0, joined: 0, invited: 0)
var isConferenceUserRoom: Bool = false
var hiddenFromUser: Bool = false
var storedHash: UInt = 0
var lastMessage: MXRoomLastMessage?
var isEncrypted: Bool = false
var trust: MXUsersTrustLevelSummary?
var localUnreadEventCount: UInt = 0
var notificationCount: UInt
var highlightCount: UInt
var hasAnyUnread: Bool {
return localUnreadEventCount > 0
}
var hasAnyNotification: Bool {
return notificationCount > 0
}
var hasAnyHighlight: Bool {
return highlightCount > 0
}
var isDirect: Bool {
return isTyped(.direct)
}
var directUserId: String?
var others: [String: NSCoding]?
var favoriteTagOrder: String?
var dataTypes: MXRoomSummaryDataTypes
func isTyped(_ types: MXRoomSummaryDataTypes) -> Bool {
return (dataTypes.rawValue & types.rawValue) != 0
}
var sentStatus: MXRoomSummarySentStatus
var spaceChildInfo: MXSpaceChildInfo?
var parentSpaceIds: Set<String> = []
var userIdsSharingLiveBeacon: Set<String> = []
/// Initializer with a dictionary obtained by a fetch request, with result type `.dictionaryResultType`. Only parses some properties.
/// - Parameter dictionary: Dictionary object representing an `MXRoomSummaryMO` instance
init(withDictionary dictionary: [String: Any]) {
dataTypes = MXRoomSummaryDataTypes(rawValue: Int(dictionary[kPropertyNameDataTypesInt] as? Int64 ?? 0))
sentStatus = MXRoomSummarySentStatus(rawValue: UInt(dictionary[kPropertyNameSentStatusInt] as? Int16 ?? 0)) ?? .ok
notificationCount = UInt(dictionary[kPropertyNameNotificationCount] as? Int16 ?? 0)
highlightCount = UInt(dictionary[kPropertyNameHighlightCount] as? Int16 ?? 0)
super.init()
}
override var description: String {
return "<RoomSummaryForTotalCounts: \(roomId) \(String(describing: displayname))>"
}
}
| apache-2.0 | a6e8cb9c292cfef330d9b307eb03a78f | 39.259023 | 174 | 0.609218 | 5.501015 | false | false | false | false |
maxbritto/cours-ios11-swift4 | Niveau_avance/Objectif 4/demos/demos/ViewController.swift | 1 | 3848 | //
// ViewController.swift
// demos
//
// Created by Maxime Britto on 26/01/2018.
// Copyright © 2018 Maxime Britto. All rights reserved.
//
import UIKit
import AVFoundation
import Vision
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet weak var ui_titleLabel: UILabel!
@IBOutlet weak var ui_infoLabel: UILabel!
@IBOutlet weak var ui_preview: UIView!
let captureSession = AVCaptureSession()
lazy var imageRecognitionRequest: VNRequest = {
let model = try! VNCoreMLModel(for: Inceptionv3().model)
let request = VNCoreMLRequest(model: model, completionHandler:self.imageRecognitionHandler)
return request
}()
func imageRecognitionHandler(request:VNRequest, error:Error?) {
guard let observations = request.results as? [VNClassificationObservation],
let bestGuess = observations.first else {
return
}
var finalIdentifier = bestGuess.identifier
if finalIdentifier.contains("hotdog") {
finalIdentifier = "!! 🌭 !!"
} else {
let commaIndex = finalIdentifier.index(of: ",") ?? finalIdentifier.endIndex
finalIdentifier = finalIdentifier[..<commaIndex] + " (not a 🌭)"
}
DispatchQueue.main.async {
if bestGuess.confidence > 0.6 {
self.ui_titleLabel.text = finalIdentifier
self.ui_infoLabel.text = "Probabilité : \(bestGuess.confidence)"
} else {
self.ui_infoLabel.text = "Recherche en cours..."
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func startSessionButtonPressed(_ sender: Any) {
if captureSession.isRunning {
captureSession.stopRunning()
} else {
if captureSession.inputs.count == 0 {
configureCaptureSession()
}
// 4 - Demarrer la session
captureSession.startRunning()
}
}
func configureCaptureSession() {
// 1 - Configurer les entrées
if let camera = AVCaptureDevice.default(for: AVMediaType.video),
let cameraFeed = try? AVCaptureDeviceInput(device: camera) {
captureSession.addInput(cameraFeed)
// 2 - Configurer les sorties
let outputFeed = AVCaptureVideoDataOutput()
outputFeed.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated))
captureSession.addOutput(outputFeed)
// 3 - Configurer l'apercu
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = ui_preview.bounds
ui_preview.layer.addSublayer(previewLayer)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation.up, options: [:])
do {
try imageRequestHandler.perform([imageRecognitionRequest])
} catch {
print(error)
}
}
func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
}
}
| apache-2.0 | f9d232bfbbb960b7a42ac3d021eca3f3 | 33.585586 | 141 | 0.625684 | 5.354254 | false | false | false | false |
sharath-cliqz/browser-ios | Storage/DefaultSuggestedSites.swift | 2 | 4152 | /* 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
open class DefaultSuggestedSites {
open static let sites = [
"default": [
SuggestedSiteData(
url: "https://m.facebook.com/",
bgColor: "0x385185",
imageUrl: "asset://suggestedsites_facebook",
faviconUrl: "asset://defaultFavicon",
trackingId: 632,
title: NSLocalizedString("Facebook", comment: "Tile title for Facebook")
),
SuggestedSiteData(
url: "https://m.youtube.com/",
bgColor: "0xcd201f",
imageUrl: "asset://suggestedsites_youtube",
faviconUrl: "asset://defaultFavicon",
trackingId: 631,
title: NSLocalizedString("YouTube", comment: "Tile title for YouTube")
),
SuggestedSiteData(
url: "https://www.amazon.com/",
bgColor: "0x000000",
imageUrl: "asset://suggestedsites_amazon",
faviconUrl: "asset://defaultFavicon",
trackingId: 630,
title: NSLocalizedString("Amazon", comment: "Tile title for Amazon")
),
SuggestedSiteData(
url: "https://www.wikipedia.org/",
bgColor: "0x000000",
imageUrl: "asset://suggestedsites_wikipedia",
faviconUrl: "asset://defaultFavicon",
trackingId: 629,
title: NSLocalizedString("Wikipedia", comment: "Tile title for Wikipedia")
),
SuggestedSiteData(
url: "https://mobile.twitter.com/",
bgColor: "0x55acee",
imageUrl: "asset://suggestedsites_twitter",
faviconUrl: "asset://defaultFavicon",
trackingId: 628,
title: NSLocalizedString("Twitter", comment: "Tile title for Twitter")
)
],
"zh_CN": [
SuggestedSiteData(
url: "http://mozilla.com.cn",
bgColor: "0xbc3326",
imageUrl: "asset://suggestedsites_mozchina",
faviconUrl: "asset://mozChinaLogo",
trackingId: 700,
title: "火狐社区"
),
SuggestedSiteData(
url: "https://m.baidu.com/?from=1000969b",
bgColor: "0x00479d",
imageUrl: "asset://suggestedsites_baidu",
faviconUrl: "asset://baiduLogo",
trackingId: 701,
title: "百度"
),
SuggestedSiteData(
url: "http://sina.cn",
bgColor: "0xe60012",
imageUrl: "asset://suggestedsites_sina",
faviconUrl: "asset://sinaLogo",
trackingId: 702,
title: "新浪"
),
SuggestedSiteData(
url: "http://info.3g.qq.com/g/s?aid=index&g_f=23946&g_ut=3",
bgColor: "0x028cca",
imageUrl: "asset://suggestedsites_qq",
faviconUrl: "asset://qqLogo",
trackingId: 703,
title: "腾讯"
),
SuggestedSiteData(
url: "http://m.taobao.com",
bgColor: "0xee5900",
imageUrl: "asset://suggestedsites_taobao",
faviconUrl: "asset://taobaoLogo",
trackingId: 704,
title: "淘宝"
),
SuggestedSiteData(
url: "http://m.jd.com/?cu=true&utm_source=c.duomai.com&utm_medium=tuiguang&utm_campaign=t_16282_51222087&utm_term=163a0d0b6b124b7b84e6e936be97a1ad",
bgColor: "0xc71622",
imageUrl: "asset://suggestedsites_jd",
faviconUrl: "asset://jdLogo",
trackingId: 705,
title: "京东"
)
]
]
}
| mpl-2.0 | 1368c63a31b816f5dcdc27616222a81d | 39.431373 | 164 | 0.491513 | 4.54185 | false | false | false | false |
danielgimenes/MusicalIntervalQuiz | MusicalIntervalQuiz/ViewController.swift | 1 | 6690 | //
// ViewController.swift
// MusicalIntervalQuiz
//
// Created by Daniel Gimenes on 3/9/16.
// Copyright © 2016 Daniel Gimenes. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var questionTextLabel: UILabel?
@IBOutlet var scoreValueLabel: UILabel?
@IBOutlet var questionCountLabel: UILabel?
@IBOutlet var aButton: UIButton?
@IBOutlet var bButton: UIButton?
@IBOutlet var cButton: UIButton?
@IBOutlet var dButton: UIButton?
var score: Int!
var currentQuestionIndex: Int!
let RIGHT_ANSWER_SCORE_POINTS = 1
let NUM_OF_QUESTIONS_PER_GAME = 10
let questions = [
Question(
interval: Interval(
startNote: Note(noteName: .E, accidental: .NATURAL),
endNote: Note(noteName: .A, accidental: .NATURAL)
),
optionA: Note(noteName: .C, accidental: .NATURAL),
optionB: Note(noteName: .D, accidental: .SHARP),
optionC: Note(noteName: .A, accidental: .NATURAL),
optionD: Note(noteName: .B, accidental: .FLAT)
),
Question(
interval: Interval(
startNote: Note(noteName: .C, accidental: .NATURAL),
endNote: Note(noteName: .E, accidental: .NATURAL)
),
optionA: Note(noteName: .G, accidental: .NATURAL),
optionB: Note(noteName: .B, accidental: .NATURAL),
optionC: Note(noteName: .A, accidental: .FLAT),
optionD: Note(noteName: .E, accidental: .NATURAL)
),
Question(
interval: Interval(
startNote: Note(noteName: .F, accidental: .NATURAL),
endNote: Note(noteName: .D, accidental: .FLAT)
),
optionA: Note(noteName: .D, accidental: .FLAT),
optionB: Note(noteName: .D, accidental: .NATURAL),
optionC: Note(noteName: .C, accidental: .NATURAL),
optionD: Note(noteName: .E, accidental: .NATURAL)
)
]
var currentQuestion: Question!
var correctAnswerButton: UIButton!
var buttonsActivated = false
override func viewDidLoad() {
super.viewDidLoad()
restartGame()
}
func restartGame() {
score = 0
currentQuestionIndex = 0
updateScoreLabel()
loadNextQuestion()
}
func updateScoreLabel() {
scoreValueLabel!.text = String(score)
}
func loadNextQuestion() {
if (currentQuestionIndex == NUM_OF_QUESTIONS_PER_GAME) {
let alert = UIAlertController(title: "Muito bom!", message: "Você acertou \(score) de \(NUM_OF_QUESTIONS_PER_GAME)", preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: { a in
self.buttonsActivated = false
self.restartGame()
})
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
} else {
questionCountLabel?.text = "\(currentQuestionIndex + 1) / \(NUM_OF_QUESTIONS_PER_GAME)"
loadQuestion(
questions[currentQuestionIndex!++ % questions.count]
)
buttonsActivated = true
}
}
@IBAction func aButtonClicked(sender: UIButton) {
guard buttonsActivated else { return }
answer(currentQuestion.optionA, selectedAnswerButton: sender)
}
@IBAction func bButtonClicked(sender: UIButton) {
guard buttonsActivated else { return }
answer(currentQuestion.optionB, selectedAnswerButton: sender)
}
@IBAction func cButtonClicked(sender: UIButton) {
guard buttonsActivated else { return }
answer(currentQuestion.optionC, selectedAnswerButton: sender)
}
@IBAction func dButtonClicked(sender: UIButton) {
guard buttonsActivated else { return }
answer(currentQuestion.optionD, selectedAnswerButton: sender)
}
func loadQuestion(question: Question) {
currentQuestion = question
questionTextLabel?.setHTMLFromString(question.text)
aButton?.setTitle(String(question.optionA), forState: UIControlState.Normal)
if (question.optionA == question.interval.endNote) {
correctAnswerButton = aButton!
}
bButton?.setTitle(String(question.optionB), forState: UIControlState.Normal)
if (question.optionB == question.interval.endNote) {
correctAnswerButton = bButton!
}
cButton?.setTitle(String(question.optionC), forState: UIControlState.Normal)
if (question.optionC == question.interval.endNote) {
correctAnswerButton = cButton!
}
dButton?.setTitle(String(question.optionD), forState: UIControlState.Normal)
if (question.optionD == question.interval.endNote) {
correctAnswerButton = dButton!
}
}
func answer(selectedAnswer: Note, selectedAnswerButton: UIButton) {
buttonsActivated = false
if (selectedAnswer == currentQuestion.interval.endNote) {
score! += RIGHT_ANSWER_SCORE_POINTS
updateScoreLabel()
} else {
// animate red
selectedAnswerButton.alpha = 0.0
selectedAnswerButton.backgroundColor = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
UIView.animateWithDuration(
0.7,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations : {
selectedAnswerButton.alpha = 1.0
},
completion : { finished in
selectedAnswerButton.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
}
)
}
// animate green
correctAnswerButton.alpha = 0.0
self.correctAnswerButton.backgroundColor = UIColor(red: 0.0, green: 1.0, blue: 0.0, alpha: 1.0)
UIView.animateWithDuration(
0.7,
delay: 0.0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations : {
self.correctAnswerButton.alpha = 1.0
},
completion : { finished in
self.correctAnswerButton.backgroundColor = UIColor(white: 1.0, alpha: 1.0)
self.loadNextQuestion()
}
)
//on animation end,
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | e6b5b3f98b21aa2408203d4e462d285b | 34.574468 | 152 | 0.589713 | 4.537313 | false | false | false | false |
keith/radars | TestCompilerError/Pods/Quick/Quick/DSL/DSL.swift | 139 | 11044 | /**
Defines a closure to be run prior to any examples in the test suite.
You may define an unlimited number of these closures, but there is no
guarantee as to the order in which they're run.
If the test suite crashes before the first example is run, this closure
will not be executed.
- parameter closure: The closure to be run prior to any examples in the test suite.
*/
public func beforeSuite(closure: BeforeSuiteClosure) {
World.sharedWorld().beforeSuite(closure)
}
/**
Defines a closure to be run after all of the examples in the test suite.
You may define an unlimited number of these closures, but there is no
guarantee as to the order in which they're run.
If the test suite crashes before all examples are run, this closure
will not be executed.
- parameter closure: The closure to be run after all of the examples in the test suite.
*/
public func afterSuite(closure: AfterSuiteClosure) {
World.sharedWorld().afterSuite(closure)
}
/**
Defines a group of shared examples. These examples can be re-used in several locations
by using the `itBehavesLike` function.
- parameter name: The name of the shared example group. This must be unique across all shared example
groups defined in a test suite.
- parameter closure: A closure containing the examples. This behaves just like an example group defined
using `describe` or `context`--the closure may contain any number of `beforeEach`
and `afterEach` closures, as well as any number of examples (defined using `it`).
*/
public func sharedExamples(name: String, closure: () -> ()) {
World.sharedWorld().sharedExamples(name, closure: { (NSDictionary) in closure() })
}
/**
Defines a group of shared examples. These examples can be re-used in several locations
by using the `itBehavesLike` function.
- parameter name: The name of the shared example group. This must be unique across all shared example
groups defined in a test suite.
- parameter closure: A closure containing the examples. This behaves just like an example group defined
using `describe` or `context`--the closure may contain any number of `beforeEach`
and `afterEach` closures, as well as any number of examples (defined using `it`).
The closure takes a SharedExampleContext as an argument. This context is a function
that can be executed to retrieve parameters passed in via an `itBehavesLike` function.
*/
public func sharedExamples(name: String, closure: SharedExampleClosure) {
World.sharedWorld().sharedExamples(name, closure: closure)
}
/**
Defines an example group. Example groups are logical groupings of examples.
Example groups can share setup and teardown code.
- parameter description: An arbitrary string describing the example group.
- parameter closure: A closure that can contain other examples.
- parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups.
*/
public func describe(description: String, flags: FilterFlags = [:], closure: () -> ()) {
World.sharedWorld().describe(description, flags: flags, closure: closure)
}
/**
Defines an example group. Equivalent to `describe`.
*/
public func context(description: String, flags: FilterFlags = [:], closure: () -> ()) {
describe(description, flags: flags, closure: closure)
}
/**
Defines a closure to be run prior to each example in the current example
group. This closure is not run for pending or otherwise disabled examples.
An example group may contain an unlimited number of beforeEach. They'll be
run in the order they're defined, but you shouldn't rely on that behavior.
- parameter closure: The closure to be run prior to each example.
*/
public func beforeEach(closure: BeforeExampleClosure) {
World.sharedWorld().beforeEach(closure)
}
/**
Identical to Quick.DSL.beforeEach, except the closure is provided with
metadata on the example that the closure is being run prior to.
*/
public func beforeEach(closure: BeforeExampleWithMetadataClosure) {
World.sharedWorld().beforeEach(closure: closure)
}
/**
Defines a closure to be run after each example in the current example
group. This closure is not run for pending or otherwise disabled examples.
An example group may contain an unlimited number of afterEach. They'll be
run in the order they're defined, but you shouldn't rely on that behavior.
- parameter closure: The closure to be run after each example.
*/
public func afterEach(closure: AfterExampleClosure) {
World.sharedWorld().afterEach(closure)
}
/**
Identical to Quick.DSL.afterEach, except the closure is provided with
metadata on the example that the closure is being run after.
*/
public func afterEach(closure: AfterExampleWithMetadataClosure) {
World.sharedWorld().afterEach(closure: closure)
}
/**
Defines an example. Examples use assertions to demonstrate how code should
behave. These are like "tests" in XCTest.
- parameter description: An arbitrary string describing what the example is meant to specify.
- parameter closure: A closure that can contain assertions.
- parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups.
Empty by default.
- parameter file: The absolute path to the file containing the example. A sensible default is provided.
- parameter line: The line containing the example. A sensible default is provided.
*/
public func it(description: String, flags: FilterFlags = [:], file: String = __FILE__, line: UInt = __LINE__, closure: () -> ()) {
World.sharedWorld().it(description, flags: flags, file: file, line: line, closure: closure)
}
/**
Inserts the examples defined using a `sharedExamples` function into the current example group.
The shared examples are executed at this location, as if they were written out manually.
- parameter name: The name of the shared examples group to be executed. This must be identical to the
name of a shared examples group defined using `sharedExamples`. If there are no shared
examples that match the name given, an exception is thrown and the test suite will crash.
- parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups.
Empty by default.
- parameter file: The absolute path to the file containing the current example group. A sensible default is provided.
- parameter line: The line containing the current example group. A sensible default is provided.
*/
public func itBehavesLike(name: String, flags: FilterFlags = [:], file: String = __FILE__, line: UInt = __LINE__) {
itBehavesLike(name, flags: flags, file: file, line: line, sharedExampleContext: { return [:] })
}
/**
Inserts the examples defined using a `sharedExamples` function into the current example group.
The shared examples are executed at this location, as if they were written out manually.
This function also passes those shared examples a context that can be evaluated to give the shared
examples extra information on the subject of the example.
- parameter name: The name of the shared examples group to be executed. This must be identical to the
name of a shared examples group defined using `sharedExamples`. If there are no shared
examples that match the name given, an exception is thrown and the test suite will crash.
- parameter sharedExampleContext: A closure that, when evaluated, returns key-value pairs that provide the
shared examples with extra information on the subject of the example.
- parameter flags: A mapping of string keys to booleans that can be used to filter examples or example groups.
Empty by default.
- parameter file: The absolute path to the file containing the current example group. A sensible default is provided.
- parameter line: The line containing the current example group. A sensible default is provided.
*/
public func itBehavesLike(name: String, flags: FilterFlags = [:], file: String = __FILE__, line: UInt = __LINE__, sharedExampleContext: SharedExampleContext) {
World.sharedWorld().itBehavesLike(name, sharedExampleContext: sharedExampleContext, flags: flags, file: file, line: line)
}
/**
Defines an example or example group that should not be executed. Use `pending` to temporarily disable
examples or groups that should not be run yet.
- parameter description: An arbitrary string describing the example or example group.
- parameter closure: A closure that will not be evaluated.
*/
public func pending(description: String, closure: () -> ()) {
World.sharedWorld().pending(description, closure: closure)
}
/**
Use this to quickly mark a `describe` closure as pending.
This disables all examples within the closure.
*/
public func xdescribe(description: String, flags: FilterFlags, closure: () -> ()) {
World.sharedWorld().xdescribe(description, flags: flags, closure: closure)
}
/**
Use this to quickly mark a `context` closure as pending.
This disables all examples within the closure.
*/
public func xcontext(description: String, flags: FilterFlags, closure: () -> ()) {
xdescribe(description, flags: flags, closure: closure)
}
/**
Use this to quickly mark an `it` closure as pending.
This disables the example and ensures the code within the closure is never run.
*/
public func xit(description: String, flags: FilterFlags = [:], file: String = __FILE__, line: UInt = __LINE__, closure: () -> ()) {
World.sharedWorld().xit(description, flags: flags, file: file, line: line, closure: closure)
}
/**
Use this to quickly focus a `describe` closure, focusing the examples in the closure.
If any examples in the test suite are focused, only those examples are executed.
This trumps any explicitly focused or unfocused examples within the closure--they are all treated as focused.
*/
public func fdescribe(description: String, flags: FilterFlags = [:], closure: () -> ()) {
World.sharedWorld().fdescribe(description, flags: flags, closure: closure)
}
/**
Use this to quickly focus a `context` closure. Equivalent to `fdescribe`.
*/
public func fcontext(description: String, flags: FilterFlags = [:], closure: () -> ()) {
fdescribe(description, flags: flags, closure: closure)
}
/**
Use this to quickly focus an `it` closure, focusing the example.
If any examples in the test suite are focused, only those examples are executed.
*/
public func fit(description: String, flags: FilterFlags = [:], file: String = __FILE__, line: UInt = __LINE__, closure: () -> ()) {
World.sharedWorld().fit(description, flags: flags, file: file, line: line, closure: closure)
}
| mit | 53c09a7ba9cf783bcac842f8859d0209 | 47.651982 | 159 | 0.716135 | 4.697575 | false | true | false | false |
Jamol/Nutil | Sources/SSL/OpenSslLib.swift | 1 | 9677 | //
// OpenSslLib.swift
// Nutil
//
// Created by Jamol Bao on 11/4/16.
// Copyright © 2016 Jamol Bao. All rights reserved.
//
import Foundation
import COpenSSL
typealias AlpnProtos = [UInt8]
var alpnProtos: AlpnProtos = [2, 104, 50]
fileprivate var certsPath = "./"
fileprivate var sslCtxServer: UnsafeMutablePointer<SSL_CTX>?
fileprivate var sslCtxClient: UnsafeMutablePointer<SSL_CTX>?
class OpenSslLib {
class var initSslOnce: Bool {
return initOpenSslLib()
}
}
func initOpenSslLib() -> Bool {
if SSL_library_init() != 1 {
return false
}
//OpenSSL_add_all_algorithms()
SSL_load_error_strings()
initSslThreading()
// PRNG
RAND_poll()
while(RAND_status() == 0) {
var rand_ret = arc4random()
RAND_seed(&rand_ret, Int32(MemoryLayout.size(ofValue: rand_ret)))
}
let execPath = Bundle.main.executablePath!
let path = (execPath as NSString).deletingLastPathComponent
certsPath = "\(path)/cert"
return true
}
func deinitOpenSslLib() {
EVP_cleanup()
CRYPTO_cleanup_all_ex_data()
ERR_free_strings()
deinitSslThreading()
}
func createSslContext(_ caFile: String, _ certFile: String, _ keyFile: String, _ clientMode: Bool) -> UnsafeMutablePointer<SSL_CTX>? {
var ctx_ok = false
var method = SSLv23_client_method();
if !clientMode {
method = SSLv23_server_method();
}
var sslContext = SSL_CTX_new(method)
guard let ctx = sslContext else {
return nil
}
repeat {
if (SSL_CTX_set_ecdh_auto(ctx, 1) != 1) {
warnTrace("SSL_CTX_set_ecdh_auto failed, err=\(ERR_reason_error_string(ERR_get_error()))");
}
#if arch(arm)
var flags = UInt(SSL_OP_ALL) | UInt(SSL_OP_NO_SSLv2) | UInt(SSL_OP_NO_SSLv3) | UInt(SSL_OP_NO_TLSv1) | UInt(SSL_OP_NO_TLSv1_1)
flags |= UInt(SSL_OP_NO_COMPRESSION)
_ = SSL_CTX_set_options(ctx, Int(bitPattern: flags))
#else
var flags = SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1
flags |= SSL_OP_NO_COMPRESSION
//let flags = UInt32(SSL_OP_ALL) | UInt32(SSL_OP_NO_COMPRESSION)
// SSL_OP_SAFARI_ECDHE_ECDSA_BUG
_ = SSL_CTX_set_options(ctx, flags)
#endif
//SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)
_ = SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
_ = SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE)
_ = SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY)
if !certFile.isEmpty && !keyFile.isEmpty {
if(SSL_CTX_use_certificate_chain_file(ctx, certFile) != 1) {
warnTrace("SSL_CTX_use_certificate_chain_file failed, file=\(certFile), err=\(ERR_reason_error_string(ERR_get_error()))")
break
}
SSL_CTX_set_default_passwd_cb(ctx, passwdCallback)
SSL_CTX_set_default_passwd_cb_userdata(ctx, ctx)
if(SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) != 1) {
warnTrace("SSL_CTX_use_PrivateKey_file failed, file=\(keyFile), err=\(ERR_reason_error_string(ERR_get_error()))")
break
}
if(SSL_CTX_check_private_key(ctx) != 1) {
warnTrace("SSL_CTX_check_private_key failed, err=\(ERR_reason_error_string(ERR_get_error()))");
break
}
}
if (!caFile.isEmpty) {
if(SSL_CTX_load_verify_locations(ctx, caFile, nil) != 1) {
warnTrace("SSL_CTX_load_verify_locations failed, file=\(caFile), err=\(ERR_reason_error_string(ERR_get_error()))")
break
}
if(SSL_CTX_set_default_verify_paths(ctx) != 1) {
warnTrace("SSL_CTX_set_default_verify_paths failed, err=\(ERR_reason_error_string(ERR_get_error()))")
break
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verifyCallback)
//SSL_CTX_set_verify_depth(ctx, 4)
//app_verify_arg arg1
//SSL_CTX_set_cert_verify_callback(ctx, appVerifyCallback, &arg1)
}
if !clientMode {
SSL_CTX_set_alpn_select_cb(ctx, alpnCallback, &alpnProtos)
_ = _SSL_CTX_set_tlsext_servername_callback(ctx, serverNameCallback)
_ = SSL_CTX_set_tlsext_servername_arg(ctx, ctx)
}
ctx_ok = true
} while false
if !ctx_ok {
SSL_CTX_free(ctx)
sslContext = nil
}
return sslContext
}
func defaultClientContext() -> UnsafeMutablePointer<SSL_CTX>!
{
if sslCtxClient == nil {
let certFile = ""
let keyFile = ""
let caFile = "\(certsPath)/ca.pem"
sslCtxClient = createSslContext(caFile, certFile, keyFile, true)
}
return sslCtxClient
}
func defaultServerContext() -> UnsafeMutablePointer<SSL_CTX>!
{
if sslCtxServer == nil {
let certFile = "\(certsPath)/server.pem"
let keyFile = "\(certsPath)/server.key"
let caFile = ""
sslCtxServer = createSslContext(caFile, certFile, keyFile, false)
}
return sslCtxServer
}
func getSslContext(_ hostName: UnsafePointer<CChar>) -> UnsafeMutablePointer<SSL_CTX>
{
return defaultServerContext()
}
/////////////////////////////////////////////////////////////////////////////
// callbacks
func verifyCallback(_ ok: Int32, _ ctx: UnsafeMutablePointer<X509_STORE_CTX>?) -> Int32
{
guard let ctx = ctx else {
return ok
}
var ok = ok
//SSL* ssl = static_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
//SSL_CTX* ssl_ctx = ::SSL_get_SSL_CTX(ssl);
if let cert = ctx.pointee.current_cert {
var cbuf = [Int8](repeating: 0, count: 1024)
let s = X509_NAME_oneline(X509_get_subject_name(cert), &cbuf, Int32(cbuf.count));
if s != nil {
if ok != 0 {
let str = String(cString: cbuf)
infoTrace("verifyCallback ok, depth=\(ctx.pointee.error_depth), subject=\(str)");
if X509_NAME_oneline(X509_get_issuer_name(cert), &cbuf, Int32(cbuf.count)) != nil {
let str = String(cString: cbuf)
infoTrace("verifyCallback, issuer=\(str)")
}
} else {
errTrace("verifyCallback failed, depth=\(ctx.pointee.error_depth), err=\(ctx.pointee.error)");
}
}
}
if 0 == ok {
infoTrace("verifyCallback, err=\(X509_verify_cert_error_string(Int(ctx.pointee.error)))")
switch (ctx.pointee.error)
{
//case X509_V_ERR_CERT_NOT_YET_VALID:
//case X509_V_ERR_CERT_HAS_EXPIRED:
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
infoTrace("verifyCallback, ... ignored, err=\(ctx.pointee.error)")
ok = 1
default:
break
}
}
return ok
}
func alpnCallback(ssl: UnsafeMutablePointer<SSL>?, out: UnsafeMutablePointer<UnsafePointer<UInt8>?>?, outlen: UnsafeMutablePointer<UInt8>?, _in: UnsafePointer<UInt8>?, inlen: UInt32, arg: UnsafeMutableRawPointer?) -> Int32
{
guard let arg = arg else {
return SSL_TLSEXT_ERR_OK
}
let alpn = arg.assumingMemoryBound(to: [UInt8].self)
out?.withMemoryRebound(to: (UnsafeMutablePointer<UInt8>?.self), capacity: 1) {
if (SSL_select_next_proto($0, outlen, alpn.pointee, UInt32(alpn.pointee.count), _in, inlen) != OPENSSL_NPN_NEGOTIATED) {
}
}
/*if (SSL_select_next_proto(out, outlen, alpn.pointee, UInt32(alpn.pointee.count), _in, inlen) != OPENSSL_NPN_NEGOTIATED) {
return SSL_TLSEXT_ERR_NOACK;
}*/
return SSL_TLSEXT_ERR_OK
}
func serverNameCallback(ssl: UnsafeMutablePointer<SSL>?, ad: UnsafeMutablePointer<Int32>?, arg: UnsafeMutableRawPointer?) -> Int32
{
guard let ssl = ssl else {
return SSL_TLSEXT_ERR_NOACK
}
let serverName = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name)
if let sn = serverName {
let ssl_ctx_old = arg?.assumingMemoryBound(to: SSL_CTX.self)
let ssl_ctx_new = getSslContext(sn)
if ssl_ctx_new != ssl_ctx_old {
SSL_set_SSL_CTX(ssl, ssl_ctx_new)
}
}
return SSL_TLSEXT_ERR_NOACK
}
func passwdCallback(buf: UnsafeMutablePointer<Int8>?, size: Int32, rwflag: Int32, userdata: UnsafeMutableRawPointer?) -> Int32
{
//if(size < (int)strlen(pass)+1) return 0;
return 0;
}
/////////////////////////////////////////////////////////////////////////////
//
func SSL_CTX_set_ecdh_auto(_ ctx: UnsafeMutablePointer<SSL_CTX>, _ onoff: Int) -> Int {
return SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, nil)
}
func SSL_CTX_set_options(_ ctx: UnsafeMutablePointer<SSL_CTX>, _ op: Int) -> Int {
return SSL_CTX_ctrl(ctx, SSL_CTRL_OPTIONS, op, nil)
}
func SSL_CTX_set_mode(_ ctx: UnsafeMutablePointer<SSL_CTX>, _ op: Int) -> Int {
return SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, op, nil)
}
/*func SSL_CTX_set_tlsext_servername_callback(_ ctx: UnsafeMutablePointer<SSL_CTX>, _ cb: @escaping ((UnsafeMutablePointer<SSL>?, UnsafeMutablePointer<Int32>?, UnsafeMutableRawPointer?) -> Int32)) -> Int {
return SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cb)
}*/
func SSL_CTX_set_tlsext_servername_arg(_ ctx: UnsafeMutablePointer<SSL_CTX>, _ arg: UnsafeMutableRawPointer?) -> Int {
return SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, arg)
}
func SSL_set_tlsext_host_name(_ ssl: UnsafeMutablePointer<SSL>, _ name: UnsafeMutablePointer<Int8>?) -> Int {
return SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, Int(TLSEXT_NAMETYPE_host_name), name)
}
| mit | 4070a413a08e523f93289f99edc60374 | 35.651515 | 222 | 0.604589 | 3.353899 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.