repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jovito-royeca/ManaKit
|
refs/heads/master
|
Example/ManaKit/Maintainer/Maintainer+CardsPostgres.swift
|
mit
|
1
|
//
// Maintainer+CardsPostgres.swift
// ManaKit_Example
//
// Created by Vito Royeca on 10/27/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
import ManaKit
import PostgresClientKit
import PromiseKit
extension Maintainer {
func createArtistPromise(artist: String, connection: Connection) -> Promise<Void> {
let names = artist.components(separatedBy: " ")
var firstName = ""
var lastName = ""
var nameSection = ""
if names.count > 1 {
if let last = names.last {
lastName = last
nameSection = lastName
}
for i in 0...names.count - 2 {
firstName.append("\(names[i])")
if i != names.count - 2 && names.count >= 3 {
firstName.append(" ")
}
}
} else {
firstName = names.first ?? "NULL"
nameSection = firstName
}
nameSection = sectionFor(name: nameSection) ?? "NULL"
let query = "SELECT createOrUpdateArtist($1,$2,$3,$4)"
let parameters = [artist,
firstName,
lastName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createRarityPromise(rarity: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: rarity))
let nameSection = sectionFor(name: rarity) ?? "NULL"
let query = "SELECT createOrUpdateRarity($1,$2)"
let parameters = [capName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createLanguagePromise(code: String, displayCode: String, name: String, connection: Connection) -> Promise<Void> {
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateLanguage($1,$2,$3,$4)"
let parameters = [code,
displayCode,
name,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createLayoutPromise(name: String, description_: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateLayout($1,$2,$3)"
let parameters = [capName,
nameSection,
description_]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createWatermarkPromise(name: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateWatermark($1,$2)"
let parameters = [capName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createFramePromise(name: String, description_: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateFrame($1,$2,$3)"
let parameters = [capName,
nameSection,
description_]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createFrameEffectPromise(id: String, name: String, description_: String, connection: Connection) -> Promise<Void> {
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateFrameEffect($1,$2,$3,$4)"
let parameters = [id,
name,
nameSection,
description_]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createColorPromise(symbol: String, name: String, isManaColor: Bool, connection: Connection) -> Promise<Void> {
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateColor($1,$2,$3,$4)"
let parameters = [symbol,
name,
nameSection,
isManaColor] as [Any]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createFormatPromise(name: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateFormat($1,$2)"
let parameters = [capName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createLegalityPromise(name: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateLegality($1,$2)"
let parameters = [capName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createCardTypePromise(name: String, parent: String, connection: Connection) -> Promise<Void> {
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateCardType($1,$2,$3)"
let parameters = [name,
nameSection,
parent]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createComponentPromise(name: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: name))
let nameSection = sectionFor(name: name) ?? "NULL"
let query = "SELECT createOrUpdateComponent($1,$2)"
let parameters = [capName,
nameSection]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createDeleteFacesPromise(connection: Connection) -> Promise<Void> {
let query = "DELETE FROM cmcard_face"
return createPromise(with: query,
parameters: nil,
connection: connection)
}
func createFacePromise(card: String, cardFace: String, connection: Connection) -> Promise<Void> {
let query = "SELECT createOrUpdateCardFaces($1,$2)"
let parameters = [card,
cardFace]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createDeletePartsPromise(connection: Connection) -> Promise<Void> {
let query = "DELETE FROM cmcard_component_part"
return createPromise(with: query,
parameters: nil,
connection: connection)
}
func createPartPromise(card: String, component: String, cardPart: String, connection: Connection) -> Promise<Void> {
let capName = capitalize(string: displayFor(name: component))
let query = "SELECT createOrUpdateCardParts($1,$2,$3)"
let parameters = [card,
capName,
cardPart]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func createOtherLanguagesPromise() -> Promise<Void> {
return createPromise(with: "select createOrUpdateCardOtherLanguages()",
parameters: nil,
connection: nil)
}
func createOtherPrintingsPromise() -> Promise<Void> {
return createPromise(with: "select createOrUpdateCardOtherPrintings()",
parameters: nil,
connection: nil)
}
func createVariationsPromise() -> Promise<Void> {
return createPromise(with: "select createOrUpdateCardVariations()",
parameters: nil,
connection: nil)
}
func createCardPromise(dict: [String: Any], connection: Connection) -> Promise<Void> {
let collectorNumber = dict["collector_number"] as? String ?? "NULL"
let cmc = dict["cmc"] as? Double ?? Double(0)
let flavorText = dict["flavor_text"] as? String ?? "NULL"
let isFoil = dict["foil"] as? Bool ?? false
let isFullArt = dict["full_art"] as? Bool ?? false
let isHighresImage = dict["highres_image"] as? Bool ?? false
let isNonfoil = dict["nonfoil"] as? Bool ?? false
let isOversized = dict["oversized"] as? Bool ?? false
let isReserved = dict["reserved"] as? Bool ?? false
let isStorySpotlight = dict["story_spotlight"] as? Bool ?? false
let loyalty = dict["loyalty"] as? String ?? "NULL"
let manaCost = dict["mana_cost"] as? String ?? "NULL"
var multiverseIds = "{}"
if let a = dict["multiverse_ids"] as? [Int],
!a.isEmpty {
multiverseIds = "\(a)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var myNameSection = "NULL"
if let name = dict["name"] as? String {
myNameSection = sectionFor(name: name) ?? "NULL"
}
var myNumberOrder = Double(0)
if collectorNumber != "NULL" {
myNumberOrder = order(of: collectorNumber)
}
let name = dict["name"] as? String ?? "NULL"
let oracleText = dict["oracle_text"] as? String ?? "NULL"
let power = dict["power"] as? String ?? "NULL"
let printedName = dict["printed_name"] as? String ?? "NULL"
let printedText = dict["printed_text"] as? String ?? "NULL"
let toughness = dict["toughness"] as? String ?? "NULL"
let arenaId = dict["arena_id"] as? String ?? "NULL"
let mtgoId = dict["mtgo_id"] as? String ?? "NULL"
let tcgplayerId = dict["tcgplayer_id"] as? Int ?? Int(0)
let handModifier = dict["hand_modifier"] as? String ?? "NULL"
let lifeModifier = dict["life_modifier"] as? String ?? "NULL"
let isBooster = dict["booster"] as? Bool ?? false
let isDigital = dict["digital"] as? Bool ?? false
let isPromo = dict["promo"] as? Bool ?? false
let releasedAt = dict["released_at"] as? String ?? "NULL"
let isTextless = dict["textless"] as? Bool ?? false
let mtgoFoilId = dict["mtgo_foil_id"] as? String ?? "NULL"
let isReprint = dict["reprint"] as? Bool ?? false
let id = dict["id"] as? String ?? "NULL"
let cardBackId = dict["card_back_id"] as? String ?? "NULL"
let oracleId = dict["oracle_id"] as? String ?? "NULL"
let illustrationId = dict["illustration_id"] as? String ?? "NULL"
let artist = dict["artist"] as? String ?? "NULL"
let set = dict["set"] as? String ?? "NULL"
let rarity = capitalize(string: dict["rarity"] as? String ?? "NULL")
let language = dict["lang"] as? String ?? "NULL"
let layout = capitalize(string: displayFor(name: dict["layout"] as? String ?? "NULL"))
let watermark = capitalize(string: dict["watermark"] as? String ?? "NULL")
let frame = capitalize(string: dict["frame"] as? String ?? "NULL")
var frameEffects = "{}"
if let a = dict["frame_effects"] as? [String],
!a.isEmpty {
frameEffects = "\(a)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var colors = "{}"
if let a = dict["colors"] as? [String],
!a.isEmpty {
colors = "\(a)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var colorIdentities = "{}"
if let a = dict["color_identity"] as? [String],
!a.isEmpty {
colorIdentities = "\(a)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var colorIndicators = "{}"
if let a = dict["color_indicator"] as? [String],
!a.isEmpty {
colorIndicators = "\(a)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var legalities = "{}"
if let legalitiesDict = dict["legalities"] as? [String: String] {
var newLegalities = [String: String]()
for (k,v) in legalitiesDict {
newLegalities[capitalize(string: displayFor(name: k))] = capitalize(string: displayFor(name: v))
}
legalities = "\(newLegalities)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
let typeLine = dict["type_line"] as? String ?? "NULL"
let printedTypeLine = dict["printed_type_line"] as? String ?? "NULL"
var cardtypeSubtypes = "{}"
if let tl = dict["type_line"] as? String {
let subtypes = extractSubtypesFrom(tl)
cardtypeSubtypes = "\(subtypes)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
var cardtypeSupertypes = "{}"
if let tl = dict["type_line"] as? String {
let supertypes = extractSupertypesFrom(tl)
cardtypeSupertypes = "\(supertypes)"
.replacingOccurrences(of: "[", with: "{")
.replacingOccurrences(of: "]", with: "}")
}
let faceOrder = dict["face_order"] as? Int ?? Int(0)
// unhandled...
// border_color
// games
// promo_types
// preview.previewed_at
// preview.source_uri
// preview.source
let query = "SELECT createOrUpdateCard($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32,$33,$34,$35,$36,$37,$38,$39,$40,$41,$42,$43,$44,$45,$46,$47,$48,$49,$50,$51,$52,$53,$54)"
let parameters = [collectorNumber,
cmc,
flavorText,
isFoil,
isFullArt,
isHighresImage,
isNonfoil,
isOversized,
isReserved,
isStorySpotlight,
loyalty,
manaCost,
multiverseIds,
myNameSection,
myNumberOrder,
name,
oracleText,
power,
printedName,
printedText,
toughness,
arenaId,
mtgoId,
tcgplayerId,
handModifier,
lifeModifier,
isBooster,
isDigital,
isPromo,
releasedAt,
isTextless,
mtgoFoilId,
isReprint,
id,
cardBackId,
oracleId,
illustrationId,
artist,
set,
rarity,
language,
layout,
watermark,
frame,
frameEffects,
colors,
colorIdentities,
colorIndicators,
legalities,
typeLine,
printedTypeLine,
cardtypeSubtypes,
cardtypeSupertypes,
faceOrder] as [Any]
return createPromise(with: query,
parameters: parameters,
connection: connection)
}
func extractImageUrls(set: String, language: String, id: String, imageUrisDict: [String: String]) -> [String: String] {
var dict = [String: String]()
if let artCrop = imageUrisDict["art_crop"],
let u = artCrop.components(separatedBy: "?").first,
let ext = u.components(separatedBy: ".").last {
dict["art_crop"] = "\(set)/\(language)/\(id)/art_crop.\(ext)"
}
if let normal = imageUrisDict["normal"],
let u = normal.components(separatedBy: "?").first,
let ext = u.components(separatedBy: ".").last {
dict["normal"] = "\(set)/\(language)/\(id)/normal.\(ext)"
}
return dict
}
}
|
a9f3be3d102a9a4c9ce4aa3fba074c86
| 41.413242 | 255 | 0.498089 | false | false | false | false |
onmyway133/Xmas
|
refs/heads/master
|
Xmas/NSObject_Extension.swift
|
mit
|
1
|
//
// NSObject_Extension.swift
//
// Created by Khoa Pham on 12/18/15.
// Copyright © 2015 Fantageek. All rights reserved.
//
import Foundation
extension NSObject {
class func pluginDidLoad(bundle: NSBundle) {
let appName = NSBundle.mainBundle().infoDictionary?["CFBundleName"] as? NSString
if appName == "Xcode" {
if sharedPlugin == nil {
sharedPlugin = Xmas(bundle: bundle)
}
}
}
}
|
806eda5c77d74dd24ccfca24302091fc
| 22.631579 | 88 | 0.620536 | false | false | false | false |
ragnar/VindsidenApp
|
refs/heads/develop
|
watchkitapp Extension/ExtensionDelegate.swift
|
bsd-2-clause
|
1
|
//
// ExtensionDelegate.swift
// VindsidenApp
//
// Created by Ragnar Henriksen on 10.06.15.
// Copyright © 2015 RHC. All rights reserved.
//
import WatchKit
import VindsidenWatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
var timestamp: TimeInterval = 0
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
}
func applicationDidBecomeActive() {
WCFetcher.sharedInstance.activate()
scheduleRefresh()
if Date().timeIntervalSinceReferenceDate < timestamp + 60 {
return
}
timestamp = Date().timeIntervalSinceReferenceDate
DataManager.shared.cleanupPlots { () -> Void in
NotificationCenter.default.post(name: Notification.Name.FetchingPlots, object: nil)
WindManager.sharedManager.fetch({ (result: WindManagerResult) -> Void in
NotificationCenter.default.post(name: Notification.Name.ReceivedPlots, object: nil)
})
}
}
func applicationWillResignActive() {
PlotFetcher.invalidate()
StationFetcher.invalidate()
}
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
// Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
for task in backgroundTasks {
// Use a switch statement to check the task type
switch task {
case let backgroundTask as WKApplicationRefreshBackgroundTask:
// Be sure to complete the background task once you’re done.
if (WKExtension.shared().applicationState != .background) {
if #available(watchOSApplicationExtension 4.0, *) {
backgroundTask.setTaskCompletedWithSnapshot(false)
} else {
backgroundTask.setTaskCompleted()
}
return
}
WindManager.sharedManager.fetch({ (result: WindManagerResult) -> Void in
NotificationCenter.default.post(name: Notification.Name.ReceivedPlots, object: nil)
if #available(watchOSApplicationExtension 4.0, *) {
backgroundTask.setTaskCompletedWithSnapshot(false)
} else {
backgroundTask.setTaskCompleted()
}
self.scheduleRefresh()
})
// case let snapshotTask as WKSnapshotRefreshBackgroundTask:
// // Snapshot tasks have a unique completion call, make sure to set your expiration date
// snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil)
// case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask:
// // Be sure to complete the connectivity task once you’re done.
// connectivityTask.setTaskCompleted()
// case let urlSessionTask as WKURLSessionRefreshBackgroundTask:
// // Be sure to complete the URL session task once you’re done.
// urlSessionTask.setTaskCompleted()
default:
// make sure to complete unhandled task types
if #available(watchOSApplicationExtension 4.0, *) {
task.setTaskCompletedWithSnapshot(false)
} else {
task.setTaskCompleted()
}
}
}
}
func scheduleRefresh() {
// let fireDate = Date(timeIntervalSinceNow: 60.0*30.0)
// let userInfo = ["reason" : "background update"] as NSDictionary
//
// WKExtension.shared().scheduleBackgroundRefresh(withPreferredDate: fireDate, userInfo: userInfo) { (error) in
// if error != nil {
// DLOG("Schedule background failed: \(String(describing: error))")
// }
// }
}
}
|
9c07c2b0a2f2efef9b6f9cf66c075737
| 37.386792 | 160 | 0.605308 | false | false | false | false |
AmitaiB/MyPhotoViewer
|
refs/heads/master
|
Acornote_iOS/Pods/Cache/Source/Shared/Library/ImageWrapper.swift
|
apache-2.0
|
3
|
import Foundation
public struct ImageWrapper: Codable {
public let image: Image
public enum CodingKeys: String, CodingKey {
case image
}
public init(image: Image) {
self.image = image
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let data = try container.decode(Data.self, forKey: CodingKeys.image)
guard let image = Image(data: data) else {
throw StorageError.decodingFailed
}
self.image = image
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
guard let data = image.cache_toData() else {
throw StorageError.encodingFailed
}
try container.encode(data, forKey: CodingKeys.image)
}
}
|
5e4e725be5d3133604719842d2c15325
| 23.78125 | 72 | 0.696091 | false | false | false | false |
ekgorter/MyWikiTravel
|
refs/heads/master
|
MyWikiTravel/MyWikiTravel/SearchViewController.swift
|
unlicense
|
1
|
//
// SearchViewController.swift
// MyWikiTravel
//
// Created by Elias Gorter on 04-06-15.
// Copyright (c) 2015 EliasGorter6052274. All rights reserved.
//
// Allows user to search wikitravel.org for articles. Search results are displayed in table.
import UIKit
class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, MediaWikiAPIProtocol {
var searchResults = [Searchresult]()
var guide: Guide!
let cellIdentifier = "searchResultCell"
var api: MediaWikiAPI!
@IBOutlet weak var articleSearchBar: UISearchBar!
@IBOutlet weak var searchResultsTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Uses the MediaWiki API to get data from wikitravel.org.
api = MediaWikiAPI(delegate: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
// Show search results in cells of tableview.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! UITableViewCell!
let article = searchResults[indexPath.row]
cell.textLabel?.text = article.title
return cell
}
// Displays the the results of the inputted search term in the tableview.
func searchAPIResults(searchResult: NSArray) {
dispatch_async(dispatch_get_main_queue(), {
self.searchResults = Searchresult.searchresultsFromJson(searchResult, guide: self.guide)
self.searchResultsTableView!.reloadData()
})
}
// Searches wikitravel.org with inputted search term.
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
api.searchWikiTravel(articleSearchBar.text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
}
// Displays selected article contents in new view.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let articleViewController: ArticleViewController = segue.destinationViewController as? ArticleViewController {
var articleIndex = searchResultsTableView!.indexPathForSelectedRow()!.row
articleViewController.onlineSource = true
articleViewController.article = searchResults[articleIndex]
}
}
}
|
542a9c603f55a37271dfad89970cea76
| 37.746269 | 133 | 0.71379 | false | false | false | false |
brocktonpoint/CawBoxKit
|
refs/heads/master
|
CawBoxKitTests/BinaryValueArrayTest.swift
|
mit
|
1
|
/*
The MIT License (MIT)
Copyright (c) 2015 CawBox
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import XCTest
import CoreLocation
@testable import CawBoxKit
class BinaryValueArrayTest: XCTestCase {
func testCoreLocationBinaryArray () {
var input = [
CLLocationCoordinate2D (latitude: 49.287, longitude: 123.12),
CLLocationCoordinate2D (latitude: 49.3, longitude: 123.2),
CLLocationCoordinate2D (latitude: 49.1, longitude: 123.0)
]
let data = NSData (bytes: &input, length: input.count * sizeof (CLLocationCoordinate2D))
let output = BinaryValueArray<CLLocationCoordinate2D> (data: data, zeroValue: kCLLocationCoordinate2DInvalid).results
XCTAssert (input.count == output.count, "Input != Output Count")
for (index, location) in input.enumerated () {
XCTAssert (location.latitude == output[index].latitude && location.longitude == output[index].longitude, "Input[\(index)] != Output[\(index)] Count")
}
}
}
|
d466bfa774881e041a1a95e7450a81e3
| 42.212766 | 161 | 0.731034 | false | true | false | false |
looker-open-source/sdk-codegen
|
refs/heads/main
|
examples/swift/sample-swift-sdk/sample-swift-sdk/LookerSwiftSDK/partial.swift
|
mit
|
3
|
// from https://josephduffy.co.uk/partial-in-swift
// TODO not currently used and not sure it makes sense
import Foundation
struct Partial<Wrapped>: CustomStringConvertible, CustomDebugStringConvertible {
enum Error<ValueType>: Swift.Error {
case missingKey(KeyPath<Wrapped, ValueType>)
case invalidValueType(key: KeyPath<Wrapped, ValueType>, actualValue: Any)
}
private var values: [PartialKeyPath<Wrapped>: Any?] = [:]
private var backingValue: Wrapped? = nil
var description: String {
let backingValueDescription: String
if let backingValue = backingValue as? CustomStringConvertible {
backingValueDescription = backingValue.description
} else {
backingValueDescription = String(describing: backingValue)
}
return "<\(type(of: self)) values=\(values.description); backingValue=\(backingValueDescription)>"
}
var debugDescription: String {
if let backingValue = backingValue {
return debugDescription(utilising: backingValue)
} else {
return "<\(type(of: self)) values=\(values.debugDescription); backingValue=\(backingValue.debugDescription))>"
}
}
init(backingValue: Wrapped? = nil) {
self.backingValue = backingValue
}
func value<ValueType>(for key: KeyPath<Wrapped, ValueType>) throws -> ValueType {
if let value = values[key] {
if let value = value as? ValueType {
return value
} else if let value = value {
throw Error.invalidValueType(key: key, actualValue: value)
}
} else if let value = backingValue?[keyPath: key] {
return value
}
throw Error.missingKey(key)
}
func value<ValueType>(for key: KeyPath<Wrapped, ValueType?>) throws -> ValueType {
if let value = values[key] {
if let value = value as? ValueType {
return value
} else if let value = value {
throw Error.invalidValueType(key: key, actualValue: value)
}
} else if let value = backingValue?[keyPath: key] {
return value
}
throw Error.missingKey(key)
}
func value<ValueType>(for key: KeyPath<Wrapped, ValueType>) throws -> ValueType where ValueType: PartialConvertible {
if let value = values[key] {
if let value = value as? ValueType {
return value
} else if let partial = value as? Partial<ValueType> {
return try ValueType(partial: partial)
} else if let value = value {
throw Error.invalidValueType(key: key, actualValue: value)
}
} else if let value = backingValue?[keyPath: key] {
return value
}
throw Error.missingKey(key)
}
func value<ValueType>(for key: KeyPath<Wrapped, ValueType?>) throws -> ValueType where ValueType: PartialConvertible {
if let value = values[key] {
if let value = value as? ValueType {
return value
} else if let partial = value as? Partial<ValueType> {
return try ValueType(partial: partial)
} else if let value = value {
throw Error.invalidValueType(key: key, actualValue: value)
}
} else if let value = backingValue?[keyPath: key] {
return value
}
throw Error.missingKey(key)
}
subscript<ValueType>(key: KeyPath<Wrapped, ValueType>) -> ValueType? {
get {
return try? value(for: key)
}
set {
/**
Uses `updateValue(_:forKey:)` to ensure the value is set to `nil`.
When the subscript is used the key is removed from the dictionary.
This ensures that the `backingValue`'s value will not be used when
a `backingValue` is set and a key is explicitly set to `nil`
*/
values.updateValue(newValue, forKey: key)
}
}
subscript<ValueType>(key: KeyPath<Wrapped, ValueType?>) -> ValueType? {
get {
return try? value(for: key)
}
set {
values.updateValue(newValue, forKey: key)
}
}
subscript<ValueType>(key: KeyPath<Wrapped, ValueType>) -> Partial<ValueType> where ValueType: PartialConvertible {
get {
if let value = try? self.value(for: key) {
return Partial<ValueType>(backingValue: value)
} else if let partial = values[key] as? Partial<ValueType> {
return partial
} else {
return Partial<ValueType>()
}
}
set {
values.updateValue(newValue, forKey: key)
}
}
subscript<ValueType>(key: KeyPath<Wrapped, ValueType?>) -> Partial<ValueType> where ValueType: PartialConvertible {
get {
if let value = try? self.value(for: key) {
return Partial<ValueType>(backingValue: value)
} else if let partial = values[key] as? Partial<ValueType> {
return partial
} else {
return Partial<ValueType>()
}
}
set {
values.updateValue(newValue, forKey: key)
}
}
}
extension Partial {
func debugDescription(utilising instance: Wrapped) -> String {
var namedValues: [String: Any] = [:]
var unnamedValues: [PartialKeyPath<Wrapped>: Any] = [:]
let mirror = Mirror(reflecting: instance)
for (key, value) in self.values {
var foundKey = false
for child in mirror.children {
if let propertyName = child.label {
foundKey = (value as AnyObject) === (child.value as AnyObject)
if foundKey {
namedValues[propertyName] = value
break
}
}
}
if !foundKey {
unnamedValues[key] = value
}
}
return "<\(type(of: self)) values=\(namedValues.debugDescription), \(unnamedValues.debugDescription); backingValue=\(backingValue.debugDescription))>"
}
}
extension Partial where Wrapped: PartialConvertible {
var debugDescription: String {
if let instance = try? Wrapped(partial: self) {
return debugDescription(utilising: instance)
} else {
return "<\(type(of: self)) values=\(values.debugDescription); backingValue=\(backingValue.debugDescription))>"
}
}
}
protocol PartialConvertible {
init(partial: Partial<Self>) throws
}
|
13b91dd375be192c2fd8bdbb0b79bf99
| 31.781553 | 158 | 0.573375 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client
|
refs/heads/master
|
TrolleyTracker/Controllers/UI/MapContainer/MapViewDelegate.swift
|
mit
|
1
|
//
// MapViewDelegate.swift
// TrolleyTracker
//
// Created by Austin Younts on 10/11/15.
// Copyright © 2015 Code For Greenville. All rights reserved.
//
import MapKit
class TrolleyMapViewDelegate: NSObject, MKMapViewDelegate {
private enum Identifiers {
static let trolley = "TrolleyAnnotation"
static let stop = "StopAnnotation"
static let user = "UserAnnotation"
}
typealias MapViewSelectionAction = (_ annotationView: MKAnnotationView) -> Void
var annotationSelectionAction: MapViewSelectionAction?
var annotationDeselectionAction: MapViewSelectionAction?
var shouldShowCallouts: Bool = false
var highlightedRoute: TrolleyRoute?
var highlightedTrolley: Trolley?
var shouldDimStops: Bool = false
func mapView(_ mapView: MKMapView,
viewFor annotation: MKAnnotation) -> MKAnnotationView? {
// User
if (annotation is MKUserLocation) {
let view = mapView.dequeueAnnotationView(ofType: MKAnnotationView.self,
for: annotation)
let image = UIImage.ttUserPin
view.image = image
view.centerOffset = CGPoint(x: 0,
y: -(image.size.height / 2))
view.annotation = annotation
return view
}
// Trolley Stops
if annotation is TrolleyStop {
let view = mapView.dequeueAnnotationView(ofType: TrolleyStopAnnotationView.self,
for: annotation)
view.frame = CGRect(x: 0, y: 0, width: 22, height: 22)
view.canShowCallout = shouldShowCallouts
view.annotation = annotation
view.tintColor = UIColor(white: 0.3, alpha: 1)
view.alpha = shouldDimStops ? .fadedStop : .unfadedStop
return view
}
// Trolleys
if let trolleyAnnotation = annotation as? Trolley {
let view = mapView.dequeueAnnotationView(ofType: TrolleyAnnotationView.self,
for: annotation)
view.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
view.tintColor = trolleyAnnotation.tintColor
view.trolleyName = trolleyAnnotation.displayNameShort
view.annotation = trolleyAnnotation
if let highlighted = highlightedTrolley {
view.alpha = highlighted.ID == trolleyAnnotation.ID ? .unfadedTrolley : .fadedTrolley
}
else {
// No highlighted Trolley, all should be equal
view.alpha = .unfadedTrolley
}
return view
}
return nil
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.lineWidth = 4.0
guard let routeOverlay = overlay as? TrolleyRouteOverlay else {
return renderer
}
renderer.strokeColor = routeOverlay.color
if let highlighted = highlightedRoute {
renderer.alpha = highlighted.color == routeOverlay.color ? .unfadedRoute : .fadedRoute
}
return renderer
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
annotationSelectionAction?(view)
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
self.deSelectIfNeeded(mapView, view: view)
}
}
private func deSelectIfNeeded(_ mapView: MKMapView, view: MKAnnotationView) {
guard mapView.selectedAnnotations.isEmpty else { return }
annotationDeselectionAction?(view)
}
}
extension MKMapView {
func dequeueAnnotationView<T>(ofType type: T.Type,
for annotation: MKAnnotation) -> T where T: MKAnnotationView {
let id = String(describing: type)
let view = dequeueReusableAnnotationView(withIdentifier: id)
if let typedView = view as? T {
return typedView
}
return T(annotation: annotation, reuseIdentifier: id)
}
}
|
962076cfcbc205aa706bc97eb1d7bc24
| 30.891304 | 101 | 0.591911 | false | false | false | false |
apple/swift-nio
|
refs/heads/main
|
Sources/NIOPosix/SelectableEventLoop.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
import NIOCore
import NIOConcurrencyHelpers
import _NIODataStructures
import Atomics
/// Execute the given closure and ensure we release all auto pools if needed.
@inlinable
internal func withAutoReleasePool<T>(_ execute: () throws -> T) rethrows -> T {
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS)
return try autoreleasepool {
try execute()
}
#else
return try execute()
#endif
}
/// `EventLoop` implementation that uses a `Selector` to get notified once there is more I/O or tasks to process.
/// The whole processing of I/O and tasks is done by a `NIOThread` that is tied to the `SelectableEventLoop`. This `NIOThread`
/// is guaranteed to never change!
@usableFromInline
internal final class SelectableEventLoop: EventLoop {
static let strictModeEnabled: Bool = {
switch getenv("SWIFTNIO_STRICT").map({ String.init(cString: $0).lowercased() }) {
case "true", "y", "yes", "on", "1":
return true
default:
return false
}
}()
/// The different state in the lifecycle of an `EventLoop` seen from _outside_ the `EventLoop`.
private enum ExternalState {
/// `EventLoop` is open and so can process more work.
case open
/// `EventLoop` is currently in the process of closing.
case closing
/// `EventLoop` is closed.
case closed
/// `EventLoop` is closed and is currently trying to reclaim resources (such as the EventLoop thread).
case reclaimingResources
/// `EventLoop` is closed and all the resources (such as the EventLoop thread) have been reclaimed.
case resourcesReclaimed
}
/// The different state in the lifecycle of an `EventLoop` seen from _inside_ the `EventLoop`.
private enum InternalState {
case runningAndAcceptingNewRegistrations
case runningButNotAcceptingNewRegistrations
case noLongerRunning
case exitingThread
}
/* private but tests */ internal let _selector: NIOPosix.Selector<NIORegistration>
private let thread: NIOThread
@usableFromInline
// _pendingTaskPop is set to `true` if the event loop is about to pop tasks off the task queue.
// This may only be read/written while holding the _tasksLock.
internal var _pendingTaskPop = false
@usableFromInline
internal var scheduledTaskCounter = ManagedAtomic<UInt64>(0)
@usableFromInline
internal var _scheduledTasks = PriorityQueue<ScheduledTask>()
// We only need the ScheduledTask's task closure. However, an `Array<() -> Void>` allocates
// for every appended closure. https://bugs.swift.org/browse/SR-15872
private var tasksCopy = ContiguousArray<ScheduledTask>()
@usableFromInline
internal var _succeededVoidFuture: Optional<EventLoopFuture<Void>> = nil {
didSet {
self.assertInEventLoop()
}
}
private let canBeShutdownIndividually: Bool
@usableFromInline
internal let _tasksLock = NIOLock()
private let _externalStateLock = NIOLock()
private var externalStateLock: NIOLock {
// The assert is here to check that we never try to read the external state on the EventLoop unless we're
// shutting down.
assert(!self.inEventLoop || self.internalState != .runningAndAcceptingNewRegistrations,
"lifecycle lock taken whilst up and running and in EventLoop")
return self._externalStateLock
}
private var internalState: InternalState = .runningAndAcceptingNewRegistrations // protected by the EventLoop thread
private var externalState: ExternalState = .open // protected by externalStateLock
private let _iovecs: UnsafeMutablePointer<IOVector>
private let _storageRefs: UnsafeMutablePointer<Unmanaged<AnyObject>>
let iovecs: UnsafeMutableBufferPointer<IOVector>
let storageRefs: UnsafeMutableBufferPointer<Unmanaged<AnyObject>>
// Used for gathering UDP writes.
private let _msgs: UnsafeMutablePointer<MMsgHdr>
private let _addresses: UnsafeMutablePointer<sockaddr_storage>
let msgs: UnsafeMutableBufferPointer<MMsgHdr>
let addresses: UnsafeMutableBufferPointer<sockaddr_storage>
// Used for UDP control messages.
private(set) var controlMessageStorage: UnsafeControlMessageStorage
// The `_parentGroup` will always be set unless this is a thread takeover or we shut down.
@usableFromInline
internal var _parentGroup: Optional<MultiThreadedEventLoopGroup>
/// Creates a new `SelectableEventLoop` instance that is tied to the given `pthread_t`.
private let promiseCreationStoreLock = NIOLock()
private var _promiseCreationStore: [_NIOEventLoopFutureIdentifier: (file: StaticString, line: UInt)] = [:]
@usableFromInline
internal func _promiseCreated(futureIdentifier: _NIOEventLoopFutureIdentifier, file: StaticString, line: UInt) {
precondition(_isDebugAssertConfiguration())
self.promiseCreationStoreLock.withLock {
self._promiseCreationStore[futureIdentifier] = (file: file, line: line)
}
}
@usableFromInline
internal func _promiseCompleted(futureIdentifier: _NIOEventLoopFutureIdentifier) -> (file: StaticString, line: UInt)? {
precondition(_isDebugAssertConfiguration())
return self.promiseCreationStoreLock.withLock {
self._promiseCreationStore.removeValue(forKey: futureIdentifier)
}
}
@usableFromInline
internal func _preconditionSafeToWait(file: StaticString, line: UInt) {
let explainer: () -> String = { """
BUG DETECTED: wait() must not be called when on an EventLoop.
Calling wait() on any EventLoop can lead to
- deadlocks
- stalling processing of other connections (Channels) that are handled on the EventLoop that wait was called on
Further information:
- current eventLoop: \(MultiThreadedEventLoopGroup.currentEventLoop.debugDescription)
- event loop associated to future: \(self)
"""
}
precondition(!self.inEventLoop, explainer(), file: file, line: line)
precondition(MultiThreadedEventLoopGroup.currentEventLoop == nil, explainer(), file: file, line: line)
}
@usableFromInline
internal var _validInternalStateToScheduleTasks: Bool {
switch self.internalState {
case .exitingThread:
return false
case .runningAndAcceptingNewRegistrations, .runningButNotAcceptingNewRegistrations, .noLongerRunning:
return true
}
}
// access with `externalStateLock` held
private var validExternalStateToScheduleTasks: Bool {
switch self.externalState {
case .open, .closing:
return true
case .closed, .reclaimingResources, .resourcesReclaimed:
return false
}
}
internal var testsOnly_validExternalStateToScheduleTasks: Bool {
return self.externalStateLock.withLock {
return self.validExternalStateToScheduleTasks
}
}
internal init(thread: NIOThread,
parentGroup: MultiThreadedEventLoopGroup?, /* nil iff thread take-over */
selector: NIOPosix.Selector<NIORegistration>,
canBeShutdownIndividually: Bool) {
self._parentGroup = parentGroup
self._selector = selector
self.thread = thread
self._iovecs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors)
self._storageRefs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors)
self.iovecs = UnsafeMutableBufferPointer(start: self._iovecs, count: Socket.writevLimitIOVectors)
self.storageRefs = UnsafeMutableBufferPointer(start: self._storageRefs, count: Socket.writevLimitIOVectors)
self._msgs = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors)
self._addresses = UnsafeMutablePointer.allocate(capacity: Socket.writevLimitIOVectors)
self.msgs = UnsafeMutableBufferPointer(start: _msgs, count: Socket.writevLimitIOVectors)
self.addresses = UnsafeMutableBufferPointer(start: _addresses, count: Socket.writevLimitIOVectors)
self.controlMessageStorage = UnsafeControlMessageStorage.allocate(msghdrCount: Socket.writevLimitIOVectors)
// We will process 4096 tasks per while loop.
self.tasksCopy.reserveCapacity(4096)
self.canBeShutdownIndividually = canBeShutdownIndividually
// note: We are creating a reference cycle here that we'll break when shutting the SelectableEventLoop down.
// note: We have to create the promise and complete it because otherwise we'll hit a loop in `makeSucceededFuture`. This is
// fairly dumb, but it's the only option we have.
let voidPromise = self.makePromise(of: Void.self)
voidPromise.succeed(())
self._succeededVoidFuture = voidPromise.futureResult
}
deinit {
assert(self.internalState == .exitingThread,
"illegal internal state on deinit: \(self.internalState)")
assert(self.externalState == .resourcesReclaimed,
"illegal external state on shutdown: \(self.externalState)")
_iovecs.deallocate()
_storageRefs.deallocate()
_msgs.deallocate()
_addresses.deallocate()
self.controlMessageStorage.deallocate()
}
/// Is this `SelectableEventLoop` still open (ie. not shutting down or shut down)
internal var isOpen: Bool {
self.assertInEventLoop()
switch self.internalState {
case .noLongerRunning, .runningButNotAcceptingNewRegistrations, .exitingThread:
return false
case .runningAndAcceptingNewRegistrations:
return true
}
}
/// Register the given `SelectableChannel` with this `SelectableEventLoop`. After this point all I/O for the `SelectableChannel` will be processed by this `SelectableEventLoop` until it
/// is deregistered by calling `deregister`.
internal func register<C: SelectableChannel>(channel: C) throws {
self.assertInEventLoop()
// Don't allow registration when we're closed.
guard self.isOpen else {
throw EventLoopError.shutdown
}
try channel.register(selector: self._selector, interested: channel.interestedEvent)
}
/// Deregister the given `SelectableChannel` from this `SelectableEventLoop`.
internal func deregister<C: SelectableChannel>(channel: C, mode: CloseMode = .all) throws {
self.assertInEventLoop()
guard self.isOpen else {
// It's possible the EventLoop was closed before we were able to call deregister, so just return in this case as there is no harm.
return
}
try channel.deregister(selector: self._selector, mode: mode)
}
/// Register the given `SelectableChannel` with this `SelectableEventLoop`. This should be done whenever `channel.interestedEvents` has changed and it should be taken into account when
/// waiting for new I/O for the given `SelectableChannel`.
internal func reregister<C: SelectableChannel>(channel: C) throws {
self.assertInEventLoop()
try channel.reregister(selector: self._selector, interested: channel.interestedEvent)
}
/// - see: `EventLoop.inEventLoop`
@usableFromInline
internal var inEventLoop: Bool {
return thread.isCurrent
}
/// - see: `EventLoop.scheduleTask(deadline:_:)`
@inlinable
internal func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
let promise: EventLoopPromise<T> = self.makePromise()
let task = ScheduledTask(id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), {
do {
promise.succeed(try task())
} catch let err {
promise.fail(err)
}
}, { error in
promise.fail(error)
}, deadline)
let taskId = task.id
let scheduled = Scheduled(promise: promise, cancellationTask: {
self._tasksLock.withLock { () -> Void in
self._scheduledTasks.removeFirst(where: { $0.id == taskId })
}
// We don't need to wake up the selector here, the scheduled task will never be picked up. Waking up the
// selector would mean that we may be able to recalculate the shutdown to a later date. The cost of not
// doing the recalculation is one potentially unnecessary wakeup which is exactly what we're
// saving here. So in the worst case, we didn't do a performance optimisation, in the best case, we saved
// one wakeup.
})
do {
try self._schedule0(task)
} catch {
promise.fail(error)
}
return scheduled
}
/// - see: `EventLoop.scheduleTask(in:_:)`
@inlinable
internal func scheduleTask<T>(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled<T> {
return scheduleTask(deadline: .now() + `in`, task)
}
// - see: `EventLoop.execute`
@inlinable
internal func execute(_ task: @escaping () -> Void) {
// nothing we can do if we fail enqueuing here.
try? self._schedule0(ScheduledTask(id: self.scheduledTaskCounter.loadThenWrappingIncrement(ordering: .relaxed), task, { error in
// do nothing
}, .now()))
}
/// Add the `ScheduledTask` to be executed.
@usableFromInline
internal func _schedule0(_ task: ScheduledTask) throws {
if self.inEventLoop {
precondition(self._validInternalStateToScheduleTasks,
"BUG IN NIO (please report): EventLoop is shutdown, yet we're on the EventLoop.")
self._tasksLock.withLock { () -> Void in
self._scheduledTasks.push(task)
}
} else {
let shouldWakeSelector: Bool = self.externalStateLock.withLock {
guard self.validExternalStateToScheduleTasks else {
if Self.strictModeEnabled {
fatalError("Cannot schedule tasks on an EventLoop that has already shut down.")
}
fputs(
"""
ERROR: Cannot schedule tasks on an EventLoop that has already shut down. \
This will be upgraded to a forced crash in future SwiftNIO versions.\n
""",
stderr
)
return false
}
return self._tasksLock.withLock {
self._scheduledTasks.push(task)
if self._pendingTaskPop == false {
// Our job to wake the selector.
self._pendingTaskPop = true
return true
} else {
// There is already an event-loop-tick scheduled, we don't need to wake the selector.
return false
}
}
}
// We only need to wake up the selector if we're not in the EventLoop. If we're in the EventLoop already, we're
// either doing IO tasks (which happens before checking the scheduled tasks) or we're running a scheduled task
// already which means that we'll check at least once more if there are other scheduled tasks runnable. While we
// had the task lock we also checked whether the loop was _already_ going to be woken. This saves us a syscall on
// hot loops.
//
// In the future we'll use an MPSC queue here and that will complicate things, so we may get some spurious wakeups,
// but as long as we're using the big dumb lock we can make this optimization safely.
if shouldWakeSelector {
try self._wakeupSelector()
}
}
}
/// Wake the `Selector` which means `Selector.whenReady(...)` will unblock.
@usableFromInline
internal func _wakeupSelector() throws {
try _selector.wakeup()
}
/// Handle the given `SelectorEventSet` for the `SelectableChannel`.
internal final func handleEvent<C: SelectableChannel>(_ ev: SelectorEventSet, channel: C) {
guard channel.isOpen else {
return
}
// process resets first as they'll just cause the writes to fail anyway.
if ev.contains(.reset) {
channel.reset()
} else {
if ev.contains(.writeEOF) {
channel.writeEOF()
guard channel.isOpen else {
return
}
} else if ev.contains(.write) {
channel.writable()
guard channel.isOpen else {
return
}
}
if ev.contains(.readEOF) {
channel.readEOF()
} else if ev.contains(.read) {
channel.readable()
}
}
}
private func currentSelectorStrategy(nextReadyTask: ScheduledTask?) -> SelectorStrategy {
guard let sched = nextReadyTask else {
// No tasks to handle so just block. If any tasks were added in the meantime wakeup(...) was called and so this
// will directly unblock.
return .block
}
let nextReady = sched.readyIn(.now())
if nextReady <= .nanoseconds(0) {
// Something is ready to be processed just do a non-blocking select of events.
return .now
} else {
return .blockUntilTimeout(nextReady)
}
}
/// Start processing I/O and tasks for this `SelectableEventLoop`. This method will continue running (and so block) until the `SelectableEventLoop` is closed.
internal func run() throws {
self.preconditionInEventLoop()
defer {
var scheduledTasksCopy = ContiguousArray<ScheduledTask>()
var iterations = 0
repeat { // We may need to do multiple rounds of this because failing tasks may lead to more work.
scheduledTasksCopy.removeAll(keepingCapacity: true)
self._tasksLock.withLock { () -> Void in
// In this state we never want the selector to be woken again, so we pretend we're permanently running.
self._pendingTaskPop = true
// reserve the correct capacity so we don't need to realloc later on.
scheduledTasksCopy.reserveCapacity(self._scheduledTasks.count)
while let sched = self._scheduledTasks.pop() {
scheduledTasksCopy.append(sched)
}
}
// Fail all the scheduled tasks.
for task in scheduledTasksCopy {
task.fail(EventLoopError.shutdown)
}
iterations += 1
} while scheduledTasksCopy.count > 0 && iterations < 1000
precondition(scheduledTasksCopy.count == 0, "EventLoop \(self) didn't quiesce after 1000 ticks.")
assert(self.internalState == .noLongerRunning, "illegal state: \(self.internalState)")
self.internalState = .exitingThread
}
var nextReadyTask: ScheduledTask? = nil
self._tasksLock.withLock {
if let firstTask = self._scheduledTasks.peek() {
// The reason this is necessary is a very interesting race:
// In theory (and with `makeEventLoopFromCallingThread` even in practise), we could publish an
// `EventLoop` reference _before_ the EL thread has entered the `run` function.
// If that is the case, we need to schedule the first wakeup at the ready time for this task that was
// enqueued really early on, so let's do that :).
nextReadyTask = firstTask
}
}
while self.internalState != .noLongerRunning && self.internalState != .exitingThread {
// Block until there are events to handle or the selector was woken up
/* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */
try withAutoReleasePool {
try self._selector.whenReady(
strategy: currentSelectorStrategy(nextReadyTask: nextReadyTask),
onLoopBegin: { self._tasksLock.withLock { () -> Void in self._pendingTaskPop = true } }
) { ev in
switch ev.registration.channel {
case .serverSocketChannel(let chan):
self.handleEvent(ev.io, channel: chan)
case .socketChannel(let chan):
self.handleEvent(ev.io, channel: chan)
case .datagramChannel(let chan):
self.handleEvent(ev.io, channel: chan)
case .pipeChannel(let chan, let direction):
var ev = ev
if ev.io.contains(.reset) {
// .reset needs special treatment here because we're dealing with two separate pipes instead
// of one socket. So we turn .reset input .readEOF/.writeEOF.
ev.io.subtract([.reset])
ev.io.formUnion([direction == .input ? .readEOF : .writeEOF])
}
self.handleEvent(ev.io, channel: chan)
}
}
}
// We need to ensure we process all tasks, even if a task added another task again
while true {
// TODO: Better locking
self._tasksLock.withLock { () -> Void in
if !self._scheduledTasks.isEmpty {
// We only fetch the time one time as this may be expensive and is generally good enough as if we miss anything we will just do a non-blocking select again anyway.
let now: NIODeadline = .now()
// Make a copy of the tasks so we can execute these while not holding the lock anymore
while tasksCopy.count < tasksCopy.capacity, let task = self._scheduledTasks.peek() {
if task.readyIn(now) <= .nanoseconds(0) {
self._scheduledTasks.pop()
self.tasksCopy.append(task)
} else {
nextReadyTask = task
break
}
}
} else {
// Reset nextReadyTask to nil which means we will do a blocking select.
nextReadyTask = nil
}
if self.tasksCopy.isEmpty {
// We will not continue to loop here. We need to be woken if a new task is enqueued.
self._pendingTaskPop = false
}
}
// all pending tasks are set to occur in the future, so we can stop looping.
if self.tasksCopy.isEmpty {
break
}
// Execute all the tasks that were submitted
for task in self.tasksCopy {
/* for macOS: in case any calls we make to Foundation put objects into an autoreleasepool */
withAutoReleasePool {
task.task()
}
}
// Drop everything (but keep the capacity) so we can fill it again on the next iteration.
self.tasksCopy.removeAll(keepingCapacity: true)
}
}
// This EventLoop was closed so also close the underlying selector.
try self._selector.close()
// This breaks the retain cycle created in `init`.
self._succeededVoidFuture = nil
}
internal func initiateClose(queue: DispatchQueue, completionHandler: @escaping (Result<Void, Error>) -> Void) {
func doClose() {
self.assertInEventLoop()
self._parentGroup = nil // break the cycle
// There should only ever be one call into this function so we need to be up and running, ...
assert(self.internalState == .runningAndAcceptingNewRegistrations)
self.internalState = .runningButNotAcceptingNewRegistrations
self.externalStateLock.withLock {
// ... but before this call happened, the lifecycle state should have been changed on some other thread.
assert(self.externalState == .closing)
}
self._selector.closeGently(eventLoop: self).whenComplete { result in
self.assertInEventLoop()
assert(self.internalState == .runningButNotAcceptingNewRegistrations)
self.internalState = .noLongerRunning
self.execute {} // force a new event loop tick, so the event loop definitely stops looping very soon.
self.externalStateLock.withLock {
assert(self.externalState == .closing)
self.externalState = .closed
}
queue.async {
completionHandler(result)
}
}
}
if self.inEventLoop {
queue.async {
self.initiateClose(queue: queue, completionHandler: completionHandler)
}
} else {
let goAhead = self.externalStateLock.withLock { () -> Bool in
if self.externalState == .open {
self.externalState = .closing
return true
} else {
return false
}
}
guard goAhead else {
queue.async {
completionHandler(Result.failure(EventLoopError.shutdown))
}
return
}
self.execute {
doClose()
}
}
}
internal func syncFinaliseClose(joinThread: Bool) {
// This may not be true in the future but today we need to join all ELs that can't be shut down individually.
assert(joinThread != self.canBeShutdownIndividually)
let goAhead = self.externalStateLock.withLock { () -> Bool in
switch self.externalState {
case .closed:
self.externalState = .reclaimingResources
return true
case .resourcesReclaimed, .reclaimingResources:
return false
default:
preconditionFailure("illegal lifecycle state in syncFinaliseClose: \(self.externalState)")
}
}
guard goAhead else {
return
}
if joinThread {
self.thread.join()
}
self.externalStateLock.withLock {
precondition(self.externalState == .reclaimingResources)
self.externalState = .resourcesReclaimed
}
}
@usableFromInline
func shutdownGracefully(queue: DispatchQueue, _ callback: @escaping (Error?) -> Void) {
if self.canBeShutdownIndividually {
self.initiateClose(queue: queue) { result in
self.syncFinaliseClose(joinThread: false) // This thread was taken over by somebody else
switch result {
case .success:
callback(nil)
case .failure(let error):
callback(error)
}
}
} else {
// This function is never called legally because the only possibly owner of an `SelectableEventLoop` is
// `MultiThreadedEventLoopGroup` which calls `initiateClose` followed by `syncFinaliseClose`.
queue.async {
callback(EventLoopError.unsupportedOperation)
}
}
}
@inlinable
public func makeSucceededVoidFuture() -> EventLoopFuture<Void> {
guard self.inEventLoop, let voidFuture = self._succeededVoidFuture else {
// We have to create the promise and complete it because otherwise we'll hit a loop in `makeSucceededFuture`. This is
// fairly dumb, but it's the only option we have. This one can only happen after the loop is shut down, or when calling from off the loop.
let voidPromise = self.makePromise(of: Void.self)
voidPromise.succeed(())
return voidPromise.futureResult
}
return voidFuture
}
@inlinable
internal func parentGroupCallableFromThisEventLoopOnly() -> MultiThreadedEventLoopGroup? {
self.assertInEventLoop()
return self._parentGroup
}
}
extension SelectableEventLoop: CustomStringConvertible, CustomDebugStringConvertible {
@usableFromInline
var description: String {
return "SelectableEventLoop { selector = \(self._selector), thread = \(self.thread) }"
}
@usableFromInline
var debugDescription: String {
return self._tasksLock.withLock {
return "SelectableEventLoop { selector = \(self._selector), thread = \(self.thread), scheduledTasks = \(self._scheduledTasks.description) }"
}
}
}
|
82964be8176629c23892fb6a26d92738
| 42.768559 | 189 | 0.607237 | false | false | false | false |
mittsuu/MarkedView-for-iOS
|
refs/heads/master
|
Pod/Classes/WKMarkedView.swift
|
mit
|
1
|
//
// WKMarkedView.swift
// Markdown preview for WKWebView
//
// Created by mittsu on 2016/04/19.
//
import UIKit
import WebKit
@objc public protocol WKMarkViewDelegate: NSObjectProtocol {
@objc optional func markViewRedirect(url: URL)
}
open class WKMarkedView: UIView {
fileprivate var webView: WKWebView!
fileprivate var mdContents: String?
fileprivate var requestHtml: URLRequest?
fileprivate var codeScrollDisable = false
weak open var delegate: WKMarkViewDelegate?
convenience init () {
self.init(frame:CGRect.zero)
}
override init (frame : CGRect) {
super.init(frame : frame)
initView()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initView() {
let bundle = Bundle(for: WKMarkedView.self)
let path = bundle.path(forResource: "MarkedView.bundle/md_preview", ofType:"html")
requestHtml = URLRequest(url: URL(fileURLWithPath: path!))
// Disables pinch to zoom
let source: String = "var meta = document.createElement('meta');"
+ "meta.name = 'viewport';"
+ "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';"
+ "var head = document.getElementsByTagName('head')[0];"
+ "head.appendChild(meta);"
+ "document.documentElement.style.webkitTouchCallout = 'none';";
let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
// Create the configuration
let userContentController = WKUserContentController()
userContentController.addUserScript(script)
let configuration = WKWebViewConfiguration()
configuration.userContentController = userContentController
webView = WKWebView(frame: self.frame, configuration: configuration)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
addSubview(webView)
// The size of the custom View to the same size as himself
let bindings: [String : UIView] = ["view": webView]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|",
options:NSLayoutFormatOptions(rawValue: 0),
metrics:nil,
views: bindings))
// Hide background
webView.backgroundColor = UIColor.clear
}
/**
Load from markdown file
- parameter filePath: markdown file path
*/
public func loadFile(_ filePath: String?) {
guard let mdData = try? Data(contentsOf: URL(fileURLWithPath: filePath!)) else {
return
}
textToMark(String().data2String(mdData))
}
/**
To set the text to display
- parameter mdText: markdown text
*/
public func textToMark(_ mdText: String?) {
guard let url = requestHtml, let contents = mdText else {
return;
}
mdContents = toMarkdownFormat(contents)
webView.load(url)
}
fileprivate func toMarkdownFormat(_ contents: String) -> String {
let conversion = ConversionMDFormat();
let imgChanged = conversion.imgToBase64(contents)
return conversion.escapeForText(imgChanged)
}
/** option **/
open func setCodeScrollDisable() {
codeScrollDisable = true
}
}
// MARK: - <#WKNavigationDelegate#>
extension WKMarkedView: WKNavigationDelegate {
public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.cancel)
return;
}
if url.scheme == "file" {
decisionHandler(.allow)
} else if url.scheme == "https" {
delegate?.markViewRedirect?(url: url)
decisionHandler(.cancel)
} else {
decisionHandler(.cancel)
}
}
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let contents = mdContents else {
return;
}
let script = "preview('\(contents)', \(codeScrollDisable));"
webView.evaluateJavaScript(script, completionHandler: { (html, error) -> Void in } )
}
}
|
b205386c160e1c6ab2fb9d884b906589
| 31.62069 | 170 | 0.627061 | false | false | false | false |
khizkhiz/swift
|
refs/heads/master
|
test/SILOptimizer/let_properties_opts_runtime.swift
|
apache-2.0
|
1
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift -O %s -o %t/a.out
// RUN: %target-run %t/a.out | FileCheck %s -check-prefix=CHECK-OUTPUT
// REQUIRES: executable_test
// Check that in optimized builds the compiler generates correct code for
// initializations of let properties, which is assigned multiple times inside
// initializers.
public class Foo1 {
internal let Prop1: Int32
internal let Prop2: Int32
// Initialize Prop3 as part of declaration.
internal let Prop3: Int32 = 20
internal let Prop4: Int32
@inline(never)
init(_ count: Int32) {
// Initialize Prop4 unconditionally and only once.
Prop4 = 300
// There are two different assignments to Prop1 and Prop2
// on different branches of the if-statement.
if count < 2 {
// Initialize Prop1 and Prop2 conditionally.
// Use other properties in the definition of Prop1 and Prop2.
Prop1 = 5
Prop2 = 10 - Prop1 + Prop4 - Prop3
} else {
// Initialize Prop1 and Prop2 conditionally.
// Use other properties in the definition of Prop1 and Prop2.
Prop1 = 100
Prop2 = 200 + Prop1 - Prop4 - Prop3
}
}
}
public func testClassLet(f: Foo1) -> Int32 {
return f.Prop1 + f.Prop2 + f.Prop3 + f.Prop4
}
// Prop1 = 5, Prop2 = (10-5+300-20) = 285, Prop3 = 20, Prop4 = 300
// Hence Prop1 + Prop2 + Prop3 + Prop4 = 610
// CHECK-OUTPUT: 610
print(testClassLet(Foo1(1)))
// Prop1 = 100, Prop2 = (200+100-300-20) = -20, Prop3 = 20, Prop4 = 300
// Hence Prop1 + Prop2 + Prop3 + Prop4 = 610
// CHECK-OUTPUT: 400
print(testClassLet(Foo1(10)))
|
9f0bcfa6c71cf868d404046cbb5e1f5e
| 30.76 | 77 | 0.65932 | false | true | false | false |
psmortal/Berry
|
refs/heads/master
|
Pod/Classes/RainbowString/RainbowString.swift
|
mit
|
1
|
//
// RainbowString.swift
// tianshidaoyi
//
// Created by ydf on 2017/8/11.
// Copyright © 2017年 zengdaqian. All rights reserved.
//
import Foundation
public extension String {
public var rb:Rainbow{
return Rainbow(self)
}
}
public extension String{
public subscript(_ range:CountableClosedRange<Int>)->String{
return (self as NSString).substring(with: NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1))
}
public func locations(of:String)->[Int]{
var result = [Int]()
if !contains(of) || of.characters.count == 0 || self.characters.count < of.characters.count {return []}
for i in 0...(characters.count - of.characters.count){
if self[i...(i + of.characters.count - 1)] == of {
result.append(i)
}
}
return result
}
}
public class Rainbow {
public let base:String
private let attributedString:NSMutableAttributedString
var operatingString:String? // 当前操作的子字符串
var operatingRanges:[NSRange] //当前操作的range
var attributes:[String:Any] = [:]
public func match(_ subString:String)->Rainbow{
self.operatingString = subString
if base.contains(subString){
self.operatingRanges = base.locations(of: subString).map{NSMakeRange($0, subString.characters.count)}
}else{
self.operatingRanges = []
}
return self
}
public func all()->Rainbow{
return match(base)
}
public subscript(_ range:CountableClosedRange<Int>)->Rainbow{
self.operatingRanges = [NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1)]
return self
}
public func range(_ range:CountableClosedRange<Int>)->Rainbow{
self.operatingRanges = [NSMakeRange(range.lowerBound, range.upperBound - range.lowerBound + 1)]
return self
}
init(_ base:String) {
self.base = base
self.attributedString = NSMutableAttributedString(string: base)
self.operatingRanges = [NSMakeRange(0, base.characters.count)]
}
public var done:NSMutableAttributedString{
return attributedString
}
public func fontSize(_ size:CGFloat)->Rainbow{
for range in operatingRanges{
attributedString.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: size)], range:range)
}
return self
}
public func font(_ font:UIFont)->Rainbow{
for range in operatingRanges{
attributedString.addAttributes([NSFontAttributeName:font], range:range)
}
return self
}
public func color(_ color:UIColor)->Rainbow{
for range in operatingRanges{
attributedString.addAttributes([NSForegroundColorAttributeName:color], range:range)
}
return self
}
}
|
2355deec04979062a28fbb4a12eba328
| 23.444444 | 121 | 0.595779 | false | false | false | false |
libec/StackOverflow
|
refs/heads/master
|
05-GenericTableViewControllers/GenericPicker/ViewController.swift
|
mit
|
1
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Libor Huspenina
//
// 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 ViewController: UIViewController {
private var payees: [Payee] {
var retVal = [Payee]()
retVal.append(Payee(payee: "Pepa"))
retVal.append(Payee(payee: "Kodl"))
retVal.append(Payee(payee: "Igec"))
retVal.append(Payee(payee: "Zdenal"))
retVal.append(Payee(payee: "Pavka"))
return retVal
}
private var operators: [Operator] {
var retVal = [Operator]()
retVal.append(Operator(name: "Vodaphone"))
retVal.append(Operator(name: "O2"))
retVal.append(Operator(name: "T-Mobile"))
return retVal
}
@IBAction func openOperators(sender: AnyObject) {
let controller = PickerViewController<Operator>(style: .Plain)
controller.items = operators
navigationController?.pushViewController(controller, animated: true)
}
@IBAction func openPayees(sender: AnyObject) {
let controller = PickerViewController<Payee>(style: .Plain)
controller.items = payees
navigationController?.pushViewController(controller, animated: true)
}
}
|
af72a49c6ba9cb23cc2d9eb15926a4db
| 37.2 | 82 | 0.690663 | false | false | false | false |
banxi1988/BXAppKit
|
refs/heads/master
|
BXiOSUtils/NSDateExtenstions.swift
|
mit
|
1
|
// File.swift
// ExSwift
//
// Created by Piergiuseppe Longo on 23/11/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension Date {
// MARK: NSDate Manipulation
// MARK: Date comparison
/**
Checks if self is after input NSDate
:param: date NSDate to compare
:returns: True if self is after the input NSDate, false otherwise
*/
public func isAfter(_ date: Date) -> Bool{
return self > date
}
/**
Checks if self is before input NSDate
:param: date NSDate to compare
:returns: True if self is before the input NSDate, false otherwise
*/
public func isBefore(_ date: Date) -> Bool{
return self < date
}
// MARK: Getter
/**
Date year
*/
public var year : Int {
get {
return getComponent(.year)
}
}
/**
Date month
*/
public var month : Int {
get {
return getComponent(.month)
}
}
/**
Date weekday
*/
public var weekday : Int {
get {
return getComponent(.weekday)
}
}
/**
Date weekMonth
*/
public var weekMonth : Int {
get {
return getComponent(.weekOfMonth)
}
}
/**
Date days
*/
public var days : Int {
get {
return getComponent(.day)
}
}
/**
Date hours
*/
public var hours : Int {
get {
return getComponent(.hour)
}
}
/**
Date minuts
*/
public var minutes : Int {
get {
return getComponent(.minute)
}
}
/**
Date seconds
*/
public var seconds : Int {
get {
return getComponent(.second)
}
}
/**
Returns the value of the NSDate component
:param: component NSCalendarUnit
:returns: the value of the component
*/
public func getComponent (_ component : Calendar.Component) -> Int {
let calendar = Calendar.current
return calendar.component(component, from:self)
}
}
func -(date: Date, otherDate: Date) -> TimeInterval {
return date.timeIntervalSince(otherDate)
}
extension Date{
public var bx_shortDateString:String{
return bx_dateTimeStringWithFormatStyle(.short, timeStyle: .none)
}
public var bx_longDateString:String{
return bx_dateTimeStringWithFormatStyle(.medium, timeStyle: .none)
}
public var bx_shortTimeString:String{
return bx_dateTimeStringWithFormatStyle(.none, timeStyle: .short)
}
public var bx_dateTimeString:String{
return bx_dateTimeStringWithFormatStyle(.medium, timeStyle: .medium)
}
public var bx_shortDateTimeString:String{
return bx_dateTimeStringWithFormatStyle(.short, timeStyle: .short)
}
public func bx_dateTimeStringWithFormatStyle(_ dateStyle:DateFormatter.Style,timeStyle:DateFormatter.Style) -> String{
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: self)
}
public var bx_relativeDateTimeString:String{
let secondsToNow = abs(Int(timeIntervalSinceNow))
let now = Date()
let calendar = Calendar.current
switch secondsToNow{
case 0..<60: return i18n("刚刚")
case 60..<300:
return str(i18n("%d分钟前"),secondsToNow / 60)
default:
if calendar.isDateInYesterday(self){
return i18n("昨天") + " " + bx_shortTimeString
}else if calendar.isDateInToday(self){
return bx_shortTimeString
}else if now.year == year{
return bx_shortDateString
}else{
return self.bx_longDateString
}
}
}
}
|
11324c6371e63d4511728e3d96236d48
| 18.38587 | 120 | 0.631904 | false | false | false | false |
einsteinx2/iSub
|
refs/heads/master
|
Classes/Data Model/IgnoredArticlesRepository.swift
|
gpl-3.0
|
1
|
//
// IgnoredArticlesRepository.swift
// iSub Beta
//
// Created by Benjamin Baron on 9/17/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
struct IgnoredArticleRepository: ItemRepository {
static let si = IgnoredArticleRepository()
fileprivate let gr = GenericItemRepository.si
let table = "ignoredArticles"
let cachedTable = "ignoredArticles"
let itemIdField = "articleId"
func article(articleId: Int64, serverId: Int64) -> IgnoredArticle? {
return gr.item(repository: self, itemId: articleId, serverId: serverId)
}
func allArticles(serverId: Int64? = nil) -> [IgnoredArticle] {
return gr.allItems(repository: self, serverId: serverId)
}
@discardableResult func deleteAllArticles(serverId: Int64?) -> Bool {
return gr.deleteAllItems(repository: self, serverId: serverId)
}
func isPersisted(article: IgnoredArticle) -> Bool {
return gr.isPersisted(repository: self, item: article)
}
func isPersisted(articleId: Int64, serverId: Int64) -> Bool {
return gr.isPersisted(repository: self, itemId: articleId, serverId: serverId)
}
func delete(article: IgnoredArticle) -> Bool {
return gr.delete(repository: self, item: article)
}
func articles(serverId: Int64) -> [IgnoredArticle] {
var articles = [IgnoredArticle]()
Database.si.read.inDatabase { db in
let table = tableName(repository: self)
let query = "SELECT * FROM \(table) WHERE serverId = ?"
do {
let result = try db.executeQuery(query, serverId)
while result.next() {
let article = IgnoredArticle(result: result)
articles.append(article)
}
result.close()
} catch {
printError(error)
}
}
return articles
}
func insert(serverId: Int64, name: String) -> Bool {
var success = true
Database.si.write.inDatabase { db in
do {
let table = tableName(repository: self)
let query = "INSERT INTO \(table) VALUES (?, ?, ?)"
try db.executeUpdate(query, NSNull(), serverId, name)
} catch {
success = false
printError(error)
}
}
return success
}
func replace(article: IgnoredArticle) -> Bool {
var success = true
Database.si.write.inDatabase { db in
do {
let table = tableName(repository: self)
let query = "REPLACE INTO \(table) VALUES (?, ?, ?)"
try db.executeUpdate(query, article.articleId, article.serverId, article.name)
} catch {
success = false
printError(error)
}
}
return success
}
}
extension IgnoredArticle: PersistedItem {
convenience init(result: FMResultSet, repository: ItemRepository = IgnoredArticleRepository.si) {
let articleId = result.longLongInt(forColumnIndex: 0)
let serverId = result.longLongInt(forColumnIndex: 1)
let name = result.string(forColumnIndex: 1) ?? ""
let repository = repository as! IgnoredArticleRepository
self.init(articleId: articleId, serverId: serverId, name: name, repository: repository)
}
class func item(itemId: Int64, serverId: Int64, repository: ItemRepository = IgnoredArticleRepository.si) -> Item? {
return (repository as? IgnoredArticleRepository)?.article(articleId: itemId, serverId: serverId)
}
var isPersisted: Bool {
return repository.isPersisted(article: self)
}
var hasCachedSubItems: Bool {
return false
}
@discardableResult func replace() -> Bool {
return repository.replace(article: self)
}
@discardableResult func cache() -> Bool {
return repository.replace(article: self)
}
@discardableResult func delete() -> Bool {
return repository.delete(article: self)
}
@discardableResult func deleteCache() -> Bool {
return repository.delete(article: self)
}
func loadSubItems() {
}
}
|
9c3ced115282f1d5b6984a642d0f8e97
| 31.631579 | 120 | 0.595622 | false | false | false | false |
mariopavlovic/codility-lessons
|
refs/heads/master
|
codility-lessons/codility-lessons/Lesson5.swift
|
mit
|
1
|
import Foundation
public class Lesson5 {
/*!
Counts passing cars
- parameter A: non-empty array of cars, valid values are 0 and 1.
0: car driving from W -> E
1: car driving from E -> W
- returns: number of passing cars. If result is greather
then 1,000,000,000 return will be -1
*/
public func countPassingCars(A: [Int]) -> Int {
var carsOnRightSide = A.reduce(0, combine: +)
var numPassedCars = 0
for car in A {
switch car {
case 0:
numPassedCars += carsOnRightSide
case 1:
carsOnRightSide -= 1
default:
print("Error case")
}
if numPassedCars > 1000000000 {
return -1
}
}
return numPassedCars
}
/*!
Returns number of dividable elements by K in [A, B] range
- parameter A: range stat (inclusive)
- parameter B: range end (inclusive)
- parameter K: divider
- returns: Number of dividiable elements
*/
public func countDivisible(A: Int, _ B: Int, _ K: Int) -> Int {
//cover the edge case where A is 0
if A == 0 {
return (B - (B % K)) / K + 1
}
return (B - (B % K)) / K - (A - 1) / K
}
/*!
Calculates minimal impact factor of nucleotides.
Impact factor:
A - 1
C - 2
G - 3
T - 4
- parameter S: DNA sequence
- parameter P: analyzed nucleotides start index
- parameter Q: analyzed nucleotides end index
- returns: Array of minimal impacts for start/end indexes
*/
public func minimalImpactFactors(S : String, _ P : [Int], _ Q : [Int]) -> [Int] {
//sanitize
guard P.count == Q.count else {
return []
}
//map
let impactFactors = S.characters.map { (nucleotid) -> Int in
return impactForNucleotid(nucleotid)
}
//slice and find minimal
var result = Array(count: P.count, repeatedValue: 0)
for (index, start) in P.enumerate() {
let end = Q[index]
if let minimal = impactFactors[start...end].minElement() {
result[index] = minimal
}
}
return result
}
func impactForNucleotid(nucleotid: Character) -> Int {
switch (nucleotid) {
case "A": return 1
case "C": return 2
case "G": return 3
case "T": return 4
default: return 0
}
}
/*!
Returns a start index of a minimal array slice. Minimal
is measured as a average value of slice elements
- parameter A: input Int array
- returns: start index of a slice
*/
public func findStartOfMinimalSlice(A : [Int]) -> Int {
var minStart = -1
var minAvg = Float(Int.max)
for index in 0 ..< A.count - 1 {
var numItems = 2
var sum = A[index] + A[index + 1]
while Float(sum) / Float(numItems) < minAvg {
minStart = index
minAvg = Float(sum) / Float(numItems)
if (index + numItems < A.count ) {
sum += A[index + numItems]
numItems += 1
} else {
break
}
}
}
return minStart
}
}
|
21975c1a730cff1c4ccc7398b4add8de
| 24.707143 | 85 | 0.479022 | false | false | false | false |
ilyapuchka/ViewControllerThinning
|
refs/heads/master
|
ViewControllerThinning/Views/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ViewControllerThinning
//
// Created by Ilya Puchka on 27.09.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import UIKit
import SwiftNetworking
class ViewController: UIViewController {
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override var nibName: String? {
return "AuthView"
}
var authView: AuthView! {
return view as! AuthView
}
@IBOutlet
var formBehaviour: AuthFormBehaviour! {
didSet {
formBehaviour?.onLoggedIn = {[unowned self] in self.handleLogin($0, performedRequest: $1)}
}
}
func handleLogin(error: NSError?, performedRequest: Bool) {
if let error = error {
authView.userNameInput.invalidInput = error.isInvalidUserNameError()
authView.passwordInput.invalidInput = error.isInvalidPasswordError()
if performedRequest {
self.displayError(error)
}
}
else {
authView.userNameInput.invalidInput = false
authView.passwordInput.invalidInput = false
}
}
}
extension APIClient {
//Fake login
func login(username: String!, password: String!, completion: (error: NSError?, performedRequest: Bool)->()) {
var error: NSError?
var performedRequest: Bool = false
if username == nil || username.characters.count == 0 {
error = NSError.errorWithUnderlyingError(NSError(code: .InvalidUserName), code: .InvalidCredentials)
}
else if password == nil || password.characters.count == 0 {
error = NSError.errorWithUnderlyingError(NSError(code: .InvalidPassword), code: .InvalidCredentials)
}
else {
error = NSError(code: NetworkErrorCode.BackendError, userInfo: [NSLocalizedDescriptionKey: "Failed to login."])
performedRequest = true
}
dispatch_after(1, dispatch_get_main_queue()) {
completion(error: error, performedRequest: performedRequest)
}
}
}
|
b64d061b1413e92cfd08d2adb956176e
| 28.930556 | 123 | 0.625986 | false | false | false | false |
aquarchitect/MyKit
|
refs/heads/master
|
Sources/macOS/Extensions/AppKit/NSImage+.swift
|
mit
|
1
|
//
// NSImage+.swift
// MyKit
//
// Created by Hai Nguyen.
// Copyright (c) 2016 Hai Nguyen.
//
import AppKit
public extension NSImage {
func image(withTintColor color: NSColor) -> NSImage {
guard self.isTemplate else { return self }
return (self.copy() as? NSImage)?.then {
$0.lockFocus()
color.set()
#if swift(>=4.0)
NSRect(origin: .zero, size: $0.size).fill(using: .sourceAtop)
#else
NSRectFillUsingOperation(.init(origin: .zero, size: $0.size), .sourceAtop)
#endif
$0.unlockFocus()
$0.isTemplate = false
} ?? self
}
}
public extension NSImage {
class func render(_ attributedString: NSAttributedString, scale: CGFloat = 1.0) -> NSImage {
let transform = CGAffineTransform(scaleX: scale, y: scale)
let size = attributedString.size().applying(transform)
let rect = CGRect(origin: .zero, size: size)
return NSImage(size: size).then {
$0.lockFocus()
attributedString.draw(in: rect)
$0.unlockFocus()
}
}
}
|
bdc8b5cb8448f123da2230feec8e61c1
| 23.733333 | 96 | 0.58221 | false | false | false | false |
wmcginty/Shifty
|
refs/heads/main
|
Sources/Shifty/Model/Shared/ReplicationStrategy.swift
|
mit
|
1
|
//
// ReplicationStrategy.swift
// Shifty
//
// Created by William McGinty on 8/30/19.
// Copyright © 2019 Will McGinty. All rights reserved.
//
import UIKit
public enum ReplicationStrategy {
public typealias Configurator = (_ baseView: UIView) -> UIView
case snapshot
case configured(Configurator)
case none
// MARK: - Interface
var canVisuallyShift: Bool {
switch self {
case .snapshot: return false
default: return true
}
}
public func configuredShiftingView(for baseView: UIView, afterScreenUpdates: Bool) -> UIView {
switch self {
case .snapshot: return snapshot(of: baseView, afterScreenUpdates: afterScreenUpdates)
case .configured(let configurator): return configurator(baseView)
case .none: return baseView
}
}
}
// MARK: - Helper
private extension ReplicationStrategy {
func snapshot(of baseView: UIView, afterScreenUpdates: Bool) -> SnapshotView {
//Ensure we take the snapshot with no corner radius, and then apply that radius to the snapshot (and reset the baseView).
let cornerRadius = baseView.layer.cornerRadius
baseView.layer.cornerRadius = 0
guard let contentView = baseView.snapshotView(afterScreenUpdates: afterScreenUpdates) else { fatalError("Unable to snapshot view: \(baseView)") }
let snapshot = SnapshotView(contentView: contentView)
//Apply the known corner radius to both the replicant view and the base view
snapshot.layer.cornerRadius = cornerRadius
snapshot.layer.masksToBounds = cornerRadius > 0
baseView.layer.cornerRadius = cornerRadius
return snapshot
}
}
// MARK: - Convenience
public extension ReplicationStrategy {
static let replication = ReplicationStrategy.configured { baseView -> UIView in
return baseView.replicant
}
static func debug(with backgroundColor: UIColor = .red, alpha: CGFloat = 0.5) -> ReplicationStrategy {
return ReplicationStrategy.configured { baseView -> UIView in
let copy = UIView(frame: baseView.frame)
copy.backgroundColor = backgroundColor.withAlphaComponent(alpha)
copy.layer.cornerRadius = baseView.layer.cornerRadius
copy.layer.masksToBounds = baseView.layer.masksToBounds
return copy
}
}
}
|
adfc7e964e19d84988bfa6034b3de33a
| 32.520548 | 153 | 0.66653 | false | true | false | false |
arietis/codility-swift
|
refs/heads/master
|
4.3.swift
|
mit
|
1
|
public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2
var a: [Int:Bool] = [:]
for i in A {
a[i] = true
}
var i = 1
while true {
if a[i] == nil {
return i
}
i += 1
}
}
|
80d8addcc9f7b244401a3661775cdd69
| 15 | 46 | 0.368056 | false | false | false | false |
tristanchu/FlavorFinder
|
refs/heads/master
|
FlavorFinder/FlavorFinder/SettingsPageController.swift
|
mit
|
1
|
//
// SettingsPageController.swift
// FlavorFinder
//
// Created by Courtney Ligh on 2/10/16.
// Copyright © 2016 TeamFive. All rights reserved.
//
import Foundation
import UIKit
import Parse
class SettingsPageController : LoginModuleParentViewController {
// MARK: Properties: --------------------------------------------------
// Labels:
@IBOutlet weak var pagePromptLabel: UILabel!
@IBOutlet weak var passwordSentLabel: UILabel!
@IBOutlet weak var containerView: UIView!
var loggedOutMessage : UILabel?
// Segues:
let segueLoginEmbedded = "embedSettingsToLogin"
// Text:
let pageTitle = "Settings"
let loggedOutText = "You must be logged in to have settings."
let LOGOUT_TEXT = "Logged out of "
// Placement:
let loggedOutPlacementHeightMultiplier : CGFloat = 0.5
// Buttons:
@IBOutlet weak var resetPasswordButton: UIButton!
@IBOutlet weak var logoutButton: UIButton!
// Button actions:
@IBAction func resetPasswordBtn(sender: UIButton) {
passwordSentLabel.hidden = false
// Commented out because it actually sents an email:
// requestPasswordReset()
}
@IBAction func logoutBtn(sender: UIButton) {
if isUserLoggedIn() {
let userName = currentUser!.username!
let ToastText = "\(LOGOUT_TEXT)\(userName)"
PFUser.logOutInBackground()
currentUser = nil
displayLoggedOut()
self.view.makeToast(ToastText, duration: TOAST_DURATION, position: .Bottom)
}
}
// MARK: Override methods: ----------------------------------------------
/* viewDidLoad:
- Setup when view is loaded into memory
*/
override func viewDidLoad() {
super.viewDidLoad()
// set button borders:
setDefaultButtonUI(logoutButton)
setSecondaryButtonUI(resetPasswordButton)
view.backgroundColor = BACKGROUND_COLOR
}
/* viewDidAppear:
- Setup when user goes into page.
*/
override func viewDidAppear(animated: Bool) {
// Get navigation bar on top:
if let navi = self.tabBarController?.navigationController
as? MainNavigationController {
self.tabBarController?.navigationItem.setLeftBarButtonItems(
[], animated: true)
self.tabBarController?.navigationItem.setRightBarButtonItems(
[], animated: true)
navi.reset_navigationBar()
self.tabBarController?.navigationItem.title = pageTitle
}
super.viewDidAppear(animated)
if let _ = loggedOutMessage { // avoid stacking labels
loggedOutMessage?.hidden = true
loggedOutMessage?.removeFromSuperview()
}
loggedOutMessage = emptyBackgroundText(loggedOutText, view: self.view)
// move message up to make room
loggedOutMessage?.frame.size.height = self.view.frame.size.height * loggedOutPlacementHeightMultiplier
self.view.addSubview(loggedOutMessage!)
setUpLoginContainerUI()
if isUserLoggedIn() {
displayLoggedIn()
} else {
displayLoggedOut()
}
}
/* prepareForSegue:
- setup before seguing
- prior to container's embed segue, will set up parent class variable to have
access to contained VC
*/
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if self.segueEmbeddedContent == nil {
self.setValue(segueLoginEmbedded, forKey: "segueEmbeddedContent")
}
super.prepareForSegue(segue, sender: sender)
}
/* loginSucceeded:
- handle successful login via module
*/
override func loginSucceeded() {
super.loginSucceeded() // hides module
displayLoggedIn()
}
// MARK: Other functions -------------------------------------------------
/* displayLoggedIn
- hides or unhides subviews for the logged-in display
*/
func displayLoggedIn() {
// Logged-in UI
logoutButton.hidden = false
resetPasswordButton.hidden = false
passwordSentLabel.hidden = true
pagePromptLabel.hidden = false
// Logged-out UI
loggedOutMessage?.hidden = true
containerVC?.view.hidden = true // embedded login module
}
/* displayLoggedOut
- hides or unhides subviews for the logged-out display
*/
func displayLoggedOut() {
// Logged-in UI
logoutButton.hidden = true
resetPasswordButton.hidden = true
passwordSentLabel.hidden = true
pagePromptLabel.hidden = true
// Logged-out UI
loggedOutMessage?.hidden = false
containerVC?.view.hidden = false // embedded login module
goToLogin()
}
}
|
05bf639dbc21fd211b76001f66ffc031
| 30 | 110 | 0.604557 | false | false | false | false |
soapyigu/LeetCode_Swift
|
refs/heads/master
|
Stack/SimplifyPath.swift
|
mit
|
1
|
/**
* Question Link: https://leetcode.com/problems/simplify-path/
* Primary idea: Use a stack, normal to push, .. to pop
* Time Complexity: O(n), Space Complexity: O(n)
*/
class SimplifyPath {
func simplifyPath(_ path: String) -> String {
let dirs = path.components(separatedBy: "/")
var stack = [String]()
for dir in dirs {
if dir == "." {
continue
} else if dir == ".." {
if !stack.isEmpty {
stack.removeLast()
}
} else {
if dir != "" {
stack.append(dir)
}
}
}
let res = stack.reduce("") { total, dir in "\(total)/\(dir)" }
return res.isEmpty ? "/" : res
}
}
|
177ea015caf6308be31e1e9a9cd64899
| 26.266667 | 70 | 0.432069 | false | false | false | false |
AirChen/ACSwiftDemoes
|
refs/heads/master
|
Target13-Machine/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Target13-Machine
//
// Created by Air_chen on 2016/11/7.
// Copyright © 2016年 Air_chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var picker:UIPickerView!
@IBOutlet weak var beginBtn:UIButton!
@IBOutlet weak var lab:UILabel!
var imageArray = [String]()
var dataArray1 = [Int]()
var dataArray2 = [Int]()
var dataArray3 = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imageArray = ["👻","👸","💩","😘","🍔","🤖","🍟","🐼","🚖","🐷"]
for _ in 0...99 {
dataArray1.append((Int)(arc4random() % 10 ))
dataArray2.append((Int)(arc4random() % 10 ))
dataArray3.append((Int)(arc4random() % 10 ))
}
lab.text = ""
picker.delegate = self
picker.dataSource = self
beginBtn.addTarget(self, action: #selector(ViewController.touchBeginAction), for: UIControlEvents.touchUpInside)
}
func touchBeginAction() {
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 0, animated: true)
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 1, animated: true)
picker.selectRow((Int)(arc4random() % 10 ), inComponent: 2, animated: true)
if (dataArray1[picker.selectedRow(inComponent: 0)] == dataArray2[picker.selectedRow(inComponent: 1)]) && (dataArray2[picker.selectedRow(inComponent: 1)] == dataArray3[picker.selectedRow(inComponent: 2)]) {
lab.text = "Bingo!!"
}else{
lab.text = "💔"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 3
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 100
}
func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 100.0
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let pickerLab = UILabel()
if component == 0{
pickerLab.text = imageArray[Int(dataArray1[row])]
}else if component == 1{
pickerLab.text = imageArray[Int(dataArray2[row])]
}else{
pickerLab.text = imageArray[Int(dataArray3[row])]
}
pickerLab.font = UIFont(name: "Apple Color Emoji", size: 80)
pickerLab.textAlignment = NSTextAlignment.center
return pickerLab
}
}
|
af6f9387a59726f73f2fb707192084dc
| 29.91 | 213 | 0.599159 | false | false | false | false |
el-hoshino/NotAutoLayout
|
refs/heads/master
|
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleLeftRight.Individual.swift
|
apache-2.0
|
1
|
//
// MiddleLeftRight.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct MiddleLeftRight {
let middleLeft: LayoutElement.Point
let right: LayoutElement.Horizontal
}
}
// MARK: - Make Frame
extension IndividualProperty.MiddleLeftRight {
private func makeFrame(middleLeft: Point, right: Float, top: Float) -> Rect {
let height = (middleLeft.y - top).double
return self.makeFrame(middleLeft: middleLeft, right: right, height: height)
}
private func makeFrame(middleLeft: Point, right: Float, bottom: Float) -> Rect {
let height = (bottom - middleLeft.y).double
return self.makeFrame(middleLeft: middleLeft, right: right, height: height)
}
private func makeFrame(middleLeft: Point, right: Float, height: Float) -> Rect {
let x = middleLeft.x
let y = middleLeft.y - height.half
let width = right - middleLeft.x
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Line -
// MARK: Top
extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreTopToEvaluateFrameType {
public func evaluateFrame(top: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleLeft = self.middleLeft.evaluated(from: parameters)
let right = self.right.evaluated(from: parameters)
let top = top.evaluated(from: parameters)
return self.makeFrame(middleLeft: middleLeft, right: right, top: top)
}
}
// MARK: Bottom
extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreBottomToEvaluateFrameType {
public func evaluateFrame(bottom: LayoutElement.Vertical, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleLeft = self.middleLeft.evaluated(from: parameters)
let right = self.right.evaluated(from: parameters)
let bottom = bottom.evaluated(from: parameters)
return self.makeFrame(middleLeft: middleLeft, right: right, bottom: bottom)
}
}
// MARK: - Set A Length -
// MARK: Height
extension IndividualProperty.MiddleLeftRight: LayoutPropertyCanStoreHeightToEvaluateFrameType {
public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleLeft = self.middleLeft.evaluated(from: parameters)
let right = self.right.evaluated(from: parameters)
let width = right - middleLeft.x
let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width))
return self.makeFrame(middleLeft: middleLeft, right: right, height: height)
}
}
|
91f31cfcafb5a8e69318be0094ef8782
| 25.49505 | 118 | 0.738416 | false | false | false | false |
gscalzo/PrettyWeather
|
refs/heads/master
|
PrettyWeather/CurrentWeatherView.swift
|
mit
|
1
|
//
// CurrentWeatherView.swift
// PrettyWeather
//
// Created by Giordano Scalzo on 03/02/2015.
// Copyright (c) 2015 Effective Code. All rights reserved.
//
import UIKit
import Cartography
import LatoFont
import WeatherIconsKit
class CurrentWeatherView: UIView {
private var didSetupConstraints = false
private let cityLbl = UILabel()
private let maxTempLbl = UILabel()
private let minTempLbl = UILabel()
private let iconLbl = UILabel()
private let weatherLbl = UILabel()
private let currentTempLbl = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
style()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if didSetupConstraints {
super.updateConstraints()
return
}
layoutView()
super.updateConstraints()
didSetupConstraints = true
}
}
// MARK: Setup
private extension CurrentWeatherView{
func setup(){
addSubview(cityLbl)
addSubview(currentTempLbl)
addSubview(maxTempLbl)
addSubview(minTempLbl)
addSubview(iconLbl)
addSubview(weatherLbl)
}
}
// MARK: Layout
private extension CurrentWeatherView{
func layoutView(){
layout(self) { view in
view.height == 160
}
layout(iconLbl) { view in
view.top == view.superview!.top
view.left == view.superview!.left + 20
view.width == 30
view.width == view.height
}
layout(weatherLbl, iconLbl) { view, view2 in
view.top == view2.top
view.left == view2.right + 10
view.height == view2.height
view.width == 200
}
layout(currentTempLbl, iconLbl) { view, view2 in
view.top == view2.bottom
view.left == view2.left
}
layout(currentTempLbl, minTempLbl) { view, view2 in
view.bottom == view2.top
view.left == view2.left
}
layout(minTempLbl) { view in
view.bottom == view.superview!.bottom
view.height == 30
}
layout(maxTempLbl, minTempLbl) { view, view2 in
view.top == view2.top
view.height == view2.height
view.left == view2.right + 10
}
layout(cityLbl) { view in
view.bottom == view.superview!.bottom
view.right == view.superview!.right - 10
view.height == 30
view.width == 200
}
}
}
// MARK: Style
private extension CurrentWeatherView{
func style(){
iconLbl.textColor = UIColor.whiteColor()
weatherLbl.font = UIFont.latoLightFontOfSize(20)
weatherLbl.textColor = UIColor.whiteColor()
currentTempLbl.font = UIFont.latoLightFontOfSize(96)
currentTempLbl.textColor = UIColor.whiteColor()
maxTempLbl.font = UIFont.latoLightFontOfSize(18)
maxTempLbl.textColor = UIColor.whiteColor()
minTempLbl.font = UIFont.latoLightFontOfSize(18)
minTempLbl.textColor = UIColor.whiteColor()
cityLbl.font = UIFont.latoLightFontOfSize(18)
cityLbl.textColor = UIColor.whiteColor()
cityLbl.textAlignment = .Right
}
}
// MARK: Render
extension CurrentWeatherView{
func render(weatherCondition: WeatherCondition){
iconLbl.attributedText = iconStringFromIcon(weatherCondition.icon!, 20)
weatherLbl.text = weatherCondition.weather
var usesMetric = false
if let localeSystem = NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem) as? Bool {
usesMetric = localeSystem
}
if usesMetric {
minTempLbl.text = "\(weatherCondition.minTempCelsius.roundToInt())°"
maxTempLbl.text = "\(weatherCondition.maxTempCelsius.roundToInt())°"
currentTempLbl.text = "\(weatherCondition.tempCelsius.roundToInt())°"
} else {
minTempLbl.text = "\(weatherCondition.minTempFahrenheit.roundToInt())°"
maxTempLbl.text = "\(weatherCondition.maxTempFahrenheit.roundToInt())°"
currentTempLbl.text = "\(weatherCondition.tempFahrenheit.roundToInt())°"
}
cityLbl.text = weatherCondition.cityName ?? ""
}
}
|
eae1a869f651e16442749e28909f1a1e
| 29.147651 | 104 | 0.601069 | false | false | false | false |
zhubinchen/MarkLite
|
refs/heads/master
|
MarkLite/Utils/Localization.swift
|
gpl-3.0
|
2
|
//
// Localization.swift
// Markdown
//
// Created by zhubch on 2017/8/21.
// Copyright © 2017年 zhubch. All rights reserved.
//
import UIKit
fileprivate let ignoreTag = 4654
prefix operator /
prefix func /(string: String) -> String {
return string.localizations
}
extension String {
var localizations: String {
return NSLocalizedString(self, comment: "")
}
}
protocol Localizable {
func localize()
}
extension UIButton: Localizable {
func localize() {
setTitle(/(title(for: .normal) ?? ""), for: .normal)
setTitle(/(title(for: .disabled) ?? ""), for: .disabled)
setTitle(/(title(for: .selected) ?? ""), for: .selected)
}
}
extension UITextField: Localizable {
func localize() {
text = /(text ?? "")
placeholder = /(placeholder ?? "")
}
}
extension UILabel: Localizable {
func localize() {
text = /(text ?? "")
}
}
private let swizzling: (UIView.Type) -> () = { view in
let originalSelector = #selector(view.awakeFromNib)
let swizzledSelector = #selector(view.swizzled_localization_awakeFromNib)
let originalMethod = class_getInstanceMethod(view, originalSelector)
let swizzledMethod = class_getInstanceMethod(view, swizzledSelector)
let didAddMethod = class_addMethod(view, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(view, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!)
}
}
extension UIView {
open class func initializeOnceMethod() {
guard self === UIView.self else {
return
}
swizzling(self)
}
@objc func swizzled_localization_awakeFromNib() {
swizzled_localization_awakeFromNib()
if let localizableView = self as? Localizable {
if tag != ignoreTag {
localizableView.localize()
}
}
}
}
|
149b863a8c32872b46696b51f7280a44
| 24.60241 | 146 | 0.637647 | false | false | false | false |
knutnyg/ios-iou
|
refs/heads/master
|
iou/LocaleUtils.swift
|
bsd-2-clause
|
1
|
import Foundation
func localeStringFromNumber(locale:NSLocale, number:Double) -> String {
let formatter:NSNumberFormatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.locale = locale
return formatter.stringFromNumber(number)!
}
func localeNumberFromString(string:String) -> Double{
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
return formatter.numberFromString(string)!.doubleValue
}
|
35bbae378757310be0506c7a8e107886
| 25.277778 | 71 | 0.769556 | false | false | false | false |
victorchee/BluetoothPi
|
refs/heads/master
|
BluetoothPi/BluetoothPi/BeaconReceiverController.swift
|
mit
|
1
|
//
// BeaconReceiver.swift
// BluetoothPi
//
// Created by qihaijun on 1/30/15.
// Copyright (c) 2015 VictorChee. All rights reserved.
//
import UIKit
import CoreLocation
class BeaconReceiverController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var statusLabel: UILabel!
let locationManager: CLLocationManager = CLLocationManager()
var beaconRegion:CLBeaconRegion!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.requestWhenInUseAuthorization()
// locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
let uuid:NSUUID = NSUUID(UUIDString: "E2C56DB5-DFFB-48D2-B060-D0F5A71096E0")!
beaconRegion = CLBeaconRegion(proximityUUID: uuid, identifier: "")
beaconRegion.notifyEntryStateOnDisplay = true
beaconRegion.notifyOnEntry = true
beaconRegion.notifyOnExit = true
locationManager.startRangingBeaconsInRegion(beaconRegion)
locationManager.startMonitoringForRegion(beaconRegion)
// locationManager.stopMonitoringForRegion(beaconRegion)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// start ranging
locationManager.startRangingBeaconsInRegion(beaconRegion)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// stop ranging
locationManager.stopRangingBeaconsInRegion(beaconRegion)
}
/*
// 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.
}
*/
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
if !beacons.isEmpty {
println("Beacons found")
let nearestBeacon: CLBeacon = beacons.first as CLBeacon
println("nearest uuid = \(nearestBeacon.proximityUUID)\nnearest major = \(nearestBeacon.major)\nnearest minor = \(nearestBeacon.minor)\nnearest rssi = \(nearestBeacon.rssi)\nnearest accuracy = \(nearestBeacon.accuracy)")
switch nearestBeacon.proximity {
case CLProximity.Unknown :
println("Beacon proximity unknown")
case .Far :
println("Beacon proximity far")
case .Near :
println("Beacon proximity near")
case .Immediate :
println("Beacon proximity immediate")
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.statusLabel.text = "uuid = \(nearestBeacon.proximityUUID.UUIDString)\nmajor = \(nearestBeacon.major)\nminor = \(nearestBeacon.minor)\nrssi = \(nearestBeacon.rssi)\naccuracy = \(nearestBeacon.accuracy)"
})
} else {
println("No bvim eacons found")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.statusLabel.text = nil
})
}
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
if region.isKindOfClass(CLBeaconRegion) {
var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertBody = "Will enter region"
UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
locationManager.startRangingBeaconsInRegion(region as CLBeaconRegion)
}
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
if region.isKindOfClass(CLBeaconRegion) {
var localNotification: UILocalNotification = UILocalNotification()
localNotification.alertBody = "Will exit region"
UIApplication.sharedApplication().presentLocalNotificationNow(localNotification)
locationManager.stopRangingBeaconsInRegion(region as CLBeaconRegion)
}
}
}
|
baa3bf1ebb9d23f5c86249dc5ab3dd82
| 39.429825 | 232 | 0.662834 | false | false | false | false |
sberrevoets/SDCAlertView
|
refs/heads/master
|
Source/Presentation/AnimationController.swift
|
mit
|
1
|
import UIKit
private let kInitialScale: CGFloat = 1.2
private let kSpringDamping: CGFloat = 45.71
private let kSpringVelocity: CGFloat = 0
class AnimationController: NSObject, UIViewControllerAnimatedTransitioning {
private var isPresentation = false
init(presentation: Bool) {
self.isPresentation = presentation
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.404
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard
let fromController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
let fromView = fromController.view,
let toView = toController.view else
{
return
}
if self.isPresentation {
transitionContext.containerView.addSubview(toView)
}
let animatingController = self.isPresentation ? toController : fromController
let animatingView = animatingController.view
animatingView?.frame = transitionContext.finalFrame(for: animatingController)
if self.isPresentation {
animatingView?.transform = CGAffineTransform(scaleX: kInitialScale, y: kInitialScale)
animatingView?.alpha = 0
self.animate({
animatingView?.transform = CGAffineTransform(scaleX: 1, y: 1)
animatingView?.alpha = 1
}, inContext: transitionContext, withCompletion: { finished in
transitionContext.completeTransition(finished)
})
} else {
self.animate({
animatingView?.alpha = 0
}, inContext: transitionContext, withCompletion: { finished in
fromView.removeFromSuperview()
transitionContext.completeTransition(finished)
})
}
}
private func animate(_ animations: @escaping (() -> Void),
inContext context: UIViewControllerContextTransitioning,
withCompletion completion: @escaping (Bool) -> Void)
{
UIView.animate(withDuration: self.transitionDuration(using: context), delay: 0,
usingSpringWithDamping: kSpringDamping, initialSpringVelocity: kSpringVelocity, options: [],
animations: animations, completion: completion)
}
}
|
c4198190ffc8ac2512f97e94849a991b
| 36.956522 | 109 | 0.642612 | false | false | false | false |
googleapis/google-api-swift-client
|
refs/heads/main
|
Sources/google-cli-swift-generator/main.swift
|
apache-2.0
|
1
|
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Discovery
var stderr = FileHandle.standardError
func printerr(_ s : String) {
stderr.write(("google-cli-swift-generator WARNING: "+s+"\n").data(using:.utf8)!)
}
let ParameterPrefix = ""
let RequestObjectPrefix = "request_"
func optionDeclaration(_ prefix: String, _ name: String, _ schema: Schema) -> String {
if schema.type == "string" {
// https://github.com/kylef/Commander/issues/49
var s = "Options<String>(\""
s += prefix + name
s += "\", default: [], count: 1, description: \""
if let d = schema.description {
s += d.oneLine()
}
s += "\"),"
return s
} else if schema.type == "integer" {
var s = "Options<Int>(\""
s += prefix + name
s += "\", default: [], count: 1, description: \""
if let d = schema.description {
s += d.oneLine()
}
s += "\"),"
return s
} else if let items = schema.items,
schema.type == "array",
items.type == "string" {
var s = "VariadicOption<String>(\""
s += prefix + name
s += "\", default: [], description: \""
if let d = schema.description {
s += d.oneLine()
}
s += "\"),"
return s
} else if let items = schema.items,
schema.type == "array",
items.type == "any" {
var s = "VariadicOption<JSONAny>(\""
s += prefix + name
s += "\", default: [], description: \""
if let d = schema.description {
s += d.oneLine()
}
s += "\"),"
return s
} else {
let jsonData = try! JSONEncoder().encode(schema)
let jsonString = String(data: jsonData, encoding: .utf8)!
printerr("Unsupported schema for option \(prefix)\(name): \(jsonString)")
return ""
}
}
extension Discovery.Method {
func parametersString() -> String {
var s = ""
if let parameters = parameters {
for p in parameters.sorted(by: { $0.key < $1.key }) {
if p.value.type == "string" || p.value.type == "integer" {
if s != "" {
s += ", "
}
s += ParameterPrefix + p.key
}
}
}
return s
}
func requestPropertiesString(requestSchema: Schema?) -> String {
var s = ""
if let requestSchema = requestSchema,
let properties = requestSchema.properties {
for p in properties.sorted(by: { $0.key < $1.key }) {
if p.value.type == "string" || p.value.type == "integer" {
if s != "" {
s += ", "
}
s += RequestObjectPrefix + p.key
} else if let items = p.value.items,
p.value.type == "array",
items.type == "string" {
if s != "" {
s += ", "
}
s += RequestObjectPrefix + p.key
} else if let items = p.value.items,
p.value.type == "array",
items.type == "any" {
if s != "" {
s += ", "
}
s += RequestObjectPrefix + p.key
}
}
}
return s
}
func Invocation(serviceName: String,
resourceName : String,
resource: Discovery.Resource,
methodName : String,
method: Discovery.Method,
requestSchema: Schema?) -> String {
var s = "\n"
s.addLine(indent:4, "$0.command(")
s.addLine(indent:6, "\"" + resourceName + "." + methodName + "\",")
if let parameters = parameters {
for p in parameters.sorted(by: { $0.key < $1.key }) {
let d = optionDeclaration(ParameterPrefix, p.key, p.value)
if d.count > 0 {
s.addLine(indent:6, d)
}
}
}
if let requestSchema = requestSchema,
let properties = requestSchema.properties {
for p in properties.sorted(by: { $0.key < $1.key }) {
let d = optionDeclaration(RequestObjectPrefix, p.key, p.value)
if d.count > 0 {
s.addLine(indent:6, d)
}
}
}
if let description = method.description {
s.addLine(indent:6, "description: \"" + description.oneLine() + "\") {")
} else {
s.addLine(indent:6, "description: \"\") {")
}
let p = self.parametersString()
let r = self.requestPropertiesString(requestSchema: requestSchema)
if p != "" && r != "" {
s.addLine(indent:6, p + ", " + r + " in")
} else if p != "" {
s.addLine(indent:6, p + " in")
} else if r != "" {
s.addLine(indent:6, r + " in")
}
s.addLine(indent:6, "do {")
if self.HasParameters() {
s.addLine(indent:8, "var parameters = " + serviceName.capitalized() + "."
+ self.ParametersTypeName(resource:resourceName, method:methodName) + "()")
if let parameters = parameters {
for p in parameters.sorted(by: { $0.key < $1.key }) {
if p.value.type == "string" || p.value.type == "integer" {
s.addLine(indent:8, "if let " + ParameterPrefix + p.key + " = " + ParameterPrefix + p.key + ".first {")
s.addLine(indent:10, "parameters." + p.key + " = " + ParameterPrefix + p.key)
s.addLine(indent:8, "}")
}
}
}
}
if self.HasRequest() {
s.addLine(indent:8, "var request = " + serviceName.capitalized() + "."
+ self.RequestTypeName() + "()")
if let requestSchema = requestSchema,
let properties = requestSchema.properties {
for p in properties.sorted(by: { $0.key < $1.key }) {
if p.value.type == "string" || p.value.type == "integer" {
s.addLine(indent:8, "if let " + RequestObjectPrefix + p.key + " = " + RequestObjectPrefix + p.key + ".first {")
s.addLine(indent:10, "request." + p.key + " = " + RequestObjectPrefix + p.key)
s.addLine(indent:8, "}")
} else if let items = p.value.items,
p.value.type == "array",
items.type == "string" {
s.addLine(indent:8, "if " + RequestObjectPrefix + p.key + ".count > 0 {")
s.addLine(indent:10, "request." + p.key + " = " + RequestObjectPrefix + p.key)
s.addLine(indent:8, "}")
}
}
}
}
s.addLine(indent:8, "let sem = DispatchSemaphore(value: 0)")
let fullMethodName = (resourceName + "_" + methodName)
var invocation = "try " + serviceName + "." + fullMethodName + "("
if self.HasRequest() {
if self.HasParameters() {
invocation += "request: request, parameters:parameters"
} else {
invocation += "request:request"
}
} else {
if self.HasParameters() {
invocation += "parameters:parameters"
}
}
invocation += ") {"
s.addLine(indent:8, invocation)
var arguments = ""
if self.HasResponse() {
arguments += "response, "
}
arguments += "error in"
s.addLine(indent:10, arguments)
if self.HasResponse() {
s.addLine(indent:10, "if let response = response { print (\"RESPONSE: \\(response)\") }")
}
s.addLine(indent:10, "if let error = error { print (\"ERROR: \\(error)\") }")
s.addLine(indent:10, "sem.signal()")
s.addLine(indent:8, "}")
s.addLine(indent:8, "_ = sem.wait()")
s.addLine(indent:6, "} catch let error {")
s.addLine(indent:8, "print (\"Client error: \\(error)\")")
s.addLine(indent:6, "}")
s.addLine(indent:4, "}")
return s
}
}
extension Discovery.Resource {
func generate(service: Service, name: String) -> String {
var s = ""
if let methods = self.methods {
for m in methods.sorted(by: { $0.key < $1.key }) {
let requestSchema = service.schema(name: m.value.RequestTypeName())
s += m.value.Invocation(serviceName:service.serviceName(),
resourceName:name,
resource:self,
methodName:m.key,
method:m.value,
requestSchema:requestSchema
)
}
}
if let resources = self.resources {
for r in resources.sorted(by: { $0.key < $1.key }) {
s += r.value.generate(service: service, name: name + "_" + r.key)
}
}
return s
}
}
extension Discovery.Service {
func serviceTitle() -> String {
return self.name.capitalized()
}
func serviceName() -> String {
return self.name
}
func scopes() -> [String] {
var scopeSet = Set<String>()
if let resources = resources {
for r in resources {
if let methods = r.value.methods {
for m in methods {
if let scopes = m.value.scopes {
for scope in scopes {
scopeSet.insert(scope)
}
}
}
}
}
}
return scopeSet.sorted()
}
func generate() -> String {
var s = Discovery.License
s.addLine()
for i in
["Foundation",
"Dispatch",
"OAuth2",
"GoogleAPIRuntime",
"Commander"] {
s.addLine("import " + i)
}
s.addLine()
s.addLine("let CLIENT_CREDENTIALS = \"" + serviceName() + ".json\"")
s.addLine("let TOKEN = \"" + serviceName() + ".json\"")
s.addLine()
s.addLine("func main() throws {")
let scopes = self.scopes()
if scopes.count == 1 {
s.addLine(indent:2, "let scopes = \(scopes)")
} else {
s.addLine(indent:2, "let scopes = [")
s += " \"" + scopes.joined(separator:"\",\n \"") + "\"]\n"
}
s.addLine()
s.addLine(indent:2, "guard let tokenProvider = BrowserTokenProvider(credentials:CLIENT_CREDENTIALS, token:TOKEN) else {")
s.addLine(indent:4, "return")
s.addLine(indent:2, "}")
s.addLine(indent:2, "let \(self.serviceName()) = try \(self.serviceTitle())(tokenProvider:tokenProvider)")
s.addLine()
s.addLine(indent:2, "let group = Group {")
s.addLine(indent:4, "$0.command(\"login\", description:\"Log in with browser-based authentication.\") {")
s.addLine(indent:6, "try tokenProvider.signIn(scopes:scopes)")
s.addLine(indent:6, "try tokenProvider.saveToken(TOKEN)")
s.addLine(indent:4, "}")
if let resources = resources {
for r in resources.sorted(by: { $0.key < $1.key }) {
s += r.value.generate(service: self, name: r.key)
}
}
s.addLine(indent:2, "}")
s.addLine(indent:2, "group.run()")
s.addLine(indent:0, "}")
s.addLine()
s.addLine(indent:0, "do {")
s.addLine(indent:2, "try main()")
s.addLine(indent:0, "} catch (let error) {")
s.addLine(indent:2, "print(\"Application error: \\(error)\")")
s.addLine(indent:0, "}")
return s
}
}
func main() throws {
let arguments = CommandLine.arguments
let path = arguments[1]
let data = try Data(contentsOf: URL(fileURLWithPath: path))
let decoder = JSONDecoder()
do {
let service = try decoder.decode(Service.self, from: data)
let code = service.generate()
print(code)
} catch {
print("error \(error)\n")
}
}
do {
try main()
} catch (let error) {
print("ERROR: \(error)\n")
}
|
4fe274fc0d08b126fbd61ef5a1632402
| 31.74221 | 125 | 0.548192 | false | false | false | false |
a2/Kitty
|
refs/heads/master
|
Kitty Share Extension/ShareViewController.swift
|
mit
|
1
|
//
// ShareViewController.swift
// Kitty Share Extension
//
// Created by Alexsander Akers on 11/9/15.
// Copyright © 2015 Rocket Apps Limited. All rights reserved.
//
import Cocoa
import KittyKit
class ShareViewController: NSViewController {
@IBOutlet var resultTextField: NSTextField!
@IBOutlet var slider: NSSlider!
var APIClient: APIClientProtocol = KittyKit.APIClient()
var URL: String!
var shortenedURL: String!
override var nibName: String? {
return "ShareViewController"
}
override func loadView() {
super.loadView()
if let item = extensionContext!.inputItems.first as? NSExtensionItem, attachments = item.attachments,
itemProvider = attachments.first as? NSItemProvider where itemProvider.hasItemConformingToTypeIdentifier(kUTTypeURL as String) {
itemProvider.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil) { (URL: NSSecureCoding?, error: NSError?) in
self.URL = (URL as! NSURL).absoluteString
}
} else {
print("No attachments")
}
}
@IBAction func send(sender: AnyObject?) {
if resultTextField.hidden {
APIClient.fetchAuthenticityToken { result in
result.either(ifLeft: { token in
let expiry: URLExpiry = {
switch self.slider.integerValue {
case 0: return .TenMins
case 1: return .OneHour
case 2: return .OneDay
case 3: return .OneWeek
default:
fatalError("Unexpected slider value")
}
}()
self.APIClient.submitURL(self.URL, expiry: expiry, token: token) { result in
result.either(ifLeft: { URL in
dispatch_async(dispatch_get_main_queue()) {
self.slider.enabled = false
self.resultTextField.stringValue = URL
self.resultTextField.hidden = false
self.resultTextField.selectText(self)
self.shortenedURL = URL
}
}, ifRight: { error in
self.extensionContext!.cancelRequestWithError(error as NSError)
})
}
}, ifRight: { error in
self.extensionContext!.cancelRequestWithError(error as NSError)
})
}
} else {
let outputItem = NSExtensionItem()
outputItem.attachments = [shortenedURL]
let outputItems = [outputItem]
extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil)
}
}
@IBAction func cancel(sender: AnyObject?) {
let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
extensionContext!.cancelRequestWithError(cancelError)
}
}
|
b9e054a64cdcc572268d9cbf75d911c1
| 37.240964 | 140 | 0.549779 | false | false | false | false |
sfurlani/addsumfun
|
refs/heads/master
|
Add Sum Fun/Add Sum Fun/NumberView.swift
|
mit
|
1
|
//
// NumberCollectionViewCell.swift
// Add Sum Fun
//
// Created by SFurlani on 8/26/15.
// Copyright © 2015 Dig-It! Games. All rights reserved.
//
import UIKit
class NumberView: UIView {
class func newWithNumber(number: UInt?) -> NumberView? {
let nib = UINib(nibName: "NumberView", bundle: nil)
let views = nib.instantiateWithOwner(nil, options: nil)
guard views.count > 0 else {
return nil
}
guard let numberView = views[0] as? NumberView else {
return nil
}
numberView.number = number
return numberView
}
@IBOutlet var label: UILabel! {
didSet {
update()
}
}
@IBInspectable var number: UInt? {
didSet {
update()
}
}
override func awakeFromNib() {
super.awakeFromNib()
layer.cornerRadius = 8.0
layer.borderWidth = 1.0
layer.borderColor = UIColor.blackColor().CGColor
}
private func update() {
guard let label = label else {
return
}
if let number = number {
backgroundColor = UIColor.whiteColor()
label.text = "\(number)"
}
else {
backgroundColor = UIColor(white: 0.9, alpha: 1.0)
label.text = nil
}
setNeedsDisplay()
}
override func layoutSubviews() {
super.layoutSubviews()
label.font = label.font.fontWithSize(bounds.height)
}
}
|
a28d142a47ccd18e0f4809e567a7e7f8
| 21.166667 | 63 | 0.51817 | false | false | false | false |
think-dev/MadridBUS
|
refs/heads/master
|
MadridBUS/Source/UI/LineNodeDetailPresenter.swift
|
mit
|
1
|
import Foundation
protocol LineNodeDetailPresenter {
func nodes(on line: String)
func config(using view: View)
}
class LineNodeDetailPresenterBase: Presenter, LineNodeDetailPresenter {
private weak var view: LineNodeDetailView!
private var busNodesForLine: BusNodesForBusLinesInteractor!
required init(injector: Injector) {
busNodesForLine = injector.instanceOf(BusNodesForBusLinesInteractor.self)
super.init(injector: injector)
}
func config(using view: View) {
guard let lineNodeDetailView = view as? LineNodeDetailView else {
fatalError("\(view) is not an LineNodeDetailView")
}
self.view = lineNodeDetailView
super.config(view: view)
}
func nodes(on line: String) {
busNodesForLine.subscribeHandleErrorDelegate(delegate: self)
let dto = BusNodesForBusLinesDTO(using: [line])
busNodesForLine.execute(dto) { (busNodes) in
var graphicNodes: [LineSchemeNodeModel] = []
var i = 0
for aNode in busNodes {
var nodeModel: LineSchemeNodeModel
if aNode.type == .nodeForward || aNode.type == .vertexForward {
nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .forward, latitude: aNode.latitude, longitude: aNode.longitude)
} else if aNode.type == .nodeBackwards || aNode.type == .vertexBackwards {
nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .backwards, latitude: aNode.latitude, longitude: aNode.longitude)
} else {
nodeModel = LineSchemeNodeModel(id: aNode.id, name: aNode.name.capitalized, position: i, direction: .undefined, latitude: aNode.latitude, longitude: aNode.longitude)
}
graphicNodes.append(nodeModel)
i = i + 1
}
self.view.update(withNodes: graphicNodes)
}
}
}
|
6161904e0a30d235b783dff05cafead6
| 38.981132 | 185 | 0.622935 | false | true | false | false |
jkolb/midnightbacon
|
refs/heads/master
|
MidnightBacon/Reddit/RedditRequest.swift
|
mit
|
1
|
//
// RedditRequest.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Common
public class RedditRequest {
let clientID: String
let redirectURI: NSURL
let mapperFactory = RedditFactory()
let scope: [OAuthScope] = [
.Account,
.Edit,
.History,
.Identity,
.MySubreddits,
.PrivateMessages,
.Read,
.Report,
.Save,
.Submit,
.Subscribe,
.Vote
]
let duration = TokenDuration.Permanent
public var tokenPrototype: NSURLRequest!
public var oauthPrototype: NSURLRequest!
public init(clientID: String, redirectURI: NSURL) {
self.clientID = clientID
self.redirectURI = redirectURI
}
public func authorizeURL(state: String) -> NSURL {
let request = AuthorizeRequest(clientID: clientID, state: state, redirectURI: redirectURI, duration: duration, scope: scope)
return request.buildURL(tokenPrototype.URL!)!
}
public func userAccessToken(authorizeResponse: OAuthAuthorizeResponse) -> APIRequestOf<OAuthAccessToken> {
return APIRequestOf(OAuthAuthorizationCodeRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, authorizeResponse: authorizeResponse, redirectURI: redirectURI))
}
public func refreshAccessToken(accessToken: OAuthAccessToken) -> APIRequestOf<OAuthAccessToken> {
return APIRequestOf(OAuthRefreshTokenRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, accessToken: accessToken))
}
public func applicationAccessToken(deviceID: NSUUID) -> APIRequestOf<OAuthAccessToken> {
return APIRequestOf(OAuthInstalledClientRequest(mapperFactory: mapperFactory, prototype: tokenPrototype, clientID: clientID, deviceID: deviceID))
}
public func userAccount() -> APIRequestOf<Account> {
return APIRequestOf(MeRequest(mapperFactory: mapperFactory, prototype: oauthPrototype))
}
public func subredditLinks(path: String, after: String? = nil) -> APIRequestOf<Listing> {
return APIRequestOf(SubredditRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, path: path, after: after))
}
public func linkComments(link: Link) -> APIRequestOf<(Listing, [Thing])> {
return APIRequestOf(CommentsRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, article: link))
}
public func submit(kind kind: SubmitKind, subreddit: String, title: String, url: NSURL?, text: String?, sendReplies: Bool) -> APIRequestOf<Bool> {
return APIRequestOf(SubmitRequest(prototype: oauthPrototype, kind: kind, subreddit: subreddit, title: title, url: url, text: text, sendReplies: sendReplies))
}
public func privateMessagesWhere(messageWhere: MessageWhere) -> APIRequestOf<Listing> {
return APIRequestOf(MessageRequest(mapperFactory: mapperFactory, prototype: oauthPrototype, messageWhere: messageWhere, mark: nil, mid: nil, after: nil, before: nil, count: nil, limit: nil, show: nil, expandSubreddits: nil))
}
}
|
fab1d3a89f837123ed5c64d8b3c45bff
| 45.065217 | 232 | 0.726286 | false | false | false | false |
bililioo/CBRoundedCorners
|
refs/heads/master
|
CBRoundedCornersDemo/CBRoundedCornersDemo/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// CBRoundedCornersDemo
//
// Created by Bin on 17/1/30.
// Copyright © 2017年 cb. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow()
window?.frame = UIScreen.main.bounds
let vc = ViewController()
let nav = UINavigationController.init(rootViewController:vc)
window?.rootViewController = nav
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
240e3ff96a5fa37410d965359e1144ef
| 43.636364 | 285 | 0.731161 | false | false | false | false |
Cleverlance/Pyramid
|
refs/heads/master
|
Sources/Common/Testing/RepositoryTestDoubles.swift
|
mit
|
1
|
//
// Copyright © 2016 Cleverlance. All rights reserved.
//
class RepositoryDummy<Model>: Repository<Model> {
override func deleteAll() throws {}
override func load() throws -> Model? { return nil }
override func save(_ model: Model) throws {}
}
public class RepositorySpy<Model>: Repository<Model> {
public enum Operation { case load, deleteAll, save }
public var savedModels = [Model]()
public var loadCalled = 0
public var deleteAllCalled = 0
public var operations = [Operation]()
override public func deleteAll() throws {
deleteAllCalled += 1
operations.append(.deleteAll)
}
override public func load() throws -> Model? {
loadCalled += 1
operations.append(.load)
return nil
}
override public func save(_ model: Model) throws {
savedModels.append(model)
}
}
class RepositoryThrowing<Model>: Repository<Model> {
fileprivate let error: Error
init(_ error: Error = TestError()) {
self.error = error
}
override func deleteAll() throws { throw error }
override func load() throws -> Model? { throw error }
override func save(_ model: Model) throws { throw error }
}
class RepositoryReturning<Model>: Repository<Model> {
fileprivate let model: Model?
init(_ model: Model?) {
self.model = model
}
override func deleteAll() throws {}
override func load() throws -> Model? { return model }
override func save(_ model: Model) throws {}
}
public class RepositoryFake<Model>: Repository<Model> {
public var model: Model?
override public func deleteAll() throws {
model = nil
}
override public func load() throws -> Model? {
return model
}
override public func save(_ model: Model) throws {
self.model = model
}
}
extension Repository {
public static func dummy() -> Repository<Model> {
return RepositoryDummy()
}
public static func spy() -> RepositorySpy<Model> {
return RepositorySpy()
}
public static func throwing(_ error: Error = TestError()) -> Repository<Model> {
return RepositoryThrowing(error)
}
public static func returning(_ model: Model?) -> Repository<Model> {
return RepositoryReturning(model)
}
public static func fake() -> RepositoryFake<Model> {
return RepositoryFake()
}
}
|
03caf81d439eeafbbbf09a8ef55d8413
| 24.052083 | 84 | 0.639085 | false | false | false | false |
exsortis/TenCenturiesKit
|
refs/heads/master
|
Sources/TenCenturiesKit/Models/DeleteResponse.swift
|
mit
|
1
|
import Foundation
public struct DeleteResponse {
public let id : Int
public let isVisible : Bool
public let isDeleted : Bool
}
extension DeleteResponse : Serializable {
public init?(from json : JSONDictionary) {
guard
let id = json["id"] as? Int,
let isVisible = json["is_visible"] as? Bool,
let isDeleted = json["is_deleted"] as? Bool
else { return nil }
self.id = id
self.isVisible = isVisible
self.isDeleted = isDeleted
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
"id" : id,
"is_visible" : isVisible,
"is_deleted" : isDeleted,
]
return dict
}
}
|
1f47f603bc77720c6549b8d437147a75
| 20.942857 | 56 | 0.549479 | false | false | false | false |
mirai418/leaflet-ios
|
refs/heads/master
|
leaflet/PointsOfInterestListViewController.swift
|
mit
|
1
|
//
// PointsOfInterestListViewController.swift
// leaflet
//
// Created by Cindy Zeng on 4/8/15.
// Copyright (c) 2015 parks-and-rec. All rights reserved.
//
import UIKit
class PointsOfInterestListViewController: UITableViewController, ENSideMenuDelegate {
@IBOutlet weak var menuButton: UIBarButtonItem!
private var allPois = [FecPoi]()
var selectedPoi: FecPoi!
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("pointOfInterest") as? PointsOfInterestListViewCell ?? PointsOfInterestListViewCell()
var pointOfInterest = self.allPois[indexPath.row]
cell.poiName.text = pointOfInterest.title
cell.locationAway.text = pointOfInterest.getHumanDistance()
cell.poiImage.image = pointOfInterest.image
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allPois.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedPoi = allPois[indexPath.row]
self.performSegueWithIdentifier("toContentFromList", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
self.navigationController?.navigationBar.barTintColor = UIColor(hex: GlobalConstants.defaultNavColor)
self.tableView.rowHeight = 60.0
allPois = LibraryAPI.sharedInstance.getPois()
self.navigationController?.navigationBar.barTintColor = UIColor(hex: GlobalConstants.defaultNavColor)
self.navigationController?.navigationBar.translucent = false
self.navigationController?.navigationBar.clipsToBounds = false
self.sideMenuController()?.sideMenu?.delegate = self
hideSideMenuView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func revealCompassView(sender: AnyObject) {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : UIViewController
destViewController = mainStoryboard.instantiateViewControllerWithIdentifier("compassView") as! UIViewController
sideMenuController()?.setContentViewController(destViewController)
}
@IBAction func toggleSideMenu(sender: AnyObject) {
toggleSideMenuView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case "toContentFromList":
if var poiVC = segue.destinationViewController as? DetailedViewController {
poiVC.selectedPoi = self.selectedPoi
}
default:
break
}
}
}
|
0d52b3892f22385b90133ad0eb9b1c60
| 35.755814 | 148 | 0.686808 | false | false | false | false |
maghov/IS-213
|
refs/heads/master
|
LoginV1/LoginV1/SecondViewController.swift
|
mit
|
1
|
//
// SecondViewController.swift
// RoomBooking3
//
// Created by Gruppe10 on 18.04.2017.
// Copyright © 2017 Gruppe10. All rights reserved.
//
import UIKit
import Firebase
var roomList = [RoomModel]()
var refRooms: FIRDatabaseReference!
var myIndex = Int()
class SecondViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var viewDropDownMenu: UIView!
@IBOutlet weak var textFieldSpace: UITextField!
@IBOutlet weak var textFieldName: UITextField!
@IBOutlet weak var textFieldDetails: UITextField!
@IBOutlet weak var tblRooms: UITableView!
//Code for dropdown menu
@IBAction func showDropDownMenu(_ sender: UIBarButtonItem) {
if (viewDropDownMenu.isHidden == true){
viewDropDownMenu.isHidden = false
}
else if (viewDropDownMenu.isHidden == false){
viewDropDownMenu.isHidden = true
}
}
//Logs out the user
@IBAction func logoutButtonPressed(_ sender: UIButton) {
try! FIRAuth.auth()?.signOut()
performSegue(withIdentifier: "SegueChooseRoomToLogin", sender: self)
}
//This button runs the function addRoom()
@IBAction func buttonAddRoom(_ sender: UIButton) {
addRoom()
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
myIndex = indexPath.row
print("IndexPath ", indexPath.row)
performSegue(withIdentifier: "segue", sender: self)
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return roomList.count
}
//Creates rows for every room in the database.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as!ViewControllerTableViewCell
let room: RoomModel
room = roomList[indexPath.row]
cell.lblName.text = room.name
cell.lblSpace.text = "Antall plasser " + room.space!
cell.lblDetails.text = room.details
return cell
}
//Function to add a room
func addRoom() {
let key = textFieldName.text! as String
let room = ["id": key,
"name": textFieldName.text! as String,
"space": textFieldSpace.text! as String,
"details": textFieldDetails.text! as String
]
refRooms.child(key).setValue(room)
}
override func viewDidLoad() {
super.viewDidLoad()
viewDropDownMenu.isHidden = true
refRooms = FIRDatabase.database().reference().child("list")
refRooms.observe(FIRDataEventType.value, with:{(snapshot) in
if snapshot.childrenCount > 0 {
roomList.removeAll()
for rooms in snapshot.children.allObjects as! [FIRDataSnapshot] {
let roomObject = rooms.value as? [String: AnyObject]
let name = roomObject?["name"]
let space = roomObject?["space"]
let id = roomObject?["id"]
let details = roomObject? ["details"]
let tiElleve = roomObject? ["tiElleve"]
let elleveTolv = roomObject? ["elleveTolv"]
let tolvEtt = roomObject? ["tolvEtt"]
let ettTo = roomObject? ["ettTo"]
let toTre = roomObject? ["toTre"]
let treFire = roomObject? ["treFire"]
let booketAvTiElleve = roomObject? ["booketAvTiElleve"]
let booketAvElleveTolv = roomObject? ["booketAvElleveTolv"]
let booketAvTolvEtt = roomObject? ["booketAvTolvEtt"]
let booketAvEttTo = roomObject? ["booketAvEttTo"]
let booketAvToTre = roomObject? ["booketAvToTre"]
let booketAvTreFire = roomObject? ["booketAvTreFire"]
let room = RoomModel(id: id as! String?,
name: name as! String?,
space: space as! String?,
details: details as! String?,
tiElleve: tiElleve as! String?,
elleveTolv: elleveTolv as! String?,
tolvEtt: tolvEtt as! String?,
ettTo: ettTo as! String?,
toTre: toTre as! String?,
treFire: treFire as! String?,
booketAvTiElleve: booketAvTiElleve as! String?,
booketAvElleveTolv: booketAvElleveTolv as! String?,
booketAvTolvEtt: booketAvTolvEtt as! String?,
booketAvEttTo: booketAvEttTo as! String?,
booketAvToTre: booketAvToTre as! String?,
booketAvTreFire: booketAvTreFire as! String?)
roomList.append(room)
}
}
self.tblRooms.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Hides keyboard when user touches outside textfield
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
|
7f25bbe30e9ccbc1025e3bd026618fd6
| 35.323171 | 119 | 0.533994 | false | false | false | false |
TIEmerald/UNDanielBasicTool_Swift
|
refs/heads/master
|
UNDanielBasicTool_Swift/Classes/Useful Views/Drop Down List/UNDDropDownListTableViewController.swift
|
mit
|
1
|
//
// UNDDropDownListTableViewController.swift
// Pods
//
// Created by 尓健 倪 on 17/6/17.
//
//
import UIKit
public protocol UNDDropDownListDelegate : NSObjectProtocol {
func dropdownList(_ dropdownList: UNDDropDownListTableViewController, didSelectCellAtIndexPath indexPath: IndexPath) -> Void
func dropdownList(_ dropdownList: UNDDropDownListTableViewController, dataAtIndexPath indexPath: IndexPath) -> Any
func numberOfCellsInDropdownList(_ dropdownList: UNDDropDownListTableViewController) -> Int
}
open class UNDDropDownListTableViewController: UITableViewController {
/// Mark : - Interfaces
public weak var delegate : UNDDropDownListDelegate?
public var identifierTag : Int?
public var isMultipleSelectable : Bool {
get{
return self.tableView.allowsMultipleSelection
}
set(newValue){
self.tableView.allowsMultipleSelection = newValue
}
}
/// Set this property tell us how many cells you what to show up in the Drop Down List each time
public var numberOfDisplayingCells : Int{
get{
return _numberOfDisplayingCells
}
set(newValue){
_ = self.resignFirstResponder()
_numberOfDisplayingCells = newValue
}
}
/// Normally, you should let us know that is the Width of the Dropdown List
public var width : CGFloat{
get{
return _width
}
set(newValue){
_ = self.resignFirstResponder()
_width = newValue
}
}
/// And you'd better tell us what is the origin Point of the Dropdown List
public var originPoint : CGPoint{
get{
return _originPoint
}
set(newValue){
_ = self.resignFirstResponder()
_originPoint = newValue
}
}
/// You need o set this property to let us know should we hide the default seperator for the table view cells or not.... Ifyou want use your custom Seperator, you'd better set this property to YES
public var shouldHideSeperator : Bool {
get{
return hideSeperator
}
set(newValue){
hideSeperator = newValue
self.setTableViewSeperator()
}
}
/// You need to update this property if you want your Drop down list be transparent
public var dropdownListAlpha : CGFloat = 1
/// You need to update this property if you want your Drop down list show up or hide quicker
public var dropdownListShowUpAndHideDuration : TimeInterval = 0.5
/// MARK : Read Only Property
open var dropdownListHeight : CGFloat{
return self.usingCellHeight * CGFloat.init(min(self.numberOfDisplayingCells, getSupportTotalCellRows()))
}
open var dropdownListOriginPoint : CGPoint {
return _originPoint
}
open var dropdownListWidth : CGFloat{
return _width
}
private var usingFrame : CGRect{
return CGRect(origin: dropdownListOriginPoint,
size: CGSize(width: dropdownListWidth,
height: dropdownListHeight))
}
/// MARK : Private Properties
private var hideSeperator : Bool = false
private var usingCellHeight : CGFloat = 44.0
private var usingCellIdentifier : String?
private var _numberOfDisplayingCells : Int = 5
private var _width : CGFloat = 0
private var _originPoint : CGPoint = CGPoint(x: 0, y: 0)
/// MARK : - Public Methods
public func setupWithTarget(_ target : UNDDropDownListDelegate, showUpView view: UIView, andCell cell : UNDBaseTableViewCell){
self.registerCell(cell)
view.addSubview(self.view)
self.view.alpha = 0
self.delegate = target
}
public func registerCell(_ cell: UNDBaseTableViewCell){
type(of: cell).registerSelf(intoTableView:self.tableView)
self.usingCellHeight = type(of: cell).cellHeight
self.usingCellIdentifier = type(of: cell).cellIdentifierName
}
public func showUp(){
self.view.frame = usingFrame
self.view.superview?.bringSubview(toFront: self.view)
UNDanielUtilsTool.log("_____ Trying to show Dropdown List:\(self) in superView :\(String(describing: self.view.superview)) in Frame :\(usingFrame)")
UIView.animate(withDuration: self.dropdownListShowUpAndHideDuration) {
self.view.alpha = self.dropdownListAlpha
}
}
public func reloadData(){
self.tableView.reloadData()
}
public func hideDropdownList(){
if self.view.alpha > 0.0 {
UIView.animate(withDuration: self.dropdownListShowUpAndHideDuration,
animations: {
self.view.alpha = 0.0
})
}
}
public func setUpDispalyingPositionWithView(_ view: UIView, andExtendWidth extendWidth: CGFloat ){
if let convertedRect = view.superview?.convert(view.frame,
to: self.view.superview){
_originPoint = CGPoint(x: convertedRect.origin.x,
y: convertedRect.origin.y + convertedRect.size.height)
_width = convertedRect.size.width + extendWidth
} else {
_originPoint = CGPoint(x: 0,
y: 0)
_width = 0.0 + extendWidth
}
}
open override func resignFirstResponder() -> Bool {
self.hideDropdownList()
return super.resignFirstResponder()
}
/// MARK : - Privete Methods
/// MARK : - UI View Controller
override open func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.view.backgroundColor = UIColor.clear
self.tableView.backgroundView = UIView()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
self.tableView.bounces = false
self.tableView.alwaysBounceVertical = false
self.tableView.alwaysBounceHorizontal = false
self.setTableViewSeperator()
}
// MARK: - Table view data source
override open func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return getSupportTotalCellRows()
}
override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return self.usingCellHeight
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : UNDBaseTableViewCell = UNDDDLSampleTableViewCell()
if let unwrapedCellIdentifier = self.usingCellIdentifier {
cell = tableView.dequeueReusableCell(withIdentifier: unwrapedCellIdentifier,
for: indexPath) as! UNDBaseTableViewCell
}
if let unwrapDelegate = self.delegate {
var model : Any?
if unwrapDelegate.responds(to: Selector(("dropdownList:dataAtIndexPath:"))) {
model = unwrapDelegate.dropdownList(self,
dataAtIndexPath: indexPath)
}
if let unwrapedModel = model {
cell.setupCell(basedOnModelDictionary: [UNDBaseTableViewCell.UITableViewCell_BaseModle_Key : unwrapedModel])
}
}
return cell
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let unwrapDelegate = self.delegate {
if unwrapDelegate.responds(to: Selector(("dropdownList:didSelectCellAtIndexPath:"))) {
unwrapDelegate.dropdownList(self,
didSelectCellAtIndexPath: indexPath)
}
}
}
/// MARK: - Support Methods
func setTableViewSeperator() -> Void {
if !hideSeperator {
self.tableView.separatorStyle = .singleLine
} else {
self.tableView.separatorStyle = .none
}
}
func getSupportTotalCellRows() -> Int {
var returnInt : Int = 0
if let unwrapDelegate = self.delegate {
if unwrapDelegate.responds(to: Selector(("numberOfCellsInDropdownList:"))) {
returnInt = unwrapDelegate.numberOfCellsInDropdownList(self)
}
}
return returnInt
}
}
|
cfb64eb6477897be72ed71c1117f4e87
| 34.992278 | 200 | 0.618108 | false | false | false | false |
Ramotion/elongation-preview
|
refs/heads/master
|
ElongationPreview/Source/ElongationTransition.swift
|
mit
|
2
|
//
// ElongationTransition.swift
// ElongationPreview
//
// Created by Abdurahim Jauzee on 11/02/2017.
// Copyright © 2017 Ramotion. All rights reserved.
//
import UIKit
/// Provides transition animations between `ElongationViewController` & `ElongationDetailViewController`.
public class ElongationTransition: NSObject {
// MARK: Constructor
internal convenience init(presenting: Bool) {
self.init()
self.presenting = presenting
}
// MARK: Properties
fileprivate var presenting = true
fileprivate var appearance: ElongationConfig { return ElongationConfig.shared }
fileprivate let additionalOffsetY: CGFloat = 30
fileprivate var rootKey: UITransitionContextViewControllerKey {
return presenting ? .from : .to
}
fileprivate var detailKey: UITransitionContextViewControllerKey {
return presenting ? .to : .from
}
fileprivate var rootViewKey: UITransitionContextViewKey {
return presenting ? .from : .to
}
fileprivate var detailViewKey: UITransitionContextViewKey {
return presenting ? .to : .from
}
fileprivate func root(from context: UIViewControllerContextTransitioning) -> ElongationViewController {
let viewController = context.viewController(forKey: rootKey)
if let navi = viewController as? UINavigationController {
for case let elongationViewController as ElongationViewController in navi.viewControllers {
return elongationViewController
}
} else if let tab = viewController as? UITabBarController, let elongationViewController = tab.selectedViewController as? ElongationViewController {
return elongationViewController
} else if let elongationViewController = viewController as? ElongationViewController {
return elongationViewController
}
fatalError("Can't get `ElongationViewController` from UINavigationController nor from context's viewController itself.")
}
fileprivate func detail(from context: UIViewControllerContextTransitioning) -> ElongationDetailViewController {
return context.viewController(forKey: detailKey) as? ElongationDetailViewController ?? ElongationDetailViewController(nibName: nil, bundle: nil)
}
}
// MARK: - Transition Protocol Implementation
extension ElongationTransition: UIViewControllerAnimatedTransitioning {
/// :nodoc:
open func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return presenting ? appearance.detailPresentingDuration : appearance.detailDismissingDuration
}
/// :nodoc:
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
presenting ? present(using: transitionContext) : dismiss(using: transitionContext)
}
}
// MARK: - Presenting Animation
extension ElongationTransition {
fileprivate func present(using context: UIViewControllerContextTransitioning) {
let duration = transitionDuration(using: context)
let containerView = context.containerView
let root = self.root(from: context) // ElongationViewController
let detail = self.detail(from: context) // ElongationDetailViewController
let rootView = context.view(forKey: rootViewKey)
let detailView = context.view(forKey: detailViewKey)
let detailViewFinalFrame = context.finalFrame(for: detail) // Final frame for presenting view controller
let statusBarHeight: CGFloat
if #available(iOS 11, *) {
statusBarHeight = UIApplication.shared.statusBarFrame.height
} else {
statusBarHeight = 0
}
guard
let rootTableView = root.tableView, // get `tableView` from root
let path = root.expandedIndexPath ?? rootTableView.indexPathForSelectedRow, // get expanded or selected indexPath
let cell = rootTableView.cellForRow(at: path) as? ElongationCell, // get expanded cell from root `tableView`
let view = detailView // unwrap optional `detailView`
else { return }
// Determine are `root` view is in expanded state.
// We need to know that because animation depends on the state.
let isExpanded = root.state == .expanded
// Create `ElongationHeader` from `ElongationCell` and set it as `headerView` to `detail` view controller
let header = cell.elongationHeader
detail.headerView = header
// Get frame of expanded cell and convert it to `containerView` coordinates
let rect = rootTableView.rectForRow(at: path)
let cellFrame = rootTableView.convert(rect, to: containerView)
// Whole view snapshot
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let fullImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
// Header snapshot
UIGraphicsBeginImageContextWithOptions(header.frame.size, true, 0)
fullImage.draw(at: CGPoint(x: 0, y: 0))
let headerSnapsot = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
// TableView snapshot
let cellsSize = CGSize(width: view.frame.width, height: view.frame.height - header.frame.height)
UIGraphicsBeginImageContextWithOptions(cellsSize, true, 0)
fullImage.draw(at: CGPoint(x: 0, y: -header.frame.height - statusBarHeight))
let tableSnapshot = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
let headerSnapshotView = UIImageView(image: headerSnapsot)
let tableViewSnapshotView = UIImageView(image: tableSnapshot)
let tempView = UIView()
tempView.backgroundColor = header.bottomView.backgroundColor
// Add coming `view` to temporary `containerView`
containerView.addSubview(view)
containerView.addSubview(tempView)
containerView.addSubview(tableViewSnapshotView)
// Update `bottomView`s top constraint and invalidate layout
header.bottomViewTopConstraint.constant = appearance.topViewHeight
header.bottomView.setNeedsLayout()
let height = isExpanded ? cellFrame.height : appearance.topViewHeight + appearance.bottomViewHeight
view.frame = CGRect(x: 0, y: cellFrame.minY - statusBarHeight, width: detailViewFinalFrame.width, height: cellFrame.height)
headerSnapshotView.frame = CGRect(x: 0, y: cellFrame.minY - statusBarHeight, width: cellFrame.width, height: height)
tableViewSnapshotView.frame = CGRect(x: 0, y: detailViewFinalFrame.maxY, width: cellsSize.width, height: cellsSize.height)
tempView.frame = CGRect(x: 0, y: cellFrame.maxY - statusBarHeight, width: detailViewFinalFrame.width, height: 0)
// Animate to new state
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
root.view?.alpha = 0
header.scalableView.transform = .identity // reset scale to 1.0
header.contentView.frame = CGRect(x: 0, y: 0, width: cellFrame.width, height: cellFrame.height + self.appearance.bottomViewOffset)
header.contentView.setNeedsLayout()
header.contentView.layoutIfNeeded()
view.frame = detailViewFinalFrame
headerSnapshotView.frame = CGRect(x: 0, y: 0, width: cellFrame.width, height: height)
tableViewSnapshotView.frame = CGRect(x: 0, y: header.frame.height + statusBarHeight, width: detailViewFinalFrame.width, height: cellsSize.height)
tempView.frame = CGRect(x: 0, y: headerSnapshotView.frame.maxY, width: detailViewFinalFrame.width, height: detailViewFinalFrame.height)
}) { completed in
rootView?.removeFromSuperview()
tempView.removeFromSuperview()
headerSnapshotView.removeFromSuperview()
tableViewSnapshotView.removeFromSuperview()
context.completeTransition(completed)
}
}
}
// MARK: - Dismiss Animation
extension ElongationTransition {
fileprivate func dismiss(using context: UIViewControllerContextTransitioning) {
let root = self.root(from: context)
let detail = self.detail(from: context)
let containerView = context.containerView
let duration = transitionDuration(using: context)
guard
let header = detail.headerView,
let view = context.view(forKey: detailViewKey), // actual view of `detail` view controller
let rootTableView = root.tableView, // `tableView` of root view controller
let detailTableView = detail.tableView, // `tableView` of detail view controller
let path = root.expandedIndexPath ?? rootTableView.indexPathForSelectedRow, // `indexPath` of expanded or selected cell
let expandedCell = rootTableView.cellForRow(at: path) as? ElongationCell
else { return }
// Collapse root view controller without animation
root.collapseCells(animated: false)
expandedCell.topViewTopConstraint.constant = 0
expandedCell.topViewHeightConstraint.constant = appearance.topViewHeight
expandedCell.hideSeparator(false, animated: true)
expandedCell.topView.setNeedsLayout()
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
UIGraphicsEndImageContext()
let yOffset = detailTableView.contentOffset.y
let topViewSize = CGSize(width: view.bounds.width, height: appearance.topViewHeight)
UIGraphicsBeginImageContextWithOptions(topViewSize, true, 0)
header.topView.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: topViewSize), afterScreenUpdates: true)
let topViewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let bottomViewSize = CGSize(width: view.bounds.width, height: appearance.bottomViewHeight)
UIGraphicsBeginImageContextWithOptions(bottomViewSize, true, 0)
header.bottomView.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: bottomViewSize), afterScreenUpdates: true)
let bottomViewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let size = CGSize(width: view.bounds.width, height: view.bounds.height - header.frame.height)
UIGraphicsBeginImageContextWithOptions(size, true, 0)
image.draw(at: CGPoint(x: 0, y: -header.frame.height))
let tableViewImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let bottomViewImageView = UIImageView(image: bottomViewImage)
let topViewImageView = UIImageView(image: topViewImage)
let tableViewSnapshotView = UIImageView(image: tableViewImage)
// Add `header` and `tableView` snapshot to temporary container
containerView.addSubview(bottomViewImageView)
containerView.addSubview(tableViewSnapshotView)
containerView.addSubview(topViewImageView)
// Prepare view to dismissing
let rect = rootTableView.rectForRow(at: path)
let cellFrame = rootTableView.convert(rect, to: containerView)
detailTableView.alpha = 0
// Place views at their start points.
topViewImageView.frame = CGRect(x: 0, y: -yOffset, width: topViewSize.width, height: topViewSize.height)
bottomViewImageView.frame = CGRect(x: 0, y: -yOffset + topViewSize.height, width: view.bounds.width, height: bottomViewSize.height)
tableViewSnapshotView.frame = CGRect(x: 0, y: header.frame.maxY - yOffset, width: view.bounds.width, height: tableViewSnapshotView.frame.height)
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
root.view?.alpha = 1
tableViewSnapshotView.alpha = 0
// Animate views to collapsed cell size
let collapsedFrame = CGRect(x: 0, y: cellFrame.origin.y, width: header.frame.width, height: cellFrame.height)
topViewImageView.frame = collapsedFrame
bottomViewImageView.frame = collapsedFrame
tableViewSnapshotView.frame = collapsedFrame
expandedCell.contentView.layoutIfNeeded()
}, completion: { completed in
root.state = .normal
root.expandedIndexPath = nil
view.removeFromSuperview()
context.completeTransition(completed)
})
}
}
|
a1154cee4d21b9d6cf2277331e82ee0e
| 46.737828 | 157 | 0.707908 | false | false | false | false |
coshx/caravel
|
refs/heads/master
|
caravel/internal/DataSerializer.swift
|
mit
|
1
|
import Foundation
/**
**DataSerializer**
Serializes data to JS format and parses data coming from JS
*/
internal class DataSerializer {
internal static func serialize<T>(_ input: T) throws -> String {
var output: String?
if let b = input as? Bool {
output = b ? "true" : "false"
} else if let i = input as? Int {
output = "\(i)"
} else if let f = input as? Float {
output = "\(f)"
} else if let d = input as? Double {
output = "\(d)"
} else if var s = input as? String {
// As this string is going to be unwrapped from quotes, when passed to JS, all quotes need to be escaped
s = s.replacingOccurrences(of: "\"", with: "\\\"", options: NSString.CompareOptions(), range: nil)
s = s.replacingOccurrences(of: "'", with: "\'", options: NSString.CompareOptions(), range: nil)
output = "\"\(s)\""
} else if let a = input as? NSArray {
// Array and Dictionary are serialized to JSON.
// They should wrap only "basic" data (same types than supported ones)
let json = try! JSONSerialization.data(withJSONObject: a, options: JSONSerialization.WritingOptions())
output = NSString(data: json, encoding: String.Encoding.utf8.rawValue)! as String
} else if let d = input as? NSDictionary {
let json = try! JSONSerialization.data(withJSONObject: d, options: JSONSerialization.WritingOptions())
output = NSString(data: json, encoding: String.Encoding.utf8.rawValue)! as String
} else {
throw CaravelError.serializationUnsupportedData
}
return output!
}
internal static func deserialize(_ input: String) -> AnyObject {
if input.characters.count > 0 {
if (input.first == "[" && input.last == "]") || (input.first == "{" && input.last == "}") {
// Array or Dictionary, matching JSON format
let json = input.data(using: String.Encoding.utf8, allowLossyConversion: false)!
return try! JSONSerialization.jsonObject(with: json, options: JSONSerialization.ReadingOptions()) as AnyObject
}
if input == "true" {
return true as AnyObject
} else if input == "false" {
return false as AnyObject
}
var isNumber = true
for i in 0..<input.characters.count {
if Int(input[i]) != nil || input[i] == "." || input[i] == "," {
// Do nothing
} else {
isNumber = false
break
}
}
if isNumber {
if let i = Int(input) {
return i as AnyObject
} else {
return (input as NSString).doubleValue as AnyObject
}
}
}
return input as AnyObject
}
}
|
de3d66185b27a1104ce413da9c0cfe9d
| 39.552632 | 126 | 0.522388 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro
|
refs/heads/master
|
Former/RowFormers/SelectorDatePickerRowFormer.swift
|
mit
|
2
|
//
// SelectorDatePickerRowFormer.swift
// Former-Demo
//
// Created by Ryo Aoyama on 8/24/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public protocol SelectorDatePickerFormableRow: FormableRow {
var selectorDatePicker: UIDatePicker? { get set } // Needs NOT to set instance.
var selectorAccessoryView: UIView? { get set } // Needs NOT to set instance.
func formTitleLabel() -> UILabel?
func formDisplayLabel() -> UILabel?
func formDefaultDisplayDate() -> NSDate?
func formDefaultDisplayLabelText() -> String? //If formDefaultDisplayDate() returns a real date, the return value from this is ignored
}
open class SelectorDatePickerRowFormer<T: UITableViewCell>
: BaseRowFormer<T>, Formable, UpdatableSelectorForm where T: SelectorDatePickerFormableRow {
// MARK: Public
override open var canBecomeEditing: Bool {
return enabled
}
open var date: Date? = nil
open var inputAccessoryView: UIView?
open var titleDisabledColor: UIColor? = .lightGray
open var displayDisabledColor: UIColor? = .lightGray
open var titleEditingColor: UIColor?
open var displayEditingColor: UIColor?
public private(set) final lazy var selectorView: UIDatePicker = { [unowned self] in
let datePicker = UIDatePicker()
datePicker.addTarget(self, action: #selector(SelectorDatePickerRowFormer.dateChanged(datePicker:)), for: .valueChanged)
return datePicker
}()
public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: ((T) -> Void)? = nil) {
super.init(instantiateType: instantiateType, cellSetup: cellSetup)
}
@discardableResult
public final func onDateChanged(_ handler: @escaping ((Date) -> Void)) -> Self {
onDateChanged = handler
return self
}
@discardableResult
public final func displayTextFromDate(_ handler: @escaping ((Date) -> String)) -> Self {
displayTextFromDate = handler
return self
}
open override func update() {
super.update()
cell.selectorDatePicker = selectorView
cell.selectorAccessoryView = inputAccessoryView
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
if let date = date {
displayLabel?.text = displayTextFromDate?(date) ?? "\(date)"
} else if let defaultDate = cell.formDefaultDisplayDate() {
self.date = defaultDate as Date
displayLabel?.text = displayTextFromDate?(defaultDate as Date) ?? "\(defaultDate)"
} else if let defaultDisplayText = cell.formDefaultDisplayLabelText() {
displayLabel?.text = defaultDisplayText
}
if self.enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
_ = displayTextColor.map { displayLabel?.textColor = $0 }
titleColor = nil
displayTextColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .black }
if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black }
titleLabel?.textColor = titleDisabledColor
displayLabel?.textColor = displayDisabledColor
}
}
open override func cellSelected(indexPath: IndexPath) {
former?.deselect(animated: true)
}
public func editingDidBegin() {
if enabled {
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
if titleColor == nil { titleColor = titleLabel?.textColor ?? .black }
if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black }
_ = titleEditingColor.map { titleLabel?.textColor = $0 }
_ = displayEditingColor.map { displayEditingColor = $0 }
isEditing = true
}
}
public func editingDidEnd() {
isEditing = false
let titleLabel = cell.formTitleLabel()
let displayLabel = cell.formDisplayLabel()
if enabled {
_ = titleColor.map { titleLabel?.textColor = $0 }
_ = displayTextColor.map { displayLabel?.textColor = $0 }
titleColor = nil
displayTextColor = nil
} else {
if titleColor == nil { titleColor = titleLabel?.textColor ?? .black }
if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .black }
titleLabel?.textColor = titleDisabledColor
displayLabel?.textColor = displayDisabledColor
}
}
// MARK: Private
private final var onDateChanged: ((Date) -> Void)?
private final var displayTextFromDate: ((Date) -> String)?
private final var titleColor: UIColor?
private final var displayTextColor: UIColor?
@objc private dynamic func dateChanged(datePicker: UIDatePicker) {
let date = datePicker.date
self.date = date
cell.formDisplayLabel()?.text = displayTextFromDate?(date) ?? "\(date)"
onDateChanged?(date)
}
}
|
39357da12e9fb3a8deae67109130cb21
| 35.957447 | 138 | 0.633468 | false | false | false | false |
knutigro/AppReviews
|
refs/heads/develop
|
AppReviews/NSImageView+Networking.swift
|
gpl-3.0
|
1
|
//
// NSImageView+Networking.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-13.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import AppKit
protocol AFImageCacheProtocol:class{
func cachedImageForRequest(request:NSURLRequest) -> NSImage?
func cacheImage(image:NSImage, forRequest request:NSURLRequest);
}
extension NSImageView {
private struct AssociatedKeys {
static var SharedImageCache = "SharedImageCache"
static var RequestImageOperation = "RequestImageOperation"
static var URLRequestImage = "UrlRequestImage"
}
class func setSharedImageCache(cache:AFImageCacheProtocol?) {
objc_setAssociatedObject(self, &AssociatedKeys.SharedImageCache, cache, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
class func sharedImageCache() -> AFImageCacheProtocol {
struct Static {
static var token: dispatch_once_t = 0
static var defaultImageCache:AFImageCache?
}
dispatch_once(&Static.token, { () -> Void in
Static.defaultImageCache = AFImageCache()
})
return objc_getAssociatedObject(self, &AssociatedKeys.SharedImageCache) as? AFImageCache ?? Static.defaultImageCache!
}
class func af_sharedImageRequestOperationQueue() -> NSOperationQueue {
struct Static {
static var token:dispatch_once_t = 0
static var queue:NSOperationQueue?
}
dispatch_once(&Static.token, { () -> Void in
Static.queue = NSOperationQueue()
Static.queue!.maxConcurrentOperationCount = NSOperationQueueDefaultMaxConcurrentOperationCount
})
return Static.queue!
}
private var af_requestImageOperation:(operation:NSOperation?, request: NSURLRequest?) {
get {
let operation:NSOperation? = objc_getAssociatedObject(self, &AssociatedKeys.RequestImageOperation) as? NSOperation
let request:NSURLRequest? = objc_getAssociatedObject(self, &AssociatedKeys.URLRequestImage) as? NSURLRequest
return (operation, request)
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.RequestImageOperation, newValue.operation, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
objc_setAssociatedObject(self, &AssociatedKeys.URLRequestImage, newValue.request, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func setImageWithUrl(url:NSURL, placeHolderImage:NSImage? = nil) {
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.addValue("image/*", forHTTPHeaderField: "Accept")
setImageWithUrlRequest(request, placeHolderImage: placeHolderImage, success: nil, failure: nil)
}
func setImageWithUrlRequest(request:NSURLRequest, placeHolderImage:NSImage? = nil,
success:((request:NSURLRequest?, response:NSURLResponse?, image:NSImage) -> Void)?,
failure:((request:NSURLRequest?, response:NSURLResponse?, error:NSError) -> Void)?)
{
cancelImageRequestOperation()
if let cachedImage = NSImageView.sharedImageCache().cachedImageForRequest(request) {
if success != nil {
success!(request: nil, response:nil, image: cachedImage)
}
else {
image = cachedImage
}
return
}
if placeHolderImage != nil {
image = placeHolderImage
}
af_requestImageOperation = (NSBlockOperation(block: { () -> Void in
var response:NSURLResponse?
var error:NSError?
let data: NSData?
do {
data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
} catch let error1 as NSError {
error = error1
data = nil
} catch {
fatalError()
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if request.URL!.isEqual(self.af_requestImageOperation.request?.URL) {
let image:NSImage? = (data != nil ? NSImage(data: data!): nil)
if image != nil {
if success != nil {
success!(request: request, response: response, image: image!)
}
else {
self.image = image!
}
}
else {
if failure != nil {
failure!(request: request, response:response, error: error!)
}
}
self.af_requestImageOperation = (nil, nil)
}
})
}), request)
NSImageView.af_sharedImageRequestOperationQueue().addOperation(af_requestImageOperation.operation!)
}
private func cancelImageRequestOperation() {
af_requestImageOperation.operation?.cancel()
af_requestImageOperation = (nil, nil)
}
}
func AFImageCacheKeyFromURLRequest(request:NSURLRequest) -> String {
return request.URL!.absoluteString
}
class AFImageCache: NSCache, AFImageCacheProtocol {
func cachedImageForRequest(request: NSURLRequest) -> NSImage? {
switch request.cachePolicy {
case NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData,
NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData:
return nil
default:
break
}
return objectForKey(AFImageCacheKeyFromURLRequest(request)) as? NSImage
}
func cacheImage(image: NSImage, forRequest request: NSURLRequest) {
setObject(image, forKey: AFImageCacheKeyFromURLRequest(request))
}
}
|
c8a1976e37f63cf6850e911f00e4a6ad
| 37.816993 | 159 | 0.611991 | false | false | false | false |
marty-suzuki/QiitaApiClient
|
refs/heads/master
|
QiitaApiClient/QiitaApplicationInfo.swift
|
mit
|
1
|
//
// QiitaApplicationInfo.swift
// QiitaApiClient
//
// Created by Taiki Suzuki on 2016/08/19.
//
//
import Foundation
class QiitaApplicationInfo {
private struct Const {
static let QiitaCodeKey = "qiita_code"
static let QiitaAccessTokenKey = "qiita_access_token"
}
static let sharedInfo: QiitaApplicationInfo = .init()
let clientId: String
let clientSecret: String
let redirectURL: String
let scope: String
var code: String? {
get {
return NSUserDefaults.standardUserDefaults().stringForKey(Const.QiitaCodeKey)
}
set {
let ud = NSUserDefaults.standardUserDefaults()
ud.setObject(newValue, forKey: Const.QiitaCodeKey)
ud.synchronize()
}
}
var accessToken: String? {
get {
return NSUserDefaults.standardUserDefaults().stringForKey(Const.QiitaAccessTokenKey)
}
set {
let ud = NSUserDefaults.standardUserDefaults()
ud.setObject(newValue, forKey: Const.QiitaAccessTokenKey)
ud.synchronize()
}
}
private init() {
guard let infoDict = NSBundle.mainBundle().infoDictionary?["QiitaApplicaiontInfo"] as? [String : NSObject] else {
fatalError("can not find Qiita Applicaiont Info")
}
guard let clientId = infoDict["client_id"] as? String where !clientId.isEmpty else {
fatalError("can not find Qiita Applicationt Client Id")
}
guard let clientSecret = infoDict["client_secret"] as? String where !clientSecret.isEmpty else {
fatalError("can not find Qiita Applicationt Client Secret")
}
guard let redirectURL = infoDict["redirect_url"] as? String where !redirectURL.isEmpty else {
fatalError("can not find Qiita Applicationt redirect URL")
}
guard let rawScope = infoDict["scope"] as? [String] else {
fatalError("can not find Qiita Application scope")
}
self.clientId = clientId
self.clientSecret = clientSecret
self.redirectURL = redirectURL
let scopes: [QiitaAuthorizeScope] = rawScope.map {
guard let scope = QiitaAuthorizeScope(rawValue: $0) else {
fatalError("invalid scope string \"\($0)\"")
}
return scope
}
let scopeStrings: [String] = scopes.map { $0.rawValue }
let scopeString: String = scopeStrings.reduce("") { $0 == "" ? $1 : $0 + "+" + $1 }
self.scope = scopeString
}
}
|
dba4cf55c8e3fdb281c4293f82817257
| 34.315068 | 121 | 0.611952 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS
|
refs/heads/master
|
SmartReceipts/Common/UI/TabBarViewController/TabBarViewController.swift
|
agpl-3.0
|
2
|
//
// TabBarViewController.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 14.11.2019.
// Copyright © 2019 Will Baumann. All rights reserved.
//
import Foundation
class TabBarViewController: UITabBarController, UITabBarControllerDelegate, Storyboardable {
private var tabBarView: TabBar?
override func viewDidLoad() {
tabBarView = tabBar as? TabBar
tabBar.unselectedItemTintColor = UIColor.black.withAlphaComponent(0.3)
tabBar.tintColor = #colorLiteral(red: 0.2705882353, green: 0.1568627451, blue: 0.6235294118, alpha: 1)
tabBarView?.updateIndicatorPosition(item: selectedViewController?.tabBarItem)
tabBarView?.actionButton.addTarget(self, action: #selector(didTapActionButton), for: .touchUpInside)
delegate = self
}
@objc func didTapActionButton() {
let tabWithAction = viewControllers?[selectedIndex] as? TabHasMainAction
tabWithAction?.mainAction()
}
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
UIView.animate(withDuration: DEFAULT_ANIMATION_DURATION) { [weak self] in
self?.tabBarView?.updateIndicatorPosition(item: item)
}
guard let index = tabBar.items?.firstIndex(of: item) else { return }
let tabWithAction = viewControllers?[index] as? TabHasMainAction
guard let icon = tabWithAction?.actionIcon else { return }
tabBarView?.actionButton.setImage(icon.withRenderingMode(.alwaysOriginal), for: .normal)
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
return viewController.tabBarItem.tag > Constants.unselectableTag
}
}
extension TabBarViewController {
enum Constants {
static let unselectableTag = -1
}
}
protocol TabHasMainAction {
func mainAction()
var actionIcon: UIImage { get }
}
extension TabHasMainAction {
var actionIcon: UIImage {
return #imageLiteral(resourceName: "white_plus")
}
}
|
8304225c99a7e498127273648a6b0a8f
| 33.881356 | 122 | 0.704568 | false | false | false | false |
HTWDD/HTWDresden-iOS
|
refs/heads/master
|
HTWDD/Components/RoomOccupancy/Main/Views/RoomViewCell.swift
|
gpl-2.0
|
1
|
//
// RoomViewCell.swift
// HTWDD
//
// Created by Mustafa Karademir on 26.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
class RoomViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var main: UIView!
@IBOutlet weak var lblRoomName: BadgeLabel!
@IBOutlet weak var lblCountOfOccupancies: BadgeLabel!
@IBOutlet weak var lblCurrentLesson: UILabel!
@IBOutlet weak var imageViewChevron: UIImageView!
@IBOutlet weak var viewSeparator: UIView!
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
main.apply {
$0.layer.cornerRadius = 4
$0.backgroundColor = UIColor.htw.cellBackground
}
lblRoomName.apply {
$0.textColor = UIColor.htw.Label.primary
}
lblCurrentLesson.apply {
$0.textColor = UIColor.htw.Label.secondary
}
lblCountOfOccupancies.apply {
$0.textColor = UIColor.htw.Label.primary
$0.backgroundColor = UIColor.htw.Badge.primary
}
imageViewChevron.apply {
$0.tintColor = UIColor.htw.Icon.primary
}
}
}
// MARK: - Nib Loadable
extension RoomViewCell: FromNibLoadable {
// MARK: - Setup
func setup(with model: RoomRealm) {
lblRoomName.text = model.name.uppercased()
lblCountOfOccupancies.text = "\(model.occupancies.count)"
// Get current occupancy for the day
let occupanciesToday = Array(model.occupancies.filter("day = \(Date().weekday.dayByAdding(days: 1).rawValue)")).map { content -> Occupancy in
let weeks = String(String(content.weeksOnly.dropFirst()).dropLast()).replacingOccurrences(of: " ", with: "").components(separatedBy: ",")
return Occupancy(id: content.id,
name: content.name,
type: content.type,
day: content.day,
beginTime: content.beginTime,
endTime: content.endTime,
week: content.week,
professor: content.professor,
weeksOnly: weeks.compactMap( { Int($0) }))
}
if let current = occupanciesToday.filter({ $0.weeksOnly.contains(Date().weekday.rawValue) && ($0.beginTime...$0.endTime).contains(Date().string(format: "HH:mm:ss"))
}).first {
lblCurrentLesson.text = current.name
viewSeparator.backgroundColor = UIColor.htw.Material.red
} else {
lblCurrentLesson.text = R.string.localizable.roomOccupancyFree()
viewSeparator.backgroundColor = UIColor.htw.Material.green
}
}
}
|
fb290365dea384d8e0a7543d10f0b5d6
| 34.493827 | 172 | 0.570435 | false | false | false | false |
roddi/UltraschallHub
|
refs/heads/develop
|
Application/UltraschallHub/AudioEngineCell.swift
|
mit
|
1
|
//
// AudioEngineCell.swift
// UltraschallHub
//
// Created by Daniel Lindenfelser on 05.10.14.
// Copyright (c) 2014 Daniel Lindenfelser. All rights reserved.
//
import Cocoa
@IBDesignable
class AudioEngineCell: NSTableCellView, NSTextFieldDelegate {
@IBOutlet weak var statusLabel: NSTextField!
@IBOutlet weak var numChannelsPopUpButton: NSPopUpButton!
var engine: AudioEngine?
override func controlTextDidChange(obj: NSNotification) {
if (engine != nil) {
engine!.engineDescription = statusLabel.stringValue
}
}
@IBAction func valueChanged(sender: AnyObject) {
var value = numChannelsPopUpButton.itemTitleAtIndex(numChannelsPopUpButton.indexOfSelectedItem)
if let number = value.toInt() {
if (engine != nil) {
engine!.engineChannels = number
}
}
}
func setAudioEngine(engine :AudioEngine) {
statusLabel.editable = true
self.engine = engine
statusLabel.stringValue = engine.engineDescription
numChannelsPopUpButton.selectItemWithTitle(String(engine.engineChannels))
statusLabel.delegate = self
}
}
|
4e12fefedc3749f9db2f1d7397b1355d
| 28.85 | 103 | 0.670017 | false | false | false | false |
che1404/RGViperChat
|
refs/heads/master
|
RGViperChat/Signup/Interactor/SignupInteractorSpec.swift
|
mit
|
1
|
//
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Quick
import Nimble
import Cuckoo
@testable import RGViperChat
class SignupInteractorSpec: QuickSpec {
var interactor: SignupInteractor!
var mockPresenter: MockSignupInteractorOutputProtocol!
var mockAPIDataManager: MockSignupAPIDataManagerInputProtocol!
var mockLocalDataManager: MockSignupLocalDataManagerInputProtocol!
override func spec() {
beforeEach {
self.mockPresenter = MockSignupInteractorOutputProtocol()
self.mockAPIDataManager = MockSignupAPIDataManagerInputProtocol()
self.mockLocalDataManager = MockSignupLocalDataManagerInputProtocol()
self.interactor = SignupInteractor()
self.interactor.presenter = self.mockPresenter
self.interactor.APIDataManager = self.mockAPIDataManager
self.interactor.localDataManager = self.mockLocalDataManager
}
context("When sign up use case is selected") {
beforeEach {
stub(self.mockAPIDataManager) { mock in
when(mock).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure()).thenDoNothing()
}
self.interactor.signup(withUsername: "roberto", email: "[email protected]", password: "viperchat")
}
it("Calls the sigup method on the API data manager") {
verify(self.mockAPIDataManager).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure())
}
context("When the sign up was OK") {
beforeEach {
stub(self.mockAPIDataManager) { mock in
when(mock).signup(withUsername: anyString(), email: anyString(), password: anyString(), completion: anyClosure()).then { _, _, _, completion in
completion(true)
}
}
stub(self.mockPresenter) { mock in
when(mock).successfulSignup().thenDoNothing()
}
self.interactor.signup(withUsername: "roberto", email: "[email protected]", password: "viperchat")
}
it("Responds the presenter with successful signup") {
verify(self.mockPresenter).successfulSignup()
}
}
}
afterEach {
self.interactor = nil
self.mockPresenter = nil
self.mockAPIDataManager = nil
}
}
}
|
cdd1913ba5743b66139db52518bc4787
| 39.059701 | 167 | 0.605067 | false | false | false | false |
a2/Gulliver
|
refs/heads/master
|
Gulliver Tests/Source/AlternateBirthdaySpec.swift
|
mit
|
1
|
import AddressBook
import Gulliver
import Nimble
import Quick
class AlternateBirthdaySpec: QuickSpec {
override func spec() {
describe("rawValue") {
it("should contain the correct data") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let rawValue = birthday.rawValue
expect((rawValue[kABPersonAlternateBirthdayCalendarIdentifierKey as String] as! String)) == NSCalendarIdentifierHebrew
expect((rawValue[kABPersonAlternateBirthdayDayKey as String] as! Int)) == 14
expect((rawValue[kABPersonAlternateBirthdayEraKey as String] as! Int)) == 0
expect((rawValue[kABPersonAlternateBirthdayIsLeapMonthKey as String] as! Bool)) == false
expect((rawValue[kABPersonAlternateBirthdayMonthKey as String] as! Int)) == 4
expect((rawValue[kABPersonAlternateBirthdayYearKey as String] as! Int)) == 5718
}
it("is a valid representation") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let record: ABRecordRef = ABPersonCreate().takeRetainedValue()
var error: Unmanaged<CFErrorRef>? = nil
if !ABRecordSetValue(record, kABPersonAlternateBirthdayProperty, birthday.rawValue, &error) {
let nsError = (error?.takeUnretainedValue()).map { unsafeBitCast($0, NSError.self) }
fail("Could not set value on record: \(nsError?.localizedDescription)")
}
}
}
describe("init(rawValue:)") {
it("creates a valid AlternateBirthday") {
let rawValue: [NSObject : AnyObject] = [
kABPersonAlternateBirthdayCalendarIdentifierKey as String: NSCalendarIdentifierHebrew,
kABPersonAlternateBirthdayDayKey as String: 14,
kABPersonAlternateBirthdayEraKey as String: 0,
kABPersonAlternateBirthdayIsLeapMonthKey as String: false,
kABPersonAlternateBirthdayMonthKey as String: 4,
kABPersonAlternateBirthdayYearKey as String: 5718,
]
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
it("fails if a required key is not present") {
let correctRawValue: [NSObject : AnyObject] = [
kABPersonAlternateBirthdayCalendarIdentifierKey as String: NSCalendarIdentifierHebrew,
kABPersonAlternateBirthdayDayKey as String: 14,
kABPersonAlternateBirthdayEraKey as String: 0,
kABPersonAlternateBirthdayIsLeapMonthKey as String: false,
kABPersonAlternateBirthdayMonthKey as String: 4,
kABPersonAlternateBirthdayYearKey as String: 5718,
]
for index in indices(correctRawValue) {
var rawValue = correctRawValue
rawValue.removeAtIndex(index)
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).to(beNil())
}
}
it("works with vCard data") {
let fileURL = NSBundle(forClass: AlternateBirthdaySpec.self).URLForResource("Johnny B. Goode", withExtension: "vcf")!
let data = NSData(contentsOfURL: fileURL)!
let records = ABPersonCreatePeopleInSourceWithVCardRepresentation(nil, data as CFDataRef).takeRetainedValue() as [ABRecordRef]
let rawValue = ABRecordCopyValue(records[0], kABPersonAlternateBirthdayProperty)!.takeRetainedValue() as! [NSObject : AnyObject]
let birthday = AlternateBirthday(rawValue: rawValue)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
}
describe("dateComponents") {
it("should contain the correct data") {
let birthday = AlternateBirthday(calendarIdentifier: NSCalendarIdentifierHebrew, era: 0, year: 5718, month: 4, day: 14, isLeapMonth: false)
let components = birthday.dateComponents
expect(components.calendar?.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(components.day) == 14
expect(components.era) == 0
expect(components.leapMonth) == false
expect(components.month) == 4
expect(components.year) == 5718
}
}
describe("init(dateComponents:)") {
it("creates a valid AlternateBirthday") {
let dateComponents = NSDateComponents()
dateComponents.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew)
dateComponents.day = 14
dateComponents.era = 0
dateComponents.leapMonth = false
dateComponents.month = 4
dateComponents.year = 5718
let birthday = AlternateBirthday(dateComponents: dateComponents)
expect(birthday).notTo(beNil())
expect(birthday!.calendarIdentifier) == NSCalendarIdentifierHebrew
expect(birthday!.day) == 14
expect(birthday!.era) == 0
expect(birthday!.isLeapMonth) == false
expect(birthday!.month) == 4
expect(birthday!.year) == 5718
}
it("fails if a required value is not present") {
let allConfigurationBlocks: [NSDateComponents -> Void] = [
{ $0.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierHebrew) },
{ $0.day = 14 },
{ $0.era = 0 },
{ $0.month = 4 },
{ $0.year = 5718 },
]
for index in indices(allConfigurationBlocks) {
let dateComponents = NSDateComponents()
var configurationBlocks = allConfigurationBlocks
// Assignment to _ is necessary because the result is "NSDateComponents -> Void"
// and the compiler warns about an unused function result. The idea is that we
// don't want to execute it, but simply remove it from the array.
_ = configurationBlocks.removeAtIndex(index)
for block in configurationBlocks {
block(dateComponents)
}
let birthday = AlternateBirthday(dateComponents: dateComponents)
expect(birthday).to(beNil())
}
}
}
}
}
|
406f6a420c8c2aa12eab8d97aea016de
| 48.736842 | 155 | 0.57963 | false | false | false | false |
realm/SwiftLint
|
refs/heads/main
|
Source/SwiftLintFramework/Rules/Metrics/NestingRule.swift
|
mit
|
1
|
import SourceKittenFramework
struct NestingRule: ConfigurationProviderRule {
var configuration = NestingConfiguration(typeLevelWarning: 1,
typeLevelError: nil,
functionLevelWarning: 2,
functionLevelError: nil)
init() {}
static let description = RuleDescription(
identifier: "nesting",
name: "Nesting",
description:
"Types should be nested at most 1 level deep, and functions should be nested at most 2 levels deep.",
kind: .metrics,
nonTriggeringExamples: NestingRuleExamples.nonTriggeringExamples,
triggeringExamples: NestingRuleExamples.triggeringExamples
)
private let omittedStructureKinds = SwiftDeclarationKind.variableKinds
.union([.enumcase, .enumelement])
.map(SwiftStructureKind.declaration)
private struct ValidationArgs {
var typeLevel: Int = -1
var functionLevel: Int = -1
var previousKind: SwiftStructureKind?
var violations: [StyleViolation] = []
func with(previousKind: SwiftStructureKind?) -> ValidationArgs {
var args = self
args.previousKind = previousKind
return args
}
}
func validate(file: SwiftLintFile) -> [StyleViolation] {
return validate(file: file, substructure: file.structureDictionary.substructure, args: ValidationArgs())
}
private func validate(file: SwiftLintFile, substructure: [SourceKittenDictionary],
args: ValidationArgs) -> [StyleViolation] {
return args.violations + substructure.flatMap { dictionary -> [StyleViolation] in
guard let kindString = dictionary.kind, let structureKind = SwiftStructureKind(kindString) else {
return validate(file: file, substructure: dictionary.substructure, args: args.with(previousKind: nil))
}
guard !omittedStructureKinds.contains(structureKind) else {
return args.violations
}
switch structureKind {
case let .declaration(declarationKind):
return validate(file: file, structureKind: structureKind,
declarationKind: declarationKind, dictionary: dictionary, args: args)
case .expression, .statement:
guard configuration.checkNestingInClosuresAndStatements else {
return args.violations
}
return validate(file: file, substructure: dictionary.substructure,
args: args.with(previousKind: structureKind))
}
}
}
private func validate(file: SwiftLintFile, structureKind: SwiftStructureKind, declarationKind: SwiftDeclarationKind,
dictionary: SourceKittenDictionary, args: ValidationArgs) -> [StyleViolation] {
let isTypeOrExtension = SwiftDeclarationKind.typeKinds.contains(declarationKind)
|| SwiftDeclarationKind.extensionKinds.contains(declarationKind)
let isFunction = SwiftDeclarationKind.functionKinds.contains(declarationKind)
guard isTypeOrExtension || isFunction else {
return validate(file: file, substructure: dictionary.substructure,
args: args.with(previousKind: structureKind))
}
let currentTypeLevel = isTypeOrExtension ? args.typeLevel + 1 : args.typeLevel
let currentFunctionLevel = isFunction ? args.functionLevel + 1 : args.functionLevel
var violations = args.violations
if let violation = levelViolation(file: file, dictionary: dictionary,
previousKind: args.previousKind,
level: isFunction ? currentFunctionLevel : currentTypeLevel,
forFunction: isFunction) {
violations.append(violation)
}
return validate(file: file, substructure: dictionary.substructure,
args: ValidationArgs(
typeLevel: currentTypeLevel,
functionLevel: currentFunctionLevel,
previousKind: structureKind,
violations: violations
)
)
}
private func levelViolation(file: SwiftLintFile, dictionary: SourceKittenDictionary,
previousKind: SwiftStructureKind?, level: Int, forFunction: Bool) -> StyleViolation? {
guard let offset = dictionary.offset else {
return nil
}
let targetLevel = forFunction ? configuration.functionLevel : configuration.typeLevel
var violatingSeverity: ViolationSeverity?
if configuration.alwaysAllowOneTypeInFunctions,
case let .declaration(previousDeclarationKind)? = previousKind,
!SwiftDeclarationKind.functionKinds.contains(previousDeclarationKind) {
violatingSeverity = configuration.severity(with: targetLevel, for: level)
} else if forFunction || !configuration.alwaysAllowOneTypeInFunctions || previousKind == nil {
violatingSeverity = configuration.severity(with: targetLevel, for: level)
} else {
violatingSeverity = nil
}
guard let severity = violatingSeverity else {
return nil
}
let targetName = forFunction ? "Functions" : "Types"
let threshold = configuration.threshold(with: targetLevel, for: severity)
let pluralSuffix = threshold > 1 ? "s" : ""
return StyleViolation(
ruleDescription: Self.description,
severity: severity,
location: Location(file: file, byteOffset: offset),
reason: "\(targetName) should be nested at most \(threshold) level\(pluralSuffix) deep"
)
}
}
private enum SwiftStructureKind: Equatable {
case declaration(SwiftDeclarationKind)
case expression(SwiftExpressionKind)
case statement(StatementKind)
init?(_ structureKind: String) {
if let declarationKind = SwiftDeclarationKind(rawValue: structureKind) {
self = .declaration(declarationKind)
} else if let expressionKind = SwiftExpressionKind(rawValue: structureKind) {
self = .expression(expressionKind)
} else if let statementKind = StatementKind(rawValue: structureKind) {
self = .statement(statementKind)
} else {
return nil
}
}
}
|
14a99d3235d87a3ba1a8139359916a9e
| 43.624161 | 120 | 0.623853 | false | true | false | false |
wagnersouz4/replay
|
refs/heads/master
|
Replay/Replay/Source/Models/Movie.swift
|
mit
|
1
|
//
// Movie.swift
// Replay
//
// Created by Wagner Souza on 24/03/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import Foundation
struct Movie {
var movieId: Int
var genres: [String]
var title: String
var overview: String
var releaseDate: Date
/// Not every movie has a posterPath
var posterPath: String?
var videos: [YoutubeVideo]
/// Array of backdrops images sorted by its rating.
var backdropImagesPath: [String]
var runtime: Int
}
// MARK: Conforming to JSONable
extension Movie: JSONable {
init?(json: JSONDictionary) {
guard let genresList = json["genres"] as? [JSONDictionary],
let genres: [String] = JsonHelper.generateList(using: genresList, key: "name") else { return nil }
guard let videosList = json["videos"] as? JSONDictionary,
let videosResult = videosList["results"] as? [JSONDictionary],
let videos: [YoutubeVideo] = JsonHelper.generateList(using: videosResult) else { return nil }
guard let images = json["images"] as? JSONDictionary,
let backdropImages = images["backdrops"] as? [JSONDictionary],
let backdropImagesPath: [String] = JsonHelper.generateList(using: backdropImages,
key: "file_path")
else { return nil }
guard let movieId = json["id"] as? Int,
let title = json["original_title"] as? String,
let overview = json["overview"] as? String,
let poster = json["poster_path"] as? String,
let releaseDateString = json["release_date"] as? String,
let runtime = json["runtime"] as? Int else { return nil }
let posterPath = (poster == "N/A") ? nil : poster
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-d"
guard let releaseDate = formatter.date(from: releaseDateString) else {
fatalError("Invalid date format")
}
self.init(movieId: movieId,
genres: genres,
title: title,
overview: overview,
releaseDate: releaseDate,
posterPath: posterPath,
videos: videos,
backdropImagesPath: backdropImagesPath,
runtime: runtime)
}
}
// MARK: Conforming to GriddableContent
extension Movie: GriddableContent {
var identifier: Any? {
return movieId
}
var gridPortraitImageUrl: URL? {
guard let imagePath = posterPath else { return nil }
return TMDbHelper.createImageURL(using: imagePath)
}
var gridLandscapeImageUrl: URL? {
guard !backdropImagesPath.isEmpty else { return nil }
return TMDbHelper.createImageURL(using: backdropImagesPath[0])
}
var gridTitle: String {
return title
}
}
|
af2f46c6cdb1eb3dcf5083b56c9fdca9
| 31.311111 | 110 | 0.601788 | false | false | false | false |
vhart/PPL-iOS
|
refs/heads/master
|
PPL-iOS/LogManager.swift
|
mit
|
1
|
//
// LogManager.swift
// PPL-iOS
//
// Created by Jovanny Espinal on 2/17/16.
// Copyright © 2016 Jovanny Espinal. All rights reserved.
//
import Foundation
import CoreData
class LogManager {
static let sharedInstance = LogManager()
var collectionOfWorkoutLogs = NSOrderedSet()
private init()
{
collectionOfWorkoutLogs = NSOrderedSet()
}
func setProperties(exercises: [WorkoutLog])
{
let mutableCopy = collectionOfWorkoutLogs.mutableCopy() as! NSMutableOrderedSet
mutableCopy.addObjectsFromArray(exercises)
collectionOfWorkoutLogs = mutableCopy
}
func createWorkoutLog(managedContext: NSManagedObjectContext) -> WorkoutLog
{
let currentWorkoutLog = WorkoutLog(typeOfWorkout: LogManager.sharedInstance.getWorkoutType(), context: managedContext)
return currentWorkoutLog
}
func addWorkoutLog(workoutLog: WorkoutLog)
{
let setOfworkoutLogs = collectionOfWorkoutLogs.mutableCopy() as! NSMutableOrderedSet
var arrayOfWorkoutLogs = [WorkoutLog]()
arrayOfWorkoutLogs.append(workoutLog)
setOfworkoutLogs.addObjectsFromArray(arrayOfWorkoutLogs)
collectionOfWorkoutLogs = setOfworkoutLogs
}
}
extension LogManager {
}
|
fb5110e62b5ba24ddcd6ab0da2c81cda
| 23.462963 | 126 | 0.691143 | false | false | false | false |
larryhou/swift
|
refs/heads/master
|
Tachograph/Tachograph/VideoScrollController.swift
|
mit
|
1
|
//
// VideoScrollController.swift
// Tachograph
//
// Created by larryhou on 04/08/2017.
// Copyright © 2017 larryhou. All rights reserved.
//
import Foundation
import UIKit
import AVKit
class VideoPlayController: AVPlayerViewController, PageProtocol {
var PlayerStatusContext: String?
static func instantiate(_ storyboard: UIStoryboard) -> PageProtocol {
return storyboard.instantiateViewController(withIdentifier: "VideoPlayController") as! PageProtocol
}
var pageAsset: Any? {
didSet {
if let data = self.pageAsset as? CameraModel.CameraAsset {
self.url = data.url
}
}
}
var index: Int = -1
var url: String?
override func viewDidLoad() {
super.viewDidLoad()
self.player = AVPlayer()
let press = UILongPressGestureRecognizer(target: self, action: #selector(pressUpdate(sender:)))
view.addGestureRecognizer(press)
}
@objc func pressUpdate(sender: UILongPressGestureRecognizer) {
if sender.state != .began {return}
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "保存到相册", style: .default, handler: { _ in self.saveToAlbum() }))
alertController.addAction(UIAlertAction(title: "分享", style: .default, handler: { _ in self.share() }))
alertController.addAction(UIAlertAction(title: "删除", style: .destructive, handler: { _ in self.delete() }))
alertController.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: nil))
present(alertController, animated: true, completion: nil)
}
func delete() {
guard let url = self.url else {return}
dismiss(animated: true) {
let success = AssetManager.shared.remove(url)
AlertManager.show(title: success ? "文件删除成功" : "文件删除失败", message: url, sender: self)
}
}
func saveToAlbum() {
guard let url = self.url else {return}
UISaveVideoAtPathToSavedPhotosAlbum(url, self, #selector(video(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func video(_ videoPath: String, didFinishSavingWithError error: NSError?, contextInfo context: Any?) {
AlertManager.show(title: error == nil ? "视频保存成功" : "视频保存失败", message: error?.debugDescription, sender: self)
}
func share() {
guard let url = self.url else {return}
if let location = AssetManager.shared.get(cacheOf: url) {
let controller = UIActivityViewController(activityItems: [location], applicationActivities: nil)
present(controller, animated: true, completion: nil)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.player?.pause()
if let identifier = self.observerIdentifier {
self.player?.removeTimeObserver(identifier)
self.observerIdentifier = nil
}
}
var lastUrl: String?
var observerIdentifier: Any?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let player = self.player else {return}
guard let url = self.url else {
player.pause()
player.replaceCurrentItem(with: nil)
return
}
let interval = CMTime(seconds: 1, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
observerIdentifier = player.addPeriodicTimeObserver(forInterval: interval, queue: .main) {
if let duration = player.currentItem?.duration, $0 >= duration {
self.play(from: 0)
}
}
if lastUrl == url { return }
let item: AVPlayerItem
if url.hasPrefix("http") {
item = AVPlayerItem(url: URL(string: url)!)
} else {
item = AVPlayerItem(url: URL(fileURLWithPath: url))
}
player.replaceCurrentItem(with: item)
lastUrl = url
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.player?.play()
}
func play(from position: Double = 0) {
guard let player = self.player else {return}
let position = CMTime(seconds: position, preferredTimescale: CMTimeScale(NSEC_PER_SEC))
player.seek(to: position)
player.play()
}
}
class VideoScrollController: PageController<VideoPlayController, CameraModel.CameraAsset>, UIGestureRecognizerDelegate {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIViewPropertyAnimator.init(duration: 0.25, dampingRatio: 1.0) {
self.navigationController?.navigationBar.alpha = 0
}.startAnimation()
let pan = UIPanGestureRecognizer(target: self, action: #selector(panUpdate(sender:)))
pan.delegate = self
view.addGestureRecognizer(pan)
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return UIDevice.current.orientation.isPortrait
}
var fractionComplete = CGFloat.nan
var dismissAnimator: UIViewPropertyAnimator!
@objc func panUpdate(sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
dismissAnimator = UIViewPropertyAnimator(duration: 0.2, curve: .linear) { [unowned self] in
self.view.frame.origin.y = self.view.frame.height
}
dismissAnimator.addCompletion { [unowned self] position in
if position == .end {
self.dismiss(animated: false, completion: nil)
}
self.fractionComplete = CGFloat.nan
}
dismissAnimator.pauseAnimation()
case .changed:
if fractionComplete.isNaN {fractionComplete = 0}
let translation = sender.translation(in: view)
fractionComplete += translation.y / view.frame.height
fractionComplete = min(1, max(0, fractionComplete))
dismissAnimator.fractionComplete = fractionComplete
sender.setTranslation(CGPoint.zero, in: view)
default:
if dismissAnimator.fractionComplete <= 0.25 {
dismissAnimator.isReversed = true
}
dismissAnimator.continueAnimation(withTimingParameters: nil, durationFactor: 1.0)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIViewPropertyAnimator.init(duration: 0.25, dampingRatio: 1.0) {
self.navigationController?.navigationBar.alpha = 1
}.startAnimation()
}
}
|
7c2abc4543904130cd7438447b262cdf
| 36.131148 | 120 | 0.63223 | false | false | false | false |
yscode001/YSExtension
|
refs/heads/master
|
YSExtension/YSExtension/YSExtension/UIKit/UIImage+ysExtension.swift
|
mit
|
1
|
import UIKit
extension UIImage{
public var ys_width:CGFloat{
get{
return size.width
}
}
public var ys_height:CGFloat{
get{
return size.height
}
}
}
extension UIImage{
/// 创建图片
public static func ys_create(color:UIColor,size:CGSize) -> UIImage?{
if size == CGSize.zero{
return nil
}
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(size)
context.setFillColor(color.cgColor)
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 等比例缩放
public func ys_scale(width:CGFloat) -> UIImage?{
if width <= 0{
return nil
}
let scaleHeight = width / size.width * size.height
let scaleSize = CGSize(width: width, height: scaleHeight)
UIGraphicsBeginImageContextWithOptions(scaleSize, false, 0)
draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
/// 异步裁切
public func ys_corner(size:CGSize,fillColor:UIColor,callBack:((UIImage) -> ())?){
if size.width <= 0 || size.height <= 0{
callBack?(self)
return
}
DispatchQueue.global().async {
UIGraphicsBeginImageContextWithOptions(size, true, 0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
fillColor.setFill()
UIRectFill(rect)
let path = UIBezierPath(ovalIn: rect)
path.addClip()
self.draw(in: rect)
if let img = UIGraphicsGetImageFromCurrentImageContext(){
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(img)
}
} else{
UIGraphicsEndImageContext()
DispatchQueue.main.sync {
callBack?(self)
}
}
}
}
/// 颜色填充
public func ys_tint(color:UIColor) -> UIImage?{
guard let context = UIGraphicsGetCurrentContext() else{
return nil
}
guard let cgImg = cgImage else{
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
context.setBlendMode(.normal)
context.draw(cgImg, in: rect)
context.setBlendMode(.sourceIn)
color.setFill()
context.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
extension UIImage{
/// 生成二维码
public static func ys_qrCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
// 1、创建滤镜:CIQRCodeGenerator
guard let filter = CIFilter(name: "CIQRCodeGenerator") else{
return nil
}
// 2、设置属性:先设置默认、再设置自定义选项
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
// 3、根据滤镜生成图片
guard var ciImage = filter.outputImage else{
return nil
}
// 4、设置缩放,要不模糊
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
/// 生成条形码
public static func ys_barCode(code:String,width:CGFloat,height:CGFloat) -> UIImage?{
guard let filter = CIFilter(name: "CICode128BarcodeGenerator") else{
return nil
}
filter.setDefaults()
filter.setValue(code.data(using: .utf8), forKey: "inputMessage")
guard var ciImage = filter.outputImage else{
return nil
}
let scaleX = width / ciImage.extent.size.width
let scaleY = height / ciImage.extent.size.height
ciImage = ciImage.transformed(by: CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
return UIImage(ciImage: ciImage)
}
}
|
8fb9eb41c181f5b37819e227a3a6950e
| 28.202454 | 100 | 0.554622 | false | false | false | false |
powerytg/Accented
|
refs/heads/master
|
Accented/UI/User/ViewModels/UserFriendsStreamCardViewModel.swift
|
mit
|
1
|
//
// UserFriendsStreamCardViewModel.swift
// Accented
//
// Created by Tiangong You on 9/9/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class UserFriendsStreamCardViewModel: SingleHeaderStreamViewModel {
var user : UserModel
override var headerHeight: CGFloat {
return UserStreamLayoutSpec.streamHeaderHeight
}
override var cardRendererReuseIdentifier : String {
return "cardRenderer"
}
override func registerCellTypes() {
super.registerCellTypes()
collectionView.register(StreamCardPhotoCell.self, forCellWithReuseIdentifier: cardRendererReuseIdentifier)
}
override func createLayoutTemplateGenerator(_ maxWidth: CGFloat) -> StreamTemplateGenerator {
return PhotoCardTemplateGenerator(maxWidth: maxWidth)
}
required init(user : UserModel, stream : StreamModel, collectionView : UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
self.user = user
super.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: flowLayoutDelegate)
}
required init(stream: StreamModel, collectionView: UICollectionView, flowLayoutDelegate: UICollectionViewDelegateFlowLayout) {
fatalError("init(stream:collectionView:flowLayoutDelegate:) has not been implemented")
}
override func streamHeader(_ indexPath : IndexPath) -> UICollectionViewCell {
let streamHeaderCell = collectionView.dequeueReusableCell(withReuseIdentifier: streamHeaderReuseIdentifier, for: indexPath) as! DefaultSingleStreamHeaderCell
let userName = TextUtils.preferredAuthorName(user).uppercased()
streamHeaderCell.titleLabel.text = "PHOTOS FROM\n\(userName)'S FRIENDS"
if let photoCount = user.photoCount {
if photoCount == 0 {
streamHeaderCell.subtitleLabel.text = "NO ITEMS"
} else if photoCount == 1 {
streamHeaderCell.subtitleLabel.text = "1 ITEM"
} else {
streamHeaderCell.subtitleLabel.text = "\(photoCount) ITEMS"
}
} else {
streamHeaderCell.subtitleLabel.isHidden = true
}
streamHeaderCell.orderButton.isHidden = true
streamHeaderCell.orderLabel.isHidden = true
return streamHeaderCell
}
}
|
0a186296993956ecce12cdc0f5c67af5
| 37.532258 | 165 | 0.695689 | false | false | false | false |
AnyPresence/justapis-swift-sdk
|
refs/heads/master
|
Source/FoundationNetworkAdapter.swift
|
mit
|
1
|
//
// FoundationNetworkAdapter.swift
// JustApisSwiftSDK
//
// Created by Andrew Palumbo on 12/9/15.
// Copyright © 2015 AnyPresence. All rights reserved.
//
import Foundation
public class FoundationNetworkAdapter : NSObject, NetworkAdapter, NSURLSessionDataDelegate, NSURLSessionDelegate
{
typealias TaskCompletionHandler = (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void;
public init(sslCertificate:SSLCertificate? = nil)
{
self.sslCertificate = sslCertificate
super.init()
self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: nil)
}
private let sslCertificate:SSLCertificate?
private var session:NSURLSession!
private var taskToRequestMap = [Int: (request:Request, handler:TaskCompletionHandler)]()
@objc public func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response:
NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void) {
if let taskRequest = self.taskToRequestMap[task.taskIdentifier]
{
if (taskRequest.request.followRedirects)
{
// Allow redirect
completionHandler(request)
}
else
{
// Reject redirect
completionHandler(nil)
// HACK: For a currently unclear reason, the data task's completion handler doesn't
// get called by the NSURLSession framework if we reject the redirect here.
// So we call it here explicitly.
taskRequest.handler(data:nil, response: response, error:nil)
}
}
else
{
completionHandler(request)
}
}
@objc public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// If we have a SSL certificate for certificate pinning, verify it
guard let serverTrust = challenge.protectionSpace.serverTrust else
{
// APPROVE: This isn't the challenge we're looking for
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, nil)
return
}
let credential = NSURLCredential(forTrust: serverTrust)
guard let sslCertificate = self.sslCertificate else
{
// APPROVE: We're not worried about trusting the server as we have no certificate pinned
challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
return
}
guard let remoteCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else
{
// FAIL: We want to verify the server ceritifate, but it didn't give us one!
challenge.sender?.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
return
}
guard let
remoteCertificateData:NSData = SecCertificateCopyData(remoteCertificate)
where
remoteCertificateData.isEqualToData(sslCertificate.data) else
{
// FAIL: The certificates didn't match!
challenge.sender?.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
return
}
// APPROVE: We checked for a certificate and it was valid!
challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
return
}
public func submitRequest(request: Request, gateway:CompositedGateway)
{
// Build the request
guard let urlRequest:NSURLRequest = request.toNSURLRequest(gateway) else
{
// TODO: construct error indicating invalid request and invoke callback
return
}
var taskIdentifier:Int!
let taskCompletionHandler = { [weak self]
(data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
var gatewayResponse:MutableResponseProperties? = nil
// Generate a Gateway Response, if there's
if let foundationResponse = response as? NSHTTPURLResponse
{
gatewayResponse = MutableResponseProperties(foundationResponse, data:data, requestedURL:urlRequest.URL!, gateway: gateway, request: request)
}
self?.taskToRequestMap.removeValueForKey(taskIdentifier)
// Let the gateway finish processing the response (on main thread)
dispatch_async(dispatch_get_main_queue(), {
gateway.fulfillRequest(request, response:gatewayResponse, error:error);
})
}
// Submit the request on the session
let task = self.session.dataTaskWithRequest(urlRequest, completionHandler: taskCompletionHandler)
taskIdentifier = task.taskIdentifier
self.taskToRequestMap[taskIdentifier] = (request, taskCompletionHandler)
task.resume()
}
}
internal extension MutableResponseProperties
{
// Internal initializer method to populate an Immutable Response
internal init(_ response:NSHTTPURLResponse, data:NSData?, requestedURL:NSURL, gateway:Gateway, request:Request)
{
self.gateway = gateway
self.request = request
self.statusCode = response.statusCode
var headers = Headers()
for (key, value) in response.allHeaderFields
{
if let keyString = key as? String, let valueString = value as? String
{
headers[keyString] = valueString
}
}
self.headers = headers
self.requestedURL = requestedURL
self.resolvedURL = response.URL ?? nil
self.body = data
self.parsedBody = nil
self.retreivedFromCache = false
}
}
internal extension Request
{
/// Internal method to convert any type of Request to a NSURLRequest for Foundation networking
internal func toNSURLRequest(gateway:Gateway) -> NSURLRequest?
{
// Identify the absolute URL endpoint
let endpointUrl:NSURL = gateway.baseUrl.URLByAppendingPathComponent(self.path);
var url:NSURL = endpointUrl
// If params are assigned, apply them
if nil != self.params && self.params!.count > 0
{
let params = self.params!
// Create a components object
guard let urlComponents:NSURLComponents = NSURLComponents(URL: endpointUrl, resolvingAgainstBaseURL: false) else
{
// Could not parse NSURL through this technique
return nil
}
// Build query list
var queryItems = Array<NSURLQueryItem>()
for (key,value) in params
{
if let arrayValue = value as? Array<AnyObject>
{
for (innerValue) in arrayValue
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key + "[]", value:String(innerValue))
queryItems.append(queryItem)
}
}
else if let _ = value as? NSNull
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key, value: nil);
queryItems.append(queryItem)
}
else if let stringValue = value as? CustomStringConvertible
{
let queryItem:NSURLQueryItem = NSURLQueryItem(name: key, value: String(stringValue));
queryItems.append(queryItem)
}
else
{
assert(false, "Unsupported query item value. Must be array, NSNull, or a CustomStringConvertible type")
}
}
urlComponents.queryItems = queryItems
// Try to resolve the URLComponents
guard let completeUrl = urlComponents.URL else
{
// Could not resolve to URL once we included query parameters
return nil
}
url = completeUrl
}
// Create the request object
let urlRequest:NSMutableURLRequest = NSMutableURLRequest(URL: url);
// Set the method
urlRequest.HTTPMethod = self.method;
// If headers were assigned, apply them
if nil != self.headers && self.headers!.count > 0
{
let headers = self.headers!
for (field,value) in headers
{
urlRequest.addValue(value, forHTTPHeaderField: field);
}
}
// If a body was assigned, apply it
if let body = self.body
{
urlRequest.HTTPBody = body
}
return urlRequest
}
}
|
b4882d083d1ed9caad82eb445d8ab548
| 37.794355 | 203 | 0.600769 | false | false | false | false |
BenziAhamed/Nevergrid
|
refs/heads/master
|
NeverGrid/Source/CreditsScene.swift
|
isc
|
1
|
//
// CreditsScene.swift
// NeverGrid
//
// Created by Benzi on 05/03/15.
// Copyright (c) 2015 Benzi Ahamed. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class CreditsScene : NavigatingScene {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init () {
super.init(context:NavigationContext())
}
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
setBackgroundImage("background_credits")
let logo = textSprite("credits")
logo.position = frame.mid() //CGPointMake(frame.midX, 0.66 * frame.height)
worldNode.addChild(logo)
// home button
let home = textSprite("home_level")
let homeButton = WobbleButton(node: home, action: Callback(self, CreditsScene.goToHome))
homeButton.position = CGPointMake(
self.frame.width - home.frame.width,
home.frame.height
)
worldNode.addChild(homeButton)
// twitter button
let twitter = textSprite("twitter")
let twitterButton = WobbleButton(node: twitter, action: Callback(self, CreditsScene.showTwitter))
twitterButton.position = CGPointMake(logo.position.x, logo.position.y-logo.frame.height/2.0-twitter.frame.height)
worldNode.addChild(twitterButton)
}
func goToHome() {
self.navigation.displayMainMenuWithReveal(SKTransitionDirection.Left)
}
func showTwitter() {
UIApplication.sharedApplication().openURL(NSURL(string: "http://twitter.com/benziahamed")!)
}
}
|
99e366ae3b97508d1ea635949f44554b
| 27.877193 | 121 | 0.643769 | false | false | false | false |
ChenWeiLee/Black-Fu
|
refs/heads/master
|
Black-Fu/Black-Fu/NewsWebViewController.swift
|
gpl-2.0
|
1
|
//
// NewsWebViewController.swift
// Black-Fu
//
// Created by Li Chen wei on 2016/1/8.
// Copyright © 2016年 TWML. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class NewsWebViewController: UIViewController,UIWebViewDelegate {
@IBOutlet var newsWebView: UIWebView!
var loadWebString:String = String()
var loadingActivity:NVActivityIndicatorView = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100), type: .BallClipRotatePulse, color: UIColor(red: 0.49, green: 0.87, blue: 0.47, alpha: 1.0), size: CGSizeMake(100, 100))
override func viewDidLoad() {
super.viewDidLoad()
loadingActivity.center = self.view.center
self.view.addSubview(loadingActivity)
guard let requestURL = NSURL(string:loadWebString) else {
return
}
let request = NSURLRequest(URL: requestURL)
newsWebView.loadRequest(request)
}
func webViewDidStartLoad(webView: UIWebView) {
loadingActivity.startAnimation()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
loadingActivity.stopAnimation()
print("\(error)")
}
func webViewDidFinishLoad(webView: UIWebView) {
loadingActivity.stopAnimation()
}
}
|
0c4ec85d43a81b9ebd3b811f17178967
| 24.309091 | 245 | 0.637213 | false | false | false | false |
ahmed93/AAShimmerView
|
refs/heads/master
|
AAShimmerView/Classes/UIView+AAShimmerView.swift
|
mit
|
1
|
//
// UIView+AAShimmerView.swift
// AAShimmerView
//
// Created by Ahmed Magdi on 6/11/17.
// Copyright © 2017 Ahmed Magdi. All rights reserved.
//
import UIKit
public enum ShimmerAlignment {
case center
case top
case bottom
}
public extension UIView {
private static let association_subViews = ObjectAssociation<[UIView]>()
private static let association_viewHeight = ObjectAssociation<CGFloat>()
private static let association_viewAlpha = ObjectAssociation<CGFloat>()
private static let association_FBShimmerView = ObjectAssociation<AAShimmerView>()
private static let association_shimmerColors = ObjectAssociation<[UIColor]>()
private static let association_shimmerVerticalAlignment = ObjectAssociation<ShimmerAlignment>()
private var shimmerView: AAShimmerView? {
get { return UIView.association_FBShimmerView[self] }
set { UIView.association_FBShimmerView[self] = newValue }
}
var aaShimmerViewAlpha: CGFloat {
get { return UIView.association_viewAlpha[self] ?? self.alpha }
set { UIView.association_viewAlpha[self] = newValue }
}
public var aaShimmerSubViews: [UIView]? {
get { return UIView.association_subViews[self] }
set { UIView.association_subViews[self] = newValue }
}
public var aaShimmerHeight: CGFloat {
get { return UIView.association_viewHeight[self] ?? self.frame.height }
set { UIView.association_viewHeight[self] = newValue }
}
public var isShimmering:Bool {
return shimmerView != nil
}
public var aashimmerColors:[UIColor]? {
get { return UIView.association_shimmerColors[self] }
set { UIView.association_shimmerColors[self] = newValue }
}
/// Vertical Alignment by default is set to center.
public var aashimmerVerticalAlignment:ShimmerAlignment {
get { return UIView.association_shimmerVerticalAlignment[self] ?? .center }
set { UIView.association_shimmerVerticalAlignment[self] = newValue }
}
public func startShimmering() {
if shimmerView == nil {
shimmerView = AAShimmerView(rootView: self)
}
shimmerView?.start()
}
public func stopShimmering() {
if shimmerView == nil {
return
}
shimmerView?.stop()
shimmerView = nil
}
}
|
111daf2a3ccca02aa482af58077a6216
| 30.973333 | 99 | 0.667223 | false | false | false | false |
sunlijian/sinaBlog_repository
|
refs/heads/master
|
sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/View/IWComposeView.swift
|
apache-2.0
|
1
|
//
// IWComposeView.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/18.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
import pop
let COMPOSE_BUTTON_MAGIN: CGFloat = (SCREEN_W - 3*COMPOSE_BUTTON_W) / 4
class IWComposeView: UIView {
var targetVC : UIViewController?
override init(frame: CGRect) {
super.init(frame: frame)
//设置大小
self.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H)
//添加背景图片
let imageView = UIImageView(image: screenImage())
imageView.size = size
addSubview(imageView)
//添加 button
addMeumButton()
//添加compose_slogan
addCompose_sloganImage()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//屏幕载图
private func screenImage() -> UIImage{
//取出 window
let window = UIApplication.sharedApplication().keyWindow
//开启图形上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_W, SCREEN_H), false, 0)
//把当前 window 显示的图形添加到上下文中
window?.drawViewHierarchyInRect(window!.bounds, afterScreenUpdates: false)
//获取图片
var image = UIGraphicsGetImageFromCurrentImageContext()
//进行模糊渲染
image = image.applyLightEffect()
//关闭图形上下文
UIGraphicsEndImageContext()
return image
}
//添加 button
private func addMeumButton(){
//解析 plist 文件
let path = NSBundle.mainBundle().pathForResource("compose", ofType: "plist")
let composeButtonInfos = NSArray(contentsOfFile: path!)
//遍历添加 button
for i in 0..<composeButtonInfos!.count{
//创建 button
let buttonInfo = IWComposeButton()
//添加监听事件
buttonInfo.addTarget(self, action: "composeButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
//取出字典
let info = composeButtonInfos![i] as! [String: AnyObject]
//给 button 赋值
buttonInfo.setImage(UIImage(named: (info["icon"] as! String)), forState: UIControlState.Normal)
buttonInfo.setTitle((info["title"] as! String), forState: UIControlState.Normal)
//设置 button 的 位置
let rowIndex = i / 3
let colIndex = i % 3
buttonInfo.x = CGFloat(colIndex) * COMPOSE_BUTTON_W + CGFloat(colIndex + 1) * COMPOSE_BUTTON_MAGIN
buttonInfo.y = CGFloat(rowIndex) * COMPOSE_BUTTON_H + CGFloat(rowIndex + 1) * COMPOSE_BUTTON_MAGIN + SCREEN_H
print(buttonInfo.x)
//添加到当前 view 上
addSubview(buttonInfo)
//添加到数组中
composeButtons.append(buttonInfo)
}
}
//点击加号按钮
func show(target:UIViewController){
target.view.addSubview(self)
self.targetVC = target
//添加动画
for (index, value) in composeButtons.enumerate(){
anmi(value, centerY: value.centerY - 400, index: index)
}
}
//点击屏幕消失
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
dismiss()
}
func dismiss(){
for (index, value) in composeButtons.reverse().enumerate(){
anmi(value, centerY: value.centerY + 400, index: index)
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
self.removeFromSuperview()
}
}
//初始化添加顶部控件到 view 上
private func addCompose_sloganImage(){
addSubview(sloganImage)
}
//懒加载顶部的 logo控件
private lazy var sloganImage : UIImageView = {
let imageView = UIImageView(image: UIImage(named: "compose_slogan"))
imageView.centerX = SCREEN_W * 0.5
imageView.y = 100
return imageView
}()
//button 数组的懒加载
private lazy var composeButtons :[IWComposeButton] = [IWComposeButton]()
//button 的点击事件
@objc private func composeButtonClick(button: IWComposeButton){
UIView.animateWithDuration(0.25, animations: { () -> Void in
//改变 button 的 transform
for value in self.composeButtons{
if value == button {
value.transform = CGAffineTransformMakeScale(2, 2)
}else{
value.transform = CGAffineTransformMakeScale(0, 0)
}
value.alpha = 0
}
}) { (finish) -> Void in
let vc = IWComposeViewController()
let nv = IWNavigationController(rootViewController: vc)
self.targetVC?.presentViewController(nv, animated: true, completion: { () -> Void in
self.removeFromSuperview()
})
}
}
//动画
private func anmi(value:UIButton, centerY:CGFloat, index: Int){
//初始化一个弹性动画对象
let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
anim.toValue = NSValue(CGPoint: CGPointMake(value.centerX, centerY))
//动画的弹性幅度
anim.springBounciness = 10
//动画的速度
anim.springSpeed = 10
//动画的执行时间(相对于现在来说 向后延迟多少秒)
anim.beginTime = CACurrentMediaTime() + Double(index) * 0.025
//给控件添加动画对象
value.pop_addAnimation(anim, forKey: nil)
}
}
|
e99eb79fc276caae91323f8096a89615
| 32.233129 | 134 | 0.587595 | false | false | false | false |
nlgb/VVSPageView
|
refs/heads/master
|
VVSPageView/VVSPageView/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// VVSPageView
//
// Created by sw on 17/4/19.
// Copyright © 2017年 sw. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let style = VVSPageStyle()
style.titleIsScrollEnable = false
automaticallyAdjustsScrollViewInsets = false
let titles = ["精华","热门视频","图片","文字"]
// let titles = ["精华","热门视频","动态图片","搞笑文字","热门游戏","广告"]
var childVcs = [UIViewController]()
for _ in 0..<titles.count {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1.0)
childVcs.append(vc)
}
let pageViewFrame = CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64)
let pageView = VVSPageView(frame: pageViewFrame, style: style, titles: titles, childVcs: childVcs, parentVc: self)
pageView.backgroundColor = .blue
view.addSubview(pageView)
}
}
|
3a80d361c8ba872b760d25c2c5b3ab2c
| 31.297297 | 195 | 0.628452 | false | false | false | false |
balthild/Mathemalpha
|
refs/heads/master
|
Carthage/Checkouts/KeyHolder/Carthage/Checkouts/Magnet/Lib/Magnet/HotKey.swift
|
gpl-3.0
|
1
|
//
// HotKey.swift
// Magnet
//
// Created by 古林俊佑 on 2016/03/09.
// Copyright © 2016年 Shunsuke Furubayashi. All rights reserved.
//
import Cocoa
import Carbon
public final class HotKey: Equatable {
// MARK: - Properties
public let identifier: String
public let keyCombo: KeyCombo
public var target: AnyObject?
public var action: Selector?
public var hotKeyId: UInt32?
public var hotKeyRef: EventHotKeyRef?
// MARK: - Init
public init(identifier: String, keyCombo: KeyCombo, target: AnyObject? = nil, action: Selector? = nil) {
self.identifier = identifier
self.keyCombo = keyCombo
self.target = target
self.action = action
}
}
// MARK: - Invoke
public extension HotKey {
public func invoke() {
if let target = target as? NSObject, let selector = action {
if target.responds(to: selector) {
target.perform(selector, with: self)
}
}
}
}
// MARK: - Register & UnRegister
public extension HotKey {
@discardableResult
public func register() -> Bool {
return HotKeyCenter.shared.register(with: self)
}
public func unregister() {
return HotKeyCenter.shared.unregister(with: self)
}
}
// MARK: - Equatable
public func ==(lhs: HotKey, rhs: HotKey) -> Bool {
return lhs.identifier == rhs.identifier &&
lhs.keyCombo == rhs.keyCombo &&
lhs.hotKeyId == rhs.hotKeyId &&
lhs.hotKeyRef == rhs.hotKeyRef
}
|
69cf065a0c9a05adc811eb7258a1385c
| 24.466667 | 108 | 0.61911 | false | false | false | false |
yuenhsi/interactive-bridge
|
refs/heads/master
|
Interactive Bridge/Interactive Bridge/Hand.swift
|
mit
|
1
|
//
// Hand.swift
// Interactive Bridge
//
// Created by Yuen Hsi Chang on 1/26/17.
// Copyright © 2017 Yuen Hsi Chang. All rights reserved.
//
import Foundation
class Hand {
var cards: [Card]!
init(_ cards: [Card]) {
self.cards = cards
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func sortCardsBySuit(first: Card, second: Card) -> Bool {
if first.Suit == second.Suit {
return first.Rank.hashValue > second.Rank.hashValue
} else {
return first.Suit.hashValue > second.Suit.hashValue
}
}
func cardsIn(suit: Suit) -> Int {
return (cards.filter { $0.Suit == suit }).count
}
func addCard(card: Card) {
self.cards.append(card)
}
func removeCard(card: Card) {
self.cards = self.cards.filter() { $0 != card }
}
func sort() {
self.cards.sort { sortCardsBySuit(first: $0, second: $1) }
}
func removeAll() {
self.cards.removeAll()
}
func hasSuit(suit: Suit?) -> Bool {
if suit == nil {
return false
}
return self.cards.contains(where: { $0.Suit == suit} )
}
}
|
19b5977372e7e633825feee34ddee9c0
| 21.62963 | 66 | 0.536825 | false | false | false | false |
mikina/Right-Direction
|
refs/heads/master
|
RightDirection/RightDirection/Controller/GameBoardViewController.swift
|
mit
|
1
|
//
// GameBoardViewController.swift
// RightDirection
//
// Created by Mike Mikina on 3/3/16.
// Copyright © 2016 FDT. All rights reserved.
//
import UIKit
class GameBoardViewController: UIViewController {
let topBarHeight = 44 //size of top navigation bar, navbar here it's just normal UIView
let minDirectionViewSquare = 200 //minimum size of view with directions
let maxDirectionViewSquare = 250 //maximum size of view with directions
let playTime = 60
@IBOutlet weak var directionsViewHeight: NSLayoutConstraint!
@IBOutlet weak var directionsViewWidth: NSLayoutConstraint!
@IBOutlet weak var directionsViewAxisX: NSLayoutConstraint!
@IBOutlet weak var directionsViewAxisY: NSLayoutConstraint!
@IBOutlet weak var directionsView: DirectionsView!
var scoreManager: ScoreManager?
var timeManager: TimerManager?
var updatePoints: ((points: Int) -> ())?
var updateTime: ((time: Int) -> ())?
var badgeView: BadgeView?
// When false we block all swipe gestures,
// game is inactive at the begining and at the end when time pass
var isGameActive = false
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.showHelloMessages([NSLocalizedString("Prepare...", comment: "Prepare..."), NSLocalizedString("3", comment: "3"), NSLocalizedString("2", comment: "2"), NSLocalizedString("1", comment: "1"), NSLocalizedString("Go!", comment: "Go!")])
}
func startGame() {
self.isGameActive = true
self.timeManager?.startCountdown(self.playTime)
self.setupDirections()
self.setRandomPosition()
}
func finishGame() {
self.isGameActive = false
self.directionsView.cleanUp()
if let scoreManager = self.scoreManager {
let finalMessage = NSLocalizedString("You have: ", comment: "You have: ") + String(scoreManager.userScore) + NSLocalizedString(" points!", comment: " points!")
self.showFinalMessage(finalMessage)
}
self.getFromUser(NSLocalizedString("Enter your name", comment: "Enter your name")) { (name) -> () in
self.scoreManager?.saveScoreForUser(name)
}
}
func setup() {
self.scoreManager = ScoreManager()
self.setupView()
self.timeManager = TimerManager()
if let update = self.updateTime, time = self.timeManager {
// This closure is called every second the timer is running, we use it
// to run another closure which updates label in GameTabVC
time.tick = { timeValue in
update(time: timeValue)
}
// This closure is called when timer finish countdown
time.completeCountdown = {
self.finishGame()
}
}
}
func setupView() {
for direction in [.Right, .Left, .Up, .Down] as [UISwipeGestureRecognizerDirection] {
self.addSwipeRecognizerForDirection(direction)
}
if let badge = NSBundle.mainBundle().loadNibNamed("BadgeView", owner: self, options: nil)[0] as? BadgeView {
self.view.addSubview(badge)
self.badgeView = badge
badge.setupAsModal(self.view, width: badge.badgeViewWidth, height: badge.badgeViewHeight, corners: badge.badgeRoundedCorners)
}
}
func setupDirections() {
self.directionsView.cleanUp()
if let directions = NSBundle.mainBundle().loadNibNamed("DirectionsView", owner: self, options: nil)[0] as? DirectionsView {
directions.datasource = DirectionsManager.sharedInstance.getItem()
directions.setup()
self.directionsView.addSubview(directions)
directions.pinToAll(self.directionsView)
}
}
func setRandomPosition() {
let randomSquareSize = Int.random(self.minDirectionViewSquare...self.maxDirectionViewSquare)
let maxX = Int(self.view.frame.size.width) - randomSquareSize
let maxY = Int(self.view.frame.size.height - CGFloat(self.topBarHeight)) - randomSquareSize
let randomX = Int.random(1...maxX)
let randomY = Int.random(1...maxY)
self.directionsViewAxisX.constant = CGFloat(randomX)
self.directionsViewAxisY.constant = CGFloat(randomY)
self.directionsViewWidth.constant = CGFloat(randomSquareSize)
self.directionsViewHeight.constant = CGFloat(randomSquareSize)
}
func addSwipeRecognizerForDirection(direction: UISwipeGestureRecognizerDirection) {
let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(GameBoardViewController.handleSwipe(_:)))
swipeGesture.direction = direction //it's also possible to pass whole array here, but apparently in that case only left and right swipe works (Xcode 7.2)
self.view.addGestureRecognizer(swipeGesture)
}
func handleSwipe(swipe: UISwipeGestureRecognizer) {
if !self.isGameActive {
return
}
let direction: DirectionsType = swipe.direction.translateToDirection()
let result = DirectionsManager.sharedInstance.validateDirection(direction)
self.scoreManager?.calculateScore(result)
self.badgeView?.setupBadgeWithResult(result)
self.updateScoreView()
self.setupDirections()
self.setRandomPosition()
}
func updateScoreView() {
if let updatePoints = self.updatePoints {
if let score = self.scoreManager {
updatePoints(points: score.userScore)
}
}
}
}
|
881107ffa7bd2570b27f65b8b83ebc10
| 34.506667 | 240 | 0.708787 | false | false | false | false |
leizh007/HiPDA
|
refs/heads/master
|
HiPDA/HiPDA/General/Views/BaseTableView.swift
|
mit
|
1
|
//
// BaseTableView.swift
// HiPDA
//
// Created by leizh007 on 2016/11/16.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import MJRefresh
/// BaseTableView的Rx扩展
extension Reactive where Base: BaseTableView {
/// 状态
var status: UIBindingObserver<Base, DataLoadStatus> {
return UIBindingObserver(UIElement: base) { (tableView, status) in
tableView.status = status
}
}
/// 是否正在编辑
var isEditing: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: base) { (tableView, isEditing) in
tableView.isEditing = isEditing
}
}
}
class BaseTableView: UITableView, DataLoadable {
var refreshHeader: MJRefreshNormalHeader? {
get {
return mj_header as? MJRefreshNormalHeader
}
set {
mj_header = newValue
}
}
var loadMoreFooter: MJRefreshBackNormalFooter? {
get {
return mj_footer as? MJRefreshBackNormalFooter
}
set {
mj_footer = newValue
}
}
var hasRefreshHeader = false {
didSet {
didSetHasRefreshHeader()
}
}
var hasLoadMoreFooter = false {
didSet {
didSetHasLoadMoreFooter()
}
}
weak var dataLoadDelegate: DataLoadDelegate?
var status = DataLoadStatus.loading {
didSet {
didSetStatus()
}
}
lazy var noResultView: NoResultView = {
NoResultView.xibInstance
}()
override func layoutSubviews() {
super.layoutSubviews()
if noResultView.superview != nil {
noResultView.frame = bounds
noResultView.tapToLoadDelegate = self
bringSubview(toFront: noResultView)
}
}
}
|
0b71fed9069718739dfd755ac399c22d
| 21.411765 | 77 | 0.581102 | false | false | false | false |
infobip/mobile-messaging-sdk-ios
|
refs/heads/master
|
Classes/Core/User/UserStandardAttributeModels.swift
|
apache-2.0
|
1
|
//
// UserStandardAttributeModels.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 29/11/2018.
//
import Foundation
@objc public enum MMGenderNonnull: Int {
case Female
case Male
case Undefined
var toGender: MMGender? {
switch self {
case .Female : return .Female
case .Male : return .Male
case .Undefined : return nil
}
}
static func make(from gender: MMGender?) -> MMGenderNonnull {
if let gender = gender {
switch gender {
case .Female: return .Female
case .Male: return .Male
}
} else {
return .Undefined
}
}
}
public enum MMGender: Int {
case Female
case Male
public var name: String {
switch self {
case .Female : return "Female"
case .Male : return "Male"
}
}
static func make(with name: String) -> MMGender? {
switch name {
case "Female":
return MMGender.Female
case "Male":
return MMGender.Male
default:
return nil
}
}
}
@objcMembers public final class MMPhone: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable {
public let number: String
public var preferred: Bool
// more properties needed? ok but look at the code below first.
required init?(dictRepresentation dict: DictionaryRepresentation) {
fatalError("init(dictRepresentation:) has not been implemented")
}
var dictionaryRepresentation: DictionaryRepresentation {
return ["number": number]
}
public override var hash: Int {
return number.hashValue// ^ preferred.hashValue // use hasher combine
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMPhone else {
return false
}
return self.number == object.number // preferred is not supported yet on mobile api
}
convenience init?(json: JSON) {
let preferred = false
guard let number = json["number"].string else { // preferred is not supported yet on mobile api
return nil
}
self.init(number: number, preferred: preferred)
}
public init(number: String, preferred: Bool) {
self.number = number
self.preferred = preferred
}
required public init?(coder aDecoder: NSCoder) {
number = aDecoder.decodeObject(forKey: "number") as! String
preferred = aDecoder.decodeBool(forKey: "preferred")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(number, forKey: "number")
aCoder.encode(preferred, forKey: "preferred")
}
}
@objcMembers public final class MMEmail: NSObject, NSCoding, JSONDecodable, DictionaryRepresentable {
public let address: String
public var preferred: Bool
// more properties needed? ok but look at the code below first.
required init?(dictRepresentation dict: DictionaryRepresentation) {
fatalError("init(dictRepresentation:) has not been implemented")
}
var dictionaryRepresentation: DictionaryRepresentation {
return ["address": address]
}
public override var hash: Int {
return address.hashValue// ^ preferred.hashValue // use hasher combine
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMEmail else {
return false
}
return self.address == object.address
}
convenience init?(json: JSON) {
let preferred = false
guard let address = json["address"].string else { // preferred is not supported yet on mobile api
return nil
}
self.init(address: address, preferred: preferred)
}
public init(address: String, preferred: Bool) {
self.address = address
self.preferred = preferred
}
required public init?(coder aDecoder: NSCoder) {
address = aDecoder.decodeObject(forKey: "address") as! String
preferred = aDecoder.decodeBool(forKey: "preferred")
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(address, forKey: "address")
aCoder.encode(preferred, forKey: "preferred")
}
}
@objcMembers public class MMUserIdentity: NSObject {
public let phones: [String]?
public let emails: [String]?
public let externalUserId: String?
/// Default initializer. The object won't be initialized if all three arguments are nil/empty. Unique user identity must have at least one value.
@objc public init?(phones: [String]?, emails: [String]?, externalUserId: String?) {
if (phones == nil || phones!.isEmpty) && (emails == nil || emails!.isEmpty) && externalUserId == nil {
return nil
}
self.phones = phones
self.emails = emails
self.externalUserId = externalUserId
}
}
@objcMembers public class MMUserAttributes: NSObject, DictionaryRepresentable {
/// The user's first name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var firstName: String?
/// A user's middle name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var middleName: String?
/// A user's last name. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var lastName: String?
/// A user's tags. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var tags: Set<String>?
/// A user's gender. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var gender: MMGender?
public var genderNonnull: MMGenderNonnull {
set { gender = newValue.toGender }
get { return MMGenderNonnull.make(from: gender) }
}
/// A user's birthday. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var birthday: Date?
/// Returns user's custom data. Arbitrary attributes that are related to a particular user. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var customAttributes: [String: MMAttributeType]? {
willSet {
newValue?.assertCustomAttributesValid()
}
}
convenience public init(firstName: String?
,middleName: String?
,lastName: String?
,tags: Set<String>?
,genderNonnull: MMGenderNonnull
,birthday: Date?
,customAttributes: [String: MMAttributeType]?) {
self.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: genderNonnull.toGender, birthday: birthday, customAttributes: customAttributes)
}
public init(firstName: String?
,middleName: String?
,lastName: String?
,tags: Set<String>?
,gender: MMGender?
,birthday: Date?
,customAttributes: [String: MMAttributeType]?) {
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
self.tags = tags
self.gender = gender
self.birthday = birthday
self.customAttributes = customAttributes
}
public required convenience init?(dictRepresentation dict: DictionaryRepresentation) {
let value = JSON.init(dict)
self.init(firstName: value["firstName"].string,
middleName: value["middleName"].string,
lastName: value["lastName"].string,
tags: arrayToSet(arr: value["tags"].arrayObject as? [String]),
gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }),
birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON)
}
public var dictionaryRepresentation: DictionaryRepresentation {
return [
"firstName" : firstName as Any,
"middleName" : middleName as Any,
"lastName" : lastName as Any,
"tags" : tags?.asArray as Any,
"gender" : gender?.name as Any,
"birthday" : birthday.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.string(from: $0) }) as Any,
"customAttributes" : UserDataMapper.makeCustomAttributesPayload(customAttributes) as Any
]
}
}
@objcMembers public final class MMUser: MMUserAttributes, JSONDecodable, NSCoding, NSCopying, Archivable {
var version: Int = 0
static var currentPath = getDocumentsDirectory(filename: "user")
static var dirtyPath = getDocumentsDirectory(filename: "dirty-user")
static var cached = ThreadSafeDict<MMUser>()
static var empty: MMUser {
return MMUser(externalUserId: nil, firstName: nil, middleName: nil, lastName: nil, phones: nil, emails: nil, tags: nil, gender: nil, birthday: nil, customAttributes: nil, installations: nil)
}
func removeSensitiveData() {
if MobileMessaging.privacySettings.userDataPersistingDisabled == true {
self.firstName = nil
self.middleName = nil
self.lastName = nil
self.gender = nil
self.emails = nil
self.phones = nil
self.customAttributes = nil
self.birthday = nil
self.externalUserId = nil
}
}
func handleCurrentChanges(old: MMUser, new: MMUser) {
// nothing to do
}
func handleDirtyChanges(old: MMUser, new: MMUser) {
// nothing to do
}
//
static var delta: [String: Any]? {
guard let currentUserDict = MobileMessaging.sharedInstance?.currentUser().dictionaryRepresentation, let dirtyUserDict = MobileMessaging.sharedInstance?.dirtyUser().dictionaryRepresentation else {
return [:]
}
return deltaDict(currentUserDict, dirtyUserDict)
}
/// The user's id you can provide in order to link your own unique user identifier with Mobile Messaging user id, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var externalUserId: String?
/// User's phone numbers. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var phones: Array<String>? {
set {
phonesObjects = newValue?.map({ return MMPhone(number: $0, preferred: false) })
}
get {
return phonesObjects?.map({ return $0.number })
}
}
var phonesObjects: Array<MMPhone>?
/// User's email addresses. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var emails: Array<String>? {
set {
emailsObjects = newValue?.map({ return MMEmail(address: $0, preferred: false) })
}
get {
return emailsObjects?.map({ return $0.address })
}
}
var emailsObjects: Array<MMEmail>?
/// All installations personalized with the user
public internal(set) var installations: Array<MMInstallation>?
convenience init(userIdentity: MMUserIdentity, userAttributes: MMUserAttributes?) {
self.init(externalUserId: userIdentity.externalUserId, firstName: userAttributes?.firstName, middleName: userAttributes?.middleName, lastName: userAttributes?.lastName, phones: userIdentity.phones, emails: userIdentity.emails, tags: userAttributes?.tags, gender: userAttributes?.gender, birthday: userAttributes?.birthday, customAttributes: userAttributes?.customAttributes, installations: nil)
}
init(externalUserId: String?
,firstName: String?
,middleName: String?
,lastName: String?
,phones: Array<String>?
,emails: Array<String>?
,tags: Set<String>?
,gender: MMGender?
,birthday: Date?
,customAttributes: [String: MMAttributeType]?
,installations: Array<MMInstallation>?) {
super.init(firstName: firstName, middleName: middleName, lastName: lastName, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes)
self.installations = installations
self.externalUserId = externalUserId
self.phones = phones
self.emails = emails
}
convenience init?(json value: JSON) {
self.init(externalUserId: value[Attributes.externalUserId.rawValue].string,
firstName: value[Attributes.firstName.rawValue].string,
middleName: value[Attributes.middleName.rawValue].string,
lastName: value[Attributes.lastName.rawValue].string,
phones: value[Attributes.phones.rawValue].array?.compactMap({ return MMPhone(json: $0)?.number }),
emails: value[Attributes.emails.rawValue].array?.compactMap({ return MMEmail(json: $0)?.address }),
tags: arrayToSet(arr: value[Attributes.tags.rawValue].arrayObject as? [String]),
gender: value[Attributes.gender.rawValue].string.ifSome({ MMGender.make(with: $0) }),
birthday: value[Attributes.birthday.rawValue].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value[Attributes.customAttributes.rawValue].dictionary?.decodeCustomAttributesJSON,
installations: value[Attributes.instances.rawValue].array?.compactMap({ MMInstallation(json: $0) }))
}
// must be extracted to cordova plugin srcs
public required convenience init?(dictRepresentation dict: DictionaryRepresentation) {
let value = JSON.init(dict)
self.init(externalUserId: value["externalUserId"].string,
firstName: value["firstName"].string,
middleName: value["middleName"].string,
lastName: value["lastName"].string,
phones: (value["phones"].arrayObject as? [String])?.compactMap({ return MMPhone(number: $0, preferred: false).number }),
emails: (value["emails"].arrayObject as? [String])?.compactMap({ return MMEmail(address: $0, preferred: false).address }),
tags: arrayToSet(arr: value["tags"].arrayObject as? [String]),
gender: value["gender"].string.ifSome({ MMGender.make(with: $0) }),
birthday: value["birthday"].string.ifSome({ DateStaticFormatters.ContactsServiceDateFormatter.date(from: $0) }),
customAttributes: value["customAttributes"].dictionary?.decodeCustomAttributesJSON,
installations: value["installations"].array?.compactMap({ MMInstallation(json: $0) }))
}
public override var dictionaryRepresentation: DictionaryRepresentation {
var ret = super.dictionaryRepresentation
ret["externalUserId"] = externalUserId as Any
ret["phones"] = phones as Any
ret["emails"] = emails as Any
ret["installations"] = installations?.map({ return $0.dictionaryRepresentation }) as Any
return ret
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMUser else {
return false
}
return externalUserId == object.externalUserId &&
firstName == object.firstName &&
middleName == object.middleName &&
lastName == object.lastName &&
phones == object.phones &&
emails == object.emails &&
tags == object.tags &&
gender == object.gender &&
contactsServiceDateEqual(birthday, object.birthday) &&
customAttributes == object.customAttributes &&
installations == object.installations
}
required public init?(coder aDecoder: NSCoder) {
super.init(firstName: aDecoder.decodeObject(forKey: "firstName") as? String,
middleName: aDecoder.decodeObject(forKey: "middleName") as? String,
lastName: aDecoder.decodeObject(forKey: "lastName") as? String,
tags: arrayToSet(arr: aDecoder.decodeObject(forKey: "tags") as? [String]),
gender: MMGender(rawValue: (aDecoder.decodeObject(forKey: "gender") as? Int) ?? 999) ,
birthday: aDecoder.decodeObject(forKey: "birthday") as? Date,
customAttributes: aDecoder.decodeObject(forKey: "customAttributes") as? [String: MMAttributeType])
externalUserId = aDecoder.decodeObject(forKey: "externalUserId") as? String
phonesObjects = aDecoder.decodeObject(forKey: "phones") as? Array<MMPhone>
emailsObjects = aDecoder.decodeObject(forKey: "emails") as? Array<MMEmail>
installations = aDecoder.decodeObject(forKey: "installations") as? Array<MMInstallation>
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(externalUserId, forKey: "externalUserId")
aCoder.encode(firstName, forKey: "firstName")
aCoder.encode(middleName, forKey: "middleName")
aCoder.encode(lastName, forKey: "lastName")
aCoder.encode(phonesObjects, forKey: "phones")
aCoder.encode(emailsObjects, forKey: "emails")
aCoder.encode(tags, forKey: "tags")
aCoder.encode(gender?.rawValue, forKey: "gender")
aCoder.encode(birthday, forKey: "birthday")
aCoder.encode(customAttributes, forKey: "customAttributes")
aCoder.encode(installations, forKey: "installations")
}
public func copy(with zone: NSZone? = nil) -> Any {
return MMUser(externalUserId: externalUserId, firstName: firstName, middleName: middleName, lastName: lastName, phones: phones, emails: emails, tags: tags, gender: gender, birthday: birthday, customAttributes: customAttributes, installations: installations)
}
}
|
b2d797a0314e358c5f4724a24c5a7179
| 37.74359 | 396 | 0.7372 | false | false | false | false |
mahabaleshwarhnr/GitHub-challenges---iOS
|
refs/heads/master
|
GithubApiDemo/GithubApiDemo/Tasks/HttpTasksHandler.swift
|
mit
|
1
|
//
// HttpTasksHandler.swift
// GithubApiDemo
//
// Created by Mahabaleshwar on 23/08/16.
// Copyright © 2016 DP Samant. All rights reserved.
//
import Foundation
import UIKit
class HttpTasksHandler {
typealias CompletionHandler = (reponseData: NSData?, response: NSURLResponse?, error: NSError?) -> Void
var completionHandler: CompletionHandler?
var taskType: HttpTaskType = .None
var dataTask: NSURLSessionDataTask?
private var hostUrl: String?
let defaultSession: NSURLSession
//MARK:- Initialization
init?() {
defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
}
func sendGetRequest(taskType: HttpTaskType,info:[String: AnyObject]?, completionHandler:CompletionHandler) -> Void {
self.completionHandler = completionHandler
switch taskType {
case .DownloadRepositories:
let language = (info!["langauage"] as! String).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
self.hostUrl = UrlBuilder.getRepositoriesUrl(language!)
downloadRepositoriesList(language!, completionHandler: completionHandler)
break
default:
break
}
}
////MARK:- Helper Methods
func downloadRepositoriesList(langauage: String, completionHandler: CompletionHandler) -> Void {
let serviceUrl = NSURL(string: self.hostUrl!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
self.dataTask = self.defaultSession.dataTaskWithURL(serviceUrl!, completionHandler: { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
//completionHandler(reponseData: data!, response: response!, error: error!)
self.completionHandler!(reponseData: data, response: response, error: error)
}
})
dataTask?.resume()
}
}
|
6227e6717f9b128cf39672fee0c801fc
| 32.166667 | 155 | 0.656007 | false | false | false | false |
DRybochkin/Spika.swift
|
refs/heads/master
|
Spika/Views/ImagePreviewView/CSImagePreviewView.swift
|
mit
|
1
|
//
// ImagePreviewView.h
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import UIKit
class CSImagePreviewView: CSBasePreviewView {
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var backGroundView: UIView!
@IBOutlet weak var localImage: UIImageView!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
@IBAction func onClose(_ sender: Any) {
dismiss()
}
override func initializeView(message: CSMessageModel!, size: Float, dismiss: dismissPreview!) {
self.dismiss = dismiss
var viewRect: CGRect = UIScreen.main.bounds
viewRect.size.height = viewRect.size.height - CGFloat(size)
var className: String = String(describing: type(of: self))
className = className.replacingOccurrences(of: Bundle.main.object(forInfoDictionaryKey: "CFBundleExecutable") as! String, with: "")
className = className.replacingOccurrences(of: ".", with: "")
let path: String! = Bundle.main.path(forResource: className, ofType: "nib")
if (!FileManager.default.fileExists(atPath: path)) {
return
}
var array: [Any]! = Bundle.main.loadNibNamed(className, owner: self, options: nil)
assert(array.count == 1, "Invalid number of nibs")
frame = viewRect
let backGR: UIView! = array[0] as! UIView
backGR?.frame = viewRect
addSubview(backGR)
closeButton.layer.cornerRadius = closeButton.frame.size.width / 2
closeButton.layer.masksToBounds = true
closeButton.backgroundColor = kAppDefaultColor(0.8)
backGroundView.layer.cornerRadius = 10
backGroundView.layer.masksToBounds = true
setImage(message: message)
}
func setImage(path: String) {
localImage.image = UIImage(contentsOfFile: path)
localImage.contentMode = .scaleAspectFit
loadingIndicator.stopAnimating()
loadingIndicator.isHidden = true
}
func setImage(message: CSMessageModel) {
localImage.layer.cornerRadius = 8
localImage.layer.masksToBounds = true
if (message.file.thumb != nil) {
localImage.sd_setImage(with: URL(string: CSUtils.generateDownloadURLFormFileId(message.file.thumb.id)))
} else if (message.file.file != nil) {
localImage.sd_setImage(with: URL(string: CSUtils.generateDownloadURLFormFileId(message.file.file.id)))
}
}
}
|
0b7384ae18389fe643a8227144428a85
| 39.290323 | 139 | 0.672538 | false | false | false | false |
BitBaum/Swift-Big-Integer
|
refs/heads/master
|
Tests/BIntTests.swift
|
mit
|
1
|
//
// BInt.swift
// BigNumberTests
//
// Created by Zachary Gorak on 3/2/18.
// Copyright © 2018 Marcel Kröker. All rights reserved.
//
import XCTest
class BIntTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRadixInitializerAndGetter()
{
let chars: [Character] = [
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g",
"h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
"y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
]
for _ in 0..<1000
{
let fromBase = math.random(2...62)
let toBase = math.random(2...62)
let numLength = math.random(1...10)
var num = math.random(0...1) == 1 ? "-" : ""
for i in 0..<numLength
{
if i == 0
{
num.append(chars[math.random(1..<fromBase)])
}
else
{
num.append(chars[math.random(0..<fromBase)])
}
}
// Convert the random number to a BInt type
let b1 = BInt(num, radix: fromBase)
// Get the number as a string with the second base
let s1 = b1!.asString(radix: toBase)
// Convert that number to a BInt type
let b2 = BInt(s1, radix: toBase)
// Get the number back as as string in the start base
let s2 = b2!.asString(radix: fromBase)
XCTAssert(b1 == b2)
XCTAssert(s2 == num)
}
let bigHex = "abcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdef00"
let x = BInt(bigHex, radix: 16)!
XCTAssert(x.asString(radix: 16) == bigHex)
}
func testRadix() {
XCTAssert(BInt("ffff",radix:16) == 65535)
XCTAssert(BInt("ff",radix:16) == 255.0)
XCTAssert(BInt("ff",radix:16) != 100.0)
XCTAssert(BInt("ffff",radix:16)! > 255.0)
XCTAssert(BInt("f",radix:16)! < 255.0)
XCTAssert(BInt("0",radix:16)! <= 1.0)
XCTAssert(BInt("f", radix: 16)! >= 1.0)
XCTAssert(BInt("rfff",radix:16) == nil)
XCTAssert(BInt("ffff",radix:16) == 65535)
XCTAssert(BInt("rfff",radix:16) == nil)
XCTAssert(BInt("ff",radix:10) == nil)
XCTAssert(BInt("255",radix:6) == 107)
XCTAssert(BInt("999",radix:10) == 999)
XCTAssert(BInt("ff",radix:16) == 255.0)
XCTAssert(BInt("ff",radix:16) != 100.0)
XCTAssert(BInt("ffff",radix:16)! > 255.0)
XCTAssert(BInt("f",radix:16)! < 255.0)
XCTAssert(BInt("0",radix:16)! <= 1.0)
XCTAssert(BInt("f",radix:16)! >= 1.0)
XCTAssert(BInt("44",radix:5) == 24)
XCTAssert(BInt("44",radix:5) != 100.0)
XCTAssert(BInt("321",radix:5)! == 86)
XCTAssert(BInt("3",radix:5)! < 255.0)
XCTAssert(BInt("0",radix:5)! <= 1.0)
XCTAssert(BInt("4",radix:5)! >= 1.0)
XCTAssert(BInt("923492349",radix:32)! == 9967689075849)
}
func testPerformanceStringInit() {
self.measure {
for _ in (0...15000) {
let _ = BInt(String(arc4random()))
}
}
}
func testPerformanceStringRadixInit() {
self.measure {
for _ in (0...15000) {
let _ = BInt(String(arc4random()), radix: 10)
}
}
}
}
|
6b5d6b3e8172ea439b055a9742a22802
| 28.769231 | 283 | 0.59977 | false | true | false | false |
alex-vasenin/SwiftAA
|
refs/heads/master
|
Tests/SwiftAATests/TimesTests.swift
|
mit
|
1
|
//
// TimesTests.swift
// SwiftAA
//
// Created by Cédric Foellmi on 20/02/2017.
// Copyright © 2017 onekiloparsec. All rights reserved.
//
import XCTest
@testable import SwiftAA
class TimesTests: XCTestCase {
func testHourMinusSignConstructor() {
XCTAssertEqual(Hour(.minus, 1, 7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, 7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, -7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, 7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, -7, 30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, 1, -7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, 7, -30.0).value, -1.125)
XCTAssertEqual(Hour(.minus, -1, -7, -30.0).value, -1.125)
}
func testHourPlusSignConstructor() {
XCTAssertEqual(Hour(.plus, 1, 7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, 7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, -7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, 7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, -7, 30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, -7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, -1, 7, -30.0).value, 1.125)
XCTAssertEqual(Hour(.plus, 1, -7, -30.0).value, 1.125)
}
func testHourMinusZeroSignConstructor() {
XCTAssertEqual(Hour(.minus, 0, 7, 30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, -7, 30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, 7, -30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, -7, -30.0).value, -0.125)
XCTAssertEqual(Hour(.minus, 0, 0, 90.0).value, -0.025)
XCTAssertEqual(Hour(.minus, 0, 0, -90.0).value, -0.025)
}
func testHourPlusZeroSignConstructor() {
XCTAssertEqual(Hour(.plus, 0, 7, 30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, -7, 30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, 7, -30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, -7, -30.0).value, 0.125)
XCTAssertEqual(Hour(.plus, 0, 0, 90.0).value, 0.025)
XCTAssertEqual(Hour(.plus, 0, 0, -90.0).value, 0.025)
}
func testHourSexagesimalTransform() {
let hplus = Hour(1.125)
let hplussexagesimal: SexagesimalNotation = (.plus, 1, 7, 30.0)
XCTAssertTrue(hplus.sexagesimal == hplussexagesimal)
let hminus = Hour(-1.125)
let hminussexagesimal: SexagesimalNotation = (.minus, 1, 7, 30.0)
XCTAssertTrue(hminus.sexagesimal == hminussexagesimal)
}
// See AATests.cpp
func testTTtoUTRoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT
XCTAssertEqual(northwardEquinox, JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
// TT -> UT
XCTAssertEqual(northwardEquinox.TTtoUTC(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 33.112424))
// TT -> UT -> TT
XCTAssertEqual(northwardEquinox.TTtoUTC().UTCtoTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// See AATests.cpp
func testTTtoTAIRoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT -> TAI
XCTAssertEqual(northwardEquinox.TTtoTAI(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 35.047155))
// TT -> TAI -> TT
XCTAssertEqual(northwardEquinox.TTtoTAI().TAItoTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// See AATests.cpp
func testTTtoUT1RoundTripping() {
let earth = Earth(julianDay: JulianDay(year: 1962, month: 1, day: 1), highPrecision: false)
let northwardEquinox = earth.equinox(of: .northwardSpring)
XCTAssertEqual(northwardEquinox.value, JulianDay(2437744.6042503607).value)
// TT -> UT1
XCTAssertEqual(northwardEquinox.TTtoUT1(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 29, second: 33.140024))
// TT -> UT1 -> TT
XCTAssertEqual(northwardEquinox.TTtoUT1().UT1toTT(), JulianDay(year: 1962, month: 3, day: 21, hour: 2, minute: 30, second: 7.231168))
}
// Based on data downloadable from http://tycho.usno.navy.mil/systime.html
func testUT1minusUTC() {
let jd1 = JulianDay(modified: 58018.0) // 2017 9 22, the day of writing this test...
AssertEqual(jd1.UT1minusUTC(), Second(0.32103), accuracy: Second(0.01))
let jd2 = JulianDay(modified: 58118.0) // 2017 12 31
// Expected value in aaplus-1.91 = 0.19553
// Expected value in aaplus-1.99 = 0.21742
AssertEqual(jd2.UT1minusUTC(), Second(0.21742), accuracy: Second(0.001))
// Not sure why the one below fails.
// let jd3 = JulianDay(modified: 58382.0) // 2018 9 21
// AssertEqual(jd3.UT1minusUTC(), Second(-0.07169), accuracy: Second(0.01))
}
func testDaysSince2000January1() {
XCTAssertEqual(JulianDay(year: 2017, month: 9, day: 23, hour: 9, minute: 0, second: 0.0).date.daysSince2000January1(), 6476)
}
func testDayConversions() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Day(t1).inHours.value, t1*24.0)
XCTAssertEqual(Day(t2).inHours.value, t2*24.0)
XCTAssertEqual(Day(t1).inMinutes.value, t1*24.0*60.0)
XCTAssertEqual(Day(t2).inMinutes.value, t2*24.0*60.0)
XCTAssertEqual(Day(t1).inSeconds.value, t1*24.0*3600.0)
XCTAssertEqual(Day(t2).inSeconds.value, t2*24.0*3600.0)
XCTAssertEqual(Day(t1).inJulianDays.value, t1)
}
func testHourConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Hour(t1).inDays.value, t1/24.0)
XCTAssertEqual(Hour(t2).inDays.value, t2/24.0)
XCTAssertEqual(Hour(t1).inMinutes.value, t1*60.0)
XCTAssertEqual(Hour(t2).inMinutes.value, t2*60.0)
XCTAssertEqual(Hour(t1).inSeconds.value, t1*3600.0)
XCTAssertEqual(Hour(t2).inSeconds.value, t2*3600.0)
XCTAssertEqual(Hour(12.0).inRadians.value, .pi, accuracy: 0.00000000001) // rounding errors
XCTAssertEqual(Hour(-6.0).inRadians.value, -.pi/2.0, accuracy: 0.00000000001) // rounding errors
}
func testMinuteConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Minute(t1).inDays.value, t1/(24.0*60.0))
XCTAssertEqual(Minute(t2).inDays.value, t2/(24.0*60.0))
XCTAssertEqual(Minute(t1).inHours.value, t1/60.0)
XCTAssertEqual(Minute(t2).inHours.value, t2/60.0)
XCTAssertEqual(Minute(t1).inSeconds.value, t1*60.0)
XCTAssertEqual(Minute(t2).inSeconds.value, t2*60.0)
}
func testSecondConversion() {
let t1 = 3.1415
let t2 = -2.718
XCTAssertEqual(Second(t1).inDays.value, t1/(24.0*3600.0))
XCTAssertEqual(Second(t2).inDays.value, t2/(24.0*3600.0))
XCTAssertEqual(Second(t1).inHours.value, t1/3600.0)
XCTAssertEqual(Second(t2).inHours.value, t2/3600.0)
XCTAssertEqual(Second(t1).inMinutes.value, t1/60.0)
XCTAssertEqual(Second(t2).inMinutes.value, t2/60.0)
}
func testHourReduce() {
AssertEqual(Hour(-25).reduced, Hour(23))
AssertEqual(Hour(-23).reduced, Hour(1))
AssertEqual(Hour(-13).reduced, Hour(11))
AssertEqual(Hour(-1).reduced, Hour(23))
AssertEqual(Hour(1).reduced, Hour(1))
AssertEqual(Hour(13).reduced, Hour(13))
AssertEqual(Hour(23).reduced, Hour(23))
AssertEqual(Hour(25).reduced, Hour(1))
}
func testHourReduce0() {
AssertEqual(Hour(-25).reduced0, Hour(-1))
AssertEqual(Hour(-23).reduced0, Hour(1))
AssertEqual(Hour(-13).reduced0, Hour(11))
AssertEqual(Hour(-1).reduced0, Hour(-1))
AssertEqual(Hour(1).reduced0, Hour(1))
AssertEqual(Hour(13).reduced0, Hour(-11))
AssertEqual(Hour(23).reduced0, Hour(-1))
AssertEqual(Hour(25).reduced0, Hour(1))
}
func testMinuteReduce() {
AssertEqual(Minute(-61).reduced, Minute(59))
AssertEqual(Minute(-59).reduced, Minute(1))
AssertEqual(Minute(-31).reduced, Minute(29))
AssertEqual(Minute(-1).reduced, Minute(59))
AssertEqual(Minute(1).reduced, Minute(1))
AssertEqual(Minute(31).reduced, Minute(31))
AssertEqual(Minute(59).reduced, Minute(59))
AssertEqual(Minute(61).reduced, Minute(1))
}
func testDescriptions() {
XCTAssertNotNil(String(describing: Day(3.141519)))
XCTAssertNotNil(String(describing: Hour(3.141519)))
XCTAssertNotNil(String(describing: Minute(3.141519)))
XCTAssertNotNil(String(describing: Second(3.141519)))
}
}
|
029e68907d0c41c1392ecf6706f2babb
| 41.066964 | 141 | 0.615515 | false | true | false | false |
1457792186/JWSwift
|
refs/heads/master
|
SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGAssertGridViewCell.swift
|
apache-2.0
|
1
|
//
// LGAssertGridViewCell.swift
// LGChatViewController
//
// Created by jamy on 10/22/15.
// Copyright © 2015 jamy. All rights reserved.
//
import UIKit
class LGAssertGridViewCell: UICollectionViewCell {
let buttonWidth: CGFloat = 30
var assetIdentifier: String!
var imageView:UIImageView!
var playIndicator: UIImageView?
var selectIndicator: UIButton
var assetModel: LGAssetModel! {
didSet {
if assetModel.asset.mediaType == .video {
self.playIndicator?.isHidden = false
} else {
self.playIndicator?.isHidden = true
}
}
}
var buttonSelect: Bool {
willSet {
if newValue {
selectIndicator.isSelected = true
selectIndicator.setImage(UIImage(named: "CellBlueSelected"), for: UIControlState())
} else {
selectIndicator.isSelected = false
selectIndicator.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
}
}
}
override init(frame: CGRect) {
selectIndicator = UIButton(type: .custom)
selectIndicator.tag = 1
buttonSelect = false
super.init(frame: frame)
imageView = UIImageView(frame: bounds)
//imageView.contentMode = .ScaleAspectFit
contentView.addSubview(imageView)
playIndicator = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
playIndicator?.center = contentView.center
playIndicator?.image = UIImage(named: "mmplayer_idle")
contentView.addSubview(playIndicator!)
playIndicator?.isHidden = true
selectIndicator.frame = CGRect(x: bounds.width - buttonWidth , y: 0, width: buttonWidth, height: buttonWidth)
contentView.addSubview(selectIndicator)
selectIndicator.setImage(UIImage(named: "CellGreySelected"), for: UIControlState())
backgroundColor = UIColor.white
imageView.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .top, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .right, relatedBy: .equal, toItem: contentView, attribute: .right, multiplier: 1, constant: 0))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .bottom, relatedBy: .equal, toItem: contentView, attribute: .bottom, multiplier: 1, constant: 0))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let durationTime = 0.3
func selectButton(_ button: UIButton) {
if button.tag == 1 {
button.tag = 0
let groupAnimation = CAAnimationGroup()
let animationZoomOut = CABasicAnimation(keyPath: "transform.scale")
animationZoomOut.fromValue = 0
animationZoomOut.toValue = 1.2
animationZoomOut.duration = 3/4 * durationTime
let animationZoomIn = CABasicAnimation(keyPath: "transform.scale")
animationZoomIn.fromValue = 1.2
animationZoomIn.toValue = 1.0
animationZoomIn.beginTime = 3/4 * durationTime
animationZoomIn.duration = 1/4 * durationTime
groupAnimation.animations = [animationZoomOut, animationZoomIn]
buttonSelect = true
assetModel.select = true
selectIndicator.layer.add(groupAnimation, forKey: "selectZoom")
} else {
button.tag = 1
buttonSelect = false
assetModel.select = false
}
}
}
|
3858ea2313812a6676f2a0494e994a5a
| 38.544554 | 178 | 0.634201 | false | false | false | false |
neilpa/Termios
|
refs/heads/master
|
Termios/Termios.swift
|
mit
|
1
|
//
// Termios.swift
// Termios
//
// Created by Neil Pankey on 3/20/15.
// Copyright (c) 2015 Neil Pankey. All rights reserved.
//
import Darwin.POSIX.termios
import ErrNo
import Result
/// Swift wrapper around the raw C `termios` structure.
public struct Termios {
// MARK: Constructors
/// Constructs an empty `Termios` structure.
public init() {
self.init(termios())
}
/// Constructs a `Termios` structure from a given file descriptor `fd`.
public static func fetch(fd: Int32) -> Result<Termios, ErrNo> {
var raw = termios()
return tryMap(tcgetattr(fd, &raw)) { _ in Termios(raw) }
}
// MARK: Properties
/// Input flags
public var inputFlags: InputFlags {
get { return InputFlags(raw.c_iflag) }
set { raw.c_iflag = newValue.rawValue }
}
/// Output flags
public var outputFlags: OutputFlags {
get { return OutputFlags(raw.c_oflag) }
set { raw.c_oflag = newValue.rawValue }
}
/// Control flags
public var controlFlags: ControlFlags {
get { return ControlFlags(raw.c_cflag) }
set { raw.c_cflag = newValue.rawValue }
}
/// Local flags
public var localFlags: LocalFlags {
get { return LocalFlags(raw.c_lflag) }
set { raw.c_lflag = newValue.rawValue }
}
/// Input speed
public var inputSpeed: UInt {
return raw.c_ispeed
}
/// Output speed
public var outputSpeed: UInt {
return raw.c_ispeed
}
// MARK: Operations
/// Updates the file descriptor's `Termios` structure.
public mutating func update(fd: Int32) -> Result<(), ErrNo> {
return try(tcsetattr(fd, TCSANOW, &raw))
}
/// Set the input speed.
public mutating func setInputSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetispeed(&raw, baud))
}
/// Set the output speed.
public mutating func setOutputSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetospeed(&raw, baud))
}
/// Set both input and output speed.
public mutating func setSpeed(baud: UInt) -> Result<(), ErrNo> {
return try(cfsetspeed(&raw, baud))
}
// MARK: Private
/// Wraps the `termios` structure.
private init(_ termios: Darwin.termios) {
raw = termios
}
/// The wrapped termios struct.
private var raw: termios
}
|
d9e0388601941c34f2ad979453137415
| 24.178947 | 75 | 0.60786 | false | false | false | false |
Davidde94/StemCode_iOS
|
refs/heads/master
|
StemCode/Siri/CreateNoteIntentHandler.swift
|
mit
|
1
|
//
// CreateNoteIntentHandler.swift
// Siri
//
// Created by David Evans on 06/09/2018.
// Copyright © 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
import Intents
import StemProjectKit
class CreateNoteIntentHandler: NSObject, INCreateNoteIntentHandling {
func resolveTitle(for intent: INCreateNoteIntent, with completion: @escaping (INSpeakableStringResolutionResult) -> Void) {
let result: INSpeakableStringResolutionResult
if let title = intent.title {
result = INSpeakableStringResolutionResult.success(with: title)
} else {
result = INSpeakableStringResolutionResult.needsValue()
}
completion(result)
}
func handle(intent: INCreateNoteIntent, completion: @escaping (INCreateNoteIntentResponse) -> Void) {
// guard let title = intent.title else {
// let response = INCreateNoteIntentResponse(code: .failure, userActivity: nil)
// completion(response)
// return
// }
//
// let project = Stem(name: title.spokenPhrase, image: nil)
// StemManager.shared.saveProject(project, isNew: true)
//
// let projectImage = INImage(imageData: project.image.pngData()!)
// let filesModifier = project.files.count == 1 ? "file" : "files"
// let projectInfo = "Empty Project - \(project.files.count) \(filesModifier)"
//
// let contents = [
// INImageNoteContent(image: projectImage),
// INTextNoteContent(text: projectInfo)
// ]
// let createdNote = INNote(title: title, contents: contents, groupName: nil, createdDateComponents: nil, modifiedDateComponents: nil, identifier: project.identifier)
// let response = INCreateNoteIntentResponse(code: .success, userActivity: nil)
// response.createdNote = createdNote
// completion(response)
}
}
|
c8d8c2ddb5edf4ad5c25de7208d90f58
| 31.132075 | 167 | 0.739871 | false | false | false | false |
exponent/exponent
|
refs/heads/master
|
apps/bare-expo/ios/BareExpo/AppDelegate.swift
|
bsd-3-clause
|
2
|
//
// AppDelegate.swift
// BareExpo
//
// Created by the Expo team on 5/27/20.
// Copyright © 2020 Expo. All rights reserved.
//
import Foundation
import ExpoModulesCore
import EXDevMenuInterface
#if EX_DEV_MENU_ENABLED
import EXDevMenu
#endif
#if FB_SONARKIT_ENABLED && canImport(FlipperKit)
import FlipperKit
#endif
@UIApplicationMain
class AppDelegate: ExpoAppDelegate, RCTBridgeDelegate, EXDevLauncherControllerDelegate {
var bridge: RCTBridge?
var launchOptions: [UIApplication.LaunchOptionsKey: Any]?
let useDevClient: Bool = false
override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
initializeFlipper(with: application)
window = UIWindow(frame: UIScreen.main.bounds)
self.launchOptions = launchOptions;
if (useDevClient) {
let controller = EXDevLauncherController.sharedInstance()
controller.start(with: window!, delegate: self, launchOptions: launchOptions);
} else {
initializeReactNativeBridge(launchOptions);
}
super.application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
@discardableResult
func initializeReactNativeBridge(_ launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> RCTBridge {
let bridge = reactDelegate.createBridge(delegate: self, launchOptions: launchOptions)
let rootView = reactDelegate.createRootView(bridge: bridge, moduleName: "main", initialProperties: nil)
let rootViewController = reactDelegate.createRootViewController()
rootView.backgroundColor = UIColor.white
rootViewController.view = rootView
window?.rootViewController = rootViewController
window?.makeKeyAndVisible()
self.bridge = bridge
return bridge
}
#if RCT_DEV
func bridge(_ bridge: RCTBridge!, didNotFindModule moduleName: String!) -> Bool {
return true
}
#endif
override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
if (useDevClient && EXDevLauncherController.sharedInstance().onDeepLink(url, options: options)) {
return true;
}
return RCTLinkingManager.application(app, open: url, options: options)
}
private func initializeFlipper(with application: UIApplication) {
#if FB_SONARKIT_ENABLED && canImport(FlipperKit)
let client = FlipperClient.shared()
let layoutDescriptorMapper = SKDescriptorMapper(defaults: ())
client?.add(FlipperKitLayoutPlugin(rootNode: application, with: layoutDescriptorMapper!))
client?.add(FKUserDefaultsPlugin(suiteName: nil))
client?.add(FlipperKitReactPlugin())
client?.add(FlipperKitNetworkPlugin(networkAdapter: SKIOSNetworkAdapter()))
client?.start()
#endif
}
// MARK: - RCTBridgeDelegate
func sourceURL(for bridge: RCTBridge!) -> URL! {
// DEBUG must be setup in Swift projects: https://stackoverflow.com/a/24112024/4047926
#if DEBUG
if (useDevClient) {
return EXDevLauncherController.sharedInstance().sourceUrl()
} else {
return RCTBundleURLProvider.sharedSettings()?.jsBundleURL(forBundleRoot: "index", fallbackResource: nil)
}
#else
return Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
func extraModules(for bridge: RCTBridge!) -> [RCTBridgeModule] {
var extraModules = [RCTBridgeModule]()
// You can inject any extra modules that you would like here, more information at:
// https://facebook.github.io/react-native/docs/native-modules-ios.html#dependency-injection
return extraModules
}
// MARK: - EXDevelopmentClientControllerDelegate
func devLauncherController(_ developmentClientController: EXDevLauncherController, didStartWithSuccess success: Bool) {
developmentClientController.appBridge = initializeReactNativeBridge(developmentClientController.getLaunchOptions())
}
}
|
f0d7cb40b33e013b189d2a97450fab41
| 34.196429 | 152 | 0.746068 | false | false | false | false |
Plotac/DouYu
|
refs/heads/master
|
DouYu/DouYu/Classes/Main/View/PageTitleView.swift
|
apache-2.0
|
2
|
//
// PageTitleView.swift
// DouYu
//
// Created by Plo on 2017/6/14.
// Copyright © 2017年 Plo. All rights reserved.
//
import UIKit
//Mark: - 定义常量
private let kScrollLineH : CGFloat = 2
private let kNormalColor : (CGFloat,CGFloat,CGFloat) = (85,85,85)
private let kSelectColor : (CGFloat,CGFloat,CGFloat) = (255,128,0)
//Mark: - 定义协议
protocol PageTitleViewDelegate : class{
func pagetTitleView(titleView: PageTitleView,selectIndex: Int)
}
//Mark: - 定义PageTitleView类
class PageTitleView : UIView {
//定义属性
//标题数组
fileprivate var titles : [String]
fileprivate var currentIndex : Int = 0
weak var delegate : PageTitleViewDelegate?
//懒加载属性
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
//滚动视图
fileprivate lazy var scrollView : UIScrollView = {
let scroll = UIScrollView()
scroll.showsHorizontalScrollIndicator = false
scroll.scrollsToTop = false
scroll.bounces = false
return scroll
}()
//滑块
fileprivate lazy var scrollLine : UIView = {
let line = UIView()
line.backgroundColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
return line
}()
// Mark: - 自定义构造函数
init(frame: CGRect , titles: [String]) {
self.titles = titles;
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//Mark: - 设置UI
extension PageTitleView {
fileprivate func setUpUI() {
//添加ScrollView
addSubview(scrollView)
scrollView.frame = bounds
//创建label
setUpTitleLabels()
//创建滑块和底线
setUpBottomLineAndScrollLine()
}
private func setUpTitleLabels() {
let labelW : CGFloat = frame.width/CGFloat(self.titles.count)
let labelH : CGFloat = frame.height - kScrollLineH
let labelY : CGFloat = 0.0
for (index,title) in self.titles.enumerated() {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16.0)
label.textAlignment = .center
label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
label.tag = index
label.text = title
label.isUserInteractionEnabled = true
let labelX = CGFloat(index) * labelW
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels.append(label)
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.labelClick(tap:)))
label.addGestureRecognizer(tapGes)
}
}
private func setUpBottomLineAndScrollLine() {
//底部横线
let bottomLine = UIView()
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height-lineH, width: frame.size.width, height: lineH)
bottomLine.backgroundColor = UIColor.lightGray
addSubview(bottomLine)
//滑块
scrollView.addSubview(scrollLine)
guard let firstLabel = titleLabels.first else { return }
firstLabel.textColor = UIColor.orange
scrollLine.frame = CGRect(x: 10, y: frame.height-kScrollLineH, width: firstLabel.frame.width-10*2, height: kScrollLineH)
}
}
//Mark: - 监听label点击事件
extension PageTitleView {
@objc fileprivate func labelClick(tap : UITapGestureRecognizer) {
//1.拿到点击之后的当前label
guard let currentLabel = tap.view as? UILabel else {
return
}
if currentIndex == currentLabel.tag {
delegate?.pagetTitleView(titleView: self, selectIndex: currentIndex)
return
}
currentLabel.textColor = UIColor(r: kSelectColor.0, g: kSelectColor.1, b: kSelectColor.2)
//2.点击之前的旧label
let oldLabel = titleLabels[currentIndex]
oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2)
currentIndex = currentLabel.tag
//3.滑块位置改变
let linePositionX = currentLabel.frame.width * CGFloat(currentLabel.tag) + 10
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = linePositionX
}
delegate?.pagetTitleView(titleView: self, selectIndex: currentIndex)
}
}
//Mark: - 对外暴露的方法
extension PageTitleView {
func setTitlesWith(progress: CGFloat,sourceIndex: Int,targetIndex: Int) {
//取出sourceLabel和targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
//滑块渐变
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = moveTotalX * progress
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + 10 + moveX
//颜色渐变
//1.颜色变化的总范围
let colorRange = (kSelectColor.0 - kNormalColor.0,kSelectColor.1 - kNormalColor.1,kSelectColor.2 - kNormalColor.2)
//2.变化sourceLabel颜色
sourceLabel.textColor = UIColor(r: kSelectColor.0 - colorRange.0 * progress, g: kSelectColor.1 - colorRange.1 * progress, b: kSelectColor.2 - colorRange.2 * progress)
//3.变化targetLabel颜色
targetLabel.textColor = UIColor(r: kNormalColor.0 + colorRange.0 * progress, g: kNormalColor.1 + colorRange.1 * progress, b: kNormalColor.2 + colorRange.2 * progress)
//4.记录最新的Index
currentIndex = targetIndex
}
}
|
52923860439b5f021f3539bad106c1ba
| 30.005405 | 174 | 0.613842 | false | false | false | false |
nathantannar4/Parse-Dashboard-for-iOS-Pro
|
refs/heads/master
|
Parse Dashboard for iOS/Views/CollectionViewCells/ActionSheetCell.swift
|
mit
|
1
|
//
// ActionSheetCell.swift
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 11/7/17.
//
import IGListKit
import UIKit
final class ActionSheetCell: UICollectionViewCell {
// MARK: - Properties
var image: UIImage? {
didSet {
imageView.image = image?.withRenderingMode(.alwaysTemplate)
}
}
var title: String? {
didSet {
textLabel.text = title
}
}
var style: UIAlertActionStyle = .default {
didSet {
switch style {
case .default, .cancel:
textLabel.textColor = .black
imageView.tintColor = .darkGray
contentView.backgroundColor = .white
rippleColor = UIColor.white.darker()
case .destructive:
textLabel.textColor = .white
imageView.tintColor = .white
contentView.backgroundColor = .red
rippleColor = UIColor.red.darker()
}
}
}
var ripplePercent: Float = 0.8 {
didSet {
setupRippleView()
}
}
var rippleColor: UIColor = UIColor(white: 0.9, alpha: 1) {
didSet {
rippleView.backgroundColor = rippleColor
}
}
var rippleBackgroundColor: UIColor {
get {
return rippleBackgroundView.backgroundColor ?? .clear
}
set {
rippleBackgroundView.backgroundColor = newValue
}
}
var rippleOverBounds: Bool = false
var shadowRippleRadius: Float = 1
var shadowRippleEnable: Bool = false
var trackTouchLocation: Bool = true
var touchUpAnimationTime: Double = 0.3
let rippleView = UIView()
let rippleBackgroundView = UIView()
fileprivate var tempShadowRadius: CGFloat = 0
fileprivate var tempShadowOpacity: Float = 0
fileprivate var touchCenterLocation: CGPoint?
fileprivate var rippleMask: CAShapeLayer? {
get {
if !rippleOverBounds {
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds,
cornerRadius: layer.cornerRadius).cgPath
return maskLayer
} else {
return nil
}
}
}
// MARK: - Subviews
private let imageView: UIImageView = {
let view = UIImageView()
view.contentMode = .scaleAspectFit
view.tintColor = .darkGray
return view
}()
private let textLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: .medium)
label.adjustsFontSizeToFitWidth = true
return label
}()
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
contentView.addSubview(imageView)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let bounds = contentView.bounds
let insets = UIEdgeInsets(top: 2, left: 16, bottom: 2, right: 16)
if image == nil {
textLabel.frame = UIEdgeInsetsInsetRect(bounds, insets)
imageView.frame = .zero
} else {
// Layout similar to a standard UITableViewCell
let height = bounds.height - insets.top - insets.bottom
let imageViewOrigin = CGPoint(x: insets.left, y: insets.top + 8)
let imageViewSize = CGSize(width: height - 16, height: height - 16)
imageView.frame = CGRect(origin: imageViewOrigin, size: imageViewSize)
let textLabelOrigin = CGPoint(x: imageViewOrigin.x + imageViewSize.width + 24,
y: insets.top)
let textLabelSize = CGSize(width: bounds.width - insets.right - imageViewOrigin.x - imageViewSize.width - 16,
height: height)
textLabel.frame = CGRect(origin: textLabelOrigin, size: textLabelSize)
}
setupRippleView()
if let knownTouchCenterLocation = touchCenterLocation {
rippleView.center = knownTouchCenterLocation
}
rippleBackgroundView.layer.frame = bounds
rippleBackgroundView.layer.mask = rippleMask
}
// MARK: - Selection Animation
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if trackTouchLocation {
rippleView.center = touches.first?.location(in: self) ?? contentView.center
} else {
rippleView.center = contentView.center
}
UIView.animate(withDuration: 0.1, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: nil)
rippleView.transform = CGAffineTransform(scaleX: 0.5, y: 0.5)
UIView.animate(withDuration: 0.7, delay: 0, options: [UIViewAnimationOptions.curveEaseOut, UIViewAnimationOptions.allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
}, completion: nil)
if shadowRippleEnable {
tempShadowRadius = layer.shadowRadius
tempShadowOpacity = layer.shadowOpacity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = shadowRippleRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = 1
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
layer.add(groupAnim, forKey:"shadow")
}
return super.touchesBegan(touches, with: event)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
animateToNormal()
}
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
animateToNormal()
}
fileprivate func setup() {
setupRippleView()
rippleBackgroundView.backgroundColor = rippleBackgroundColor
rippleBackgroundView.frame = bounds
rippleBackgroundView.addSubview(rippleView)
rippleBackgroundView.alpha = 0
contentView.insertSubview(rippleBackgroundView, at: 0)
layer.shadowRadius = 0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor(white: 0.0, alpha: 0.5).cgColor
}
fileprivate func setupRippleView() {
let size: CGFloat = bounds.width * CGFloat(ripplePercent)
let x: CGFloat = (bounds.width/2) - (size/2)
let y: CGFloat = (bounds.height/2) - (size/2)
let corner: CGFloat = size/2
rippleView.backgroundColor = rippleColor
rippleView.frame = CGRect(x: x, y: y, width: size, height: size)
rippleView.layer.cornerRadius = corner
}
fileprivate func animateToNormal() {
UIView.animate(withDuration: 0.5, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 1
}, completion: {(success: Bool) -> () in
UIView.animate(withDuration: self.touchUpAnimationTime, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: {
self.rippleBackgroundView.alpha = 0
}, completion: nil)
})
UIView.animate(withDuration: 0.7, delay: 0, options: [.curveEaseOut, .beginFromCurrentState, .allowUserInteraction],
animations: {
self.rippleView.transform = CGAffineTransform.identity
let shadowAnim = CABasicAnimation(keyPath:"shadowRadius")
shadowAnim.toValue = self.tempShadowRadius
let opacityAnim = CABasicAnimation(keyPath:"shadowOpacity")
opacityAnim.toValue = self.tempShadowOpacity
let groupAnim = CAAnimationGroup()
groupAnim.duration = 0.7
groupAnim.fillMode = kCAFillModeForwards
groupAnim.isRemovedOnCompletion = false
groupAnim.animations = [shadowAnim, opacityAnim]
self.layer.add(groupAnim, forKey:"shadowBack")
}, completion: nil)
}
}
|
a93bacb2a137ce0269883c8b5c6e88f8
| 35.949458 | 145 | 0.599707 | false | false | false | false |
Harley-xk/SimpleDataKit
|
refs/heads/master
|
SimpleDataKit/Classes/SQLite.swift
|
mit
|
1
|
//
// SQLite.swift
// Comet
//
// Created by Harley.xk on 2018/1/7.
//
import Foundation
public protocol DataType {
}
extension Int: DataType{}
extension String: DataType{}
extension Double: DataType{}
extension Bool: DataType{}
extension Date: DataType{}
public struct Field<T: DataType> {
public let name: String
public let optional: Bool
public let `default`: T?
public let primary: Bool
public let unique: Bool
}
public protocol IdentifierType {
}
extension Int: IdentifierType {}
//public struct Field {
//
// public enum DataType {
// case id(type: IdentifierType)
// case int
// case string(length: Int?)
// case double
// case bool
// case bytes
// case date
// case custom(type: String)
// }
//
// var name: String
// var dataType: DataType
//}
protocol SQLiteTable {
}
class Student: SQLiteTable {
var name = ""
var age = 0
// var tableMap: [KeyPath<SQLiteTable, DataType>: String] {
//
// let id = Field.id
// let builder = builder
// try builder.field(for: \.name)
//
// return [
// \Student.name: "name"
// ]
// }
}
protocol SQLiteEncodable: Encodable {
associatedtype SQLiteColumns where SQLiteColumns: CodingKey
}
extension SQLiteEncodable {
func encode(to encoder: Encoder) throws {
// let c = encoder.container(keyedBy: SQLiteColumns.self)
}
}
struct User: SQLiteEncodable {
var id = 0
var name = ""
var age = 0
enum SQLiteColumns: String, CodingKey {
case id
case name
case age
}
}
|
b4b83dbb59a90d36d89f9ca34bc12925
| 16.547368 | 64 | 0.593881 | false | false | false | false |
Raizlabs/SketchyCode
|
refs/heads/master
|
SketchyCode/Generation/Writer.swift
|
mit
|
1
|
//
// Writer.swift
// SketchyCode
//
// Created by Brian King on 10/3/17.
// Copyright © 2017 Brian King. All rights reserved.
//
import Foundation
// Writer is responsible for managing the structure of the generated output.
final class Writer {
static var indentation: String = " "
var content: String = ""
var level: Int = 0
func indent(work: () throws -> Void) throws {
level += 1
try work()
level -= 1
}
func block(appending: String = "", work: () throws -> Void) throws {
append(line: "{")
try indent(work: work)
append(line: "}\(appending)")
}
var addIndentation: Bool {
return content.count == 0 || content.last == "\n"
}
func append(line: String, addNewline: Bool = true) {
var value = ""
if addIndentation {
for _ in 0..<level {
value.append(Writer.indentation)
}
}
value.append(line)
if addNewline {
value.append("\n")
}
content.append(value)
}
}
|
ab735ffa91db2b02460895f5d132f9a1
| 22.434783 | 76 | 0.540816 | false | false | false | false |
wordpress-mobile/AztecEditor-iOS
|
refs/heads/develop
|
Aztec/Classes/Processor/ShortcodeAttribute.swift
|
gpl-2.0
|
2
|
import Foundation
public class ShortcodeAttribute: CustomReflectable {
// MARK: Value
public enum Value: Equatable, CustomReflectable {
case `nil`
case string(String)
// MARK: - Equatable
public static func == (lhs: ShortcodeAttribute.Value, rhs: ShortcodeAttribute.Value) -> Bool {
switch (lhs, rhs) {
case (.nil, .nil):
return true
case let (.string(l), .string(r)):
return l == r
default:
return false
}
}
// MARK: - CustomReflectable
public var customMirror: Mirror {
get {
switch self {
case .nil:
return Mirror(self, children: ["value": 0])
case .string(let string):
return Mirror(self, children: ["value": string])
}
}
}
}
// MARK: - Attribute definition
public let key: String
public let value: Value
// MARK: - Initializers
public init(key: String, value: Value) {
self.key = key
self.value = value
}
public init(key: String, value: String) {
self.key = key
self.value = .string(value)
}
public init(key: String) {
self.key = key
self.value = .nil
}
// MARK: - CustomReflectable
public var customMirror: Mirror {
get {
return Mirror(self, children: ["key": key, "value": value])
}
}
}
|
ec7ec9e1eb8baafea4a11dc22afc0588
| 23.19403 | 102 | 0.476249 | false | false | false | false |
slavapestov/swift
|
refs/heads/master
|
stdlib/public/SDK/CoreGraphics/CoreGraphics.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import CoreGraphics
import Darwin
//===----------------------------------------------------------------------===//
// CGGeometry
//===----------------------------------------------------------------------===//
public extension CGPoint {
static var zero: CGPoint {
@_transparent // @fragile
get { return CGPoint(x: 0, y: 0) }
}
@_transparent // @fragile
init(x: Int, y: Int) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
@_transparent // @fragile
init(x: Double, y: Double) {
self.init(x: CGFloat(x), y: CGFloat(y))
}
@available(*, unavailable, renamed="zero")
static var zeroPoint: CGPoint {
fatalError("can't retrieve unavailable property")
}
}
extension CGPoint : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["x": x, "y": y], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Point(Double(x), Double(y))
}
}
extension CGPoint : CustomDebugStringConvertible {
public var debugDescription: String {
return "(\(x), \(y))"
}
}
extension CGPoint : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGPoint, rhs: CGPoint) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
public extension CGSize {
static var zero: CGSize {
@_transparent // @fragile
get { return CGSize(width: 0, height: 0) }
}
@_transparent // @fragile
init(width: Int, height: Int) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
@_transparent // @fragile
init(width: Double, height: Double) {
self.init(width: CGFloat(width), height: CGFloat(height))
}
@available(*, unavailable, renamed="zero")
static var zeroSize: CGSize {
fatalError("can't retrieve unavailable property")
}
}
extension CGSize : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["width": width, "height": height], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Size(Double(width), Double(height))
}
}
extension CGSize : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(width), \(height))"
}
}
extension CGSize : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGSize, rhs: CGSize) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
public extension CGVector {
static var zero: CGVector {
@_transparent // @fragile
get { return CGVector(dx: 0, dy: 0) }
}
@_transparent // @fragile
init(dx: Int, dy: Int) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
@_transparent // @fragile
init(dx: Double, dy: Double) {
self.init(dx: CGFloat(dx), dy: CGFloat(dy))
}
@available(*, unavailable, renamed="zero")
static var zeroVector: CGVector {
fatalError("can't retrieve unavailable property")
}
}
extension CGVector : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGVector, rhs: CGVector) -> Bool {
return lhs.dx == rhs.dx && lhs.dy == rhs.dy
}
public extension CGRect {
static var zero: CGRect {
@_transparent // @fragile
get { return CGRect(x: 0, y: 0, width: 0, height: 0) }
}
static var null: CGRect {
@_transparent // @fragile
get { return CGRectNull }
}
static var infinite: CGRect {
@_transparent // @fragile
get { return CGRectInfinite }
}
@_transparent // @fragile
init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Double, y: Double, width: Double, height: Double) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
@_transparent // @fragile
init(x: Int, y: Int, width: Int, height: Int) {
self.init(origin: CGPoint(x: x, y: y),
size: CGSize(width: width, height: height))
}
var width: CGFloat {
@_transparent // @fragile
get { return CGRectGetWidth(self) }
}
var height: CGFloat {
@_transparent // @fragile
get { return CGRectGetHeight(self) }
}
var minX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMinX(self) }
}
var midX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMidX(self) }
}
var maxX: CGFloat {
@_transparent // @fragile
get { return CGRectGetMaxX(self) }
}
var minY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMinY(self) }
}
var midY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMidY(self) }
}
var maxY: CGFloat {
@_transparent // @fragile
get { return CGRectGetMaxY(self) }
}
var isNull: Bool {
@_transparent // @fragile
get { return CGRectIsNull(self) }
}
var isEmpty: Bool {
@_transparent // @fragile
get { return CGRectIsEmpty(self) }
}
var isInfinite: Bool {
@_transparent // @fragile
get { return CGRectIsInfinite(self) }
}
var standardized: CGRect {
@_transparent // @fragile
get { return CGRectStandardize(self) }
}
var integral: CGRect {
@_transparent // @fragile
get { return CGRectIntegral(self) }
}
@_transparent // @fragile
mutating func standardizeInPlace() {
self = standardized
}
@_transparent // @fragile
mutating func makeIntegralInPlace() {
self = integral
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="insetInPlace")
func insetBy(dx dx: CGFloat, dy: CGFloat) -> CGRect {
return CGRectInset(self, dx, dy)
}
@_transparent // @fragile
mutating func insetInPlace(dx dx: CGFloat, dy: CGFloat) {
self = insetBy(dx: dx, dy: dy)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="offsetInPlace")
func offsetBy(dx dx: CGFloat, dy: CGFloat) -> CGRect {
return CGRectOffset(self, dx, dy)
}
@_transparent // @fragile
mutating func offsetInPlace(dx dx: CGFloat, dy: CGFloat) {
self = offsetBy(dx: dx, dy: dy)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="unionInPlace")
func union(rect: CGRect) -> CGRect {
return CGRectUnion(self, rect)
}
@_transparent // @fragile
mutating func unionInPlace(rect: CGRect) {
self = union(rect)
}
@_transparent // @fragile
@warn_unused_result(mutable_variant="intersectInPlace")
func intersect(rect: CGRect) -> CGRect {
return CGRectIntersection(self, rect)
}
@_transparent // @fragile
mutating func intersectInPlace(rect: CGRect) {
self = intersect(rect)
}
@_transparent // @fragile
@warn_unused_result
func divide(atDistance: CGFloat, fromEdge: CGRectEdge)
-> (slice: CGRect, remainder: CGRect)
{
var slice = CGRect.zero
var remainder = CGRect.zero
CGRectDivide(self, &slice, &remainder, atDistance, fromEdge)
return (slice, remainder)
}
@_transparent // @fragile
@warn_unused_result
func contains(rect: CGRect) -> Bool {
return CGRectContainsRect(self, rect)
}
@_transparent // @fragile
@warn_unused_result
func contains(point: CGPoint) -> Bool {
return CGRectContainsPoint(self, point)
}
@_transparent // @fragile
@warn_unused_result
func intersects(rect: CGRect) -> Bool {
return CGRectIntersectsRect(self, rect)
}
@available(*, unavailable, renamed="zero")
static var zeroRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="infinite")
static var infiniteRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="null")
static var nullRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="standardized")
var standardizedRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="integral")
var integerRect: CGRect {
fatalError("can't retrieve unavailable property")
}
@available(*, unavailable, renamed="standardizeInPlace")
mutating func standardize() -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="makeIntegralInPlace")
mutating func integerize() {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="insetBy")
func rectByInsetting(dx dx: CGFloat, dy: CGFloat) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="insetInPlace")
func inset(dx dx: CGFloat, dy: CGFloat) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="offsetBy")
func rectByOffsetting(dx dx: CGFloat, dy: CGFloat) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="offsetInPlace")
func offset(dx dx: CGFloat, dy: CGFloat) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="unionInPlace")
mutating func union(withRect: CGRect) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="union")
func rectByUnion(withRect: CGRect) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="intersectInPlace")
mutating func intersect(withRect: CGRect) {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="intersect")
func rectByIntersecting(withRect: CGRect) -> CGRect {
fatalError("can't call unavailable function")
}
@available(*, unavailable, renamed="divide")
func rectsByDividing(atDistance: CGFloat, fromEdge: CGRectEdge)
-> (slice: CGRect, remainder: CGRect) {
fatalError("can't call unavailable function")
}
}
extension CGRect : CustomReflectable, CustomPlaygroundQuickLookable {
public func customMirror() -> Mirror {
return Mirror(self, children: ["origin": origin, "size": size], displayStyle: .Struct)
}
public func customPlaygroundQuickLook() -> PlaygroundQuickLook {
return .Rectangle(Double(origin.x), Double(origin.y), Double(size.width), Double(size.height))
}
}
extension CGRect : CustomDebugStringConvertible {
public var debugDescription : String {
return "(\(origin.x), \(origin.y), \(size.width), \(size.height))"
}
}
extension CGRect : Equatable {}
@_transparent // @fragile
@warn_unused_result
public func == (lhs: CGRect, rhs: CGRect) -> Bool {
return CGRectEqualToRect(lhs, rhs)
}
// Overlay the C names of these constants with transparent definitions. The
// C constants are opaque extern globals for no good reason.
public var CGPointZero: CGPoint {
@_transparent // @fragile
get { return CGPoint.zero }
}
public var CGRectZero: CGRect {
@_transparent // @fragile
get { return CGRect.zero }
}
public var CGSizeZero: CGSize {
@_transparent // @fragile
get { return CGSize.zero }
}
public var CGAffineTransformIdentity: CGAffineTransform {
@_transparent // @fragile
get { return CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0) }
}
|
8851097f62c85ac50ea97f07affe0d68
| 26.013761 | 98 | 0.650959 | false | false | false | false |
buscarini/Collectionist
|
refs/heads/master
|
Collectionist/Classes/DataSources/Collection/CollectionViewDataSource.swift
|
mit
|
1
|
//
// CollectionViewDataSource.swift
// Collectionist
//
// Created by Jose Manuel Sánchez Peñarroja on 15/10/15.
// Copyright © 2015 vitaminew. All rights reserved.
//
import UIKit
open class CollectionViewDataSource<T: Equatable, HeaderT: Equatable, FooterT: Equatable>: NSObject, UICollectionViewDataSource, UICollectionViewDelegate {
public typealias ListType = List<T,HeaderT, FooterT>
public typealias ListSectionType = ListSection<T,HeaderT, FooterT>
public typealias ListItemType = ListItem<T>
fileprivate var refreshControl: UIRefreshControl?
public init(view: UICollectionView) {
self.view = view
self.refreshControl = UIRefreshControl()
super.init()
self.refreshControl?.addTarget(self, action: #selector(CollectionViewDataSource.refresh(_:)), for: .valueChanged)
self.viewChanged()
}
open var view : UICollectionView {
didSet {
self.viewChanged()
}
}
open var list : ListType? {
didSet {
CollectionViewDataSource.registerViews(self.list, collectionView: self.view)
self.update(oldValue, newList: list)
}
}
fileprivate func viewChanged() {
CollectionViewDataSource.registerViews(self.list, collectionView: self.view)
self.view.dataSource = self
self.view.delegate = self
}
fileprivate func update(_ oldList: ListType?, newList: ListType?) {
self.updateView(oldList, newList: newList)
self.refreshControl?.endRefreshing()
if let refreshControl = self.refreshControl , newList?.configuration?.onRefresh != nil {
self.view.addSubview(refreshControl)
self.view.alwaysBounceVertical = true
}
else {
self.refreshControl?.removeFromSuperview()
}
if let list = newList, let scrollInfo = self.list?.scrollInfo, ListType.indexPathInsideBounds(list, indexPath: scrollInfo.indexPath) {
let indexPath = scrollInfo.indexPath
self.view.scrollToItem(at: indexPath, at: CollectionViewDataSource.scrollPositionWithPosition(scrollInfo.position, collectionView: self.view), animated: scrollInfo.animated)
}
}
fileprivate func updateView(_ oldList: ListType?, newList: ListType?) {
if let oldList = oldList, let newList = newList , ListType.sameItemsCount(oldList, newList) {
let visibleIndexPaths = view.indexPathsForVisibleItems
// let listItems: [ListItem<T>?] = visibleIndexPaths.map { indexPath -> ListItem<T>? in
// guard let item = indexPath.item else { return nil }
// return newList.sections[indexPath.section].items[item]
// }
//
// let cells = visibleIndexPaths.map {
// return view.cellForItem(at: $0)
// }
//
// Zip2Sequence(_sequence1: listItems, _sequence2: cells).map { listItem, cell in
// if let fillableCell = cell as? Fillable, let listItem = listItem {
// fillableCell.fill(listItem)
// }
// return nil
// }
for indexPath in visibleIndexPaths {
let item = indexPath.item
let cell = view.cellForItem(at: indexPath)
let listItem = newList.sections[indexPath.section].items[item]
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
}
}
else {
self.view.reloadData()
}
}
static func scrollPositionWithPosition(_ position: ListScrollPosition, collectionView: UICollectionView?) -> UICollectionViewScrollPosition {
guard let collectionView = collectionView else {
return []
}
let scrollDirection : UICollectionViewScrollDirection
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
scrollDirection = flowLayout.scrollDirection
}
else {
scrollDirection = .vertical
}
switch (position,scrollDirection) {
case (.begin,.horizontal):
return .left
case (.begin,.vertical):
return .top
case (.middle,.vertical):
return .centeredVertically
case (.middle,.horizontal):
return .centeredHorizontally
case (.end, .vertical):
return .bottom
case (.end, .horizontal):
return .right
}
}
open static func registerViews(_ list: ListType?, collectionView : UICollectionView?) {
guard let list = list else { return }
let allReusableIds = List.allReusableIds(list)
for reusableId in allReusableIds {
collectionView?.register(CollectionViewCell<T>.self, forCellWithReuseIdentifier: reusableId)
}
}
// MARK: Pull to Refresh
func refresh(_ sender: AnyObject?) {
guard let list = self.list else { return }
guard let configuration = list.configuration else { return }
configuration.onRefresh?()
}
// MARK: UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.list?.sections.count ?? 0
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let list = self.list else {
return 0
}
return list.sections[section].items.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let list = self.list else {
fatalError("List is required. We shouldn't be here")
}
let listItem = list.sections[indexPath.section].items[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: listItem.cellId, for: indexPath)
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
return cell
}
open func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let list = self.list else {
return
}
let listItem = list.sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
if let fillableCell = cell as? Fillable {
fillableCell.fill(listItem)
}
}
// MARK : UICollectionViewDelegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let list = self.list else {
return
}
let listItem = list.sections[(indexPath as NSIndexPath).section].items[(indexPath as NSIndexPath).row]
if let onSelect = listItem.onSelect {
onSelect(listItem)
}
}
}
|
4fe5f024ac5afbb40da82bc49505b7b8
| 28.955665 | 176 | 0.726525 | false | false | false | false |
Arcovv/CleanArchitectureRxSwift
|
refs/heads/master
|
CleanArchitectureRxSwift/Scenes/AllPosts/PostsViewModel.swift
|
mit
|
2
|
import Foundation
import Domain
import RxSwift
import RxCocoa
final class PostsViewModel: ViewModelType {
struct Input {
let trigger: Driver<Void>
let createPostTrigger: Driver<Void>
let selection: Driver<IndexPath>
}
struct Output {
let fetching: Driver<Bool>
let posts: Driver<[PostItemViewModel]>
let createPost: Driver<Void>
let selectedPost: Driver<Post>
let error: Driver<Error>
}
private let useCase: PostsUseCase
private let navigator: PostsNavigator
init(useCase: PostsUseCase, navigator: PostsNavigator) {
self.useCase = useCase
self.navigator = navigator
}
func transform(input: Input) -> Output {
let activityIndicator = ActivityIndicator()
let errorTracker = ErrorTracker()
let posts = input.trigger.flatMapLatest {
return self.useCase.posts()
.trackActivity(activityIndicator)
.trackError(errorTracker)
.asDriverOnErrorJustComplete()
.map { $0.map { PostItemViewModel(with: $0) } }
}
let fetching = activityIndicator.asDriver()
let errors = errorTracker.asDriver()
let selectedPost = input.selection
.withLatestFrom(posts) { (indexPath, posts) -> Post in
return posts[indexPath.row].post
}
.do(onNext: navigator.toPost)
let createPost = input.createPostTrigger
.do(onNext: navigator.toCreatePost)
return Output(fetching: fetching,
posts: posts,
createPost: createPost,
selectedPost: selectedPost,
error: errors)
}
}
|
a6bd420c5dbe2d193a8dc554384c0155
| 30.803571 | 66 | 0.591802 | false | false | false | false |
franciscocgoncalves/FastCapture
|
refs/heads/master
|
FastCapture/DirectoryManager.swift
|
mit
|
1
|
//
// DirectoryManager.swift
// FastCapture
//
// Created by Francisco Gonçalves on 20/04/15.
// Copyright (c) 2015 Francisco Gonçalves. All rights reserved.
//
import Cocoa
private let _DirectoryManager = DirectoryManager()
class DirectoryManager: NSObject {
class var sharedInstance: DirectoryManager {
return _DirectoryManager
}
var url: NSURL?
func createDirectory() {
let userDefaultURL: AnyObject? = NSUserDefaults.standardUserDefaults().URLForKey("screenCaptureDirectory")
let folderDestinationURL: NSURL
if userDefaultURL == nil {
if let picturesURL = NSFileManager.defaultManager().URLsForDirectory(.PicturesDirectory, inDomains: .UserDomainMask).first{
folderDestinationURL = picturesURL.URLByAppendingPathComponent("ScreenCapture")
}
else {
//should alert user
return
}
}
else {
folderDestinationURL = userDefaultURL as! NSURL
}
var isDir = ObjCBool(true)
if !NSFileManager.defaultManager().fileExistsAtPath(folderDestinationURL.path!, isDirectory: &isDir) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(folderDestinationURL.path!, withIntermediateDirectories: true, attributes: nil)
print("sucessfuly created dir")
} catch let error as NSError {
print("Error: \(error.domain)")
//should alert user
return
}
}
setDirectory(folderDestinationURL)
}
func readDirectory(cb: ((fileURL: NSURL) -> Void)?) {
let fileManager = NSFileManager.defaultManager()
let keys = NSArray(objects: NSURLNameKey)
let options: NSDirectoryEnumerationOptions = ([NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants, NSDirectoryEnumerationOptions.SkipsHiddenFiles])
//Get Contents of directory
if(self.url == nil) {
self.url = NSUserDefaults.standardUserDefaults().URLForKey("screenCaptureDirectory")
}
var contents: [NSURL]?
do {
contents = try fileManager.contentsOfDirectoryAtURL(self.url!, includingPropertiesForKeys: keys as? [String], options: options)
} catch let error as NSError {
print(error)
contents = nil
}
ScreenCapture.sharedInstance.addNewFilesToCache(contents, cb: cb)
}
func setDirectory(folderDestinationURL: NSURL) {
NSUserDefaults.standardUserDefaults().setURL(folderDestinationURL, forKey: "screenCaptureDirectory")
self.url = folderDestinationURL
setScreenCaptureDefaultFolder(folderDestinationURL)
}
func setScreenCaptureDefaultFolder(directoryURL: NSURL) {
let task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = ["-c",
"defaults write com.apple.screencapture location \(directoryURL.path!); killall SystemUIServer"]
task.launch()
}
}
|
1bad738ca58baa095fc9d047bcd21d22
| 34.693182 | 163 | 0.633238 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS
|
refs/heads/master
|
TruckMuncher/api/RCategory.swift
|
gpl-2.0
|
1
|
//
// RCategory.swift
// TruckMuncher
//
// Created by Josh Ault on 10/27/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RCategory: RLMObject {
dynamic var id = ""
dynamic var name = ""
dynamic var notes = ""
dynamic var orderInMenu = 0
dynamic var menuItems = RLMArray(objectClassName: RMenuItem.className())
override init() {
super.init()
}
class func initFromProto(category: [String: AnyObject]) -> RCategory {
let rcategory = RCategory()
rcategory.id = category["id"] as! String
rcategory.name = category["name"] as? String ?? ""
rcategory.notes = category["notes"] as? String ?? ""
rcategory.orderInMenu = category["orderInMenu"] as? Int ?? 0
if let menuItems = category["menuItems"] as? [[String: AnyObject]] {
for menuItem in menuItems {
rcategory.menuItems.addObject(RMenuItem.initFromFullProto(menuItem))
}
}
return rcategory
}
override class func primaryKey() -> String! {
return "id"
}
}
|
e12f60baec60e6c8cde9ee2c17a1111c
| 27.325 | 84 | 0.606355 | false | false | false | false |
zuoya0820/DouYuZB
|
refs/heads/master
|
DouYuZB/DouYuZB/Classes/Main/Model/AnchorModel.swift
|
mit
|
1
|
//
// AnchorModel.swift
// DouYuZB
//
// Created by zuoya on 2017/10/22.
// Copyright © 2017年 zuoya. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
/// 房间id
var room_id : Int = 0
/// 房间图片对应的URLstring
var vertical_src : String = ""
/// 判断是手机直播还是电脑直播
/// 0: 电脑直播 1: 手机直播
var isVertical : Int = 0
/// 房间名称
var room_name : String = ""
/// 主播昵称
var nickname : String = ""
/// 观看人数
var online : Int = 0
/// 所在城市
var anchor_city : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
|
3eda612e3c11d27c37f2e4baf60433c8
| 19.457143 | 73 | 0.553073 | false | false | false | false |
SAP/SAPJamSampleCode
|
refs/heads/main
|
iOS_Integrations/mobile-sdk-ios/Swift 2.x/SAPJamSDK/SAPJamSDK/JamSession/JamAuthConfig.swift
|
apache-2.0
|
1
|
//
// JamAuthConfig.swift
// SAPJamSDK
//
// Copyright © 2016 SAP SE. All rights reserved.
//
import Foundation
import OAuthSwift
import KeychainAccess
// Keys for storage of OAuth 1.0a single use access token and secret in keychain
let kAccessToken = "accessToken"
let kAccessSecret = "accessSecret"
public class JamAuthConfig {
// Sets authentication to OAuth 1.0a
public var oauthswift: OAuth1Swift?
// Used by the "configure" method to set the OAuth 1.0a authentication server name
private var serverName = ""
// Sets the keychain domain
private let keychain = Keychain(service: "com.sap.jam")
// Creates a shared instance of the keychain
static let sharedInstance = JamAuthConfig()
// Checks if user is logged in by checking if the OAuth 1.0a token and secret have been set in the keychain
public class func isLoggedIn() -> Bool {
return sharedInstance.keychain[kAccessToken] != nil && sharedInstance.keychain[kAccessSecret] != nil
}
// Provides functions access to a successfully created OAuth 1.0a single use access token
public typealias SingleUseTokenSuccessHandler = (singleUseToken: String) -> Void
// Displays an error message in the console
public typealias ErrorHandler = (error: NSError) -> Void
// Gets the OAuth 1.0a single use access token from the authorization server so the app can access the Jam OData API
public func getSingleUseToken(success: SingleUseTokenSuccessHandler, failure: ErrorHandler?) {
let urlStr = getServerUrl() + "/v1/single_use_tokens"
// Attempts to gets the OAuth 1.0a single use access token from the authorization server
oauthswift!.client.post(urlStr,
success: {
data, response in
// Converts response object into a string
let dataString: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
// Creates a regular expression used to find the single use access token key-value pair in the string
let regex: NSRegularExpression = try! NSRegularExpression(pattern: "(?<=<single_use_token id=\")[^\"]+", options:[.CaseInsensitive])
// Executes the regular expression to determine if the single use access token is in the string
if let match = regex.firstMatchInString(dataString as String, options:[], range: NSMakeRange(0, dataString.length)) {
// Assigns the single use access token value from the key-value pair to a string
let token:String = dataString.substringWithRange(match.range)
// Assigns the OAuth 1.0a single use access token to a publicly accessible property so
// other functions can access the SAP Jam OData API.
success(singleUseToken: token)
}
else {
// Displays error information when a single use access token cannot be found in the string
let errorInfo = [NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get Single Use Token", comment: "Response from /v1/single_use_tokens does not contain a token")]
failure?(error: NSError(domain: "sapjam.error", code: -1, userInfo: errorInfo))
}
},
failure: { error in
print(error)
failure?(error: error)
}
)
}
// Creates the OAuth 1.0a authentication server URL
public func getServerUrl() -> String {
return "https://" + serverName
}
// Configures the URLs required to perform OAuth 1.0a authentication and authorization to get a single use
// access token.
public func configure(server: String, key: String, secret: String, companyDomain: String? = nil) {
serverName = server
let serverUrl = getServerUrl()
validateServer()
// Creates authorization url for normal oauth clients
var authorizeUrl = serverUrl + "/oauth/authorize"
if let domain = companyDomain {
authorizeUrl = serverUrl + "/c/" + domain + "/oauth/authorize"
}
oauthswift = OAuth1Swift(
consumerKey: key,
consumerSecret: secret,
requestTokenUrl: serverUrl + "/oauth/request_token",
authorizeUrl: authorizeUrl,
accessTokenUrl: serverUrl + "/oauth/access_token"
)
// Uses the existing single use token and secret in the keychain if the user is already logged in
if JamAuthConfig.isLoggedIn() {
oauthswift?.client.credential.oauth_token = keychain[kAccessToken]!
oauthswift?.client.credential.oauth_token_secret = keychain[kAccessSecret]!
}
}
// Validates the OAuth 1.0a authentication server domains
private func validateServer() {
// Note: this list may be subject to change (additions) in future.
// Please use the server your company is registered with.
let VALID_JAM_SERVERS = [
"developer.sapjam.com",
"jam4.sapjam.com",
"jam8.sapjam.com",
"jam10.sapjam.com",
"jam12.sapjam.com",
"jam2.sapjam.com",
"jam15.sapsf.cn",
"jam17.sapjam.com",
"jam18.sapjam.com"]
precondition(VALID_JAM_SERVERS.contains(serverName), "Must set a valid Jam server")
}
// Stores OAuth 1.0a single use token and secret in the keychain
public func storeCredentials(credential: OAuthSwiftCredential) {
keychain[kAccessToken] = credential.oauth_token
keychain[kAccessSecret] = credential.oauth_token_secret
}
}
|
8fb6aa1665aac6fcc9402e4f7ac07def
| 41.056738 | 196 | 0.622597 | false | false | false | false |
soh335/GetBSDProcessList
|
refs/heads/master
|
GetBSDProcessList/GetBSDProcessList.swift
|
mit
|
1
|
import Foundation
import Darwin
public func GetBSDProcessList() -> ([kinfo_proc]?) {
var done = false
var result: [kinfo_proc]?
var err: Int32
repeat {
let name = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0];
let namePointer = name.withUnsafeBufferPointer { UnsafeMutablePointer<Int32>($0.baseAddress) }
var length: Int = 0
err = sysctl(namePointer, u_int(name.count), nil, &length, nil, 0)
if err == -1 {
err = errno
}
if err == 0 {
let count = length / strideof(kinfo_proc)
result = [kinfo_proc](count: count, repeatedValue: kinfo_proc())
err = result!.withUnsafeMutableBufferPointer({ (inout p: UnsafeMutableBufferPointer<kinfo_proc>) -> Int32 in
return sysctl(namePointer, u_int(name.count), p.baseAddress, &length, nil, 0)
})
switch err {
case 0:
done = true
case -1:
err = errno
case ENOMEM:
err = 0
default:
fatalError()
}
}
} while err == 0 && !done
return result
}
|
6735a1d9f22dd0ae2a2461c31ef08a3b
| 28.7 | 120 | 0.518955 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
CollectionDemo/CollectionDemo/SimpleDemoViewController.swift
|
mit
|
1
|
//
// SimpleDemoViewController.swift
// CollectionDemo
//
// Created by Bear on 2017/7/6.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class SimpleDemoViewController: UIViewController {
let headerId = "simpleHead"
let footerId = "simpleFooter"
var dataSourceOne : Array<Int> = Array()
var dataSourceTwo : Array<Int> = Array()
var dataSource : Array<Array<Int>> = Array()
lazy var collectionView : UICollectionView = {
let flowLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout()
//滚动方向
flowLayout.scrollDirection = .vertical
//cell的大小
flowLayout.itemSize = CGSize(width: 80, height: 80)
//滚动方向的垂直方向上,单元格之间的间隔
flowLayout.minimumInteritemSpacing = 10
//滚动方向,单元格之间的间隔
flowLayout.minimumLineSpacing = 10
//头部的大小,只会读取滚动方向的值:水平滚动的话,读取宽度;垂直滚动,读取高度;
flowLayout.headerReferenceSize = CGSize(width: 60, height: 40)
//同上
flowLayout.footerReferenceSize = CGSize(width: 60, height: 40)
let view : UICollectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: flowLayout)
view.register(SimpleCellCollectionViewCell.self, forCellWithReuseIdentifier: String.init(describing: SimpleCellCollectionViewCell.self))
view.register(HeaderCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.headerId)
view.register(FooterCollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: self.footerId)
view.delegate = self
view.dataSource = self
view.backgroundColor = UIColor.orange
let gesture = UILongPressGestureRecognizer.init(target: self, action: #selector(self.handleLongPressGesture(gesture:)))
view.addGestureRecognizer(gesture)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
title = "Simple Demo"
view.backgroundColor = UIColor.white
for ele in 0...49 {
self.dataSourceOne.append(ele)
self.dataSourceTwo.append(ele)
}
dataSource.append(dataSourceOne)
dataSource.append(dataSourceTwo)
view.addSubview(collectionView)
}
func handleLongPressGesture(gesture: UILongPressGestureRecognizer) {
switch gesture.state {
case .began:
let touchItemIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView))
guard touchItemIndexPath != nil else {
return
}
self.collectionView.beginInteractiveMovementForItem(at: touchItemIndexPath!)
case .changed:
self.collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view))
case .ended,.cancelled:
self.collectionView.endInteractiveMovement()
default:
break
}
}
}
extension SimpleDemoViewController : UICollectionViewDelegate,UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return dataSource.count;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSource[section].count
}
//设置head foot视图
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if (kind as NSString).isEqual(to: UICollectionElementKindSectionHeader)
{
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.headerId, for: indexPath) as! HeaderCollectionReusableView
header.setupView()
return header
}
else
{
let footer = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: self.footerId, for: indexPath) as! FooterCollectionReusableView
footer.setupView()
return footer
}
}
//设置每个单元格
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String.init(describing: SimpleCellCollectionViewCell.self), for: indexPath) as! SimpleCellCollectionViewCell
cell.setupView(num: dataSource[indexPath.section][indexPath.row])
return cell
}
func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
//设置选中高亮时的颜色
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
//设置取消高亮时的颜色
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.white
}
//长按是否弹出菜单,和长按移动单元格冲突~!
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
//单元格是否可以被选中,只对下面的didSelectItemAt进行控件。高亮什么的都不归这货管
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if indexPath.row%2 == 0
{
return false
}
else
{
return true
}
}
//单元格被选中后的事件
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("\(indexPath.row)")
}
//响应哪些菜单项
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
let selectorStr = NSStringFromSelector(action) as NSString
if selectorStr.isEqual(to: "cut:")
{
return true
}
else if selectorStr.isEqual(to: "copy:")
{
return true
}
else if selectorStr.isEqual(to: "paste")
{
return true
}
else
{
return false
}
}
//响应长按菜单
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
let selectorStr = NSStringFromSelector(action) as NSString
if selectorStr.isEqual(to: "cut:")
{
let array = [indexPath]
dataSource[indexPath.section].remove(at: indexPath.row)
collectionView.deleteItems(at: array)
}
else if selectorStr.isEqual(to: "copy:")
{
}
else if selectorStr.isEqual(to: "paste")
{
}
else
{
}
}
//配合手势移动使用
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let value = dataSource[sourceIndexPath.section][sourceIndexPath.row]
dataSource[sourceIndexPath.section].remove(at: sourceIndexPath.row)
dataSource[destinationIndexPath.section].insert(value, at: destinationIndexPath.row)
}
}
|
b50117b9a49ba81a30d506e2a3f7b85b
| 31.07563 | 183 | 0.66099 | false | false | false | false |
littlelightwang/firefox-ios
|
refs/heads/master
|
Client/Frontend/Browser/BrowserToolbar.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Snappy
protocol BrowserToolbarDelegate {
func didBeginEditing()
func didClickBack()
func didClickForward()
func didClickAddTab()
func didLongPressBack()
func didLongPressForward()
func didClickReaderMode()
func didClickStop()
func didClickReload()
}
class BrowserToolbar: UIView, UITextFieldDelegate, BrowserLocationViewDelegate {
var browserToolbarDelegate: BrowserToolbarDelegate?
private var forwardButton: UIButton!
private var backButton: UIButton!
private var locationView: BrowserLocationView!
private var tabsButton: UIButton!
private var progressBar: UIProgressView!
private var longPressGestureBackButton: UILongPressGestureRecognizer!
private var longPressGestureForwardButton: UILongPressGestureRecognizer!
override init() {
super.init()
}
override init(frame: CGRect) {
super.init(frame: frame)
viewDidInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
viewDidInit()
}
private func viewDidInit() {
self.backgroundColor = UIColor(white: 0.80, alpha: 1.0)
backButton = UIButton()
backButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
backButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
backButton.setTitle("<", forState: UIControlState.Normal)
backButton.accessibilityLabel = NSLocalizedString("Back", comment: "")
backButton.addTarget(self, action: "SELdidClickBack", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureBackButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressBack:")
backButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
backButton.addGestureRecognizer(longPressGestureBackButton)
self.addSubview(backButton)
forwardButton = UIButton()
forwardButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
forwardButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
forwardButton.setTitle(">", forState: UIControlState.Normal)
forwardButton.accessibilityLabel = NSLocalizedString("Forward", comment: "")
forwardButton.addTarget(self, action: "SELdidClickForward", forControlEvents: UIControlEvents.TouchUpInside)
longPressGestureForwardButton = UILongPressGestureRecognizer(target: self, action: "SELdidLongPressForward:")
forwardButton.accessibilityHint = NSLocalizedString("Double tap and hold to open history", comment: "")
forwardButton.addGestureRecognizer(longPressGestureForwardButton)
self.addSubview(forwardButton)
locationView = BrowserLocationView(frame: CGRectZero)
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
addSubview(locationView)
progressBar = UIProgressView()
self.progressBar.trackTintColor = self.backgroundColor
self.addSubview(progressBar)
tabsButton = UIButton()
tabsButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.borderColor = UIColor.blackColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 4
tabsButton.titleLabel?.layer.borderWidth = 1
tabsButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 12)
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(24)
return
}
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(tabsButton)
self.backButton.snp_remakeConstraints { make in
make.left.equalTo(self)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
}
self.forwardButton.snp_remakeConstraints { make in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
}
self.locationView.snp_remakeConstraints { make in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self).offset(10)
}
self.tabsButton.snp_remakeConstraints { make in
make.left.equalTo(self.locationView.snp_right)
make.centerY.equalTo(self).offset(10)
make.width.height.equalTo(44)
make.right.equalTo(self).offset(-8)
}
self.progressBar.snp_remakeConstraints { make in
make.centerY.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
}
func updateURL(url: NSURL?) {
if let url = url {
locationView.url = url
}
}
func updateTabCount(count: Int) {
tabsButton.setTitle(count.description, forState: UIControlState.Normal)
tabsButton.accessibilityValue = count.description
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "")
}
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateFowardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateLoading(loading: Bool) {
locationView.loading = loading
}
func SELdidClickBack() {
browserToolbarDelegate?.didClickBack()
}
func SELdidLongPressBack(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
browserToolbarDelegate?.didLongPressBack()
}
}
func SELdidClickForward() {
browserToolbarDelegate?.didClickForward()
}
func SELdidLongPressForward(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == UIGestureRecognizerState.Began {
browserToolbarDelegate?.didLongPressForward()
}
}
func SELdidClickAddTab() {
browserToolbarDelegate?.didClickAddTab()
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {self.progressBar.alpha = 0.0},
completion: {_ in self.progressBar.setProgress(0.0, animated: false)})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress))
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickReaderMode()
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didBeginEditing()
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickReload()
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
browserToolbarDelegate?.didClickStop()
}
}
|
4fb5e64b224652eee80a51f19c26a797
| 36.362745 | 117 | 0.696143 | false | false | false | false |
tschmitz/DateIntervalOperators
|
refs/heads/master
|
DateIntervalOperators.swift
|
mit
|
1
|
//
// DateIntervalOperators.swift
// SyncTime
//
// Created by Tim Schmitz on 2/2/15.
// Copyright (c) 2015 Tap and Tonic. All rights reserved.
//
import Foundation
public extension Int {
public func day() -> NSDateComponents {
let components = NSDateComponents()
components.day = self
return components
}
public func days() -> NSDateComponents { return self.day() }
public func week() -> NSDateComponents {
let components = NSDateComponents()
components.weekOfYear = self
return components
}
public func weeks() -> NSDateComponents { return self.week() }
public func month() -> NSDateComponents {
let components = NSDateComponents()
components.month = self
return components
}
public func months() -> NSDateComponents { return self.month() }
public func year() -> NSDateComponents {
let components = NSDateComponents()
components.year = self
return components
}
public func years() -> NSDateComponents { return self.year() }
public func second() -> NSDateComponents {
let components = NSDateComponents()
components.second = self
return components
}
public func seconds() -> NSDateComponents { return self.second() }
public func minute() -> NSDateComponents {
let components = NSDateComponents()
components.minute = self
return components
}
public func minutes() -> NSDateComponents { return self.minute() }
public func hour() -> NSDateComponents {
let components = NSDateComponents()
components.hour = self
return components
}
public func hours() -> NSDateComponents { return self.hour() }
}
public func +(lhs: NSDate, rhs: NSDateComponents) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingComponents(rhs, toDate: lhs, options: nil) ?? lhs
}
public func -(lhs: NSDate, rhs: NSDateComponents) -> NSDate {
if rhs.era != Int(NSUndefinedDateComponent) { rhs.era *= -1 }
if rhs.year != Int(NSUndefinedDateComponent) { rhs.year *= -1 }
if rhs.month != Int(NSUndefinedDateComponent) { rhs.month *= -1 }
if rhs.day != Int(NSUndefinedDateComponent) { rhs.day *= -1 }
if rhs.hour != Int(NSUndefinedDateComponent) { rhs.hour *= -1 }
if rhs.minute != Int(NSUndefinedDateComponent) { rhs.minute *= -1 }
if rhs.second != Int(NSUndefinedDateComponent) { rhs.second *= -1 }
if rhs.nanosecond != Int(NSUndefinedDateComponent) { rhs.nanosecond *= -1 }
if rhs.weekday != Int(NSUndefinedDateComponent) { rhs.weekday *= -1 }
if rhs.weekdayOrdinal != Int(NSUndefinedDateComponent) { rhs.weekdayOrdinal *= -1 }
if rhs.quarter != Int(NSUndefinedDateComponent) { rhs.quarter *= -1 }
if rhs.weekOfMonth != Int(NSUndefinedDateComponent) { rhs.weekOfMonth *= -1 }
if rhs.weekOfYear != Int(NSUndefinedDateComponent) { rhs.weekOfYear *= -1 }
if rhs.yearForWeekOfYear != Int(NSUndefinedDateComponent) { rhs.yearForWeekOfYear *= -1 }
return NSCalendar.currentCalendar().dateByAddingComponents(rhs, toDate: lhs, options: nil) ?? lhs
}
|
f6033c9884ca500edbd6f0e60c204a40
| 34.13253 | 98 | 0.715266 | false | false | false | false |
JohnCoates/Aerial
|
refs/heads/master
|
Aerial/Source/Views/PrefPanel/InfoClockView.swift
|
mit
|
1
|
//
// InfoClockView.swift
// Aerial
//
// Created by Guillaume Louel on 18/12/2019.
// Copyright © 2019 Guillaume Louel. All rights reserved.
//
import Cocoa
class InfoClockView: NSView {
@IBOutlet var secondsCheckbox: NSButton!
@IBOutlet var hideAmPmCheckbox: NSButton!
@IBOutlet var clockFormat: NSPopUpButton!
@IBOutlet var customTimeFormatField: NSTextField!
// Init(ish)
func setStates() {
secondsCheckbox.state = PrefsInfo.clock.showSeconds ? .on : .off
hideAmPmCheckbox.state = PrefsInfo.clock.hideAmPm ? .on : .off
clockFormat.selectItem(at: PrefsInfo.clock.clockFormat.rawValue)
customTimeFormatField.stringValue = PrefsInfo.customTimeFormat
updateAmPmCheckbox()
}
@IBAction func secondsClick(_ sender: NSButton) {
let onState = sender.state == .on
PrefsInfo.clock.showSeconds = onState
}
@IBAction func hideAmPmCheckboxClick(_ sender: NSButton) {
let onState = sender.state == .on
PrefsInfo.clock.hideAmPm = onState
}
@IBAction func clockFormatChange(_ sender: NSPopUpButton) {
PrefsInfo.clock.clockFormat = InfoClockFormat(rawValue: sender.indexOfSelectedItem)!
updateAmPmCheckbox()
}
// Update the 12/24hr visibility
func updateAmPmCheckbox() {
switch PrefsInfo.clock.clockFormat {
case .tdefault:
hideAmPmCheckbox.isHidden = false // meh
secondsCheckbox.isHidden = false
case .t12hours:
hideAmPmCheckbox.isHidden = false
secondsCheckbox.isHidden = false
case .t24hours:
hideAmPmCheckbox.isHidden = true
secondsCheckbox.isHidden = false
case .custom:
hideAmPmCheckbox.isHidden = true
secondsCheckbox.isHidden = true
}
customTimeFormatField.isHidden = !(PrefsInfo.clock.clockFormat == .custom)
}
@IBAction func customTimeFormatFieldChange(_ sender: NSTextField) {
PrefsInfo.customTimeFormat = sender.stringValue
}
}
|
e098fee1b5950345d060b84bca9d46b1
| 30.257576 | 92 | 0.665536 | false | false | false | false |
liufengting/FTChatMessageDemoProject
|
refs/heads/master
|
FTChatMessage/FTChatMessageInput/FTChatMessageInputView.swift
|
mit
|
1
|
//
// FTChatMessageInputView.swift
// FTChatMessage
//
// Created by liufengting on 16/3/22.
// Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved.
//
import UIKit
enum FTChatMessageInputMode {
case keyboard
case record
case accessory
case none
}
protocol FTChatMessageInputViewDelegate {
func ft_chatMessageInputViewShouldBeginEditing()
func ft_chatMessageInputViewShouldEndEditing()
func ft_chatMessageInputViewShouldUpdateHeight(_ desiredHeight : CGFloat)
func ft_chatMessageInputViewShouldDoneWithText(_ textString : String)
func ft_chatMessageInputViewShouldShowRecordView()
func ft_chatMessageInputViewShouldShowAccessoryView()
}
class FTChatMessageInputView: UIToolbar, UITextViewDelegate{
var inputDelegate : FTChatMessageInputViewDelegate?
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var inputTextView: UITextView!
@IBOutlet weak var accessoryButton: UIButton!
@IBOutlet weak var inputTextViewTopMargin: NSLayoutConstraint! {
didSet {
self.layoutIfNeeded()
}
}
@IBOutlet weak var inputTextViewBottomMargin: NSLayoutConstraint! {
didSet {
self.layoutIfNeeded()
}
}
//MARK: - awakeFromNib -
override func awakeFromNib() {
super.awakeFromNib()
inputTextView.layer.cornerRadius = FTDefaultInputViewTextCornerRadius
inputTextView.layer.borderColor = UIColor.lightGray.cgColor
inputTextView.layer.borderWidth = 0.5
inputTextView.textContainerInset = FTDefaultInputTextViewEdgeInset
inputTextView.delegate = self
}
//MARK: - layoutSubviews -
override func layoutSubviews() {
super.layoutSubviews()
if self.inputTextView.attributedText.length > 0 {
self.inputTextView.scrollRangeToVisible(NSMakeRange(self.inputTextView.attributedText.length - 1, 1))
}
}
//MARK: - recordButtonTapped -
@IBAction func recordButtonTapped(_ sender: UIButton) {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldShowRecordView()
}
}
//MARK: - accessoryButtonTapped -
@IBAction func accessoryButtonTapped(_ sender: UIButton) {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldShowAccessoryView()
}
}
//MARK: - clearText -
func clearText(){
inputTextView.text = ""
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldUpdateHeight(FTDefaultInputViewHeight)
}
}
//MARK: - UITextViewDelegate -
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldBeginEditing()
}
return true
}
func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldEndEditing()
}
return true
}
func textViewDidChange(_ textView: UITextView) {
if let text : NSAttributedString = textView.attributedText {
let textRect = text.boundingRect(with: CGSize(width: textView.bounds.width - textView.textContainerInset.left - textView.textContainerInset.right, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin , .usesFontLeading], context: nil);
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldUpdateHeight(min(max(textRect.height + inputTextViewTopMargin.constant + inputTextViewBottomMargin.constant + textView.textContainerInset.top + textView.textContainerInset.bottom, FTDefaultInputViewHeight), FTDefaultInputViewMaxHeight))
}
}
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
if (textView.text as NSString).length > 0 {
if (inputDelegate != nil) {
inputDelegate!.ft_chatMessageInputViewShouldDoneWithText(textView.text)
self.clearText()
}
}
return false
}
return true
}
}
|
fe0095f9efa66351256a9320c20f42ec
| 33.674603 | 296 | 0.670405 | false | false | false | false |
yzyzsun/CurriculaTable
|
refs/heads/master
|
CurriculaTable/CurriculaTableController.swift
|
mit
|
1
|
//
// CurriculaTableController.swift
// CurriculaTable
//
// Created by Sun Yaozhu on 2016-09-10.
// Copyright © 2016 Sun Yaozhu. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CurriculaTableController: UIViewController {
weak var curriculaTable: CurriculaTable!
weak var collectionView: UICollectionView! {
didSet {
collectionView.register(CurriculaTableCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
}
}
extension CurriculaTableController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (curriculaTable.numberOfPeriods + 1) * 8
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CurriculaTableCell
cell.backgroundColor = curriculaTable.symbolsBgColor
cell.layer.borderWidth = curriculaTable.borderWidth
cell.layer.borderColor = curriculaTable.borderColor.cgColor
cell.textLabel.font = UIFont.systemFont(ofSize: curriculaTable.symbolsFontSize)
if indexPath.row == 0 {
cell.textLabel.text = ""
} else if indexPath.row < 8 {
cell.textLabel.text = curriculaTable.weekdaySymbols[indexPath.row - 1]
} else if indexPath.row % 8 == 0 {
cell.textLabel.text = String(indexPath.row / 8)
} else {
cell.textLabel.text = ""
cell.backgroundColor = UIColor.clear
}
return cell
}
}
extension CurriculaTableController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.row == 0 {
return CGSize(width: curriculaTable.widthOfPeriodSymbols, height: curriculaTable.heightOfWeekdaySymbols)
} else if indexPath.row < 8 {
return CGSize(width: curriculaTable.averageWidth, height: curriculaTable.heightOfWeekdaySymbols)
} else if indexPath.row % 8 == 0 {
return CGSize(width: curriculaTable.widthOfPeriodSymbols, height: curriculaTable.averageHeight)
} else {
return CGSize(width: curriculaTable.averageWidth, height: curriculaTable.averageHeight)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
|
b354c2cdb6660d4f1f4a0be49ddfe78b
| 38.932432 | 175 | 0.704569 | false | false | false | false |
herrkaefer/CaseAssistant
|
refs/heads/master
|
CaseAssistant/PatientViewController.swift
|
mpl-2.0
|
1
|
//
// PatientViewController.swift
// CaseAssistant
//
// Created by HerrKaefer on 15/4/23.
// Copyright (c) 2015年 HerrKaefer. All rights reserved.
//
import UIKit
import Photos
import MobileCoreServices
import QBImagePickerController
class PatientViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, QBImagePickerControllerDelegate
{
// MARK: - Variables
var patient: Patient? {
didSet {
loadData()
}
}
var records = [Record]()
var currentOperatedRecord: Record? // 当前正在操作(add photo, add voice memo, delete)的record
var imagePickerController: UIImagePickerController?
// var qbImagePickerController: QBImagePickerController?
var progressHUD: ProgressHUD!
// MARK: - IBOutlets
@IBOutlet weak var patientInfoLabel: UILabel!
@IBOutlet weak var patientDiagnosisLabel: UILabel!
@IBOutlet weak var tagsLabel: UILabel!
@IBOutlet weak var patientTableView: UITableView!
@IBOutlet weak var infoView: UIView! {
didSet {
let singleFingerTap = UITapGestureRecognizer(target: self, action: #selector(PatientViewController.handleSingleTapOnInfoView(_:)))
infoView.addGestureRecognizer(singleFingerTap)
}
}
@IBOutlet weak var starBarButtonItem: UIBarButtonItem!
// @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
// MARK: - Helper Functions
func loadData() {
records.removeAll()
records.append(contentsOf: patient!.recordsSortedDescending)
}
func updateInfoView() {
let name = patient!.g("name")
let gender = patient!.g("gender")
patientInfoLabel.text! = "\(name), \(gender), \(patient!.treatmentAge)岁"
if patient!.firstDiagnosis != nil {
patientDiagnosisLabel.text = "\(patient!.firstDiagnosis!)"
} else {
patientDiagnosisLabel.text = patient!.g("diagnosis")
}
let tagNames = patient!.tagNames
if tagNames.count > 0 {
tagsLabel.text! = " " + tagNames.joined(separator: " ") + " "
} else {
tagsLabel.text! = ""
}
tagsLabel.layer.cornerRadius = 3.0
tagsLabel.layer.masksToBounds = true
}
func updateStarBarButtonItemDisplay() {
if patient?.starred == true {
starBarButtonItem.image = UIImage(named: "star-29")
starBarButtonItem.tintColor = CaseApp.starredColor
} else {
starBarButtonItem.image = UIImage(named: "star-outline-29")
starBarButtonItem.tintColor = UIColor.white
}
}
func addLastPhotoInLibraryToPhotoMemo() {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let lastAsset = fetchResult.lastObject {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .fast
PHImageManager.default().requestImage(for: lastAsset, targetSize: PhotoMemo.imageSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) -> Void in
let result = self.currentOperatedRecord!.addPhotoMemo(image!, creationDate: lastAsset.creationDate!, shouldScaleDown: false)
if result == true {
self.patientTableView.reloadData()
// 弹出保存成功提示
popupPrompt("照片已添加", inView: self.view)
} else {
popupPrompt("照片添加失败,请再试一次", inView: self.view)
}
})
}
}
func takeOrImportPhotoForRecord() {
if currentOperatedRecord == nil {
return
}
let alert = UIAlertController(
title: nil,
message: nil,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: "相册中最新一张照片",
style: .default,
handler: {action in
// self.progressHUD.show()
self.addLastPhotoInLibraryToPhotoMemo()
// self.progressHUD.hide()
}
))
alert.addAction(UIAlertAction(
title: "拍摄照片",
style: .default,
handler: {action in
if self.imagePickerController != nil {
self.present(self.imagePickerController!, animated: true, completion: nil)
}
}
))
alert.addAction(UIAlertAction(
title: "从相册中选择",
style: .default,
handler: {action in
let qbImagePickerController = QBImagePickerController()
qbImagePickerController.mediaType = .image
qbImagePickerController.allowsMultipleSelection = true
qbImagePickerController.prompt = "选择照片(可多选)"
qbImagePickerController.showsNumberOfSelectedAssets = true
qbImagePickerController.delegate = self
self.present(qbImagePickerController, animated: true, completion: nil)
}
))
alert.addAction(UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
))
alert.modalPresentationStyle = .popover
let ppc = alert.popoverPresentationController
ppc?.barButtonItem = starBarButtonItem
present(alert, animated: true, completion: nil)
}
// MARK: - IBActions
func handleSingleTapOnInfoView(_ gesture: UITapGestureRecognizer) {
performSegue(withIdentifier: "showPatientInfo", sender: self)
}
@IBAction func showMorePatientInfo(_ sender: UIButton) {
performSegue(withIdentifier: "showPatientInfo", sender: self)
}
@IBAction func starPatient(_ sender: UIBarButtonItem) {
patient!.toggleStar()
updateStarBarButtonItemDisplay()
}
// MARK: - QBImagePickerViewController Delegate
// 从相册多选时使用
func qb_imagePickerController(_ imagePickerController: QBImagePickerController!, didFinishPickingAssets assets: [Any]!) {
// activityIndicatorView.startAnimating()
progressHUD.show()
var addCnt: Int = 0
var gotCnt: Int = 0
// save images
for asset in (assets as! [PHAsset]) {
let options = PHImageRequestOptions()
options.deliveryMode = .highQualityFormat
options.resizeMode = .fast
PHImageManager.default().requestImage(
for: asset,
targetSize: PhotoMemo.imageSize,
contentMode: .aspectFit,
options: options,
resultHandler: { (image, info) -> Void in
gotCnt += 1
let result = self.currentOperatedRecord!.addPhotoMemo(image!, creationDate: asset.creationDate!, shouldScaleDown: false)
if result == true {
addCnt += 1
}
if gotCnt == assets.count {
self.patientTableView.reloadData()
// self.activityIndicatorView.stopAnimating()
self.progressHUD.hide()
popupPrompt("\(addCnt)张照片已添加", inView: self.view)
}
})
}
imagePickerController.dismiss(animated: true, completion: nil)
}
func qb_imagePickerControllerDidCancel(_ imagePickerController: QBImagePickerController!) {
imagePickerController.dismiss(animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate
// 使用相机拍摄照片时使用
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var result = false
var image = info[UIImagePickerControllerEditedImage] as? UIImage
if image == nil {
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
if image != nil {
result = currentOperatedRecord!.addPhotoMemo(image!, creationDate: Date(), shouldScaleDown: true)
if result == true {
// also save photo to camera roll
if picker.sourceType == .camera {
UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
}
}
} else {
result = false
}
var message: String
if result == true {
message = "照片已添加"
} else {
message = "照片添加失败,请再次尝试"
}
picker.dismiss(animated: true, completion: {popupPrompt(message, inView: self.view)})
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// MARK: - ViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
patientTableView.rowHeight = 58
if UIImagePickerController.isSourceTypeAvailable(.camera) {
imagePickerController = UIImagePickerController()
imagePickerController!.sourceType = .camera
imagePickerController!.mediaTypes = [kUTTypeImage as String]
imagePickerController!.allowsEditing = false // 如果允许编辑,总是得到正方形照片
imagePickerController!.delegate = self
}
progressHUD = ProgressHUD(text: "照片添加中")
self.view.addSubview(progressHUD)
progressHUD.hide()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = "" + patient!.g("name")
loadData()
updateInfoView()
updateStarBarButtonItemDisplay()
patientTableView.reloadData()
}
// MARK: - TableView Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 2 // records + summary (行医心得)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return records.count
case 1:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
if patient != nil {
let cnt = records.count
return cnt > 0 ? "\(cnt)次就诊记录" : "尚无就诊记录"
} else {
return ""
}
default:
return ""
}
}
func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section == 0 && records.count > 0 {
return "左滑可以删除记录或快速添加照片"
} else {
return ""
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 { // records
// use SWTableViewCell
let cell = patientTableView.dequeueReusableCell(withIdentifier: "recordCell", for: indexPath) as! RecordTableViewCell
let r = records[indexPath.row]
cell.titleLabel.text = DateFormatter.localizedString(from: r.date as Date, dateStyle: .medium, timeStyle: .none)
var detailText = ""
if indexPath.row == records.count-1 {
detailText += "首诊"
} else {
detailText += "首诊后\(r.daysAfterFirstTreatment)天"
}
if let daysAfterLastOp = r.daysAfterLastOperation {
if daysAfterLastOp == 0 {
detailText += ",当天手术"
} else {
detailText += ",术后\(daysAfterLastOp)天"
}
}
cell.subtitleLabel.text = detailText
if r.photoMemos.count > 0 {
cell.photoMemoStatusImageView.image = UIImage(named: "image-20")
} else {
cell.photoMemoStatusImageView.image = nil
}
return cell
} else { // summary
let cell = patientTableView.dequeueReusableCell(withIdentifier: "summaryCell", for: indexPath)
return cell
}
}
// MARK: - TabelView Delegate
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if indexPath.section == 0 {
return true
} else {
return false
}
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
// 实现Swipe Cell的多个Control:使用Apple内置方法 (>iOS 8.0).
// 需要实现两个delegate:commitEditingStyle和editActionsForRowAtIndexPath
// 放弃SWTableViewCell因为显示太多layout warnings
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
if indexPath.section == 0 { // record
currentOperatedRecord = records[indexPath.row]
// 添加照片
let cameraAction = UITableViewRowAction(style: .normal, title: "添加照片") { (action, indexPath) -> Void in
self.takeOrImportPhotoForRecord()
}
cameraAction.backgroundColor = UIColor.gray
// shareAction.backgroundColor = UIColor(patternImage: UIImage(named:"star-toolbar")!)
// 删除记录
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "删除") { (action, indexPath) -> Void in
let alert = UIAlertController(
title: nil,
message: nil,
preferredStyle: .actionSheet
)
alert.addAction(UIAlertAction(
title: "删除检查记录",
style: .destructive,
handler: { (action) -> Void in
// print("deleting record with id: \(self.currentOperatedRecord!.date)")
self.currentOperatedRecord!.removeFromDB()
print("record deleted")
self.loadData()
self.patientTableView.reloadData()
}
))
alert.addAction(UIAlertAction(
title: "取消",
style: .cancel,
handler: nil
))
self.present(alert, animated: true, completion: nil)
}
deleteAction.backgroundColor = UIColor.red
return [deleteAction, cameraAction]
} else {
return []
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case "showRecord":
let cell = sender as! UITableViewCell
if let indexPath = patientTableView.indexPath(for: cell) {
let recordVC = segue.destination as! RecordTableViewController
recordVC.setShowRecord(records[indexPath.row])
}
case "addRecord":
if patient != nil {
let recordVC = segue.destination as! RecordTableViewController
recordVC.setNewRecord(patient!)
}
case "showSummary":
if patient != nil {
let patientSummaryVC = segue.destination as! PatientSummaryViewController
patientSummaryVC.patient = patient!
}
case "showPatientInfo":
let patientInfoVC = segue.destination as! PatientInfoTableViewController
patientInfoVC.setShowPatient(patient!)
case "showChart":
let chartVC = segue.destination as! ChartViewController
chartVC.patient = self.patient
case "showReport":
let reportVC = segue.destination as! ReportViewController
reportVC.patient = self.patient
default: break
}
}
}
}
|
ea91734f24b22b05fa5bae641ed78ddb
| 34.295597 | 187 | 0.561654 | false | false | false | false |
tensorflow/examples
|
refs/heads/master
|
lite/examples/classification_by_retrieval/ios/ImageClassifierBuilder/ModelTrainer.swift
|
apache-2.0
|
1
|
// Copyright 2021 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Photos
import ios_ImageClassifierBuilderLibObjC
struct ModelTrainer {
/// Trains a new classification model based on user-selected Photos Library albums. Every image is
/// labeled after its album name.
///
/// - Parameters:
/// - metadata: The metadata of the model to create.
/// - albums: The user-selected Photos Library albums.
/// - Returns: The Model object associated to the newly trained TFLite model.
func trainModel(metadata: ModelMetadata, on albums: [Album]) -> Model {
precondition(metadata.isValid)
precondition(!albums.isEmpty)
// Copy all images to a reasonable format in tmp.
let (labels, imagePaths) = prepareImages(from: albums)
// Create the file URL where the new model will be saved.
let modelURL = Model.makeURLForNewModel(named: metadata.name)
// Train the model.
ModelTrainingUtils.trainModel(
name: metadata.name, description: metadata.description, author: metadata.author,
version: metadata.version, license: metadata.license, labels: labels, imagePaths: imagePaths,
outputModelPath: modelURL.path)
// Get the number of distinct labels in the labelmap.
let labelsCount = Classifier(modelURL: modelURL).labels().count
let size = (try? modelURL.resourceValues(forKeys: [.fileSizeKey]))?.fileSize.map(Int64.init)
return Model(name: metadata.name, labelsCount: labelsCount, size: size)
}
/// Converts albums to a list of labels (the albums names, repeated as many times as there are
/// images in it) and an equally long list of image paths on disk (typically prepared copies
/// stored in the tmp directory).
///
/// - Parameter albums: The user-selected Photos Library albums.
/// - Returns: The pair of lists of labels and image paths on disk.
private func prepareImages(from albums: [Album]) -> (labels: [String], imagePaths: [String]) {
var labels: [String] = []
var imagePaths: [String] = []
let dispatchGroup = DispatchGroup()
for album in albums {
// Iterate over the images.
let fetchResult = PHAsset.fetchAssets(in: album.collection, options: nil)
fetchResult.enumerateObjects { (asset, index, stop) in
guard asset.mediaType == .image else { return }
// Get the image URL.
dispatchGroup.enter()
asset.requestContentEditingInput(with: PHContentEditingInputRequestOptions()) {
(input, _) in
defer { dispatchGroup.leave() }
guard let input = input,
let imageURLInLibrary = input.fullSizeImageURL,
let label = album.collection.localizedTitle
else {
return
}
// Copy the image as resized JPEG to the temporary directory.
let tmpDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
let options = PHImageRequestOptions()
options.isSynchronous = true
dispatchGroup.enter()
PHImageManager.default().requestImage(
for: asset, targetSize: CGSize(width: 640, height: 480), contentMode: .aspectFill,
options: options
) { (image, _) in
defer { dispatchGroup.leave() }
if let data = image?.jpegData(compressionQuality: 1) {
var imageURL =
tmpDirectory.appendingPathComponent(imageURLInLibrary.lastPathComponent)
imageURL.deletePathExtension()
imageURL.appendPathExtension(for: .jpeg)
do {
try data.write(to: imageURL, options: .atomic)
} catch {
fatalError("Couldn't save training image to \(imageURL): \(error)")
}
labels.append(label)
imagePaths.append(imageURL.path)
}
}
}
}
}
dispatchGroup.wait()
return (labels, imagePaths)
}
}
|
987c8e413ee8b283940c6dfd3a10bd9d
| 40.953271 | 100 | 0.663399 | false | false | false | false |
haitran2011/Rocket.Chat.iOS
|
refs/heads/develop
|
Rocket.Chat/Extensions/DateExtension.swift
|
mit
|
1
|
//
// DateExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 7/11/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
extension Date {
public static func dateFromInterval(_ interval: Double) -> Date? {
return Date(timeIntervalSince1970: interval / 1000)
}
public static func intervalFromDate(_ date: Date) -> Double {
return date.timeIntervalSince1970 * 1000
}
var weekday: String {
return self.formatted("EEE")
}
var day: String {
return self.formatted("dd")
}
var month: String {
return self.formatted("MM")
}
var monthString: String {
return self.formatted("MMMM")
}
var year: String {
return self.formatted("YYYY")
}
func formatted(_ format: String = "dd/MM/yyyy HH:mm:ss ZZZ") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
var dayOfWeek: Int {
let calendar = NSCalendar.current
let comp: DateComponents = (calendar as NSCalendar).components(.weekday, from: self)
return comp.weekday ?? -1
}
}
|
a816de929be5f2c1afbe70c0b5e8439a
| 21.867925 | 92 | 0.619637 | false | false | false | false |
nickqiao/NKBill
|
refs/heads/master
|
NKBill/Controller/NKTabBarController.swift
|
apache-2.0
|
1
|
//
// NKBaseTabBarController.swift
// NKBill
//
// Created by nick on 16/1/30.
// Copyright © 2016年 NickChen. All rights reserved.
//
import UIKit
class NKTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.delegate = self
self.tabBar.items![0].selectedImage = UIImage(named: "index")
}
override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
if item.title == "记一笔" {
performSegueWithIdentifier("compose", sender: nil)
}
}
}
extension NKTabBarController: UITabBarControllerDelegate {
func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool {
if viewController == tabBarController.viewControllers![2] {
return false
}else {
return true
}
}
}
|
62a501ce610bd479221485c0f97b964a
| 22.465116 | 134 | 0.635282 | false | false | false | false |
dps923/winter2017
|
refs/heads/edits
|
notes/week_11/WhereAmI/Classes/MyLocation.swift
|
mit
|
2
|
//
// MyLocation.swift
// Location
//
// Copyright (c) 2017 School of ICT, Seneca College. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class Pin: NSObject, MKAnnotation {
let _coordinate: CLLocationCoordinate2D
init(coordinate: CLLocationCoordinate2D) {
self._coordinate = coordinate
super.init()
}
public var coordinate: CLLocationCoordinate2D {
return _coordinate
}
public var title: String? {
return "location"
}
public var subtitle: String? {
return "subtitle"
}
}
class MyLocation: UIViewController {
var lm: CLLocationManager!
// MARK: - User interface
@IBOutlet weak var toggleLocationButton: UIButton!
@IBOutlet weak var latitude: UILabel!
@IBOutlet weak var longitude: UILabel!
@IBOutlet weak var myMap: MKMapView!
// MARK: - UI interactions
@IBAction func toggleLocation(_ sender: UIButton) {
if myMap.showsUserLocation {
lm.stopUpdatingLocation()
} else {
lm.startUpdatingLocation()
}
myMap.showsUserLocation = !myMap.showsUserLocation
}
@IBAction func onPinDrop(_ sender: UIButton) {
let pin = Pin(coordinate: myMap.centerCoordinate)
myMap.addAnnotation(pin)
}
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.configureLocationObjects()
}
fileprivate func configureLocationObjects() {
myMap.delegate = self
// Initialize and configure the location manager
lm = CLLocationManager()
lm.delegate = self
// Change these values to affect the update frequency
lm.distanceFilter = 100
lm.desiredAccuracy = kCLLocationAccuracyHundredMeters
lm.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("Location services enabled\n")
lm.startUpdatingLocation()
myMap.showsUserLocation = true
}
}
}
extension MyLocation : CLLocationManagerDelegate {
// CLLocationManagerDelegate has many methods, all are optional.
// We only need these three.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
manager.startUpdatingLocation()
myMap.showsUserLocation = true
} else {
print("User didn't authorize location services, status: \(status)")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Most recent location is the last item in the 'locations' array
// The array has CLLocation objects, 'coordinate' property has lat and long
// Other properties are 'altitude' and 'timestamp'
if let l = locations.last {
// Display the latitude and longitude
latitude.text = "Lat: \(l.coordinate.latitude)"
longitude.text = "Long: \(l.coordinate.longitude)"
print("location update \(latitude.text!) \(longitude.text!)")
// When the map first loads, it is zoomed out to show country or world level, let's detect that
// and zoom in to 2km x 2km
let kmPerDegreeLat = 111.325 // roughly!
let maxKmSpanToShow = 100.0
// If more than 100km from top-to-bottom is being shown, zoom in to 2km x 2km
if myMap.region.span.latitudeDelta * kmPerDegreeLat > maxKmSpanToShow {
// Set the display region of the map
myMap.setRegion(MKCoordinateRegionMakeWithDistance(l.coordinate, 2000, 2000), animated: true)
}
}
myMap.userTrackingMode = .follow
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error: \(error)")
let nserr = error as NSError
if nserr.domain == "kCLErrorDomain" && nserr.code == 0 {
print("(If you are in simulator: Go to Simulator app menu Debug>Location and enable a location.")
}
}
}
extension MyLocation: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "annotationView")
annotationView.canShowCallout = true
annotationView.rightCalloutAccessoryView = UIButton.init(type: UIButtonType.detailDisclosure)
return annotationView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
guard let annotation = view.annotation else{
return
}
print("calloutAccessoryControlTapped: \(annotation.coordinate.latitude),\(annotation.coordinate.longitude)")
}
}
|
22a58e33cdc18fc45e476e94cf9218fb
| 31.211538 | 129 | 0.649154 | false | false | false | false |
MilanNosal/InteractiveTransitioningContainer
|
refs/heads/master
|
InteractiveTransitioningContainer/InteractiveTransitioningContainerLayerBasedPercentDrivenInteractiveTransition.swift
|
mit
|
1
|
//
// InteractiveTransitioningContainerPercentDrivenInteractiveTransition.swift
// InteractiveTransitioningContainer
//
// Created by Milan Nosáľ on 22/01/2017.
// Copyright © 2017 Svagant. All rights reserved.
//
import UIKit
// Custom percent driven interactive transition object - should be inherited from when used with InteractiveTransitioningContainer
// I've had some problems with the original implementation of Alek Akstrom, so I use this slight modification
// This is NOT the recommended approach, left only for backward compatibility with animation
// controllers that do not provide interruptibleAnimator
// If it is possible, please use InteractiveTransitionContainerAnimatorBasedPercentDrivenInteractiveTransition instead
//
// Credits also to Alek Akstrom
// - http://www.iosnomad.com/blog/2014/5/12/interactive-custom-container-view-controller-transitions
public class InteractiveTransitionContainerLayerBasedPercentDrivenInteractiveTransition: InteractiveTransitionContainerPercentDrivenInteractiveTransition {
open override var percentComplete: CGFloat {
didSet {
let offset = TimeInterval(percentComplete * duration)
self.timeOffset = offset
}
}
// MARK: Internal fields
fileprivate var timeOffset: TimeInterval {
set {
transitionContext!.containerView.layer.timeOffset = newValue
}
get {
return transitionContext!.containerView.layer.timeOffset
}
}
fileprivate var displayLink: CADisplayLink?
open override func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) {
guard state == .isInactive else {
return
}
super.startInteractiveTransition(transitionContext)
transitionContext.containerView.layer.speed = 0
self.animator!.animateTransition(using: transitionContext)
}
open override func cancelInteractiveTransition() {
guard state == .isInteracting else {
return
}
super.cancelInteractiveTransition()
self.completeTransition()
}
open override func finishInteractiveTransition() {
guard state == .isInteracting else {
return
}
super.finishInteractiveTransition()
self.completeTransition()
}
// MARK: Internal methods
fileprivate func completeTransition() {
displayLink = CADisplayLink(target: self, selector: #selector(InteractiveTransitionContainerLayerBasedPercentDrivenInteractiveTransition.tickAnimation))
displayLink!.add(to: RunLoop.main, forMode: .commonModes)
}
@objc fileprivate func tickAnimation() {
var timeOffset = self.timeOffset
let tick = displayLink!.duration * CFTimeInterval(self.completionSpeed)
timeOffset = timeOffset + (transitionContext!.transitionWasCancelled ? -tick : tick)
if timeOffset < 0 || timeOffset > TimeInterval(self.duration) {
self.transitionFinished()
} else {
self.timeOffset = timeOffset
}
}
fileprivate func transitionFinished() {
displayLink!.invalidate()
let layer = transitionContext!.containerView.layer
layer.speed = 1
if transitionContext!.transitionWasCancelled {
// TODO: Test for glitch
} else {
layer.timeOffset = 0
layer.beginTime = 0
}
super.interactiveTransitionCompleted()
}
}
|
ae3829182678e9bcd710d9c80b485825
| 34.176471 | 160 | 0.683389 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.