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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jiankaiwang/codein
|
refs/heads/master
|
examples/oop.swift
|
mit
|
1
|
/*
* desc : structure and class definition
* docv : 0.1.0
* plat : CodeIn
* swif : 5.1.3
*/
struct Car {
var weight = 0
var horsepower = 0
var name = ""
}
class CarPhysicalProperty {
var carInfo = Car()
var acceleration : Double = 0.0
// private void function
private func calAccelerate() {
self.acceleration =
Double(self.carInfo.horsepower) / Double(self.carInfo.weight)
}
// constructor
init(carWeight : Int, carHorsepower : Int, carName : String) {
self.carInfo = Car(
weight : carWeight,
horsepower : carHorsepower,
name : carName
)
self.calAccelerate()
}
// public Double function
public func getCarAcc() -> Double {
return(self.acceleration)
}
// public String function
public func getCarName() -> String {
return(self.carInfo.name)
}
}
var firstCar = CarPhysicalProperty(
carWeight : 100, carHorsepower : 200, carName : "FCar"
)
print("The accelerate of \(firstCar.getCarName()) is \(firstCar.getCarAcc()).")
|
86b91eb217d037fc10b657640afdbd2a
| 21.979592 | 80 | 0.586146 | false | false | false | false |
CJGitH/QQMusic
|
refs/heads/master
|
QQMusic/Classes/Other/Tool/视频播放/视频播放/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// 视频播放
//
// Created by chen on 16/5/18.
// Copyright © 2016年 chen. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
var layer: AVPlayerLayer?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let url = NSURL(string: "http://v1.mukewang.com/19954d8f-e2c2-4c0a-b8c1-a4c826b5ca8b/L.mp4")
player = AVPlayer(URL: url!)
player?.play()
//添加到layer上播放
layer = AVPlayerLayer(player: player)
layer?.frame = view.bounds
view.layer.addSublayer(layer!)
}
//当点击停止时,就暂停视频播放
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
player?.pause()
}
//设置尺寸,在这里设置才zhunque
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layer?.frame = view.bounds
}
}
|
a8c88e36818ee57caa5d2f3e82572d92
| 20.446809 | 100 | 0.607143 | false | false | false | false |
xuech/OMS-WH
|
refs/heads/master
|
OMS-WH/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// OMS-WH
//
// Created by ___Gwy on 2017/8/15.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
import CoreData
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var time:Timer?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
keyBoardManager()
UIApplication.shared.statusBarStyle = .lightContent
RemoteManager.finishLaunching(at: application,with: launchOptions)
window = UIWindow(frame: SCREEN_BOUNDS)
window!.makeKeyAndVisible()
window?.rootViewController = LoginViewController()
defaultController()
return true
}
func application(_ application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
RemoteManager.shareInstance.application(application,didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
}
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.
time = Timer.scheduledTimer(timeInterval: 20.0, target: self, selector: #selector(AppDelegate.showTap), userInfo: nil, repeats: false)
}
func applicationWillEnterForeground(_ application: UIApplication) {
time!.invalidate()
RemoteManager.shareInstance.dearWithPushBadge()
}
func applicationDidBecomeActive(_ application: UIApplication) {
RemoteManager.shareInstance.dearWithPushBadge()
Method.getMethod().systemUpdate { (result, error) in
}
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "WMS")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
@objc fileprivate func showTap(){
if UserDefaults.Global.readString(forKey: .token) != nil{
if UserDefaults.Global.boolValue(forKey: .tapAllow) == true{
let tapView = TapAllowView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
self.window?.addSubview(tapView)
}
}
}
func defaultController(){
if !(UserDefaults.standard.bool(forKey: "everLaunched")){
UserDefaults.standard.set(true, forKey: "everLaunched")
self.window?.rootViewController = GuideViewController()
}else{
if let _ = UserDefaults.Global.readString(forKey: .token){
self.window?.rootViewController = OMSTabBarController()
if UserDefaults.Global.boolValue(forKey: .tapAllow) == true{
let tapView = TapAllowView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
self.window?.addSubview(tapView)
}
}else{
self.window?.rootViewController = LoginViewController()
}
}
}
}
extension AppDelegate {
//MARK:-键盘
fileprivate func keyBoardManager() {
let keyBoardManager = IQKeyboardManager.sharedManager()
keyBoardManager.enable = true
keyBoardManager.toolbarTintColor = kAppearanceColor
// keyBoardManager.shouldResignOnTouchOutside = true
// keyBoardManager.shouldToolbarUsesTextFieldTintColor = false
// keyBoardManager.enableAutoToolbar = true
}
}
|
4ab7584eceaeb7f5d717b5277d31d8cf
| 43.526316 | 285 | 0.666076 | false | false | false | false |
coderZsq/coderZsq.target.swift
|
refs/heads/master
|
StudyNotes/Swift Note/LiveBroadcast/Server/LiveBroadcastServer/Server/ServerManager.swift
|
mit
|
1
|
//
// ServerManager.swift
// LiveBroadcastServer
//
// Created by 朱双泉 on 2018/12/13.
// Copyright © 2018 Castie!. All rights reserved.
//
import Cocoa
class ServerManager {
fileprivate lazy var serverSocket = TCPServer(addr: "0.0.0.0", port: 6666)
fileprivate var isServerRunning = false
fileprivate lazy var clientManagers = [ClientManager]()
}
extension ServerManager {
func startRunning() {
serverSocket.listen()
isServerRunning = true
DispatchQueue.global().async {
while self.isServerRunning {
if let client = self.serverSocket.accept() {
DispatchQueue.global().async {
self.handlerClient(client)
}
}
}
}
}
func stopRunning() {
isServerRunning = false
}
}
extension ServerManager {
fileprivate func handlerClient(_ client: TCPClient) {
let manager = ClientManager(tcpClient: client)
clientManagers.append(manager)
manager.delegate = self
manager.startReadMessage()
}
}
extension ServerManager: ClientManagerDelegate {
func removeClient(_ client: ClientManager) {
guard let index = clientManagers.index(of: client) else { return }
clientManagers.remove(at: index)
}
func sendMsgToClient(_ data: Data) {
for manager in clientManagers {
manager.tcpClient.send(data: data)
}
}
}
|
7755234c359876f5237bcafbc41ce9cd
| 23.322581 | 78 | 0.599469 | false | false | false | false |
Speicher210/wingu-sdk-ios-demoapp
|
refs/heads/master
|
Example/Pods/KDEAudioPlayer/AudioPlayer/AudioPlayer/player/extensions/AudioPlayer+PlayerEvent.swift
|
apache-2.0
|
2
|
//
// AudioPlayer+PlayerEvent.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 03/04/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
extension AudioPlayer {
/// Handles player events.
///
/// - Parameters:
/// - producer: The event producer that generated the player event.
/// - event: The player event.
func handlePlayerEvent(from producer: EventProducer, with event: PlayerEventProducer.PlayerEvent) {
switch event {
case .endedPlaying(let error):
if let error = error {
state = .failed(.foundationError(error))
} else {
nextOrStop()
}
case .interruptionBegan where state.isPlaying || state.isBuffering:
//We pause the player when an interruption is detected
backgroundHandler.beginBackgroundTask()
pausedForInterruption = true
pause()
case .interruptionEnded where pausedForInterruption:
if resumeAfterInterruption {
resume()
}
pausedForInterruption = false
backgroundHandler.endBackgroundTask()
case .loadedDuration(let time):
if let currentItem = currentItem, let time = time.ap_timeIntervalValue {
updateNowPlayingInfoCenter()
delegate?.audioPlayer(self, didFindDuration: time, for: currentItem)
}
case .loadedMetadata(let metadata):
if let currentItem = currentItem, !metadata.isEmpty {
currentItem.parseMetadata(metadata)
delegate?.audioPlayer(self, didUpdateEmptyMetadataOn: currentItem, withData: metadata)
}
case .loadedMoreRange:
if let currentItem = currentItem, let currentItemLoadedRange = currentItemLoadedRange {
delegate?.audioPlayer(self, didLoad: currentItemLoadedRange, for: currentItem)
}
case .progressed(let time):
if let currentItemProgression = time.ap_timeIntervalValue, let item = player?.currentItem,
item.status == .readyToPlay {
//This fixes the behavior where sometimes the `playbackLikelyToKeepUp` isn't
//changed even though it's playing (happens mostly at the first play though).
if state.isBuffering || state.isPaused {
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
} else {
player?.rate = 0
state = .paused
}
backgroundHandler.endBackgroundTask()
}
//Then we can call the didUpdateProgressionTo: delegate method
let itemDuration = currentItemDuration ?? 0
let percentage = (itemDuration > 0 ? Float(currentItemProgression / itemDuration) * 100 : 0)
delegate?.audioPlayer(self, didUpdateProgressionTo: currentItemProgression, percentageRead: percentage)
}
case .readyToPlay:
//There is enough data in the buffer
if shouldResumePlaying {
stateBeforeBuffering = nil
state = .playing
player?.rate = rate
} else {
player?.rate = 0
state = .paused
}
//TODO: where to start?
retryEventProducer.stopProducingEvents()
backgroundHandler.endBackgroundTask()
case .routeChanged:
//In some route changes, the player pause automatically
//TODO: there should be a check if state == playing
if let player = player, player.rate == 0 {
state = .paused
}
case .sessionMessedUp:
#if os(iOS) || os(tvOS)
//We reenable the audio session directly in case we're in background
setAudioSession(active: true)
//Aaaaand we: restart playing/go to next
state = .stopped
qualityAdjustmentEventProducer.interruptionCount += 1
retryOrPlayNext()
#endif
case .startedBuffering:
//The buffer is empty and player is loading
if case .playing = state, !qualityIsBeingChanged {
qualityAdjustmentEventProducer.interruptionCount += 1
}
stateBeforeBuffering = state
if reachability.isReachable() || (currentItem?.soundURLs[currentQuality]?.ap_isOfflineURL ?? false) {
state = .buffering
} else {
state = .waitingForConnection
}
backgroundHandler.beginBackgroundTask()
default:
break
}
}
}
|
fb8e5f7cac7e8f5e010d9675984ac5b9
| 37.421875 | 119 | 0.565677 | false | false | false | false |
MadeByHecho/DeLorean
|
refs/heads/master
|
Carthage/Checkouts/Miles/Miles/Miles.swift
|
mit
|
2
|
//
// Miles.swift
// Miles
//
// Created by Scott Petit on 2/16/15.
// Copyright (c) 2015 Hecho. All rights reserved.
//
import XCTest
import Foundation
public extension Equatable {
public func shouldEqual<T: Equatable>(other: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to equal \(other)"
if let other = other as? Self {
XCTAssertEqual(self, other, message, file: file, line: line)
} else {
XCTAssertTrue(false, message, file: file, line: line)
}
}
}
public extension Comparable {
public func shouldBeGreaterThan<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be greater than \(other)"
if let other = other as? Self {
XCTAssertGreaterThan(self, other, message)
} else {
XCTAssertTrue(false, message)
}
}
public func shouldBeGreaterThanOrEqualTo<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be greater than or equal to \(other)"
if let other = other as? Self {
XCTAssertGreaterThanOrEqual(self, other, message)
} else {
XCTAssertTrue(false, message)
}
}
public func shouldBeLessThan<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be less than \(other)"
if let other = other as? Self {
XCTAssertLessThan(self, other, message)
} else {
XCTAssertTrue(false, message)
}
}
public func shouldBeLessThanOrEqualTo<T: Comparable>(other: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be less than or Equal to \(other)"
if let other = other as? Self {
XCTAssertLessThanOrEqual(self, other, message)
} else {
XCTAssertTrue(false, message)
}
}
}
public extension FloatingPointType {
public func shouldBeCloseTo<T: FloatingPointType>(other: T, withAccuracy accuracy: T, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be within \(accuracy) of \(other)"
if let other = other as? Self, accuracy = accuracy as? Self {
XCTAssertEqualWithAccuracy(self, other, accuracy: accuracy, message, file: file, line: line)
} else {
XCTAssertTrue(false, message)
}
}
}
public extension String {
public func shouldContain(string: String, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to contain \(string)"
XCTAssertTrue(self.rangeOfString(string) != nil, message, file: file, line: line)
}
public func shouldHavePrefix(string: String, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to have a prefix of \(string)"
XCTAssertTrue(self.hasPrefix(string), message, file: file, line: line)
}
public func shouldHaveSuffix(string: String, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to have a suffix of \(string)"
XCTAssertTrue(self.hasSuffix(string), message, file: file, line: line)
}
}
public extension Bool {
func shouldBeTrue(file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be true"
XCTAssertTrue(self, message, file: file, line: line)
}
func shouldBeFalse(file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be false"
XCTAssertFalse(self, message, file: file, line: line)
}
}
public extension NSObject {
func shouldEqual(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to equal \(object)"
XCTAssertEqual(self, object, message, file: file, line: line)
}
func shouldNotEqual(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to not equal \(object)"
XCTAssertNotEqual(self, object, message, file: file, line: line)
}
func shouldBeIdenticalTo(object: NSObject, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be identical to \(object))"
XCTAssertTrue(self === object, message, file: file, line: line)
}
func shouldBeKindOfClass(aClass: AnyClass, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be kind of Class \(aClass)"
XCTAssertTrue(self.isKindOfClass(aClass), message, file: file, line: line)
}
}
public extension CollectionType where Generator.Element : Equatable {
func shouldContain(item: Self.Generator.Element, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to contain \(item)"
var contains = false
if let _ = indexOf(item) {
contains = true
}
XCTAssertTrue(contains, message, file: file, line: line)
}
}
public extension CollectionType {
func shouldBeEmpty(file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be empty"
XCTAssertTrue(isEmpty, message, file: file, line: line)
}
}
public extension Dictionary where Value : Equatable {
func shouldContain(item: Value, file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to contain \(item)"
var contains = false
for value in values {
if value == item {
contains = true
break
}
}
XCTAssertTrue(contains, message, file: file, line: line)
}
}
public extension Optional {
public func shouldBeNil(file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to be nil"
switch self {
case .Some(_):
XCTAssertTrue(false, message, file: file, line: line)
case .None:
XCTAssertTrue(true, message, file: file, line: line)
}
}
public func shouldNotBeNil(file: String = __FILE__, line: UInt = __LINE__) {
let message = "Expected \(self) to not be nil"
switch self {
case .Some(_):
XCTAssertTrue(true, message, file: file, line: line)
case .None:
XCTAssertTrue(false, message, file: file, line: line)
}
}
}
|
75294ce42787bd10d8c45397370993fe
| 36.361582 | 139 | 0.592016 | false | false | false | false |
Chen-Dixi/SwiftHashDict
|
refs/heads/master
|
sy4/sy4/hashdict.swift
|
mit
|
1
|
//
// hashdict.swift
// sy4
//
// Created by Dixi-Chen on 16/6/16.
// Copyright © 2016年 Dixi-Chen. All rights reserved.
//
import Foundation
class hashdict<Key:Equatable,E>{
var HT : [KVpair<Key,E>!]
let EMPTYKEY:Key
let M:Int
var count:Int
var perm = [Int]()
init(sz:Int, k:Key)
{
self.count = 0
self.M = sz
self.EMPTYKEY = k
self.HT = [KVpair<Key,E>!](count: sz, repeatedValue: KVpair<Key,E>(EMPTYKEY,nil)) //这里的感叹号不是很明白
for var i=0 ; i<M; {
let temp = Int.random(M)
if nil == perm.indexOf(temp){
i = i + 1
perm.append(temp)
}
}
}
func size()->Int{
return count
}
private func h(x:Int) -> Int{
return x % M
}
private func h(x:String) -> Int{
var sum:Int = 0
for c in x.unicodeScalars {
sum += Int(c.value)
}
return sum % M
}
private func p(key:Key, i:Int) -> Int{
return perm[i-1]
}
func find(k:Key) -> E?
{
return hashSearch(k)
}
func insert(k:Key,e:E){
hashInsert(k, e: e)
count += 1
}
}
extension hashdict{
private func hashInsert(key:Key,e:E) {
var home:Int
var pos:Int
if key is Int {
home = self.h(key as! Int)
pos = home
}else {
home = self.h(key as! String)
pos = home
}
var i = 1
while EMPTYKEY != (HT[pos]).key()
{
pos = (home + p(key,i: i)) % M
assert( key != (HT[pos].key()), "Duplicates not allowed")
i += 1
}
let temp = KVpair<Key,E>(key,e)
HT[pos] = temp
}
private func hashSearch(key:Key) -> E?{
var home:Int
var pos:Int
if key is Int {
home = self.h(key as! Int)
pos = home
}else {
home = self.h(key as! String)
pos = home
}
var i = 1
while EMPTYKEY != (HT[pos]).key() && key != (HT[pos]).key()
{
pos = (home + p(key,i: i)) % M
i += 1
}
if key == (HT[pos]).key() {
return (HT[pos]).value()
}
else{
return nil
}
}
}
private extension Int{
static func random(max:Int) -> Int{
return Int(arc4random_uniform(UInt32(max)))
}
}
|
8cb16ddd9c66cb88060bb2ec817cd38b
| 19.540323 | 104 | 0.433621 | false | false | false | false |
nalexn/ViewInspector
|
refs/heads/master
|
Sources/ViewInspector/SwiftUI/LazyHGrid.swift
|
mit
|
1
|
import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct LazyHGrid: KnownViewType {
public static var typePrefix: String = "LazyHGrid"
}
}
// MARK: - Extraction from SingleViewContent parent
@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)
public extension InspectableView where View: SingleViewContent {
func lazyHGrid() throws -> InspectableView<ViewType.LazyHGrid> {
return try .init(try child(), parent: self)
}
}
// MARK: - Extraction from MultipleViewContent parent
@available(iOS 14.0, macOS 11.0, tvOS 14.0, *)
public extension InspectableView where View: MultipleViewContent {
func lazyHGrid(_ index: Int) throws -> InspectableView<ViewType.LazyHGrid> {
return try .init(try child(at: index), parent: self, index: index)
}
}
// MARK: - Content Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.LazyHGrid: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
let view = try Inspector.attribute(path: "tree|content", value: content.view)
return try Inspector.viewsInContainer(view: view, medium: content.medium)
}
}
// MARK: - Custom Attributes
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
public extension InspectableView where View == ViewType.LazyHGrid {
func alignment() throws -> VerticalAlignment {
return try Inspector.attribute(
label: "alignment", value: lazyHGridLayout(), type: VerticalAlignment.self)
}
func spacing() throws -> CGFloat? {
return try Inspector.attribute(
label: "spacing", value: lazyHGridLayout(), type: CGFloat?.self)
}
func pinnedViews() throws -> PinnedScrollableViews {
return try Inspector.attribute(
label: "pinnedViews", value: lazyHGridLayout(), type: PinnedScrollableViews.self)
}
func rows() throws -> [GridItem] {
return try Inspector.attribute(
label: "rows", value: lazyHGridLayout(), type: [GridItem].self)
}
private func lazyHGridLayout() throws -> Any {
return try Inspector.attribute(path: "tree|root", value: content.view)
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension GridItem: Equatable {
public static func == (lhs: GridItem, rhs: GridItem) -> Bool {
return lhs.size == rhs.size
&& lhs.spacing == rhs.spacing
&& lhs.alignment == rhs.alignment
}
}
@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *)
extension GridItem.Size: Equatable {
public static func == (lhs: GridItem.Size, rhs: GridItem.Size) -> Bool {
switch (lhs, rhs) {
case let (.fixed(lhsValue), .fixed(rhsValue)):
return lhsValue == rhsValue
case let (.flexible(lhsMin, lhsMax), .flexible(rhsMin, rhsMax)):
return lhsMin == rhsMin && lhsMax == rhsMax
case let (.adaptive(lhsMin, lhsMax), .adaptive(rhsMin, rhsMax)):
return lhsMin == rhsMin && lhsMax == rhsMax
default:
return false
}
}
}
|
70e24c027c718c70a37765f8a13525ff
| 32.4 | 93 | 0.64324 | false | false | false | false |
yura-voevodin/SumDUBot
|
refs/heads/master
|
Sources/App/Commands/MessengerCommand.swift
|
mit
|
1
|
//
// MessengerCommand.swift
// App
//
// Created by Yura Voevodin on 24.09.17.
//
import Vapor
final class MessengerComand: Command {
/// See `Command`
var arguments: [CommandArgument] {
return [.argument(name: "type")]
}
/// See `Command`.
public var options: [CommandOption] {
return []
}
/// See `Command`
var help: [String] {
return ["This command tests a Messenger bot"]
}
func run(using context: CommandContext) throws -> EventLoopFuture<Void> {
let type = try context.argument("type")
// TODO: Finish this command
context.console.print(type, newLine: true)
return .done(on: context.container)
}
/// Create a new `BootCommand`.
public init() { }
}
// MARK: - Methods
extension MessengerComand {
private func search(_ request: String?) throws {
// guard let request = request else { return }
//
// var searchResults: [Button] = []
// searchResults = try Auditorium.find(by: request)
//
// print(searchResults)
}
private func show(_ request: String?) throws {
// guard let request = request else { return }
//
// var result: [String] = []
// if request.hasPrefix(ObjectType.auditorium.prefix) {
// result = try Auditorium.show(for: request, client: client)
// }
// print(result)
}
}
|
2d84e3ff97fc79b082cec2101b86cdde
| 22.095238 | 77 | 0.564948 | false | false | false | false |
TouchInstinct/LeadKit
|
refs/heads/master
|
Sources/Extensions/DataLoading/PaginationDataLoading/PaginationWrapperUIDelegate+DefaultImplementation.swift
|
apache-2.0
|
1
|
//
// Copyright (c) 2018 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public extension PaginationWrapperUIDelegate {
func emptyPlaceholder() -> UIView? {
TextPlaceholderView(title: .empty)
}
func customInitialLoadingErrorHandling(for error: Error) -> Bool {
false
}
func errorPlaceholder(for error: Error) -> UIView? {
TextPlaceholderView(title: .error)
}
func initialLoadingIndicator() -> AnyLoadingIndicator? {
let indicator = UIActivityIndicatorView(style: .whiteLarge)
indicator.color = .gray
return AnyLoadingIndicator(indicator)
}
func loadingMoreIndicator() -> AnyLoadingIndicator? {
let indicator = UIActivityIndicatorView(style: .gray)
return AnyLoadingIndicator(indicator)
}
func footerRetryView() -> ButtonHolderView? {
let retryButton = UIButton(type: .custom)
retryButton.backgroundColor = .lightGray
retryButton.setTitle("Retry load more", for: .normal)
return retryButton
}
func footerRetryViewHeight() -> CGFloat {
44
}
func footerRetryViewWillAppear() {
// by default - nothing will happen
}
func footerRetryViewWillDisappear() {
// by default - nothing will happen
}
}
|
618c6f7ed4ab6234eeba9854ab339f25
| 32.323944 | 81 | 0.703297 | false | false | false | false |
envoy/Embassy
|
refs/heads/master
|
Sources/SelectSelector.swift
|
mit
|
1
|
//
// SelectSelector.swift
// Embassy
//
// Created by Fang-Pen Lin on 1/6/17.
// Copyright © 2017 Fang-Pen Lin. All rights reserved.
//
import Foundation
public final class SelectSelector: Selector {
enum Error: Swift.Error {
case keyError(fileDescriptor: Int32)
}
private var fileDescriptorMap: [Int32: SelectorKey] = [:]
public init() throws {
}
@discardableResult
public func register(
_ fileDescriptor: Int32,
events: Set<IOEvent>,
data: Any?
) throws -> SelectorKey {
// ensure the file descriptor doesn't exist already
guard fileDescriptorMap[fileDescriptor] == nil else {
throw Error.keyError(fileDescriptor: fileDescriptor)
}
let key = SelectorKey(fileDescriptor: fileDescriptor, events: events, data: data)
fileDescriptorMap[fileDescriptor] = key
return key
}
@discardableResult
public func unregister(_ fileDescriptor: Int32) throws -> SelectorKey {
// ensure the file descriptor exists
guard let key = fileDescriptorMap[fileDescriptor] else {
throw Error.keyError(fileDescriptor: fileDescriptor)
}
fileDescriptorMap.removeValue(forKey: fileDescriptor)
return key
}
public func close() {
}
public func select(timeout: TimeInterval?) throws -> [(SelectorKey, Set<IOEvent>)] {
var readSet = fd_set()
var writeSet = fd_set()
var maxFd: Int32 = 0
for (fd, key) in fileDescriptorMap {
if fd > maxFd {
maxFd = fd
}
if key.events.contains(.read) {
SystemLibrary.fdSet(fd: fd, set: &readSet)
}
if key.events.contains(.write) {
SystemLibrary.fdSet(fd: fd, set: &writeSet)
}
}
let status: Int32
let microsecondsPerSecond = 1000000
if let timeout = timeout {
var timeoutVal = timeval()
#if os(Linux)
timeoutVal.tv_sec = Int(timeout)
timeoutVal.tv_usec = Int(
Int(timeout * Double(microsecondsPerSecond)) -
timeoutVal.tv_sec * microsecondsPerSecond
)
#else
// TODO: not sure is the calculation correct here
timeoutVal.tv_sec = Int(timeout)
timeoutVal.tv_usec = __darwin_suseconds_t(
Int(timeout * Double(microsecondsPerSecond)) -
timeoutVal.tv_sec * microsecondsPerSecond
)
#endif
status = SystemLibrary.select(maxFd + 1, &readSet, &writeSet, nil, &timeoutVal)
} else {
status = SystemLibrary.select(maxFd + 1, &readSet, &writeSet, nil, nil)
}
switch status {
case 0:
// TODO: timeout?
return []
// Error
case -1:
throw OSError.lastIOError()
default:
break
}
var result: [(SelectorKey, Set<IOEvent>)] = []
for (fd, key) in fileDescriptorMap {
var events = Set<IOEvent>()
if SystemLibrary.fdIsSet(fd: fd, set: &readSet) {
events.insert(.read)
}
if SystemLibrary.fdIsSet(fd: fd, set: &writeSet) {
events.insert(.write)
}
if events.count > 0 {
result.append((key, events))
}
}
return result
}
public subscript(fileDescriptor: Int32) -> SelectorKey? {
get {
return fileDescriptorMap[fileDescriptor]
}
}
}
|
a9f39e1fd53153144e55f42e97b71754
| 29.579832 | 91 | 0.552075 | false | false | false | false |
zhou9734/Warm
|
refs/heads/master
|
Warm/Classes/Me/Model/WMenu.swift
|
mit
|
1
|
//
// Menu.swift
// Warm
//
// Created by zhoucj on 16/9/17.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
class WMenu: NSObject {
var menus: [Menu]?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forKey key: String) {
if key == "menus"{
guard let _data = value as? [[String: AnyObject]] else{
return
}
var _menus = [Menu]()
for i in _data{
let menu = Menu(dict: i)
_menus.append(menu)
}
menus = _menus
return
}
super.setValue(value, forKey: key)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
class Menu: NSObject {
var image: String?
var name: String?
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//防治没有匹配到的key报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
|
965940b65b33bc26ea3468fb99e359c4
| 23.695652 | 76 | 0.554577 | false | false | false | false |
tnantoka/GameplayKitSandbox
|
refs/heads/master
|
GameplayKitSandbox/VisualComponent.swift
|
mit
|
1
|
//
// VisualComponent.swift
// GameplayKitSandbox
//
// Created by Tatsuya Tobioka on 2015/09/21.
// Copyright © 2015年 tnantoka. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class VisualComponent: GKComponent {
let sprite: SKSpriteNode
var position = CGPoint.zero {
didSet {
sprite.position = position
}
}
init(color: SKColor, size: CGSize) {
sprite = SKSpriteNode(color: color, size: size)
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func moveTo(_ position: CGPoint) {
let action = SKAction.move(to: position, duration: 0.3)
sprite.run(action, completion: {
self.position = position
})
}
func moveBy(_ x: CGFloat, _ y: CGFloat) {
let p = CGPoint(x: position.x + x, y: position.y + y)
moveTo(p)
}
}
|
4a70a924aa495fcd1f2328c390559f9d
| 21.209302 | 63 | 0.602094 | false | false | false | false |
rivetlogic/liferay-mobile-directory-ios
|
refs/heads/master
|
MobilePeopleDirectory/PeopleListViewController.swift
|
gpl-3.0
|
1
|
//
// PeopleListViewController.swift
// MobilePeopleDirectory
//
// Created by Martin Zary on 1/6/15.
// Copyright (c) 2015 Rivet Logic. All rights reserved.
//
import UIKit
import CoreData
class PeopleListViewController: UITableViewController, NSFetchedResultsControllerDelegate, UISearchBarDelegate {
@IBOutlet weak var searchBar: UISearchBar!
var searchActive:Bool = false
var searchResultsList: [Person] = []
var personViewController: PersonViewController? = nil
var managedObjectContext: NSManagedObjectContext? = nil
var peopleDao:PeopleDao = PeopleDao()
var imageHelper:ImageHelper = ImageHelper()
var serverFetchResult : ServerFetchResult = ServerFetchResult.Success
var alertHelper:AlertHelper = AlertHelper()
var appHelper = AppHelper()
override func awakeFromNib() {
super.awakeFromNib()
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.clearsSelectionOnViewWillAppear = false
self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.personViewController = controllers[controllers.count-1].topViewController as? PersonViewController
}
self.navigationItem.leftBarButtonItem = nil
self.navigationItem.rightBarButtonItem = nil
let logoutButton = UIBarButtonItem(image: UIImage(named: "logout"), style: UIBarButtonItemStyle.Plain, target: self, action: "logout:")
self.navigationItem.rightBarButtonItem = logoutButton
navigationController?.hidesBarsOnSwipe = true
navigationController?.hidesBarsWhenKeyboardAppears = true
//search bar
if let search = self.searchBar {
self.searchBar.delegate = self
}
}
func logout(sender:UIBarButtonItem) {
self.alertHelper.confirmationMessage(self, title: "Please confirm", message: "Are you sure you want to logout?", okButtonText: "Yes", cancelButtonText: "No", confirmed: { _ in
self.appHelper.logout(self)
})
}
private func _showConnectionErrorMessage() {
alertHelper.message(self,
title: "Network",
message: "There are connectivity issues please try again",
buttonText: "OK",
callback: {})
}
override func loadView() {
if !SessionContext.loadSessionFromStore() {
self.appHelper.logout(self)
} else {
super.loadView()
}
}
override func viewWillAppear(animated: Bool) {
var this = self
var peopleSync = ServerSync(syncable: peopleDao,
primaryKey: "userId",
itemsCountKey: "activeUsersCount",
listKey: "users",
errorHandler: { error in
if error == ServerFetchResult.ConnectivityIssue {
println("Connectivity issues")
self._showConnectionErrorMessage()
}
})
serverFetchResult = peopleSync.syncData()
self.searchActive = false
self.searchResultsList = []
if let table = self.tableView {
self.tableView.reloadData()
}
if let search = self.searchBar {
self.searchBar.text = ""
}
let appDelegate: AppDelegate = appHelper.getAppDelegate()
appDelegate.statusBar.backgroundColor = navigationController?.navigationBar.backgroundColor
self.navigationController?.navigationBarHidden = false
}
override func viewDidAppear(animated: Bool) {
if serverFetchResult == .CredIssue {
let loginViewController = Storyboards.Login.Storyboard().instantiateInitialViewController() as? LoginViewController
self.parentViewController?.presentViewController(loginViewController!, animated: true, completion: nil)
}
if serverFetchResult == .ConnectivityIssue {
//TODO: Alert view informing the user of a network error and pointing the to the refresh button to try again
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
// let context = self.fetchedResultsController.managedObjectContext
// let entity = self.fetchedResultsController.fetchRequest.entity!
// let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as NSManagedObject
//
// // If appropriate, configure the new managed object.
// // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
// newManagedObject.setValue(NSDate(), forKey: "timeStamp")
//
// // Save the context.
// var error: NSError? = nil
// if !context.save(&error) {
// // Replace this implementation with code to handle the error appropriately.
// // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
// //println("Unresolved error \(error), \(error.userInfo)")
// abort()
// }
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
var person:Person
if searchActive && self.searchResultsList.count > 0 {
person = searchResultsList[indexPath.row]
} else {
person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person
}
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! PersonViewController
controller.detailItem = person
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.searchActive {
return self.searchResultsList.count
}
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 85.0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell", forIndexPath: indexPath) as! PersonViewCell
self.configureCell(cell, atIndexPath: indexPath)
if indexPath.row % 2 == 0 {
cell.contentView.backgroundColor = UIColor.whiteColor()
}
else {
cell.contentView.backgroundColor = UIColor(red: 241.0/255.0, green: 241.0/255.0, blue: 241.0/255.0, alpha: 1.0)
}
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: PersonViewCell, atIndexPath indexPath: NSIndexPath) {
var person:Person
if searchActive && self.searchResultsList.count > 0 {
person = searchResultsList[indexPath.row]
} else {
person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person
}
//NSLog(person.description)
imageHelper.addThumbnailStyles(cell.thumbnailImage, radius: 30.0)
if imageHelper.hasUserImage(person.portraitUrl) {
imageHelper.addImageFromData(cell.thumbnailImage, image: person.portraitImage)
} else {
cell.thumbnailImage.image = UIImage(named: "UserDefaultImage")
}
cell.username!.text = person.screenName
cell.skypeIcon.hidden = (person.skypeName == "")
cell.emailIcon.hidden = (person.emailAddress == "")
cell.phoneIcon.hidden = (person.userPhone == "")
cell.fullName!.text = person.fullName
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "fullName", ascending: true)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil
)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
//case .Update:
// self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)! as PersonViewCell, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
// MARK: - Search
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchActive = true;
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchActive = false;
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchActive = false;
searchBar.resignFirstResponder()
searchBar.setShowsCancelButton(false, animated: true)
tableView.reloadData()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchActive = false;
searchBar.resignFirstResponder()
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let searchString = searchText
searchResultsList.removeAll(keepCapacity: true)
if !searchString.isEmpty {
let filter:Person -> Bool = { person in
let nameLength = count(person.fullName)
let fullNameRange = person.fullName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
let screenNameRange = person.screenName.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
let emailAddress = person.emailAddress.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch)
return fullNameRange != nil || screenNameRange != nil || emailAddress != nil
}
let sectionInfo = self.fetchedResultsController.sections![0] as! NSFetchedResultsSectionInfo
let persons = sectionInfo.objects as! [Person]
searchResultsList = persons.filter(filter)
}
if(searchResultsList.count == 0){
searchActive = false;
} else {
searchActive = true;
}
self.tableView.reloadData()
}
override func viewWillDisappear(animated: Bool) {
//if searchBar.isFirstResponder() {
// searchBar.resignFirstResponder()
//}
}
}
|
56ff62d1619a949a27ae0d127da1dd8b
| 42.082902 | 360 | 0.658088 | false | false | false | false |
RMK19/UITextField-Shake
|
refs/heads/master
|
UITExtField-Shake/UITextField+Shake.swift
|
mit
|
1
|
//
// UITextField+Shake.swift
// TextField-Shake
//
// Created by Apple on 02/05/15.
// Copyright (c) 2015 Rugmangathan. All rights reserved.
//
import Foundation
import UIKit
enum ShakeDirection: Int {
case horizontal = 0, vertical
};
extension UITextField {
func shake(times: Int, delta: CGFloat) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: 0.03,
shakeDirection: .horizontal,
completionHandler: nil)
}
func shake(times: Int, delta: CGFloat, completionHandler: (() -> Void)?) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: 0.03,
shakeDirection: .horizontal,
completionHandler: completionHandler)
}
public func shake(times: Int, delta: CGFloat, speed: Double) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: speed,
shakeDirection: .horizontal,
completionHandler: nil)
}
public func shake(times: Int, delta: CGFloat, speed: Double,
completionHandler: (() -> Void)?) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: speed,
shakeDirection: .horizontal,
completionHandler: completionHandler)
}
func shake(times: Int, delta: CGFloat, speed: Double, shakeDirection: ShakeDirection) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: speed,
shakeDirection: shakeDirection,
completionHandler: nil)
}
func shake(times: Int, delta: CGFloat, speed: Double, shakeDirection: ShakeDirection,
completionHandler: (() -> Void)?) {
shake(times: times,
direction: 1,
currentTimes: 0,
withDelta: delta,
andSpeed: speed,
shakeDirection: shakeDirection,
completionHandler: completionHandler)
}
func shake(times: Int, direction: Int, currentTimes: Int, withDelta: CGFloat,
andSpeed: Double, shakeDirection: ShakeDirection, completionHandler: (() -> Void)?) {
let animations: () -> Void = { [weak self] in
guard let strongSelf = self else { return }
strongSelf.transform = (shakeDirection == .horizontal
? CGAffineTransform(translationX: withDelta * CGFloat(direction), y: 0)
: CGAffineTransform(translationX: 0, y: withDelta * CGFloat(direction)))
}
let animationCompletion: (Bool) -> Void = { [weak self] finished in
guard let strongSelf = self else { return }
if (currentTimes >= times) {
UIView.animate(withDuration: andSpeed, animations: {
strongSelf.transform = CGAffineTransform.identity
}, completion: { (complete: Bool) in
if (completionHandler != nil) {
completionHandler?()
}
})
return
}
strongSelf.shake(times: (times - 1),
direction: (direction * -1),
currentTimes: (currentTimes + 1),
withDelta: withDelta,
andSpeed: andSpeed,
shakeDirection: shakeDirection,
completionHandler: completionHandler)
}
UIView.animate(withDuration: TimeInterval(andSpeed),
animations: animations,
completion: animationCompletion)
}
}
|
e2e29f92770e157c4568b176027e9530
| 32.601695 | 100 | 0.527617 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/Utility/Networking/WordPressComRestApi+Defaults.swift
|
gpl-2.0
|
1
|
import Foundation
import WordPressKit
extension WordPressComRestApi {
@objc public static func defaultApi(oAuthToken: String? = nil,
userAgent: String? = nil,
localeKey: String = WordPressComRestApi.LocaleKeyDefault) -> WordPressComRestApi {
return WordPressComRestApi(oAuthToken: oAuthToken,
userAgent: userAgent,
localeKey: localeKey,
baseUrlString: Environment.current.wordPressComApiBase)
}
/// Returns the default API the default WP.com account using the given context
@objc public static func defaultApi(in context: NSManagedObjectContext,
userAgent: String? = WPUserAgent.wordPress(),
localeKey: String = WordPressComRestApi.LocaleKeyDefault) -> WordPressComRestApi {
let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: context)
let token: String? = defaultAccount?.authToken
return WordPressComRestApi.defaultApi(oAuthToken: token,
userAgent: WPUserAgent.wordPress())
}
}
|
d44c21573c274bcd46c57ca2290936fc
| 47.807692 | 122 | 0.584712 | false | false | false | false |
jellybeansoup/ios-sherpa
|
refs/heads/main
|
src/Sherpa/ArticleViewController.swift
|
bsd-2-clause
|
1
|
//
// Copyright © 2021 Daniel Farrelly
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
import WebKit
import SafariServices
internal class ArticleViewController: ListViewController {
// MARK: Instance life cycle
internal let article: Article!
init(document: Document, article: Article) {
self.article = article
super.init(document: document)
dataSource.sectionTitle = NSLocalizedString("Related", comment: "Title for table view section containing one or more related articles.")
dataSource.filter = { (article: Article) -> Bool in return article.key != nil && self.article.relatedKeys.contains(article.key!) }
allowSearch = false
bodyView.navigationDelegate = self
bodyView.loadHTMLString(prepareHTML, baseURL: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View life cycle
internal let contentView: UIView = UIView()
internal let bodyView: WKWebView = WKWebView()
private var loadingObserver: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = nil
contentView.preservesSuperviewLayoutMargins = true
bodyView.backgroundColor = UIColor.clear
bodyView.scrollView.isScrollEnabled = false
bodyView.isOpaque = false
contentView.addSubview(bodyView)
loadingObserver = bodyView.observe(\.isLoading) { webView, change in
guard change.newValue == false else {
return
}
self.updateHeight(for: webView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: false)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if contentView.superview == nil || contentView.frame.width != contentView.superview!.frame.width {
layoutHeaderView()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory {
bodyView.loadHTMLString(prepareHTML, baseURL: nil)
}
}
private func layoutHeaderView() {
let margins = tableView.layoutMargins
let width = tableView.frame.width
let maxSize = CGSize(width: width - margins.left - margins.right, height: CGFloat.greatestFiniteMagnitude)
let bodySize = bodyView.scrollView.contentSize
bodyView.frame = CGRect(x: margins.left, y: 30, width: maxSize.width, height: bodySize.height)
contentView.frame = CGRect(x: 0, y: 0, width: width, height: bodyView.frame.maxY)
tableView.tableHeaderView = contentView
}
fileprivate var prepareHTML: String {
let font = UIFont.preferredFont(forTextStyle: .body)
let color = self.css(for: dataSource.document.articleTextColor)
let weight = font.fontDescriptor.symbolicTraits.contains(.traitBold) ? "bold" : "normal"
var css = """
body {margin: 0;font-family: -apple-system,system-ui,sans-serif;font-size: \(font.pointSize)px;line-height: 1.4;color: \(color);font-weight: \(weight);}
img {max-width: 100%; opacity: 1;transition: opacity 0.3s;}
img[data-src] {opacity: 0;}
h1, h2, h3, h4, h5, h6 {font-weight: 500;line-height: 1.2;}
h1 {font-size: 1.6em;}
h2 {font-size: 1.4em;}
h3 {font-size: 1.2em;}
h4 {font-size: 1.0em;}
h5 {font-size: 0.8em;}
h6 {font-size: 0.6em;}
"""
if let tintColor = dataSource.document.tintColor ?? view.tintColor {
css += " a {color: \(self.css(for: tintColor));}"
}
if let articleCSS = dataSource.document.articleCSS {
css += " \(articleCSS)"
}
var string = article.body
var searchRange = Range(uncheckedBounds: (lower: string.startIndex, upper: string.endIndex))
while let range = string.range(of: "(<img[^>]*)( src=\")", options: .regularExpression, range: searchRange) {
string = string.replacingOccurrences(of: "src=\"", with: "data-src=\"", options: [], range: range)
searchRange = Range(uncheckedBounds: (lower: range.lowerBound, upper: string.endIndex))
}
return """
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<style type="text/css">\(css)</style>
<style type="text/css">body {background-color: transparent !important;}</style>
</head>
<body><h1>\(article.title)</h1>\n\(paragraphs(for: string))</body>
<script type="text/javascript">
[].forEach.call(document.querySelectorAll('img[data-src]'), function(img) {
img.setAttribute('src', img.getAttribute('data-src'));
img.onload = function() {
img.removeAttribute('data-src');
};
});
</script>
</html>
"""
}
fileprivate func css(for color: UIColor) -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return "rgba(\(Int(red * 255)), \(Int(green * 255)), \(Int(blue * 255)), \(alpha))"
}
fileprivate func paragraphs(for string: String) -> String {
var string = string.trimmingCharacters(in: .whitespacesAndNewlines)
guard string.range(of: "<(p|br)[/\\s>]", options: .regularExpression) == nil else {
return string
}
while let range = string.range(of: "\n") {
string.replaceSubrange(range, with: "<br/>")
}
return string
}
}
extension ArticleViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url, navigationAction.navigationType != .other else {
decisionHandler(.allow)
return
}
let configuration = SFSafariViewController.Configuration()
let viewController = SFSafariViewController(url: url, configuration: configuration)
self.present(viewController, animated: true, completion: nil)
decisionHandler(.cancel)
}
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
continuouslyUpdateHeight(for: webView)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
updateHeight(for: webView)
}
private func continuouslyUpdateHeight(for webView: WKWebView) {
updateHeight(for: webView)
guard webView.isLoading else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
self?.continuouslyUpdateHeight(for: webView)
}
}
private func updateHeight(for webView: WKWebView) {
webView.evaluateJavaScript("document.body.scrollHeight") { response, _ in
guard let number = response as? NSNumber else {
return
}
webView.frame.size.height = CGFloat(number.doubleValue)
self.layoutHeaderView()
}
}
}
|
32f2b3e496094f6eeaa691f83e7cfbb9
| 31.631579 | 154 | 0.723945 | false | false | false | false |
leizh007/HiPDA
|
refs/heads/master
|
HiPDA/HiPDA/Sections/Login/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// HiPDA
//
// Created by leizh007 on 16/9/3.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import MessageUI
/// 登录成功后的回调
typealias LoggedInCompletionHandler = (Account) -> Void
/// 默认的容器视图的顶部constraint
private let kDefaultContainerTopConstraintValue = CGFloat(44.0)
/// 登录的ViewController
class LoginViewController: BaseViewController, StoryboardLoadable {
/// 分割线的高度constriant
@IBOutlet private var seperatorsHeightConstraint: [NSLayoutConstraint]!
/// 点击背景的手势识别
@IBOutlet private var tapBackground: UITapGestureRecognizer!
/// 显示密码被点击
@IBOutlet private var tapShowPassword: UITapGestureRecognizer!
/// 输入密码的TextField
@IBOutlet private weak var passwordTextField: UITextField!
/// 隐藏显示密码的ImageView
@IBOutlet private weak var hidePasswordImageView: UIImageView!
/// 输入姓名的TextField
@IBOutlet private weak var nameTextField: UITextField!
/// 输入答案的TextField
@IBOutlet private weak var answerTextField: UITextField!
/// 安全问题Button
@IBOutlet private weak var questionButton: UIButton!
/// 是否可取消
var cancelable = false
/// 取消按钮
@IBOutlet private weak var cancelButton: UIButton!
/// 安全问题的driver
private var questionDriver: Driver<Int>!
/// 回答的driver
private var answerDriver: Driver<String>!
/// 登录按钮
@IBOutlet private weak var loginButton: UIButton!
/// 容器视图的顶部constraint
@IBOutlet private weak var containerTopConstraint: NSLayoutConstraint!
/// 登录成功后的回调
var loggedInCompletion: LoggedInCompletionHandler?
var cancelCompletion: ((Void) -> Void)?
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
cancelButton.isHidden = !cancelable
configureKeyboard()
configureQuestionButton()
configureTapGestureRecognizer()
configureTextFields()
configureViewModel()
}
@IBAction func adviseButtonPressed(_ sender: UIButton) {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([C.URL.authorEmail])
present(mail, animated: true, completion: nil)
} else {
UIApplication.shared.openURL(URL(string: "mailto:\(C.URL.authorEmail)")!)
}
}
@IBAction func registerButtonPressed(_ sender: UIButton) {
URLDispatchManager.shared.linkActived("https://www.hi-pda.com/forum/tobenew.php")
}
override func setupConstraints() {
for heightConstraint in seperatorsHeightConstraint {
heightConstraint.constant = 1.0 / UIScreen.main.scale
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
// MARK: - private method
/// 设置手势识别
private func configureTapGestureRecognizer() {
tapShowPassword.rx.event.subscribe(onNext: { [weak self] _ in
guard let `self` = self else { return }
let isSecureTextEntry = self.passwordTextField.isSecureTextEntry
self.passwordTextField.isSecureTextEntry = !isSecureTextEntry
let image: UIImage
switch isSecureTextEntry {
case true:
image = #imageLiteral(resourceName: "login_password_show")
case false:
image = #imageLiteral(resourceName: "login_password_hide")
}
UIView.transition(with: self.hidePasswordImageView,
duration: C.UI.animationDuration,
options: .transitionCrossDissolve,
animations: {
self.hidePasswordImageView.image = image
}, completion: nil)
}).addDisposableTo(disposeBag)
}
/// 设置TextFields
private func configureTextFields() {
let textValue = Variable("")
(passwordTextField.rx.textInput <-> textValue).addDisposableTo(disposeBag)
textValue.asObservable().map { $0.characters.count == 0 }
.bindTo(hidePasswordImageView.rx.isHidden).addDisposableTo(disposeBag)
passwordTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in
self?.answerTextField.becomeFirstResponder()
}).addDisposableTo(disposeBag)
nameTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in
self?.passwordTextField.becomeFirstResponder()
}).addDisposableTo(disposeBag)
answerTextField.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: { [weak self] _ in
self?.answerTextField.resignFirstResponder()
}).addDisposableTo(disposeBag)
}
/// 配置安全问题的Button
private func configureQuestionButton() {
let questionVariable = Variable(0)
let answerVariable = Variable("")
(answerTextField.rx.textInput <-> answerVariable).addDisposableTo(disposeBag)
questionButton.rx.tap.subscribe(onNext: { [weak self] _ in
guard let `self` = self else { return }
let questions = LoginViewModel.questions
let pickerActionSheetController = PickerActionSheetController.load(from: .views)
pickerActionSheetController.pickerTitles = questions
pickerActionSheetController.initialSelelctionIndex = questions.index(of: self.questionButton.title(for: .normal)!)
pickerActionSheetController.selectedCompletionHandler = { [unowned self] (index) in
self.dismiss(animated: false, completion: nil)
if let index = index, let title = questions.safe[index] {
self.questionButton.setTitle(title, for: .normal)
questionVariable.value = index
}
}
pickerActionSheetController.modalPresentationStyle = .overCurrentContext
self.present(pickerActionSheetController, animated: false, completion: nil)
}).addDisposableTo(disposeBag)
questionDriver = questionVariable.asDriver()
questionDriver.drive(onNext: { [weak self] (index) in
guard let `self` = self else { return }
if index == 0 {
self.answerTextField.isEnabled = false
self.passwordTextField.returnKeyType = .done
} else {
self.answerTextField.isEnabled = true
self.passwordTextField.returnKeyType = .next
}
answerVariable.value = ""
}).addDisposableTo(disposeBag)
answerDriver = answerVariable.asDriver()
}
/// 处理键盘相关
private func configureKeyboard() {
let dismissEvents: [Observable<Void>] = [
tapBackground.rx.event.map { _ in () },
questionButton.rx.tap.map { _ in () },
cancelButton.rx.tap.map { _ in () },
loginButton.rx.tap.map { _ in () }
]
Observable.from(dismissEvents).merge().subscribe(onNext: { [weak self] _ in
self?.nameTextField.resignFirstResponder()
self?.passwordTextField.resignFirstResponder()
self?.answerTextField.resignFirstResponder()
}).addDisposableTo(disposeBag)
KeyboardManager.shared.keyboardChanged.drive(onNext: { [weak self, unowned keyboardManager = KeyboardManager.shared] transition in
guard let `self` = self else { return }
guard transition.toVisible.boolValue else {
self.containerTopConstraint.constant = kDefaultContainerTopConstraintValue
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
return
}
guard let textField = self.activeTextField() else { return }
let keyboardFrame = keyboardManager.convert(transition.toFrame, to: self.view)
let textFieldFrame = textField.convert(textField.frame, to: self.view)
let heightGap = textFieldFrame.origin.y + textFieldFrame.size.height - keyboardFrame.origin.y
let containerTopConstraintConstant = heightGap > 0 ? self.containerTopConstraint.constant - heightGap : kDefaultContainerTopConstraintValue
self.containerTopConstraint.constant = containerTopConstraintConstant
UIView.animate(withDuration: transition.animationDuration, delay: 0.0, options: transition.animationOption, animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}).addDisposableTo(disposeBag)
}
/// 配置ViewModel相关信息
func configureViewModel() {
let nameVariable = Variable("")
let passwordVariable = Variable("")
(nameTextField.rx.textInput <-> nameVariable).addDisposableTo(disposeBag)
(passwordTextField.rx.textInput <-> passwordVariable).addDisposableTo(disposeBag)
let viewModel = LoginViewModel(username: nameVariable.asDriver(),
password: passwordVariable.asDriver(),
questionid: questionDriver,
answer: answerDriver,
loginTaps: loginButton.rx.tap.asDriver())
viewModel.loginEnabled.drive(loginButton.rx.isEnabled).addDisposableTo(disposeBag)
viewModel.loggedIn.drive(onNext: { [unowned self] result in
self.hidePromptInformation()
switch result {
case .success(let account):
self.showPromptInformation(of: .success("登录成功"))
Settings.shared.shouldAutoLogin = true
delay(seconds: 1.0) {
self.loggedInCompletion?(account)
}
case .failure(let error):
self.showPromptInformation(of: .failure("\(error)"))
}
}).addDisposableTo(disposeBag)
loginButton.rx.tap.subscribe(onNext: { [weak self] _ in
self?.showPromptInformation(of: .loading("正在登录..."))
}).addDisposableTo(disposeBag)
cancelButton.rx.tap.subscribe(onNext: { [weak self] _ in
self?.cancelCompletion?()
self?.presentingViewController?.dismiss(animated: true, completion: nil)
}).addDisposableTo(disposeBag)
if let account = Settings.shared.lastLoggedInAccount {
nameVariable.value = account.name
passwordVariable.value = account.password
}
}
/// 找到激活的textField
///
/// - returns: 返回first responser的textField
private func activeTextField() -> UITextField? {
for textField in [nameTextField, passwordTextField, answerTextField] {
if textField!.isFirstResponder {
return textField
}
}
return nil
}
}
extension LoginViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
dismiss(animated: true, completion: nil)
}
}
|
c46b9bfb0decaa1e30d8f0e8e6b48090
| 38.923875 | 151 | 0.627058 | false | false | false | false |
RailwayStations/Bahnhofsfotos
|
refs/heads/develop
|
Modules/Data/Sources/Storage/CountryStorage.swift
|
apache-2.0
|
1
|
//
// CountryStorage.swift
// Bahnhofsfotos
//
// Created by Miguel Dönicke on 30.01.17.
// Copyright © 2017 MrHaitec. All rights reserved.
//
import Domain
import Foundation
import Shared
import SQLite
import SwiftyUserDefaults
public class CountryStorage {
enum CountryError: Error {
case message(String?)
}
public static var lastUpdatedAt: Date?
private static var _countries: [Country] = []
public static var countries: [Country] {
return _countries
}
public static var currentCountry: Country? {
return CountryStorage.countries.first(where: { (country) -> Bool in
country.code == Defaults.country
})
}
// table name for "migration" ...
private static let tableOldName = "country"
private static let tableName = "country_3"
// SQLite properties
private static let fileName = Constants.dbFilename
private static let tableOld = Table(tableOldName)
private static let table = Table(tableName)
fileprivate static let expressionCountryCode = Expression<String>(Constants.JsonConstants.kCountryCode)
fileprivate static let expressionCountryName = Expression<String>(Constants.JsonConstants.kCountryName)
fileprivate static let expressionMail = Expression<String?>(Constants.JsonConstants.kCountryEmail) // OLD
fileprivate static let expressionEmail = Expression<String?>(Constants.JsonConstants.kCountryEmail)
fileprivate static let expressionTwitterTags = Expression<String?>(Constants.JsonConstants.kCountryTwitterTags)
fileprivate static let expressionTimetableUrlTemplate = Expression<String?>(Constants.JsonConstants.kCountryTimetableUrlTemplate)
// Open connection to database
private static func openConnection() throws -> Connection {
// find path to SQLite database
guard let path = NSSearchPathForDirectoriesInDomains(
.documentDirectory, .userDomainMask, true)
.first else {
throw CountryError.message("Path not found.")
}
// open connection
let db = try Connection("\(path)/\(fileName)")
// delete old table if exists
if tableOldName != tableName {
try db.run(tableOld.drop(ifExists: true))
}
// create table if not exists
try db.run(table.create(ifNotExists: true) { table in
table.column(expressionCountryCode, primaryKey: true)
table.column(expressionCountryName)
table.column(expressionEmail)
table.column(expressionTwitterTags)
table.column(expressionTimetableUrlTemplate)
})
// return connection
return db
}
// Remove all
public static func removeAll() throws {
let db = try openConnection()
try db.run(table.delete())
lastUpdatedAt = Date()
}
// Fetch all stations
public static func fetchAll() throws {
let db = try openConnection()
_countries.removeAll()
for country in try db.prepare(table) {
let c = Country.from(row: country)
_countries.append(c)
}
_countries = _countries.sorted { $0.name < $1.name }
lastUpdatedAt = Date()
}
// Save a station
public static func create(country: Country) throws {
let db = try openConnection()
try db.run(table.insert(expressionCountryName <- country.name,
expressionCountryCode <- country.code,
expressionEmail <- country.email,
expressionTwitterTags <- country.twitterTags,
expressionTimetableUrlTemplate <- country.timetableUrlTemplate
))
_countries.append(country)
_countries = _countries.sorted { $0.name < $1.name }
lastUpdatedAt = Date()
}
}
// MARK: - Country extension
public extension Country {
public func save() throws {
try CountryStorage.create(country: self)
}
public static func from(row: Row) -> Country {
.init(
name: try! row.get(CountryStorage.expressionCountryName),
code: try! row.get(CountryStorage.expressionCountryCode),
email: try! row.get(CountryStorage.expressionEmail),
twitterTags: try! row.get(CountryStorage.expressionTwitterTags),
timetableUrlTemplate: try! row.get(CountryStorage.expressionTimetableUrlTemplate)
)
}
}
|
0907c2e7cde1c3eeca1b3a4a6af9cfc9
| 32.132353 | 133 | 0.648913 | false | false | false | false |
SwifterLC/SinaWeibo
|
refs/heads/master
|
LCSinaWeibo/LCSinaWeibo/Classes/Tools/extension/UILabel+Extension.swift
|
mit
|
1
|
//
// UILabel+Extension.swift
// LCSinaWeibo
//
// Created by 刘成 on 2017/8/3.
// Copyright © 2017年 刘成. All rights reserved.
//
import UIKit
extension UILabel{
/// 居中无行数限制 UILabel 便利构造函数
///
/// - Parameters:
/// - title: UILabel title
/// - fontSize: title 字体大小,默认系统字体14字号
/// - color: title 颜色,默认深灰色
convenience init(title: String, //label 文本
fontSize: CGFloat = 14, //字体大小
color: UIColor = UIColor.darkGray, //文字颜色
aligment:NSTextAlignment = .center, //文字对齐
margin:CGFloat = 0){ //文本框 margin
self.init()
text = title
textColor = color
textAlignment = aligment
numberOfLines = 0
font = UIFont.systemFont(ofSize: fontSize)
if margin != 0 {
preferredMaxLayoutWidth = UIScreen.main.bounds.width - 2 * margin
}
}
}
|
dd2f7fc75afe2176dd9ffb53ba273eeb
| 28.058824 | 78 | 0.511134 | false | false | false | false |
peihsendoyle/ZCPlayer
|
refs/heads/master
|
ZCPlayer/ZCPlayer/PlayerController.swift
|
apache-2.0
|
1
|
//
// PlayerController.swift
// ZCPlayer
//
// Created by Doyle Illusion on 7/4/17.
// Copyright © 2017 Zyncas Technologies. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
class PlayerController : NSObject {
fileprivate var mRestoreAfterScrubbingRate: Float = 0.0
fileprivate var player : AVPlayer!
fileprivate var playerItem : AVPlayerItem!
fileprivate var observer : AVObserver?
lazy var playerView : PlayerView = {
let view = PlayerView()
view.delegate = self
(view.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravityResizeAspect
return view
}()
fileprivate var currentTime : Double = 0.0
fileprivate var durationTime : Double = 0.0
fileprivate var timeObserver : Any?
fileprivate var isSeeking = false
required init(url: URL) {
super.init()
self.playerItem = AVPlayerItem(url: url)
self.player = AVPlayer(playerItem: self.playerItem)
self.addLifeObservers()
(self.playerView.layer as! AVPlayerLayer).player = self.player
PlayerControllerManager.shared.dict[url.absoluteString] = self
}
func addLifeObservers() {
self.observer = AVObserver(player: self.player) { (status, message, object) in
switch status {
case .playerFailed:
self.syncScrubber()
self.disableScrubber()
self.removePlayerViewFromSuperview()
print("Player failed. We don't have logic to recover from this.")
case .itemFailed:
self.removePlayerTimeObserver()
self.syncScrubber()
self.disableScrubber()
self.removePlayerViewFromSuperview()
print("Item failed. We don't have logic to recover from this.")
case .stalled:
print("Playback stalled at \(self.player.currentItem!.currentDate() ?? Date())")
case .itemReady:
self.initScrubberTimer()
self.enableScrubber()
case .accessLog:
print("New Access log")
case .errorLog:
print("New Error log")
case .playing:
print("Status: Playing")
case .paused:
print("Status: Paused")
case .likelyToKeepUp:
self.playerView.hideLoading()
case .unlikelyToKeepUp:
self.playerView.showLoading()
self.playerView.showContainerView()
case .timeJump:
print("Player reports that time jumped.")
case .loadedTimeRanges:
self.playerView.slider.setProgress(progress: self.getAvailableTime(), animated: true)
default:
break
}
}
}
func addPlayerViewToSuperview(view: UIView) {
// if self.player.currentItem == nil {
// self.player.replaceCurrentItem(with: self.playerItem)
// }
guard let player = self.player else { return }
player.play()
self.playerView.frame = view.bounds
if !view.subviews.last!.isKind(of: PlayerView.self) {
// First time init --> cell need to add playerView again
view.addSubview(self.playerView)
} else {
if let lastPlayerView = view.subviews.last as? PlayerView {
guard lastPlayerView !== self.playerView else { /* Non reuse here */ return }
/* After Reused */
lastPlayerView.removeFromSuperview()
view.addSubview(self.playerView)
}
}
}
func removePlayerViewFromSuperview() {
guard let player = self.player else { return }
player.pause()
self.playerView.hideContainerView()
// self.player.replaceCurrentItem(with: nil)
}
func initScrubberTimer() {
guard let playerDuration = self.getItemDuration() else { return }
self.durationTime = CMTimeGetSeconds(playerDuration)
self.playerView.syncDuration(value: self.durationTime)
var interval: Double = 0.1
if self.durationTime.isFinite { interval = 0.5 * self.durationTime / Double(self.playerView.slider.bounds.width) }
self.timeObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(interval, Int32(NSEC_PER_SEC)), queue: nil, using: { [weak self] (time: CMTime) -> Void in
guard let `self` = self else { return }
self.syncScrubber()
})
}
func syncScrubber() {
if self.durationTime.isFinite {
let minValue = self.playerView.slider.minimumValue
let maxValue = self.playerView.slider.maximumValue
let time = CMTimeGetSeconds(self.player.currentTime())
guard time.isFinite else { return }
self.playerView.syncTime(value: time)
self.playerView.syncSlider(value: Double((maxValue - minValue) * Float(time) / Float(self.durationTime) + minValue))
}
}
func beginScrubbing() {
mRestoreAfterScrubbingRate = self.player.rate
self.player.rate = 0.0
self.removePlayerTimeObserver()
}
func scrub(_ sender: AnyObject) {
if (sender is UISlider) && !self.isSeeking {
self.isSeeking = true
let slider = sender
if self.durationTime.isFinite {
let minValue: Float = slider.minimumValue
let maxValue: Float = slider.maximumValue
let value: Float = slider.value
let time = (self.durationTime * Double((value - minValue) / (maxValue - minValue)))
self.playerView.syncTime(value: time)
self.player.seek(to: CMTimeMakeWithSeconds(time, Int32(NSEC_PER_SEC)), completionHandler: {(finished: Bool) -> Void in
DispatchQueue.main.async(execute: { [weak self] () -> Void in
self?.isSeeking = false
})
})
}
}
}
func endScrubbing() {
guard timeObserver == nil else { return }
if mRestoreAfterScrubbingRate != 0.0 {
self.player.rate = mRestoreAfterScrubbingRate
mRestoreAfterScrubbingRate = 0.0
//self.isPlay = true
}
if self.durationTime.isFinite {
let width: CGFloat = self.playerView.slider.bounds.width
let tolerance: Double = 0.5 * self.durationTime / Double(width)
self.timeObserver = self.player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(tolerance, Int32(NSEC_PER_SEC)), queue: nil, using: { [weak self] (time: CMTime) -> Void in
guard let `self` = self else { return }
self.syncScrubber()
})
}
}
func isScrubbing() -> Bool {
return mRestoreAfterScrubbingRate != 0.0
}
func enableScrubber() {
self.playerView.enableSlider()
}
func disableScrubber() {
self.playerView.disableSlider()
}
func toggle(isPlay: Bool) {
isPlay ? self.player.pause() : self.player.play()
}
func getAvailableTime() -> Float {
let timeRange = self.playerItem.loadedTimeRanges[0].timeRangeValue
let startSeconds = CMTimeGetSeconds(timeRange.start)
let durationSeconds = CMTimeGetSeconds(timeRange.duration)
let result = startSeconds + durationSeconds
return Float(result)
}
fileprivate func getItemDuration() -> CMTime? {
guard let playerItem = self.playerItem else { return nil }
return playerItem.duration
}
func removePlayerTimeObserver() {
guard timeObserver != nil else { return }
self.player.removeTimeObserver(timeObserver!)
self.timeObserver = nil
}
func removeLifeObserver() {
self.observer?.stop()
self.observer = nil
}
}
extension PlayerController : PlayerViewDelegate {
func didTouchToggleButton(isPlay: Bool) {
self.toggle(isPlay: isPlay)
}
func didScrubbing() {
self.scrub(self.playerView.slider)
}
func didBeginScrubbing() {
self.beginScrubbing()
}
func didEndScrubbing() {
self.endScrubbing()
}
}
|
38f6e8612a48129ac9e4d1aedfd397ec
| 33.587045 | 194 | 0.586445 | false | false | false | false |
Drakken-Engine/GameEngine
|
refs/heads/master
|
DrakkenEngine/dMaterial.swift
|
gpl-3.0
|
1
|
//
// dMaterial.swift
// DrakkenEngine
//
// Created by Allison Lindner on 23/08/16.
// Copyright © 2016 Drakken Studio. All rights reserved.
//
import Foundation
public class dMaterialDef {
internal var name: String
internal var shader: String
fileprivate var buffers: [String : dBufferable] = [:]
fileprivate var textures: [String : dMaterialTexture] = [:]
public init(name: String, shader: String) {
self.name = name
self.shader = shader
}
internal func set(buffer name: String, _ data: dBufferable) {
self.buffers[name] = data
}
internal func set(texture name: String, _ data: dTexture, _ index: Int) {
let materialTexture = dMaterialTexture(texture: data, index: index)
self.textures[name] = materialTexture
}
internal func get(texture name: String) -> dTexture? {
return self.textures[name]?.texture
}
internal func get(buffer name: String) -> dBufferable? {
return self.buffers[name]
}
}
internal class dMaterial {
private var _materialDef: dMaterialDef
internal init(materialDef: dMaterialDef) {
self._materialDef = materialDef
}
internal func build() {
var buffers: [dBufferable] = []
for buffer in _materialDef.buffers {
buffers.append(buffer.value)
}
var textures: [dMaterialTexture] = []
for materialTexture in _materialDef.textures {
textures.append(materialTexture.value)
}
dCore.instance.mtManager.create(name: _materialDef.name,
shader: _materialDef.shader,
buffers: buffers,
textures: textures)
}
}
|
786002c9cc1e879068d2aadddedcf74a
| 24.396825 | 74 | 0.6675 | false | false | false | false |
inket/MacSymbolicator
|
refs/heads/master
|
MacSymbolicator/Models/Architecture.swift
|
gpl-2.0
|
1
|
//
// Architecture.swift
// MacSymbolicator
//
import Foundation
enum Architecture: Hashable {
case x86
case x86_64 // swiftlint:disable:this identifier_name
case arm64
case arm(String?)
private static let architectureRegex = #"^(?:Architecture|Code Type):(.*?)(\(.*\))?$"#
private static let binaryImagesRegex = #"Binary Images:.*\s+([^\s]+)\s+<"#
static func find(in content: String) -> Architecture? {
var result = content.scan(pattern: Self.architectureRegex).first?.first?.trimmed
.components(separatedBy: " ").first.flatMap(Architecture.init)
// In the case of plain "ARM" (without version or specifiers) the actual architecture is on
// the first line of Binary Images. Cannot find recent examples of this, but keeping behavior just in case.
if result?.isIncomplete == true {
result = (content.scan(
pattern: Self.binaryImagesRegex,
options: [.caseInsensitive, .anchorsMatchLines, .dotMatchesLineSeparators]
).first?.first?.trimmed).flatMap(Architecture.init)
}
return result
}
init?(_ string: String) {
let archString = string.lowercased()
if archString.hasPrefix("x86-64") || archString.hasPrefix("x86_64") {
// Example sub-architecture: x86_64h
self = .x86_64
} else if ["x86", "i386"].contains(archString) {
self = .x86
} else if archString == "arm" {
self = .arm(nil) // More details can be found in the binary images, e.g. arm64e
} else if ["arm-64", "arm64", "arm_64"].contains(archString) {
self = .arm64
} else if archString.hasPrefix("arm") {
// Example sub-architecture: armv7
self = .arm(archString)
} else {
return nil
}
}
var atosString: String? {
switch self {
case .x86: return "i386"
case .x86_64: return "x86_64"
case .arm64: return "arm64"
case .arm(let raw): return raw
}
}
var isIncomplete: Bool {
switch self {
case .x86, .x86_64, .arm64: return false
case .arm(let raw): return raw == nil
}
}
}
|
f5ae7fb049d50b73983075325570d62a
| 32.552239 | 115 | 0.580961 | false | false | false | false |
PureSwift/CoreModel
|
refs/heads/develop
|
Sources/CoreDataModel/NSManagedObject.swift
|
mit
|
2
|
//
// NSManagedObject.swift
// CoreDataModel
//
// Created by Alsey Coleman Miller on 11/4/18.
//
#if canImport(CoreData)
import Foundation
import CoreData
import CoreModel
public final class CoreDataManagedObject: CoreModel.ManagedObject {
internal let managedObject: NSManagedObject
internal init(_ managedObject: NSManagedObject) {
self.managedObject = managedObject
}
public var store: NSManagedObjectContext? {
return managedObject.managedObjectContext
}
public var isDeleted: Bool {
return managedObject.isDeleted
}
public func attribute(for key: String) -> AttributeValue {
return managedObject.attribute(for: key)
}
public func setAttribute(_ newValue: AttributeValue, for key: String) {
managedObject.setAttribute(newValue, for: key)
}
public func relationship(for key: String) -> RelationshipValue<CoreDataManagedObject> {
guard let objectValue = managedObject.value(forKey: key)
else { return .null }
if let managedObject = objectValue as? NSManagedObject {
return .toOne(CoreDataManagedObject(managedObject))
} else if let managedObjects = objectValue as? Set<NSManagedObject> {
return .toMany(Set(managedObjects.map { CoreDataManagedObject($0) }))
} else {
fatalError("Invalid CoreData relationship value \(objectValue)")
}
}
public func setRelationship(_ newValue: RelationshipValue<CoreDataManagedObject>, for key: String) {
let objectValue: AnyObject?
switch newValue {
case .null:
objectValue = nil
case let .toOne(value):
objectValue = value.managedObject
case let .toMany(value):
objectValue = Set(value.map({ $0.managedObject })) as NSSet
}
managedObject.setValue(objectValue, forKey: key)
}
}
public extension CoreDataManagedObject {
public static func == (lhs: CoreDataManagedObject, rhs: CoreDataManagedObject) -> Bool {
return lhs.managedObject == rhs.managedObject
}
}
public extension CoreDataManagedObject {
public var hashValue: Int {
return managedObject.hashValue
}
}
internal extension NSManagedObject {
func attribute(for key: String) -> AttributeValue {
guard let objectValue = self.value(forKey: key)
else { return .null }
if let string = objectValue as? String {
return .string(string)
} else if let data = objectValue as? Data {
return .data(data)
} else if let date = objectValue as? Date {
return .date(date)
} else if let value = objectValue as? Bool {
return .bool(value)
} else if let value = objectValue as? Int16 {
return .int16(value)
} else if let value = objectValue as? Int32 {
return .int32(value)
} else if let value = objectValue as? Int64 {
return .int64(value)
} else if let value = objectValue as? Float {
return .float(value)
} else if let value = objectValue as? Double {
return .double(value)
} else {
fatalError("Invalid CoreData attribute value \(objectValue)")
}
}
func setAttribute(_ newValue: AttributeValue, for key: String) {
let objectValue: AnyObject?
switch newValue {
case .null:
objectValue = nil
case let .string(value):
objectValue = value as NSString
case let .data(value):
objectValue = value as NSData
case let .date(value):
objectValue = value as NSDate
case let .bool(value):
objectValue = value as NSNumber
case let .int16(value):
objectValue = value as NSNumber
case let .int32(value):
objectValue = value as NSNumber
case let .int64(value):
objectValue = value as NSNumber
case let .float(value):
objectValue = value as NSNumber
case let .double(value):
objectValue = value as NSNumber
}
self.setValue(objectValue, forKey: key)
}
}
#endif
|
e640c482a6f55ecad182a7fc7e5e7d99
| 26.085714 | 104 | 0.555063 | false | false | false | false |
toggl/superday
|
refs/heads/develop
|
teferi/UI/Modules/Weekly Summary/WeeklySummaryViewController.swift
|
bsd-3-clause
|
1
|
import UIKit
import RxCocoa
import RxSwift
class WeeklySummaryViewController: UIViewController
{
fileprivate var viewModel : WeeklySummaryViewModel!
private var presenter : WeeklySummaryPresenter!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var weeklyChartView: ChartView!
@IBOutlet weak var weekLabel: UILabel!
@IBOutlet weak var previousButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var categoryButtons: ButtonsCollectionView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var pieChart: ActivityPieChartView!
@IBOutlet weak var emptyStateView: WeeklySummaryEmptyStateView!
@IBOutlet weak var monthSelectorView: UIView!
private var disposeBag = DisposeBag()
func inject(presenter:WeeklySummaryPresenter, viewModel: WeeklySummaryViewModel)
{
self.presenter = presenter
self.viewModel = viewModel
}
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = UIColor.white
self.scrollView.addSubview(self.emptyStateView)
previousButton.rx.tap
.subscribe(onNext: { [unowned self] in
self.viewModel.nextWeek()
})
.disposed(by: disposeBag)
nextButton.rx.tap
.subscribe(onNext: { [unowned self] in
self.viewModel.previousWeek()
})
.disposed(by: disposeBag)
viewModel.weekTitle
.bind(to: weekLabel.rx.text)
.disposed(by: disposeBag)
// Chart View
weeklyChartView.datasource = viewModel
weeklyChartView.delegate = self
viewModel.firstDayIndex
.subscribe(onNext:weeklyChartView.setWeekStart)
.disposed(by: disposeBag)
// Category Buttons
categoryButtons.toggleCategoryObservable
.subscribe(onNext:viewModel.toggleCategory)
.disposed(by: disposeBag)
categoryButtons.categories = viewModel.topCategories
.do(onNext: { [unowned self] _ in
self.weeklyChartView.refresh()
})
//Pie chart
viewModel
.weekActivities
.map { activityWithPercentage in
return activityWithPercentage.map { $0.0 }
}
.subscribe(onNext:self.pieChart.setActivities)
.disposed(by: disposeBag)
//Table view
tableView.rowHeight = 48
tableView.allowsSelection = false
tableView.separatorStyle = .none
viewModel.weekActivities
.do(onNext: { [unowned self] activities in
self.tableViewHeightConstraint.constant = CGFloat(activities.count * 48)
self.view.setNeedsLayout()
})
.map { [unowned self] activities in
return activities.sorted(by: self.areInIncreasingOrder)
}
.bind(to: tableView.rx.items(cellIdentifier: WeeklySummaryCategoryTableViewCell.identifier, cellType: WeeklySummaryCategoryTableViewCell.self)) {
_, model, cell in
cell.activityWithPercentage = model
}
.disposed(by: disposeBag)
//Empty state
viewModel.weekActivities
.observeOn(MainScheduler.instance)
.subscribe(onNext: { activityWithPercentage in
self.emptyStateView.isHidden = !activityWithPercentage.isEmpty
})
.disposed(by: disposeBag)
scrollView.addTopShadow()
}
override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
scrollView.flashScrollIndicators()
}
private func areInIncreasingOrder(a1: ActivityWithPercentage, a2: ActivityWithPercentage) -> Bool
{
return a1.1 > a2.1
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
self.emptyStateView.frame = self.weeklyChartView.frame
}
}
extension WeeklySummaryViewController: ChartViewDelegate
{
func pageChange(index: Int)
{
viewModel.setFirstDay(index: index)
}
}
|
4a7ca258f52bc3e3ef0a50c156615962
| 30.883212 | 157 | 0.621795 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
refs/heads/master
|
Sources/LanguageTranslatorV3/Models/Language.swift
|
apache-2.0
|
1
|
/**
* (C) Copyright IBM Corp. 2020.
*
* 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
/**
Response payload for languages.
*/
public struct Language: Codable, Equatable {
/**
The language code for the language (for example, `af`).
*/
public var language: String?
/**
The name of the language in English (for example, `Afrikaans`).
*/
public var languageName: String?
/**
The native name of the language (for example, `Afrikaans`).
*/
public var nativeLanguageName: String?
/**
The country code for the language (for example, `ZA` for South Africa).
*/
public var countryCode: String?
/**
Indicates whether words of the language are separated by whitespace: `true` if the words are separated; `false`
otherwise.
*/
public var wordsSeparated: Bool?
/**
Indicates the direction of the language: `right_to_left` or `left_to_right`.
*/
public var direction: String?
/**
Indicates whether the language can be used as the source for translation: `true` if the language can be used as the
source; `false` otherwise.
*/
public var supportedAsSource: Bool?
/**
Indicates whether the language can be used as the target for translation: `true` if the language can be used as the
target; `false` otherwise.
*/
public var supportedAsTarget: Bool?
/**
Indicates whether the language supports automatic detection: `true` if the language can be detected automatically;
`false` otherwise.
*/
public var identifiable: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case language = "language"
case languageName = "language_name"
case nativeLanguageName = "native_language_name"
case countryCode = "country_code"
case wordsSeparated = "words_separated"
case direction = "direction"
case supportedAsSource = "supported_as_source"
case supportedAsTarget = "supported_as_target"
case identifiable = "identifiable"
}
}
|
0db6fa00b18132579876b8baaae9e5d4
| 30.22093 | 120 | 0.673371 | false | false | false | false |
materik/stubborn
|
refs/heads/master
|
Stubborn/Http/Response.swift
|
mit
|
1
|
extension Stubborn {
class Response {
let url: Request.URL
let body: Body
var response: HTTPURLResponse {
return HTTPURLResponse(
url: Foundation.URL(string: self.url)!,
statusCode: statusCode,
httpVersion: nil,
headerFields: [
"Content-Type": "application/json",
"Content-Length": String(self.data.count),
]
)!
}
var statusCode: Request.StatusCode {
if let error = self.body as? Body.Error {
return error.statusCode
} else if let statusCode = self.body as? Body.Simple {
return statusCode.statusCode
} else {
return 200
}
}
var data: Data {
// NOTE(materik):
// * seems I have to print the data in order to load it because sometime the data
// turns up empty even if it's cleary not. must be a better way but this is a fix for now
print(self.body.data)
return self.body.data
}
var error: Swift.Error? {
return (self.body as? Body.Error)?.error
}
init(request: Request) {
self.url = request.url
self.body = Body([:])
}
init?(request: Request, stub: Stub) {
guard stub.isStubbing(request: request) else {
return nil
}
self.url = request.url
self.body = stub.loadBody(request)
}
}
}
|
5ffb1adc2c89254e91c1f007fc44f0a8
| 28.210526 | 103 | 0.473874 | false | false | false | false |
Chris-Perkins/Lifting-Buddy
|
refs/heads/master
|
Lifting Buddy/WorkoutTableView.swift
|
mit
|
1
|
//
// WorkoutTableView.swift
// Lifting Buddy
//
// Created by Christopher Perkins on 9/4/17.
// Copyright © 2017 Christopher Perkins. All rights reserved.
//
import UIKit
import RealmSwift
import Realm
import CDAlertView
class WorkoutTableView: UITableView {
// MARK: View Properties
// The data displayed in cells
private var sortedData: [(String, [Workout])]
private var data: AnyRealmCollection<Workout>
// MARK: Initializers
override init(frame: CGRect, style: UITableView.Style) {
let realm = try! Realm()
data = AnyRealmCollection(realm.objects(Workout.self))
sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data)
super.init(frame: frame, style: style)
setupTableView()
}
init(style: UITableView.Style) {
let realm = try! Realm()
data = AnyRealmCollection(realm.objects(Workout.self))
sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data)
super.init(frame: .zero, style: style)
setupTableView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: TableView Functions
override func reloadData() {
let realm = try! Realm()
data = AnyRealmCollection(realm.objects(Workout.self))
sortedData = Workout.getSortedWorkoutsSeparatedByDays(workouts: data)
super.reloadData()
}
// MARK: Custom functions
// Retrieve workouts
public func getSortedData() -> [(String, [Workout])] {
return sortedData
}
private func setupTableView() {
delegate = self
dataSource = self
allowsSelection = true
register(WorkoutTableViewCell.self, forCellReuseIdentifier: "cell")
backgroundColor = .clear
}
}
extension WorkoutTableView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return sortedData.count
}
// Data is what we use to fill in the table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sortedData[section].1.count
}
// Create our custom cell class
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "cell",
for: indexPath as IndexPath) as! WorkoutTableViewCell
cell.showViewDelegate = superview as? ShowViewDelegate
cell.setWorkout(workout: sortedData[indexPath.section].1[indexPath.row])
cell.updateSelectedStatus()
// IndexPath of 0 denotes that this workout is today
cell.workoutRequiresAttention = indexPath.section == 0
return cell
}
// Deletion methods
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let workout = sortedData[indexPath.section].1[indexPath.row]
if workout.canModifyCoreProperties {
let alert = CDAlertView(title: NSLocalizedString("Message.DeleteWorkout.Title", comment: ""),
message: "This will delete all records of '\(workout.getName()!)', and this includes its occurrences on other days." +
"This action cannot be undone.",
type: CDAlertViewType.warning)
alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.Cancel", comment: ""),
font: nil,
textColor: UIColor.white,
backgroundColor: UIColor.niceBlue,
handler: nil))
alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.Delete", comment: ""),
font: nil,
textColor: UIColor.white,
backgroundColor: UIColor.niceRed,
handler: { (CDAlertViewAction) in
MessageQueue.shared.append(Message(type: .objectDeleted,
identifier: workout.getName(),
value: nil))
let realm = try! Realm()
try! realm.write {
realm.delete(workout)
}
self.reloadData()
return true
}))
alert.show()
} else {
let alert = CDAlertView(title: NSLocalizedString("Message.CannotDeleteWorkout.Title",
comment: ""),
message: NSLocalizedString("Message.CannotDeleteWorkout.Desc",
comment: ""),
type: CDAlertViewType.error)
alert.add(action: CDAlertViewAction(title: NSLocalizedString("Button.OK", comment: ""),
font: nil,
textColor: UIColor.white,
backgroundColor: UIColor.niceBlue,
handler: nil))
alert.show()
}
}
}
}
extension WorkoutTableView: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.backgroundView?.backgroundColor = UIColor.lightBlackWhiteColor
headerView.textLabel?.textColor = UILabel.titleLabelTextColor
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sortedData[section].1.isEmpty ? 0 : 30
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sortedData[section].0
}
// Expand this cell, un-expand the other cell
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = cellForRow(at: indexPath) as! WorkoutTableViewCell
if indexPathForSelectedRow == indexPath {
deselectRow(at: indexPath, animated: true)
reloadData()
cell.updateSelectedStatus()
return nil
} else {
var cell2: WorkoutTableViewCell? = nil
if indexPathForSelectedRow != nil {
cell2 = cellForRow(at: indexPathForSelectedRow!) as? WorkoutTableViewCell
}
selectRow(at: indexPath, animated: false, scrollPosition: .none)
reloadData()
scrollToRow(at: indexPath, at: .none, animated: true)
cell2?.updateSelectedStatus()
cell.updateSelectedStatus()
return indexPath
}
}
// Each cell's height depends on whether or not it has been selected
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let exerCount = CGFloat(sortedData[indexPath.section].1[indexPath.row].getExercises().count)
return indexPathForSelectedRow?.elementsEqual(indexPath) ?? false ?
UITableViewCell.defaultHeight + PrettyButton.defaultHeight + exerCount * WorkoutTableViewCell.heightPerExercise + WorkoutTableViewCell.heightPerLabel :
UITableViewCell.defaultHeight
}
}
|
6697111bcdba6995a0d5cb4927876c6c
| 41.852217 | 163 | 0.524313 | false | false | false | false |
zhangliangzhi/RollCall
|
refs/heads/master
|
RollCall/UserMinePage/UserMineViewController.swift
|
mit
|
1
|
//
// UserMineViewController.swift
// RollCall
//
// Created by ZhangLiangZhi on 2016/11/24.
// Copyright © 2016年 xigk. All rights reserved.
//
import Foundation
import UIKit
import Charts
import SwiftDate
class UserMineViewController: UIViewController, ChartViewDelegate, IAxisValueFormatter {
@IBOutlet weak var barChartView: BarChartView!
struct MemCount {
let name:String
var count:Int
let id:Int32
}
var arrMemNameCount : [MemCount] = []
override func viewWillAppear(_ animated: Bool) {
if arrClassData.count > 0 {
self.navigationController?.navigationBar.topItem?.title = arrClassData[gIndexClass].classname! + "|" + arrClassData[gIndexClass].selCourse!
} else {
TipsSwift.showCenterWithText("请先创建班级!")
}
getMemCountName()
chartsGo()
}
override func viewDidLoad() {
barChartView.xAxis.valueFormatter = self
barChartView.chartDescription?.text = "by 🍉西瓜点名🍉"
}
public func stringForValue(_ value: Double, axis: Charts.AxisBase?) -> String
{
return arrMemNameCount[Int(value)].name
}
func chartsGo() {
if arrMemNameCount.count == 0 {
TipsSwift.showCenterWithText("没有班级成员!")
}
// print(arrMemNameCount.count)
var values: [Double] = []
for i in 0..<arrMemNameCount.count {
let d:Double = Double(arrMemNameCount[i].count)
values.append(d)
}
// print(values)
var entries: [ChartDataEntry] = Array()
for (i, value) in values.enumerated()
{
entries.append( BarChartDataEntry(x: Double(i), y: value) )
}
let dataSet: BarChartDataSet = BarChartDataSet(values: entries, label: "点名次数")
let data = BarChartData(dataSet: dataSet)
data.barWidth = 0.85
dataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]
barChartView.backgroundColor = NSUIColor.clear
barChartView.xAxis.labelPosition = .bottom
let xAxis = barChartView.xAxis
xAxis.drawGridLinesEnabled = false
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .linear)
barChartView.data = data
}
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
print(highlight)
print(entry)
}
// 获取成员的总点名次数
func getMemCountName() -> Void {
if arrClassData.count == 0 {
return
}
let dateStart:String = arrClassData[gIndexClass].dateStart!
let dateEnd:String = arrClassData[gIndexClass].dateEnd!
let startTime = try! DateInRegion.init(string: dateStart, format: DateFormat.custom("yyyy-MM-dd"))
let endTime = try! DateInRegion.init(string: dateEnd, format: DateFormat.custom("yyyy-MM-dd"))
arrMemNameCount = []
// 获取所有成员id
let strMembers:String = arrClassData[gIndexClass].member!
let membersJsonData = strMembers.data(using: .utf8)
var arrMembers = JSON(data:membersJsonData!)
for i in 0..<arrMembers.count {
let id:Int32 = arrMembers[i]["id"].int32Value
var one:MemCount=MemCount(name: arrMembers[i]["name"].stringValue, count: 0, id: id)
arrMemNameCount.append(one)
}
arrMemNameCount.sort(by: {$0.id<$1.id})
// 统计目前时间范围内的 次数
for i in 0..<arrCallFair.count {
let one = arrCallFair[i]
let onedate = DateInRegion.init(absoluteDate: one.date as! Date)
let id:Int = Int(one.memID)
// 统计在时间范围内的次数
if onedate >= startTime && onedate <= endTime {
// 是选定课程
if arrClassData[gIndexClass].selCourse == one.course {
for j in 0..<arrMemNameCount.count {
if arrMemNameCount[j].id == one.memID {
arrMemNameCount[j].count = arrMemNameCount[j].count + 1
break
}
}
}
}
}
// print(arrMemNameCount)
return
}
}
|
08efbac24d8448ebaa9784022b715b10
| 31.659091 | 151 | 0.583159 | false | false | false | false |
liutongchao/LCRefresh
|
refs/heads/master
|
Source/LCRefreshFooter.swift
|
mit
|
1
|
//
// LCRefreshFooter.swift
// LCRefresh
//
// Created by 刘通超 on 16/8/3.
// Copyright © 2016年 West. All rights reserved.
//
import UIKit
public final class LCRefreshFooter: UIView {
public let contenLab = UILabel()
public let activity = UIActivityIndicatorView()
var refreshStatus: LCRefreshFooterStatus?
var refreshBlock: (()->Void)?
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public init(frame: CGRect) {
super.init(frame: frame)
configView()
}
public init(refreshBlock:@escaping (()->Void)) {
super.init(frame: CGRect(x: LCRefresh.Const.Footer.X, y: LCRefresh.Const.Footer.Y, width: LCRefresh.Const.Common.screenWidth, height: LCRefresh.Const.Footer.height))
self.backgroundColor = UIColor.clear
self.refreshBlock = refreshBlock
configView()
}
public init(width:CGFloat ,refreshBlock:@escaping (()->Void)) {
super.init(frame: CGRect(x: LCRefresh.Const.Footer.X, y: LCRefresh.Const.Footer.Y, width: width, height: LCRefresh.Const.Footer.height))
self.backgroundColor = UIColor.clear
self.refreshBlock = refreshBlock
configView()
}
func configView() {
addSubview(contenLab)
addSubview(activity)
contenLab.frame = self.bounds
contenLab.textAlignment = .center
contenLab.text = "上拉加载更多数据"
contenLab.font = UIFont.systemFont(ofSize: 14)
activity.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
activity.activityIndicatorViewStyle = .gray
activity.center = CGPoint.init(x: 40, y: LCRefresh.Const.Header.height/2)
}
func setStatus(_ status:LCRefreshFooterStatus){
refreshStatus = status
switch status {
case .normal:
setNomalStatus()
break
case .waitRefresh:
setWaitRefreshStatus()
break
case .refreshing:
setRefreshingStatus()
break
case .loadover:
setLoadoverStatus()
break
}
}
}
extension LCRefreshFooter{
/** 各种状态切换 */
func setNomalStatus() {
if activity.isAnimating {
activity.stopAnimating()
}
activity.isHidden = true
contenLab.text = "上拉加载更多数据"
}
func setWaitRefreshStatus() {
if activity.isAnimating {
activity.stopAnimating()
}
activity.isHidden = true
contenLab.text = "松开加载更多数据"
}
func setRefreshingStatus() {
activity.isHidden = false
activity.startAnimating()
contenLab.text = "正在加载更多数据..."
}
func setLoadoverStatus() {
if activity.isAnimating {
activity.stopAnimating()
}
activity.isHidden = true
contenLab.text = "全部加载完毕"
}
}
|
62e6413e7726d57ef68a79fc7be7beda
| 24.827586 | 173 | 0.593792 | false | false | false | false |
weipin/jewzruxin
|
refs/heads/master
|
Jewzruxin/Source/HTTP/Service.swift
|
mit
|
1
|
//
// Service.swift
//
// Copyright (c) 2015 Weipin Xia
//
// 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
/**
This class is an abstract class you use to represent a "service". Because it is abstract, you do not use this class directly but instead subclass.
*/
public class HTTPService {
public enum Key: String {
case BaseURL = "BaseURL"
case Resources = "Resources"
case Name = "Name"
case URITemplate = "URITemplate"
case Method = "Method"
}
/**
- Create: Always create a new `HTTPCycle`.
- Reuse: If there is a `HTTPCycle` with the specified identifier, the `HTTPCycle` will be reused.
- Replace: If there is a `HTTPCycle` with the specified identifier, the `HTTPCycle` will cancelled. A new one will be created and replaces the old one.
*/
public enum CycleForResourceOption {
case Create
case Reuse
case Replace
}
/// The String represents the beginning common part of the endpoint URLs.
private var _baseURLString: String!
public var baseURLString: String {
get {
if (_baseURLString != nil) {
return _baseURLString
}
if let str = self.profile![Key.BaseURL.rawValue] as? String {
return str
}
return ""
}
set {
self._baseURLString = newValue
}
}
/// The dictionary describes the resources of a service.
public var profile: [String: AnyObject]!
public var session: HTTPSession!
/// MUST be overridden
public class func serviceName() -> String {
// TODO: Find a way to obtain class name
assert(false)
return "Service"
}
public class func filenameOfDefaultProfile() -> String {
let serviceName = self.serviceName()
let filename = serviceName + ".plist"
return filename
}
/// Override this method to return a custom `HTTPSession`
public class func defaultSession() -> HTTPSession {
return HTTPSession(configuration: nil, delegateQueue: nil, workerQueue: nil)
}
/// Override this method to customize the newly created `HTTPCycle`.
public func cycleDidCreateWithResourceName(cycle: HTTPCycle, name: String) {
}
/// Find and read the service profile in the bundle with the specified filename.
public class func profileForFilename(filename: String) throws -> [String: AnyObject] {
let bundle = NSBundle(forClass: self)
guard let URL = bundle.URLForResource(filename, withExtension: nil) else {
throw Error.FileNotFound
}
let data = try NSData(contentsOfURL: URL, options: [])
return try self.profileForData(data)
}
public class func profileForData(data: NSData) throws -> [String: AnyObject] {
let d = try NSPropertyListSerialization.propertyListWithData(data, options: [], format: nil)
guard let profile = d as? [String: AnyObject] else {
throw Error.TypeNotMatch
}
return profile
}
public class func URLStringByJoiningComponents(part1: String, part2: String) -> String {
if part1.isEmpty {
return part2
}
if part2.isEmpty {
return part1
}
var p1 = part1
var p2 = part2
if !part1.isEmpty && part1.hasSuffix("/") {
p1 = part1[part1.startIndex ..< part1.endIndex.advancedBy(-1)]
}
if !part2.isEmpty && part2.hasPrefix("/") {
p2 = part2[part2.startIndex.advancedBy(1) ..< part2.endIndex]
}
let result = p1 + "/" + p2
return result
}
/**
Initialize a `HTTPService` object.
- Parameter profile: A dictionary for profile. If nil, the default bundled file will be used to create the dictionary.
*/
public init?(profile: [String: AnyObject]? = nil) {
self.session = self.dynamicType.defaultSession()
if profile != nil {
self.profile = profile!
} else {
do {
try self.updateProfileFromLocalFile()
} catch {
NSLog("\(error)")
return nil
}
}
}
public func updateProfileFromLocalFile(URL: NSURL? = nil) throws {
if URL == nil {
let filename = self.dynamicType.filenameOfDefaultProfile()
self.profile = try self.dynamicType.profileForFilename(filename)
return
}
let data = try NSData(contentsOfURL: URL!, options: [])
self.profile = try self.dynamicType.profileForData(data)
}
/**
Check if specified profile is valid.
- Parameter profile: A dictionary as profile.
- Returns: true if valid, or false if an error occurs.
*/
public func verifyProfile(profile: [String: AnyObject]) -> Bool {
var names: Set<String> = []
guard let value: AnyObject = profile[HTTPService.Key.Resources.rawValue] else {
NSLog("Warning: no resources found in Service profile!")
return false
}
guard let resources = value as? [[String: String]] else {
NSLog("Error: Malformed Resources in Service profile (type does not match)!")
return false
}
for (index, resource) in resources.enumerate() {
guard let name = resource[HTTPService.Key.Name.rawValue] else {
NSLog("Error: Malformed Resources (name not found) in Service profile (resource index: \(index))!")
return false
}
if names.contains(name) {
NSLog("Error: Malformed Resources (duplicate name \(name)) in Service profile (resource index: \(index))!")
return false
}
if resource[HTTPService.Key.URITemplate.rawValue] == nil {
NSLog("Error: Malformed Resources (URL Template not found) in Service profile (resource index: \(index))!")
return false
}
names.insert(name)
}
return true
}
public func resourceProfileForName(name: String) -> [String: String]? {
guard let value: AnyObject = self.profile![HTTPService.Key.Resources.rawValue] else {
return nil
}
guard let resources = value as? [[String: String]] else {
return nil
}
for resource in resources {
if let n = resource[HTTPService.Key.Name.rawValue] {
if n == name {
return resource
}
}
}
return nil
}
public func cycleForIdentifer(identifier: String) -> HTTPCycle? {
return self.session.cycleForIdentifer(identifier)
}
/**
Create a `HTTPCycle` based on the specified resource profile and parameters.
- Parameter name: The name of the resource, MUST presents in the profile. The name is case sensitive.
- Parameter identifer: If presents, the identifer will be used to locate an existing `HTTPCycle`. REQUIRED if option is `Reuse` or `Replace`.
- Parameter option: Determines the HTTPCycle creation logic.
- Parameter URIValues: The object to provide values for the URI Template expanding.
- Parameter requestObject: The property `object` of the `HTTPRequest` for the `HTTPCycle`.
- Parameter solicited: The same property of `HTTPCycle`.
- Returns: A new or existing `HTTPCycle`.
*/
public func cycleForResourceWithIdentifer(name: String, identifier: String? = nil, option: CycleForResourceOption = .Create, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false) throws -> HTTPCycle {
var cycle: HTTPCycle!
switch option {
case .Create:
break
case .Reuse:
assert(identifier != nil)
cycle = self.cycleForIdentifer(identifier!)
case .Replace:
assert(identifier != nil)
cycle = self.cycleForIdentifer(identifier!)
cycle.cancel(true)
cycle = nil
}
if cycle != nil {
return cycle
}
if let resourceProfile = self.resourceProfileForName(name) {
let URITemplate = resourceProfile[HTTPService.Key.URITemplate.rawValue]
let part2 = ExpandURITemplate(URITemplate!, values: URIValues)
let URLString = HTTPService.URLStringByJoiningComponents(self.baseURLString, part2: part2)
guard let URL = NSURL(string: URLString) else {
throw Error.InvalidURL
}
var method = resourceProfile[HTTPService.Key.Method.rawValue]
if method == nil {
method = "GET"
}
cycle = HTTPCycle(requestURL: URL, taskType: .Data, session: self.session, requestMethod: method!, requestObject: requestObject)
cycle.solicited = solicited
if identifier != nil {
cycle.identifier = identifier!
}
self.cycleDidCreateWithResourceName(cycle, name: name)
} else {
assert(false, "Endpoind \(name) not found in profile!")
}
return cycle
}
/**
Create a new `HTTPCycle` object based on the specified resource profile and parameters.
- Parameter name: The name of the resouce, MUST presents in the profile. The name is case sensitive.
- Parameter URIValues: The object to provide values for the URI Template expanding.
- Parameter requestObject: The property `object` of the `HTTPRequest` for the Cycle.
- Parameter solicited: The same property of `HTTPCycle`.
- Returns: A new Cycle.
*/
public func cycleForResource(name: String, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false) throws -> HTTPCycle {
let cycle = try self.cycleForResourceWithIdentifer(name, URIValues: URIValues, requestObject: requestObject, solicited: solicited)
return cycle
}
/**
Create a `HTTPCycle` object based on the specified resource profile and parameters, and start the `HTTPCycle`. See `cycleForResourceWithIdentifer` for details.
*/
public func requestResourceWithIdentifer(name: String, identifier: String, URIValues: [String: AnyObject] = [:], requestObject: AnyObject? = nil, solicited: Bool = false, completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle {
let cycle = try self.cycleForResourceWithIdentifer(name, identifier: identifier,
URIValues: URIValues, requestObject: requestObject, solicited: solicited)
cycle.start(completionHandler)
return cycle
}
/**
Create a `HTTPCycle` object based on the specified resource profile and parameters, and start the `HTTPCycle`. See `cycleForResource` for details.
*/
public func requestResource(name: String, URIValues: [String: AnyObject] = [:],
requestObject: AnyObject? = nil, solicited: Bool = false,
completionHandler: HTTPCycle.CompletionHandler) throws -> HTTPCycle {
let cycle = try self.cycleForResourceWithIdentifer(name, identifier: nil,
URIValues: URIValues, requestObject: requestObject, solicited: solicited)
cycle.start(completionHandler)
return cycle
}
}
|
c6a37d3b56a8ab94dfd1aa5c976ab7e1
| 37.345679 | 246 | 0.634981 | false | false | false | false |
JerrySir/YCOA
|
refs/heads/master
|
YCOA/Main/Apply/Controller/JobDailyCreatViewController.swift
|
mit
|
1
|
//
// JobDailyCreatViewController.swift
// YCOA
//
// Created by Jerry on 2016/12/22.
// Copyright © 2016年 com.baochunsteel. All rights reserved.
//
// 工作日报
import UIKit
import TZImagePickerController
import MBProgressHUD
import Alamofire
class JobDailyCreatViewController: UIViewController, TZImagePickerControllerDelegate {
private var fileInfo: (id_: String, name: String)?
@IBOutlet weak var selectDateButton: UIButton! //日报日期(-1 昨天、0 今天、-2 明天)
@IBOutlet weak var contentTextView: UITextView! //内容
@IBOutlet weak var nextPlanTextField: UITextField! //下次计划
@IBOutlet weak var relatedFileButton: UIButton! //相关文件
@IBOutlet weak var submitButton: UIButton! //提交
@IBOutlet weak var backGroundView: UIScrollView! //背景View
//Private
private var date = "0"
override func viewDidLoad() {
super.viewDidLoad()
self.title = "工作日报"
self.UIConfigure()
self.ActionConfigure()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Action
//绑定控件Action
func ActionConfigure() {
//日报日期
self.selectDateButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
self.view.endEditing(true)
let dates = ["今天", "昨天", "前天"]
UIPickerView.showDidSelectView(SingleColumnDataSource: dates, onView: self.navigationController!.view, selectedTap:
{ (index) in
//不懂看接口文档去
if(index == 0){self.date = "0"}else if(index == 1){self.date = "-1"}else{self.date = "-2"}
self.selectDateButton.setTitle(dates[index], for: .normal)
})
}
//相关文件
self.relatedFileButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
self.view.endEditing(true)
// self.navigationController!.view.jrShow(withTitle: "您没有上传文件的权限")
self.updateFile()
}
//提交
self.submitButton.rac_signal(for: .touchUpInside).subscribeNext { (_) in
self.view.endEditing(true)
self.didSubmit()
}
//backGroundView
self.backGroundView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer { (sender) in
self.view.endEditing(true)
}
self.backGroundView.addGestureRecognizer(tapGestureRecognizer)
}
//提交
private func didSubmit() {
let dts_ = self.date
let content_ : String = self.contentTextView.text
guard content_.utf8.count > 0 else {
self.navigationController?.view.jrShow(withTitle: "请填写工作内容!")
return
}
var parameters : [String : Any] = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!,
"dts" : dts_,
"content" : content_]
//可选
let plan_ = self.nextPlanTextField.text
if(plan_ != nil && plan_!.utf8.count > 0){
parameters["plan"] = plan_!
}
//相关文件
if(self.fileInfo != nil){
parameters["fileid"] = self.fileInfo!.id_
}
//Get
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=flow_daily|appapi&a=saveweb&ajaxbool=true", parameters: parameters)
{ (error, returnValue) in
if(error != nil){
self.navigationController?.view.jrShow(withTitle: error!.domain)
return
}
self.navigationController?.view.jrShow(withTitle: "提交成功!")
}
}
//上传文件
private func updateFile() {
let imagePicker = TZImagePickerController(maxImagesCount: 1, delegate: self)
imagePicker?.allowPickingVideo = false
self.present(imagePicker!, animated: true, completion: nil)
}
func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable : Any]]!) {
let hud = MBProgressHUD.showAdded(to: (self.navigationController?.view)!, animated: true)
hud.mode = .indeterminate
hud.label.text = "上传中..."
let imageName = NSDate.nowTimeToTimeStamp()
let imageData: Data = UIImagePNGRepresentation(photos.first!)!
let urlPar = "/index.php?d=taskrun&m=upload|appapi&a=upfile&ajaxbool=true&adminid=\(UserCenter.shareInstance().uid!)&timekey=\(NSDate.nowTimeToTimeStamp())&token=\(UserCenter.shareInstance().token!)&cfrom=appiphone&appapikey=\(UserCenter.shareInstance().apikey!)"
guard let url_ = URL.JRURLEnCoding(string: YCOA_REQUEST_URL.appending(urlPar)) else {
hud.hide(animated: true)
self.navigationController?.view.jrShow(withTitle: "请求错误")
return
}
Alamofire.upload( multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "file", fileName: "\(imageName).png", mimeType: "image/png")
}, to: url_) { (encodingResult) in
switch encodingResult {
case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
upload.responseJSON(completionHandler: { (response) in
guard response.result.isSuccess else{
hud.hide(animated: true)
self.navigationController?.view.jrShow(withTitle: "网络错误")
return
}
guard let returnValue : NSDictionary = response.result.value as? NSDictionary else{
hud.hide(animated: true)
self.navigationController?.view.jrShow(withTitle: "服务器出错")
return
}
guard returnValue.value(forKey: "code") as! Int == 200 else{
let msg = "\(returnValue.value(forKey: "msg")!)"
hud.hide(animated: true)
self.navigationController?.view.jrShow(withTitle: msg)
return
}
//获取上传信息
hud.hide(animated: false)
NSLog("上传成功")
self.getFileInfo()
})
case .failure(let encodingError):
NSLog("Failure: \(encodingError)")
}
}
}
private func getFileInfo() {
let hud = MBProgressHUD.showAdded(to: (self.navigationController?.view)!, animated: true)
hud.mode = .indeterminate
hud.label.text = "请等待..."
let parameters = ["adminid": UserCenter.shareInstance().uid!,
"timekey": NSDate.nowTimeToTimeStamp(),
"token": UserCenter.shareInstance().token!,
"cfrom": "appiphone",
"appapikey": UserCenter.shareInstance().apikey!]
YCOA_NetWork.get(url: "/index.php?d=taskrun&m=upload|appapi&a=getfile&ajaxbool=true", parameters: parameters)
{ (error, returnValue) in
guard error == nil else{
hud.hide(animated: false)
self.view.jrShow(withTitle: error!.domain)
return
}
guard let dataDic = (returnValue as! NSDictionary).value(forKey: "data") as? NSDictionary else{
hud.hide(animated: false)
self.view.jrShow(withTitle: "暂无数据")
return
}
//同步数据
self.fileInfo = ("\(dataDic["id"] as! Int)", dataDic["filename"] as! String)
hud.hide(animated: true)
self.relatedFileButton.setTitle("相关文件(\(self.fileInfo!.name))", for: .normal)
}
}
//MARK: - UI
//配置控件UI
func UIConfigure() {
self.makeTextFieldStyle(sender: self.selectDateButton)
self.makeTextFieldStyle(sender: self.contentTextView)
self.makeTextFieldStyle(sender: self.relatedFileButton)
self.makeTextFieldStyle(sender: self.submitButton)
self.selectDateButton.setTitle("今天", for: .normal)
}
///设置控件成为TextField一样的样式
func makeTextFieldStyle(sender: UIView) {
sender.layer.masksToBounds = true
sender.layer.cornerRadius = 10/2
sender.layer.borderWidth = 0.3
sender.layer.borderColor = UIColor.lightGray.cgColor
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
0741bf61899f8dae1580d2585d3347e6
| 37.42915 | 271 | 0.558892 | false | false | false | false |
NeoGolightly/CartographyKit
|
refs/heads/master
|
CartographyKit/Edges.swift
|
mit
|
1
|
//
// Edges.swift
// CartographyKit iOS
//
// Created by Michael Helmbrecht on 07/01/2018.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
import Cartography
////////////////////////////////////////////////////////////////////////////////////////////////
//Edges
////////////////////////////////////////////////////////////////////////////////////////////////
private protocol BasicEdges{
static func edges(_ view: View) -> [NSLayoutConstraint?]
#if os(iOS)
static func edgesWithinMargins(_ view: View) -> [NSLayoutConstraint?]
#endif
}
////////////////////////////////////////////////////////////////////////////////////////////////
//BasicEdges Modifier
////////////////////////////////////////////////////////////////////////////////////////////////
private protocol EdgesInsetsPlus{
static func edges(_ view: View, plus: CGFloat) -> [NSLayoutConstraint?]
}
private protocol EdgesInsetsMinus{
static func edges(_ view: View, minus: CGFloat) -> [NSLayoutConstraint?]
}
private protocol EdgesInsets{
static func edgesInset(_ view: View, all: CGFloat) -> [NSLayoutConstraint?]
static func edgesInset(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?]
static func edgesInset(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?]
static func edgesInset(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?]
static func edgesInset(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?]
#if os(iOS)
static func edgesWithinMargins(_ view: View, all: CGFloat) -> [NSLayoutConstraint?]
static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?]
static func edgesWithinMargins(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?]
static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?]
static func edgesWithinMargins(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?]
static func edges(_ view: View, insets: UIEdgeInsets)-> [NSLayoutConstraint?]
#endif
}
extension CartographyKit: BasicEdges{
@discardableResult
public static func edges(_ view: View) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins
return
}
return c
}
}
extension CartographyKit: EdgesInsetsPlus{
@discardableResult
public static func edges(_ view: View, plus: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(by: plus)
return
}
return c
}
}
extension CartographyKit: EdgesInsetsMinus{
@discardableResult
public static func edges(_ view: View, minus: CGFloat) -> [NSLayoutConstraint?]{
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(by: -minus)
return
}
return c
}
}
extension CartographyKit: EdgesInsets{
@discardableResult
public static func edgesInset(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(by: all)
return
}
return c
}
@discardableResult
public static func edgesInset(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(horizontally: horizontal)
return
}
return c
}
@discardableResult
public static func edgesInset(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(vertically: vertical)
return
}
return c
}
@discardableResult
public static func edgesInset(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(horizontally: horizontal, vertically: vertical)
return
}
return c
}
@discardableResult
public static func edgesInset(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edges == view.superview!.edges.inseted(top: top, leading: leading, bottom: bottom, trailing: trailing)
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View, all: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(by: all)
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(horizontally: horizontal)
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View, vertically vertical: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(vertically: vertical)
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View, horizontally horizontal: CGFloat, vertically vertical: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(horizontally: horizontal, vertically: vertical)
return
}
return c
}
@discardableResult
public static func edgesWithinMargins(_ view: View, top: CGFloat, leading: CGFloat, bottom: CGFloat, trailing: CGFloat) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(top: top, leading: leading, bottom: bottom, trailing: trailing)
return
}
return c
}
@discardableResult
public static func edges(_ view: View, insets: UIEdgeInsets) -> [NSLayoutConstraint?] {
var c: [NSLayoutConstraint?] = []
constrain(view){ view in
c = view.edgesWithinMargins == view.superview!.edgesWithinMargins.inseted(by: insets)
return
}
return c
}
}
|
aee0d7f294871ec9cdd0d585ea3c51c8
| 33.516588 | 148 | 0.653714 | false | false | false | false |
UIKonf/uikonf-app
|
refs/heads/master
|
UIKonfApp/UIKonfApp/EntityLookUp.swift
|
mit
|
1
|
//
// EntityLookUp.swift
// UIKonfApp
//
// Created by Maxim Zaks on 11.04.15.
// Copyright (c) 2015 UIKonf. All rights reserved.
//
import Foundation
import Entitas
private var lookups : [Lookup] = []
class Lookup {
unowned let context : Context
private init(context : Context){
self.context = context
}
static func get(context : Context) -> Lookup {
for lookup in lookups {
if lookup.context === context {
return lookup
}
}
let lookup = Lookup(context: context)
lookups.append(lookup)
return lookup
}
lazy var personLookup: SimpleLookup<String> = SimpleLookup(group:self.context.entityGroup(Matcher.All(NameComponent, PhotoComponent))) {
(entity, removedComponent) -> String in
if let c = removedComponent as? NameComponent {
return c.name
}
return entity.get(NameComponent)!.name
}
lazy var talksLookupByTimeSlotId : SimpleLookup<String> = SimpleLookup(group: self.context.entityGroup(Matcher.All(SpeakerNameComponent, TitleComponent, TimeSlotIdComponent, TimeSlotIndexComponent))) { (entity, removedComponent) -> String in
if let c : TimeSlotIdComponent = removedComponent as? TimeSlotIdComponent {
return c.id
}
return entity.get(TimeSlotIdComponent)!.id
}
lazy var locationLookupByName : SimpleLookup<String> = SimpleLookup<String>(group: self.context.entityGroup(Matcher.All(NameComponent, AddressComponent))) { (entity, removedComponent) -> String in
if let component = removedComponent as? NameComponent {
return component.name
}
return entity.get(NameComponent)!.name
}
}
|
0073738ee97700444a72c616ef1e3ff9
| 31.236364 | 245 | 0.649549 | false | false | false | false |
mrdepth/EVEUniverse
|
refs/heads/master
|
Neocom/Neocom/Utility/UIKit+Extensions.swift
|
lgpl-2.1
|
2
|
//
// UIKit+Extensions.swift
// Neocom
//
// Created by Artem Shimanski on 11/26/19.
// Copyright © 2019 Artem Shimanski. All rights reserved.
//
import UIKit
import SafariServices
extension UIApplication {
func endEditing(_ force: Bool) {
self.windows.first{$0.isKeyWindow}?.endEditing(force)
}
}
extension Notification.Name {
static let didFinishJob = Notification.Name(rawValue: "com.shimanski.neocom.didFinishJob")
static let didFinishPaymentTransaction = Notification.Name(rawValue: "com.shimanski.neocom.didFinishPaymentTransaction")
static let didFinishStartup = Notification.Name(rawValue: "com.shimanski.neocom.didFinishStartup")
}
extension NSAttributedString {
var attachments: [NSRange: NSTextAttachment] {
var result = [NSRange: NSTextAttachment]()
enumerateAttribute(.attachment, in: NSRange(location: 0, length: length), options: []) { value, range, _ in
guard let attachment = value as? NSTextAttachment else {return}
result[range] = attachment
}
return result
}
}
extension UIBezierPath {
convenience init(points: [CGPoint]) {
self.init()
guard !points.isEmpty else {return}
move(to: points[0])
points.dropFirst().forEach { addLine(to: $0) }
}
}
extension UIViewController {
var topMostPresentedViewController: UIViewController {
return presentedViewController?.topMostPresentedViewController ?? self
}
}
extension UIAlertController {
convenience init(title: String? = NSLocalizedString("Error", comment: ""), error: Error, handler: ((UIAlertAction) -> Void)? = nil) {
self.init(title: title, message: error.localizedDescription, preferredStyle: .alert)
self.addAction(UIAlertAction(title: NSLocalizedString("Ok", comment: ""), style: .default, handler: handler))
}
}
extension UIApplication {
func openSafari(with url: URL) {
let safari = SFSafariViewController(url: url)
rootViewController?.topMostPresentedViewController.present(safari, animated: true)
}
}
|
b5e114f2df7e7934769f5761abbdc72b
| 32.111111 | 137 | 0.698945 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer
|
refs/heads/master
|
FBSnapshotsViewer/Event Listeners/RecursiveFolderEventsListener.swift
|
mit
|
1
|
//
// RecursiveFolderEventsListener.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 11/02/2017.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
/// `NonRecursiveFolderEventsListener` is responsible to watch folder
/// changes (new file, updated file, deleted file), watches only the given folder recursively.
/// It uses the 3rd party dependency under the hood.
final class RecursiveFolderEventsListener: FolderEventsListener {
/// Internal 3rd party watcher
fileprivate let watcher: FileWatcher
/// Applied filters for watched events
fileprivate let filter: FolderEventFilter?
/// Underlying listeners for subfolders
fileprivate var listeners: [String: FolderEventsListener] = [:]
/// Currently watching folder path
let folderPath: String
/// Handler for `FolderEventsListener` output
weak var output: FolderEventsListenerOutput?
/// Internal accessor for private listeners property
var dependentListeners: [String: FolderEventsListener] {
let dependentListeners = listeners
return dependentListeners
}
init(folderPath: String, filter: FolderEventFilter? = nil, fileWatcherFactory: FileWatcherFactory = FileWatcherFactory()) {
self.filter = filter
self.folderPath = folderPath
self.watcher = fileWatcherFactory.fileWatcher(for: [folderPath])
}
// MARK: - Interface
func startListening() {
try? watcher.start { [weak self] event in
let folderEvent = FolderEvent(eventFlag: event.flag, at: event.path)
self?.process(received: folderEvent)
if let existedFilter = self?.filter, !existedFilter.apply(to: folderEvent) {
return
}
if let strongSelf = self {
strongSelf.output?.folderEventsListener(strongSelf, didReceive: folderEvent)
}
}
}
func stopListening() {
watcher.stop()
}
// MARK: - Helpers
private func process(received event: FolderEvent) {
switch event {
case .created(let path, let object) where object == FolderEventObject.folder:
let listener = RecursiveFolderEventsListener(folderPath: path, filter: filter)
listener.output = output
listener.startListening()
listeners[path] = listener
case .deleted(let path, let object) where object == FolderEventObject.folder:
listeners.removeValue(forKey: path)
default: break
}
}
}
|
213d673750e739dc3827cd7eabe2ee3b
| 33.066667 | 127 | 0.670841 | false | false | false | false |
SonnyBrooks/ProjectEulerSwift
|
refs/heads/master
|
ProjectEulerSwift/Problem21.swift
|
mit
|
1
|
//
// Problem21.swift
// ProjectEulerSwift
// https://projecteuler.net/problem=21
//
// Created by Andrew Budziszek on 12/22/16.
// Copyright © 2016 Andrew Budziszek. All rights reserved.
//
//Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
//If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
//
//For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
//
//Evaluate the sum of all the amicable numbers under 10000.
//
import Foundation
class Problem21 {
var sumOfAmicableNumbers = 0
var alreadyObserved : [Int] = []
func AmicableNumbers() -> Int{
var count = 2
while count <= 10000 {
let a = sumOfDivisors(count)
let b = sumOfDivisors(a)
if b == count && a != b && !alreadyObserved.contains(count) {
alreadyObserved.append(a)
alreadyObserved.append(b)
sumOfAmicableNumbers += a + b
}
count += 1
}
return sumOfAmicableNumbers
}
func sumOfDivisors(_ n: Int) -> Int {
var sum = 0
if n / 2 > 0 {
for i in 1...n / 2 {
if n % i == 0 {
sum += i
}
}
} else {
return 0
}
return sum
}
}
|
e70a476afed3f919225684bd713d63ab
| 26.534483 | 182 | 0.522229 | false | false | false | false |
CNKCQ/DigitalKeyboard
|
refs/heads/master
|
DigitalKeyboard/Classes/DigitalKeyboard.swift
|
mit
|
1
|
//
// DigitalKeyboard.swift
// KeyBoard forKey
//
// Created by Jack on 16/9/15.
// Copyright © 2016年 Jack. All rights reserved.
//
import UIKit
import LocalAuthentication
extension UIDevice {
/// is iPhone X ?
///
/// - Returns: iPhone X
public var iPhoneXSeries: Bool {
if (UIDevice.current.userInterfaceIdiom != .phone) {
return false;
}
if #available(iOS 11.0, *) {
let mainWindow: UIWindow! = UIApplication.shared.delegate!.window!
if (mainWindow.safeAreaInsets.bottom > 0.0) {
return true
}
}
return false
}
}
private let marginvalue = CGFloat(0.5)
private let screenWith = UIScreen.main.bounds.size.width
private let safeAreaHeight: CGFloat = 224.0
private let dkAreaHeight: CGFloat = UIDevice().iPhoneXSeries ? safeAreaHeight + 34 : safeAreaHeight
public enum DKStyle {
case idcard
case number
}
public protocol DigitalKeyboardDelete: NSObjectProtocol {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: UITextRange, replacementString string: String) -> Bool
}
public class DigitalKeyboard: UIInputView {
public static let `default` = DigitalKeyboard(frame: CGRect(x: 0, y: 0, width: screenWith, height: dkAreaHeight), inputViewStyle: .keyboard)
public static let defaultDoneColor = UIColor(red: 28 / 255, green: 171 / 255, blue: 235 / 255, alpha: 1)
public var accessoryView: UIView?
public var dkstyle = DKStyle.idcard {
didSet {
setDigitButton(style: dkstyle)
}
}
public var isSafety: Bool = false {
didSet {
if isSafety {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowNotify(notifiction:)), name: UIResponder.keyboardWillShowNotification, object: nil)
}
}
}
public var shouldHighlight = true {
didSet {
highlight(heghlight: shouldHighlight)
}
}
public func customDoneButton(title: String, titleColor: UIColor = UIColor.white, theme: UIColor = DigitalKeyboard.defaultDoneColor, target: UIViewController? = nil, callback: Selector? = nil) {
setDoneButton(title: title, titleColor: titleColor, theme: theme, target: target, callback: callback)
}
private var textFields = [UITextField]()
private var superView: UIView?
private var buttions: [UIButton] = []
private lazy var bottomView: UIView = {
let subView: UIView = UIView(frame: CGRect(x: 0, y: safeAreaHeight + marginvalue * 4, width: screenWith, height: 44))
subView.backgroundColor = .white
return subView;
}()
public var delegate: DigitalKeyboardDelete?
public convenience init(_ view: UIView, accessoryView: UIView? = nil, field: UITextField? = nil) {
self.init(frame: CGRect.zero, inputViewStyle: .keyboard)
self.accessoryView = accessoryView
addKeyboard(view, field: field)
}
private override init(frame _: CGRect, inputViewStyle: UIInputView.Style) {
super.init(frame: CGRect(x: 0, y: 0, width: screenWith, height: dkAreaHeight), inputViewStyle: inputViewStyle)
backgroundColor = .lightGray
}
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func addKeyboard(_ view: UIView, field: UITextField? = nil) {
superView = view
customSubview()
if let textField = field {
textFields.append(textField)
textField.inputView = self
textField.inputAccessoryView = accessoryView
} else {
for view in (superView?.subviews)! {
if view.isKind(of: UITextField.self) {
let textField = view as! UITextField
textField.inputView = self
textField.inputAccessoryView = accessoryView
textFields.append(textField)
}
}
}
}
private func customSubview() {
var backSpace: UIImage?
var dismiss: UIImage?
let podBundle = Bundle(for: classForCoder)
if let bundleURL = podBundle.url(forResource: "DigitalKeyboard", withExtension: "bundle") {
if let bundle = Bundle(url: bundleURL) {
backSpace = UIImage(named: "Keyboard_Backspace", in: bundle, compatibleWith: nil)
dismiss = UIImage(named: "Keyboard_DismissKey", in: bundle, compatibleWith: nil)
} else {
backSpace = UIImage(named: "Keyboard_Backspace")
dismiss = UIImage(named: "Keyboard_DismissKey")
}
} else {
backSpace = UIImage(named: "Keyboard_Backspace")
dismiss = UIImage(named: "Keyboard_DismissKey")
}
for idx in 0 ... 13 {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFont(ofSize: 28)
button.backgroundColor = UIColor.white
button.tag = idx
highlight(heghlight: shouldHighlight)
addSubview(button)
addSubview(self.bottomView)
button.setTitleColor(UIColor.black, for: .normal)
switch idx {
case 9:
button.setTitle("", for: .normal)
button.setImage(dismiss, for: .normal)
case 10:
button.setTitle("0", for: .normal)
buttions.append(button)
case 11:
button.setTitle("X", for: .normal)
case 12:
button.setTitle("", for: .normal)
button.setImage(backSpace, for: .normal)
case 13:
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
button.backgroundColor = DigitalKeyboard.defaultDoneColor
button.setTitleColor(UIColor.white, for: .normal)
button.setBackgroundImage(nil, for: .normal)
button.setBackgroundImage(nil, for: .highlighted)
button.setTitle(LocalizedString(key: "Done"), for: .normal)
default:
button.setTitle("\(idx + 1)", for: .normal)
buttions.append(button)
}
button.addTarget(self, action: #selector(tap), for: .touchUpInside)
}
}
@objc func tap(sender: UIButton) {
guard let text = sender.currentTitle else {
fatalError("not found the sender's currentTitle")
}
switch sender.tag {
case 12:
firstResponder()?.deleteBackward()
case 13, 9:
firstResponder()?.resignFirstResponder()
default:
if let proxy = self.delegate, let responderField = firstResponder(), let range = responderField.selectedTextRange {
if proxy.textField(responderField, shouldChangeCharactersIn: range, replacementString: text) {
firstResponder()?.insertText(text)
}
} else {
firstResponder()?.insertText(text)
}
}
}
func firstResponder() -> UITextField? {
var firstResponder: UITextField?
for field in textFields {
if field.isFirstResponder {
firstResponder = field
}
}
return firstResponder
}
public override func layoutSubviews() {
super.layoutSubviews()
for view in subviews {
if view.isKind(of: UIButton.self) {
let width = frame.width / 4 * 3
let idx = view.tag
if idx >= 12 {
view.frame = CGRect(x: width + marginvalue, y: CGFloat((idx - 12) % 2) * (safeAreaHeight / 2.0 + marginvalue), width: frame.width / 4, height: (safeAreaHeight - marginvalue) / 2.0)
} else {
view.frame = CGRect(x: CGFloat(idx % 3) * ((width - 2 * marginvalue) / 3 + marginvalue), y: CGFloat(idx / 3) * (safeAreaHeight / 4.0 + marginvalue), width: (width - 2 * marginvalue) / 3, height: safeAreaHeight / 4.0)
}
}
}
}
func highlight(heghlight: Bool) {
for view in subviews {
if let button = view as? UIButton {
if button.tag == 13 { return }
if heghlight {
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
button.setBackgroundImage(UIImage.dk_image(with: .lightGray), for: .highlighted)
} else {
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .normal)
button.setBackgroundImage(UIImage.dk_image(with: .white), for: .highlighted)
}
}
}
}
func setDigitButton(style: DKStyle) {
guard let button = findButton(by: 11) else {
fatalError("not found the button with the tag")
}
switch style {
case .idcard:
button.setTitle("X", for: .normal)
case .number:
let locale = Locale.current
let decimalSeparator = locale.decimalSeparator! as String
button.setTitle(decimalSeparator, for: .normal)
}
}
func findButton(by tag: Int) -> UIButton? {
for button in subviews {
if button.tag == tag {
return button as? UIButton
}
}
return nil
}
func LocalizedString(key: String) -> String {
return (Bundle(identifier: "com.apple.UIKit")?.localizedString(forKey: key, value: nil, table: nil))!
}
func setDoneButton(title: String, titleColor: UIColor, theme: UIColor, target: UIViewController?, callback: Selector?) {
guard let itemButton = findButton(by: 13) else {
fatalError("not found the button with the tag")
}
if let selector = callback, let target = target {
itemButton.addTarget(target, action: selector, for: .touchUpInside)
}
itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 17)
itemButton.setTitle(title, for: .normal)
itemButton.backgroundColor = theme
itemButton.setTitleColor(titleColor, for: .normal)
}
@objc func keyboardWillShowNotify(notifiction _: NSNotification) {
titles = titles.sorted { _, _ in
arc4random() < arc4random()
}
if !buttions.isEmpty {
for (idx, item) in buttions.enumerated() {
item.setTitle(titles[idx], for: .normal)
}
}
}
private lazy var titles = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
}
extension UIImage {
public class func dk_image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
UIGraphicsBeginImageContext(size)
color.set()
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
// MARK: UIInputViewAudioFeedback
extension DigitalKeyboard: UIInputViewAudioFeedback {
open var enableInputClicksWhenVisible: Bool {
return true
}
}
|
0a776e93e0de42726e5d42af4a69d234
| 35.931373 | 236 | 0.58747 | false | false | false | false |
hanhailong/practice-swift
|
refs/heads/master
|
Calendar/Adding Alarms to Calendars/Adding Alarms to Calendars/AppDelegate.swift
|
mit
|
2
|
//
// AppDelegate.swift
// Adding Alarms to Calendars
//
// Created by Domenico on 25/05/15.
// License MIT
//
import UIKit
import EventKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.requestAuthorization()
return true
}
// Request calendar authorization
func requestAuthorization(){
let eventStore = EKEventStore()
switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){
case .Authorized:
addAlarmToCalendarWithStore(eventStore)
case .Denied:
displayAccessDenied()
case .NotDetermined:
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion:
{[weak self] (granted: Bool, error: NSError!) -> Void in
if granted{
self!.addAlarmToCalendarWithStore(eventStore)
} else {
self!.displayAccessDenied()
}
})
case .Restricted:
displayAccessRestricted()
}
}
// Find source in the event store
func sourceInEventStore(
eventStore: EKEventStore,
type: EKSourceType,
title: String) -> EKSource?{
for source in eventStore.sources() as! [EKSource]{
if source.sourceType.value == type.value &&
source.title.caseInsensitiveCompare(title) ==
NSComparisonResult.OrderedSame{
return source
}
}
return nil
}
// Find calendar by Title
func calendarWithTitle(
title: String,
type: EKCalendarType,
source: EKSource,
eventType: EKEntityType) -> EKCalendar?{
for calendar in source.calendarsForEntityType(eventType)
as! Set<EKCalendar>{
if calendar.title.caseInsensitiveCompare(title) ==
NSComparisonResult.OrderedSame &&
calendar.type.value == type.value{
return calendar
}
}
return nil
}
func addAlarmToCalendarWithStore(store: EKEventStore, calendar: EKCalendar){
/* The event starts 60 seconds from now */
let startDate = NSDate(timeIntervalSinceNow: 60.0)
/* And end the event 20 seconds after its start date */
let endDate = startDate.dateByAddingTimeInterval(20.0)
let eventWithAlarm = EKEvent(eventStore: store)
eventWithAlarm.calendar = calendar
eventWithAlarm.startDate = startDate
eventWithAlarm.endDate = endDate
/* The alarm goes off 2 seconds before the event happens */
let alarm = EKAlarm(relativeOffset: -2.0)
eventWithAlarm.title = "Event with Alarm"
eventWithAlarm.addAlarm(alarm)
var error:NSError?
if store.saveEvent(eventWithAlarm, span: EKSpanThisEvent, error: &error){
println("Saved an event that fires 60 seconds from now.")
} else if let theError = error{
println("Failed to save the event. Error = \(theError)")
}
}
func addAlarmToCalendarWithStore(store: EKEventStore){
let icloudSource = sourceInEventStore(store,
type: EKSourceTypeCalDAV,
title: "iCloud")
if icloudSource == nil{
println("You have not configured iCloud for your device.")
return
}
let calendar = calendarWithTitle("Calendar",
type: EKCalendarTypeCalDAV,
source: icloudSource!,
eventType: EKEntityTypeEvent)
if calendar == nil{
println("Could not find the calendar we were looking for.")
return
}
addAlarmToCalendarWithStore(store, calendar: calendar!)
}
//- MARK: Helper methods
func displayAccessDenied(){
println("Access to the event store is denied.")
}
func displayAccessRestricted(){
println("Access to the event store is restricted.")
}
}
|
414fe3b833be516ca4c1577bf3e2e51a
| 29.70068 | 127 | 0.56437 | false | false | false | false |
LoopKit/LoopKit
|
refs/heads/dev
|
LoopKitUI/View Controllers/DismissibleHostingController.swift
|
mit
|
1
|
//
// DismissibleHostingController.swift
// LoopKitUI
//
// Created by Michael Pangburn on 5/7/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import SwiftUI
public class DismissibleHostingController: UIHostingController<AnyView> {
public enum DismissalMode {
case modalDismiss
case pop(to: UIViewController.Type)
}
private var onDisappear: () -> Void = {}
public convenience init<Content: View> (
rootView: Content,
dismissalMode: DismissalMode = .modalDismiss,
isModalInPresentation: Bool = true,
onDisappear: @escaping () -> Void = {},
colorPalette: LoopUIColorPalette
) {
self.init(rootView: rootView,
dismissalMode: dismissalMode,
isModalInPresentation: isModalInPresentation,
onDisappear: onDisappear,
guidanceColors: colorPalette.guidanceColors,
carbTintColor: colorPalette.carbTintColor,
glucoseTintColor: colorPalette.glucoseTintColor,
insulinTintColor: colorPalette.insulinTintColor)
}
public convenience init<Content: View>(
rootView: Content,
dismissalMode: DismissalMode = .modalDismiss,
isModalInPresentation: Bool = true,
onDisappear: @escaping () -> Void = {},
guidanceColors: GuidanceColors = GuidanceColors(),
carbTintColor: Color = .green,
glucoseTintColor: Color = Color(.systemTeal),
insulinTintColor: Color = .orange
) {
// Delay initialization of dismissal closure pushed into SwiftUI Environment until after calling the designated initializer
var dismiss = {}
self.init(rootView: AnyView(rootView.environment(\.dismissAction, { dismiss() })
.environment(\.guidanceColors, guidanceColors)
.environment(\.carbTintColor, carbTintColor)
.environment(\.glucoseTintColor, glucoseTintColor)
.environment(\.insulinTintColor, insulinTintColor)))
switch dismissalMode {
case .modalDismiss:
dismiss = { [weak self] in self?.dismiss(animated: true) }
case .pop(to: let PredecessorViewController):
dismiss = { [weak self] in
guard
let navigationController = self?.navigationController,
let predecessor = navigationController.viewControllers.last(where: { $0.isKind(of: PredecessorViewController) })
else {
return
}
navigationController.popToViewController(predecessor, animated: true)
}
}
self.onDisappear = onDisappear
self.isModalInPresentation = isModalInPresentation
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
onDisappear()
}
}
|
7bf4c44dbe4f4410828bf390aa8d1010
| 36.423077 | 132 | 0.631723 | false | false | false | false |
fgengine/quickly
|
refs/heads/master
|
Quickly/ViewControllers/Stack/Animation/QStackViewControllerInteractiveAnimation.swift
|
mit
|
1
|
//
// Quickly
//
public final class QStackViewControllerinteractiveDismissAnimation : IQStackViewControllerInteractiveDismissAnimation {
public var containerViewController: IQStackContainerViewController!
public var shadow: QViewShadow
public var currentBeginFrame: CGRect
public var currentEndFrame: CGRect
public var currentViewController: IQStackViewController!
public var currentGroupbarVisibility: CGFloat
public var previousBeginFrame: CGRect
public var previousEndFrame: CGRect
public var previousViewController: IQStackViewController!
public var previousGroupbarVisibility: CGFloat
public var position: CGPoint
public var deltaPosition: CGFloat
public var velocity: CGPoint
public var distance: CGFloat
public var dismissDistanceRate: CGFloat
public var overlapping: CGFloat
public var acceleration: CGFloat
public var ease: IQAnimationEase
public private(set) var canFinish: Bool
public init(
shadow: QViewShadow = QViewShadow(color: UIColor.black, opacity: 0.45, radius: 6, offset: CGSize.zero),
overlapping: CGFloat = 1,
acceleration: CGFloat = 1200,
dismissDistanceRate: CGFloat = 0.4,
ease: IQAnimationEase = QAnimationEaseQuadraticOut()
) {
self.shadow = shadow
self.currentBeginFrame = CGRect.zero
self.currentEndFrame = CGRect.zero
self.currentGroupbarVisibility = 1
self.previousBeginFrame = CGRect.zero
self.previousEndFrame = CGRect.zero
self.previousGroupbarVisibility = 1
self.position = CGPoint.zero
self.deltaPosition = 0
self.velocity = CGPoint.zero
self.distance = 0
self.dismissDistanceRate = dismissDistanceRate
self.overlapping = overlapping
self.acceleration = acceleration
self.ease = ease
self.canFinish = false
}
public func prepare(
containerViewController: IQStackContainerViewController,
contentView: UIView,
currentViewController: IQStackViewController,
currentGroupbarVisibility: CGFloat,
previousViewController: IQStackViewController,
previousGroupbarVisibility: CGFloat,
position: CGPoint,
velocity: CGPoint
) {
let bounds = contentView.bounds
self.containerViewController = containerViewController
self.currentBeginFrame = bounds
self.currentEndFrame = CGRect(
x: bounds.maxX,
y: bounds.minY,
width: bounds.width,
height: bounds.height
)
self.currentViewController = currentViewController
self.currentViewController.view.frame = self.currentBeginFrame
self.currentViewController.view.shadow = self.shadow
self.currentViewController.layoutIfNeeded()
self.currentViewController.prepareInteractiveDismiss()
self.currentGroupbarVisibility = currentGroupbarVisibility
self.previousBeginFrame = CGRect(
x: bounds.minX - (bounds.width * self.overlapping),
y: bounds.minY,
width: bounds.width,
height: bounds.height
)
self.previousEndFrame = bounds
self.previousViewController = previousViewController
self.previousViewController.view.frame = self.previousBeginFrame
self.previousViewController.layoutIfNeeded()
self.previousViewController.prepareInteractivePresent()
self.previousGroupbarVisibility = previousGroupbarVisibility
self.position = position
self.velocity = velocity
self.distance = bounds.width
containerViewController.groupbarVisibility = currentGroupbarVisibility
contentView.insertSubview(currentViewController.view, aboveSubview: previousViewController.view)
}
public func update(position: CGPoint, velocity: CGPoint) {
self.deltaPosition = self.ease.lerp(max(0, position.x - self.position.x), from: 0, to: self.distance)
let progress = self.deltaPosition / self.distance
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility.lerp(self.previousGroupbarVisibility, progress: progress)
self.currentViewController.view.frame = self.currentBeginFrame.lerp(self.currentEndFrame, progress: progress)
self.previousViewController.view.frame = self.previousBeginFrame.lerp(self.previousEndFrame, progress: progress)
self.canFinish = self.deltaPosition > (self.distance * self.dismissDistanceRate)
}
public func finish(_ complete: @escaping (_ completed: Bool) -> Void) {
let duration = TimeInterval((self.distance - self.deltaPosition) / self.acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
self.containerViewController.groupbarVisibility = self.previousGroupbarVisibility
self.currentViewController.view.frame = self.currentEndFrame
self.previousViewController.view.frame = self.previousEndFrame
}, completion: { [weak self] (completed: Bool) in
if let self = self {
self.containerViewController.groupbarVisibility = self.previousGroupbarVisibility
self.containerViewController = nil
self.currentViewController.view.frame = self.currentEndFrame
self.currentViewController.view.shadow = nil
self.currentViewController.finishInteractiveDismiss()
self.currentViewController = nil
self.previousViewController.view.frame = self.previousEndFrame
self.previousViewController.finishInteractivePresent()
self.previousViewController = nil
}
complete(completed)
})
}
public func cancel(_ complete: @escaping (_ completed: Bool) -> Void) {
let duration = TimeInterval(self.deltaPosition / self.acceleration)
UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility
self.currentViewController.view.frame = self.currentBeginFrame
self.previousViewController.view.frame = self.previousBeginFrame
}, completion: { [weak self] (completed: Bool) in
if let self = self {
self.containerViewController.groupbarVisibility = self.currentGroupbarVisibility
self.containerViewController = nil
self.currentViewController.view.frame = self.currentBeginFrame
self.currentViewController.view.shadow = nil
self.currentViewController.cancelInteractiveDismiss()
self.currentViewController = nil
self.previousViewController.view.frame = self.previousBeginFrame
self.previousViewController.cancelInteractivePresent()
self.previousViewController = nil
}
complete(completed)
})
}
}
|
d7e4b4e237094fd89fc400802345507c
| 45.551948 | 146 | 0.693821 | false | false | false | false |
vapor/vapor
|
refs/heads/main
|
Tests/VaporTests/ValidationTests.swift
|
mit
|
1
|
import Vapor
import XCTest
class ValidationTests: XCTestCase {
func testValidate() throws {
struct User: Validatable, Codable {
enum Gender: String, CaseIterable, Codable {
case male, female, other
}
var id: Int?
var name: String
var age: Int
var gender: Gender
var email: String?
var pet: Pet
var favoritePet: Pet?
var luckyNumber: Int?
var profilePictureURL: String?
var preferredColors: [String]
var isAdmin: Bool
struct Pet: Codable {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
init(id: Int? = nil, name: String, age: Int, gender: Gender, pet: Pet, preferredColors: [String] = [], isAdmin: Bool) {
self.id = id
self.name = name
self.age = age
self.gender = gender
self.pet = pet
self.preferredColors = preferredColors
self.isAdmin = isAdmin
}
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
// validate gender is of type Gender
v.add("gender", as: String.self, is: .case(of: Gender.self))
// validate the email is valid and is not nil
v.add("email", as: String?.self, is: !.nil && .email)
v.add("email", as: String?.self, is: .email && !.nil) // test other way
// validate the email is valid or is nil
v.add("email", as: String?.self, is: .nil || .email)
v.add("email", as: String?.self, is: .email || .nil) // test other way
// validate that the lucky number is nil or is 5 or 7
v.add("luckyNumber", as: Int?.self, is: .nil || .in(5, 7))
// validate that the profile picture is nil or a valid URL
v.add("profilePictureURL", as: String?.self, is: .url || .nil)
v.add("preferredColors", as: [String].self, is: !.empty)
// pet validations
v.add("pet") { pet in
pet.add("name", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
pet.add("age", as: Int.self, is: .range(3...))
}
// optional favorite pet validations
v.add("favoritePet", required: false) { pet in
pet.add(
"name", as: String.self,
is: .count(5...) && .characterSet(.alphanumerics + .whitespaces)
)
pet.add("age", as: Int.self, is: .range(3...))
}
v.add("isAdmin", as: Bool.self)
}
}
let valid = """
{
"name": "Tanner",
"age": 24,
"gender": "male",
"email": "[email protected]",
"luckyNumber": 5,
"profilePictureURL": "https://foo.jpg",
"preferredColors": ["blue"],
"pet": {
"name": "Zizek",
"age": 3
},
"hobbies": [
{
"title": "Football"
},
{
"title": "Computer science"
}
],
"favoritePet": null,
"isAdmin": true
}
"""
XCTAssertNoThrow(try User.validate(json: valid))
let validURL: URI = "https://tanner.xyz/user?name=Tanner&age=24&gender=male&[email protected]&luckyNumber=5&profilePictureURL=https://foo.jpg&preferredColors=[blue]&pet[name]=Zizek&pet[age]=3&isAdmin=true"
XCTAssertNoThrow(try User.validate(query: validURL))
let invalidUser = """
{
"name": "Tan!ner",
"age": 24,
"gender": "other",
"email": "[email protected]",
"luckyNumber": 5,
"profilePictureURL": "https://foo.jpg",
"preferredColors": ["blue"],
"pet": {
"name": "Zizek",
"age": 3
},
"isAdmin": true,
"hobbies": [
{
"title": "Football"
},
{
"title": "Computer science"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidUser)) { error in
XCTAssertEqual("\(error)", "name contains '!' (allowed: A-Z, a-z, 0-9)")
}
let invalidUserURL: URI = "https://tanner.xyz/user?name=Tan!ner&age=24&gender=other&[email protected]&luckyNumber=5&profilePictureURL=https://foo.jpg&preferredColors=[blue]&pet[name]=Zizek&pet[age]=3&isAdmin=true"
XCTAssertThrowsError(try User.validate(query: invalidUserURL)) { error in
XCTAssertEqual("\(error)", "name contains '!' (allowed: A-Z, a-z, 0-9)")
}
}
func testValidateInternationalEmail() throws {
struct Email: Validatable, Codable {
var email: String?
init(email: String) {
self.email = email
}
static func validations(_ v: inout Validations) {
// validate the international email is valid and is not nil
v.add("email", as: String?.self, is: !.nil && .internationalEmail)
v.add("email", as: String?.self, is: .internationalEmail && !.nil) // test other way
}
}
let valid = """
{
"email": "ß@tanner.xyz"
}
"""
XCTAssertNoThrow(try Email.validate(json: valid))
let validURL: URI = "https://tanner.xyz/email?email=ß@tanner.xyz"
XCTAssertNoThrow(try Email.validate(query: validURL))
let validURL2: URI = "https://tanner.xyz/email?email=me@ßanner.xyz"
XCTAssertNoThrow(try Email.validate(query: validURL2))
let invalidUser = """
{
"email": "me@[email protected]",
}
"""
XCTAssertThrowsError(try Email.validate(json: invalidUser)) { error in
XCTAssertEqual("\(error)", "email is not a valid email address, email is not a valid email address")
}
let invalidUserURL: URI = "https://tanner.xyz/email?email=me@[email protected]"
XCTAssertThrowsError(try Email.validate(query: invalidUserURL)) { error in
XCTAssertEqual("\(error)", "email is not a valid email address, email is not a valid email address")
}
}
func testValidateNested() throws {
struct User: Validatable, Codable {
var name: String
var age: Int
var pet: Pet
struct Pet: Codable {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
// pet validations
v.add("pet") { pet in
pet.add("name", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
pet.add("age", as: Int.self, is: .range(3...))
}
}
}
let invalidPetJSON = """
{
"name": "Tanner",
"age": 24,
"pet": {
"name": "Zi!zek",
"age": 3
}
}
"""
XCTAssertThrowsError(try User.validate(json: invalidPetJSON)) { error in
XCTAssertEqual("\(error)", "pet name contains '!' (allowed: whitespace, A-Z, a-z, 0-9)")
}
let invalidPetURL: URI = "https://tanner.xyz/user?name=Tanner&age=24&pet[name]=Zi!ek&pet[age]=3"
XCTAssertThrowsError(try User.validate(query: invalidPetURL)) { error in
XCTAssertEqual("\(error)", "pet name contains '!' (allowed: whitespace, A-Z, a-z, 0-9)")
}
}
func testValidateNestedEach() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
var allergies: [Allergy]?
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
struct Allergy: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
v.add(each: "hobbies") { i, hobby in
hobby.add("title", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
}
v.add("hobbies", as: [Hobby].self, is: !.empty)
v.add(each: "allergies", required: false) { i, allergy in
allergy.add("title", as: String.self, is: .characterSet(.letters))
}
}
}
let invalidNestedArray = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football€"
},
{
"title": "Co"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray)) { error in
XCTAssertEqual("\(error)", "hobbies at index 0 title contains '€' (allowed: whitespace, A-Z, a-z, 0-9) and at index 1 title is less than minimum of 5 character(s)")
}
let invalidNestedArray2 = """
{
"name": "Tanner",
"age": 24,
"allergies": [
{
"title": "Peanuts"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray2)) { error in
XCTAssertEqual("\(error)", "hobbies is required, hobbies is required")
}
let invalidNestedArray3 = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
"allergies": [
{
"title": "Peanuts€"
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray3)) { error in
XCTAssertEqual("\(error)", "allergies at index 0 title contains '€' (allowed: A-Z, a-z)")
}
let validNestedArray = """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "Football"
}
],
}
"""
XCTAssertNoThrow(try User.validate(json: validNestedArray))
}
func testValidateNestedEachIndex() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
v.add(each: "hobbies") { i, hobby in
// don't validate first item
if i != 0 {
hobby.add("title", as: String.self, is: .characterSet(.alphanumerics + .whitespaces))
}
}
v.add("hobbies", as: [Hobby].self, is: !.empty)
}
}
XCTAssertNoThrow(try User.validate(json: """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "€"
},
{
"title": "hello"
}
]
}
"""))
XCTAssertThrowsError(try User.validate(json: """
{
"name": "Tanner",
"age": 24,
"hobbies": [
{
"title": "hello"
},
{
"title": "€"
}
]
}
""")) { error in
XCTAssertEqual("\(error)", "hobbies at index 1 title contains '€' (allowed: whitespace, A-Z, a-z, 0-9)")
}
}
func testCatchError() throws {
struct User: Validatable, Codable {
var name: String
var age: Int
static func validations(_ v: inout Validations) {
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
v.add("age", as: Int.self, is: .range(18...))
}
}
let invalidUser = """
{
"name": "Tan!ner",
"age": 24
}
"""
do {
try User.validate(json: invalidUser)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "name")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "contains '!' (allowed: A-Z, a-z, 0-9)")
let and = name.result as! ValidatorResults.And
let count = and.left as! ValidatorResults.Range<Int>
XCTAssertEqual(count.result, .greaterThanOrEqualToMin(5))
let character = and.right as! ValidatorResults.CharacterSet
XCTAssertEqual(character.invalidSlice, "!")
}
}
func testNotReadability() {
assert("vapor!🤠", fails: .ascii && .alphanumeric, "contains '🤠' (allowed: ASCII) and contains '!' (allowed: A-Z, a-z, 0-9)")
assert("vapor", fails: !(.ascii && .alphanumeric), "contains only ASCII and contains only A-Z, a-z, 0-9")
}
func testASCII() {
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", passes: .ascii)
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", fails: !.ascii, "contains only ASCII")
assert("\n\r\t", passes: .ascii)
assert("\n\r\t\u{129}", fails: .ascii, "contains 'ĩ' (allowed: ASCII)")
assert(" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", passes: .ascii)
assert("ABCDEFGHIJKLMNOPQR🤠STUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fails: .ascii, "contains '🤠' (allowed: ASCII)")
}
func testCollectionASCII() {
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], passes: .ascii)
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], fails: !.ascii, "contains only ASCII")
assert(["\n\r\t"], passes: .ascii)
assert(["\n\r\t", "\u{129}"], fails: .ascii, "string at index 1 contains 'ĩ' (allowed: ASCII)")
assert([" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"], passes: .ascii)
assert(["ABCDEFGHIJKLMNOPQR🤠STUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"], fails: .ascii, "string at index 0 contains '🤠' (allowed: ASCII)")
}
func testAlphanumeric() {
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", passes: .alphanumeric)
assert("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", fails: .alphanumeric, "contains '+' (allowed: A-Z, a-z, 0-9)")
}
func testCollectionAlphanumeric() {
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"], passes: .alphanumeric)
assert(["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef", "ghijklmnopqrstuvwxyz0123456789+/"], fails: .alphanumeric, "string at index 1 contains '+' (allowed: A-Z, a-z, 0-9)")
}
func testEmpty() {
assert("", passes: .empty)
assert("something", fails: .empty, "is not empty")
assert([Int](), passes: .empty)
assert([Int](), fails: !.empty, "is empty")
assert([1, 2], fails: .empty, "is not empty")
assert([1, 2], passes: !.empty)
}
func testEmail() {
assert("[email protected]", passes: .email)
assert("[email protected]", fails: !.email, "is a valid email address")
assert("[email protected]@vapor.codes", fails: .email, "is not a valid email address")
assert("[email protected].", fails: .email, "is not a valid email address")
assert("tanner@@vapor.codes", fails: .email, "is not a valid email address")
assert("@vapor.codes", fails: .email, "is not a valid email address")
assert("tanner@codes", fails: .email, "is not a valid email address")
assert("asdf", fails: .email, "is not a valid email address")
assert("asdf", passes: !.email)
}
func testEmailWithSpecialCharacters() {
assert("ß@b.com", passes: .internationalEmail)
assert("ß@b.com", fails: !.internationalEmail, "is a valid email address")
assert("b@ß.com", passes: .internationalEmail)
assert("b@ß.com", fails: !.internationalEmail, "is a valid email address")
}
func testRange() {
assert(4, passes: .range(-5...5))
assert(4, passes: .range(..<5))
assert(5, fails: .range(..<5), "is greater than maximum of 4")
assert(5, passes: .range(...10))
assert(11, fails: .range(...10), "is greater than maximum of 10")
assert(4, fails: !.range(-5...5), "is between -5 and 5")
assert(5, passes: .range(-5...5))
assert(-5, passes: .range(-5...5))
assert(6, fails: .range(-5...5), "is greater than maximum of 5")
assert(-6, fails: .range(-5...5), "is less than minimum of -5")
assert(.max, passes: .range(5...))
assert(4, fails: .range(5...), "is less than minimum of 5")
assert(-5, passes: .range(-5..<6))
assert(-4, passes: .range(-5..<6))
assert(5, passes: .range(-5..<6))
assert(-6, fails: .range(-5..<6), "is less than minimum of -5")
assert(6, fails: .range(-5..<6), "is greater than maximum of 5")
assert(6, passes: !.range(-5..<6))
}
func testCountCharacters() {
assert("1", passes: .count(1...6))
assert("1", fails: !.count(1...6), "is between 1 and 6 character(s)")
assert("123", passes: .count(1...6))
assert("123456", passes: .count(1...6))
assert("", fails: .count(1...6), "is less than minimum of 1 character(s)")
assert("1234567", fails: .count(1...6), "is greater than maximum of 6 character(s)")
}
func testCountItems() {
assert([1], passes: .count(1...6))
assert([1], fails: !.count(1...6), "is between 1 and 6 item(s)")
assert([1], passes: .count(...1))
assert([1], fails: .count(..<1), "is greater than maximum of 0 item(s)")
assert([1, 2, 3], passes: .count(1...6))
assert([1, 2, 3, 4, 5, 6], passes: .count(1...6))
assert([Int](), fails: .count(1...6), "is less than minimum of 1 item(s)")
assert([1, 2, 3, 4, 5, 6, 7], fails: .count(1...6), "is greater than maximum of 6 item(s)")
}
func testURL() {
assert("https://www.somedomain.com/somepath.png", passes: .url)
assert("https://www.somedomain.com/somepath.png", fails: !.url, "is a valid URL")
assert("https://www.somedomain.com/", passes: .url)
assert("file:///Users/vapor/rocks/somePath.png", passes: .url)
assert("www.somedomain.com/", fails: .url, "is an invalid URL")
assert("bananas", fails: .url, "is an invalid URL")
assert("bananas", passes: !.url)
}
func testValid() {
assert("some random string", passes: .valid)
assert(true, passes: .valid)
assert("123", passes: .valid)
assert([1, 2, 3], passes: .valid)
assert(Date.init(), passes: .valid)
assert("some random string", fails: !.valid, "is valid")
assert(true, fails: !.valid, "is valid")
assert("123", fails: !.valid, "is valid")
}
func testPattern() {
assert("this are not numbers", fails: .pattern("^[0-9]*$"), "is not a valid pattern ^[0-9]*$")
assert("12345", passes: .pattern("^[0-9]*$"))
}
func testPreexistingValidatorResultIsIncluded() throws {
struct CustomValidatorResult: ValidatorResult {
var isFailure: Bool {
true
}
var successDescription: String? {
nil
}
var failureDescription: String? {
"custom description"
}
}
var validations = Validations()
validations.add("key", result: CustomValidatorResult())
let error = try validations.validate(json: "{}").error
XCTAssertEqual(error?.description, "key custom description")
}
func testDoubleNegationIsAvoided() throws {
var validations = Validations()
validations.add("key", as: String.self, is: !.empty)
let error = try validations.validate(json: #"{"key": ""}"#).error
XCTAssertEqual(error?.description, "key is empty")
}
func testCaseOf() {
enum StringEnumType: String, CaseIterable {
case case1, case2, case3 = "CASE3"
}
assert("case1", passes: .case(of: StringEnumType.self))
assert("case2", passes: .case(of: StringEnumType.self))
assert("case1", fails: !.case(of: StringEnumType.self), "is case1, case2, or CASE3")
assert("case3", fails: .case(of: StringEnumType.self), "is not case1, case2, or CASE3")
enum IntEnumType: Int, CaseIterable {
case case1 = 1, case2 = 2
}
assert(1, passes: .case(of: IntEnumType.self))
assert(2, passes: .case(of: IntEnumType.self))
assert(1, fails: !.case(of: IntEnumType.self), "is 1 or 2")
assert(3, fails: .case(of: IntEnumType.self), "is not 1 or 2")
enum SingleCaseEnum: String, CaseIterable {
case case1 = "CASE1"
}
assert("CASE1", passes: .case(of: SingleCaseEnum.self))
assert("CASE1", fails: !.case(of: SingleCaseEnum.self), "is CASE1")
assert("CASE2", fails: .case(of: SingleCaseEnum.self), "is not CASE1")
}
func testCustomResponseMiddleware() throws {
// Test item
struct User: Validatable {
let name: String
let age: Int
static func validations(_ v: inout Validations) {
// validate name is at least 5 characters and alphanumeric
v.add("name", as: String.self, is: .count(5...) && .alphanumeric)
// validate age is 18 or older
v.add("age", as: Int.self, is: .range(18...))
}
}
// Setup
let app = Application(.testing)
defer { app.shutdown() }
// Converts validation errors to a custom response.
final class ValidationErrorMiddleware: Middleware {
// Defines the format of the custom error response.
struct ErrorResponse: Content {
var errors: [String]
}
func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
next.respond(to: request).flatMapErrorThrowing { error in
// Check to see if this is a validation error.
if let validationError = error as? ValidationsError {
// Convert each failed ValidatorResults to a String
// for the sake of this example.
let errorMessages = validationError.failures.map { failure -> String in
let reason: String
// The failure result will be one of the ValidatorResults subtypes.
//
// Each validator extends ValidatorResults with a nested type.
// For example, the .email validator's result type is:
//
// struct ValidatorResults.Email {
// let isValidEmail: Bool
// }
//
// You can handle as many or as few of these types as you want.
// Vapor and third party packages may add additional types.
// This switch is only handling two cases as an example.
//
// If you want to localize your validation failures, this is a
// good place to do it.
switch failure.result {
case is ValidatorResults.Missing:
reason = "is required"
case let error as ValidatorResults.TypeMismatch:
reason = "is not \(error.type)"
default:
reason = "unknown"
}
return "\(failure.key) \(reason)"
}
// Create the 400 response and encode the custom error content.
let response = Response(status: .badRequest)
try response.content.encode(ErrorResponse(errors: errorMessages))
return response
} else {
// This isn't a validation error, rethrow it and let
// ErrorMiddleware handle it.
throw error
}
}
}
}
app.middleware.use(ValidationErrorMiddleware())
app.post("users") { req -> HTTPStatus in
try User.validate(content: req)
return .ok
}
// Test that the custom validation error middleware is working.
try app.test(.POST, "users", beforeRequest: { req in
try req.content.encode([
"name": "Vapor",
"age": "asdf"
])
}, afterResponse: { res in
XCTAssertEqual(res.status, .badRequest)
let content = try res.content.decode(ValidationErrorMiddleware.ErrorResponse.self)
XCTAssertEqual(content.errors.count, 1)
})
}
func testValidateNullWhenNotRequired() throws {
struct Site: Validatable, Codable {
var url: String?
var number: Int?
var name: String?
static func validations(_ v: inout Validations) {
v.add("url", as: String.self, is: .url, required: false)
v.add("number", as: Int.self, required: false)
v.add("name", as: String.self, required: false)
}
}
let valid = """
{
"url": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid))
let valid2 = """
{
}
"""
XCTAssertNoThrow(try Site.validate(json: valid2))
let valid3 = """
{
"name": "Tim"
}
"""
XCTAssertNoThrow(try Site.validate(json: valid3))
let valid4 = """
{
"name": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid4))
let valid5 = """
{
"number": 3
}
"""
XCTAssertNoThrow(try Site.validate(json: valid5))
let valid6 = """
{
"number": null
}
"""
XCTAssertNoThrow(try Site.validate(json: valid6))
let invalid1 = """
{
"number": "Tim"
}
"""
do {
try Site.validate(json: invalid1)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "number")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "is not a(n) Int")
}
let invalid2 = """
{
"name": 3
}
"""
do {
try Site.validate(json: invalid2)
} catch let error as ValidationsError {
XCTAssertEqual(error.failures.count, 1)
let name = error.failures[0]
XCTAssertEqual(name.key.stringValue, "name")
XCTAssertEqual(name.result.isFailure, true)
XCTAssertEqual(name.result.failureDescription, "is not a(n) String")
}
}
func testCustomFailureDescriptions() throws {
struct User: Validatable {
var name: String
var age: Int
var hobbies: [Hobby]
struct Hobby: Codable {
var title: String
init(title: String) {
self.title = title
}
}
static func validations(_ v: inout Validations) {
struct CustomValidatorResult: ValidatorResult {
var isFailure: Bool {
true
}
var successDescription: String? {
nil
}
var failureDescription: String? {
"custom description"
}
}
v.add("key", result: CustomValidatorResult(), customFailureDescription: "Something went wrong with the provided data")
v.add("name", as: String.self, is: .count(5...) && !.alphanumeric, customFailureDescription: "The provided name is invalid")
v.add(each: "hobbies", customFailureDescription: "A provided hobby value was not alphanumeric") { i, hobby in
hobby.add("title", as: String.self, is: .count(5...) && .characterSet(.alphanumerics + .whitespaces))
}
v.add("hobbies", customFailureDescription: "A provided hobby value was empty") { hobby in
hobby.add("title", as: String.self, is: !.empty)
}
}
}
let invalidNestedArray = """
{
"name": "Andre",
"age": 26,
"hobbies": [
{
"title": "Running€"
},
{
"title": "Co"
},
{
"title": ""
}
]
}
"""
XCTAssertThrowsError(try User.validate(json: invalidNestedArray)) { error in
XCTAssertEqual("\(error)", "Something went wrong with the provided data, The provided name is invalid, A provided hobby value was not alphanumeric, A provided hobby value was empty")
}
}
override class func setUp() {
XCTAssert(isLoggingConfigured)
}
}
private func assert<T>(
_ data: T,
fails validator: Validator<T>,
_ description: String,
file: StaticString = #file,
line: UInt = #line
) {
let file = (file)
let result = validator.validate(data)
XCTAssert(result.isFailure, result.successDescription ?? "n/a", file: file, line: line)
XCTAssertEqual(description, result.failureDescription ?? "n/a", file: file, line: line)
}
private func assert<T>(
_ data: T,
passes validator: Validator<T>,
file: StaticString = #file,
line: UInt = #line
) {
let file = (file)
let result = validator.validate(data)
XCTAssert(!result.isFailure, result.failureDescription ?? "n/a", file: file, line: line)
}
|
08940085cfe38ac909ecff40f6118408
| 37.316338 | 223 | 0.498745 | false | false | false | false |
XWebView/XWebView
|
refs/heads/master
|
XWebView/XWVObject.swift
|
apache-2.0
|
2
|
/*
Copyright 2015 XWebView
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 WebKit
private let webViewInvalidated =
NSError(domain: WKErrorDomain, code: WKError.webViewInvalidated.rawValue, userInfo: nil)
public class XWVObject : NSObject {
public let namespace: String
private(set) public weak var webView: WKWebView?
private weak var origin: XWVObject?
private let reference: Int
// initializer for plugin object.
init(namespace: String, webView: WKWebView) {
self.namespace = namespace
self.webView = webView
reference = 0
super.init()
origin = self
}
// initializer for script object with global namespace.
init(namespace: String, origin: XWVObject) {
self.namespace = namespace
self.origin = origin
webView = origin.webView
reference = 0
super.init()
}
// initializer for script object which is retained on script side.
init(reference: Int, origin: XWVObject) {
self.reference = reference
self.origin = origin
webView = origin.webView
namespace = "\(origin.namespace).$references[\(reference)]"
super.init()
}
deinit {
guard let webView = webView else { return }
let script: String
if origin === self {
script = "delete \(namespace)"
} else if reference != 0, let origin = origin {
script = "\(origin.namespace).$releaseObject(\(reference))"
} else {
return
}
webView.asyncEvaluateJavaScript(script, completionHandler: nil)
}
// Evaluate JavaScript expression
public func evaluateExpression(_ expression: String) throws -> Any {
guard let webView = webView else {
throw webViewInvalidated
}
let result = try webView.syncEvaluateJavaScript(scriptForRetaining(expression))
return wrapScriptObject(result)
}
public typealias Handler = ((Any?, Error?) -> Void)?
public func evaluateExpression(_ expression: String, completionHandler: Handler) {
guard let webView = webView else {
completionHandler?(nil, webViewInvalidated)
return
}
guard let completionHandler = completionHandler else {
webView.asyncEvaluateJavaScript(expression, completionHandler: nil)
return
}
webView.asyncEvaluateJavaScript(scriptForRetaining(expression)) {
[weak self](result: Any?, error: Error?)->Void in
if let error = error {
completionHandler(nil, error)
} else if let result = result {
completionHandler(self?.wrapScriptObject(result) ?? result, nil)
} else {
completionHandler(undefined, error)
}
}
}
private func scriptForRetaining(_ script: String) -> String {
guard let origin = origin else { return script }
return "\(origin.namespace).$retainObject(\(script))"
}
func wrapScriptObject(_ object: Any) -> Any {
guard let origin = origin else { return object }
if let dict = object as? [String: Any], dict["$sig"] as? NSNumber == 0x5857574F {
if let num = dict["$ref"] as? NSNumber, num != 0 {
return XWVScriptObject(reference: num.intValue, origin: origin)
} else if let namespace = dict["$ns"] as? String {
return XWVScriptObject(namespace: namespace, origin: origin)
}
}
return object
}
}
extension XWVObject : CustomJSONStringable {
public var jsonString: String? {
return namespace
}
}
|
fa9ba622a8a9b13bf8b429355d45fe3d
| 33.925 | 92 | 0.635409 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Mac/Preferences/Accounts/AccountsFeedWranglerWindowController.swift
|
mit
|
1
|
//
// AccountsFeedWranglerWindowController.swift
// NetNewsWire
//
// Created by Jonathan Bennett on 2019-08-29.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import Account
import RSWeb
import Secrets
class AccountsFeedWranglerWindowController: NSWindowController {
@IBOutlet weak var signInTextField: NSTextField!
@IBOutlet weak var noAccountTextField: NSTextField!
@IBOutlet weak var createNewAccountButton: NSButton!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
@IBOutlet weak var usernameTextField: NSTextField!
@IBOutlet weak var passwordTextField: NSSecureTextField!
@IBOutlet weak var errorMessageLabel: NSTextField!
@IBOutlet weak var actionButton: NSButton!
var account: Account?
private weak var hostWindow: NSWindow?
convenience init() {
self.init(windowNibName: NSNib.Name("AccountsFeedWrangler"))
}
override func windowDidLoad() {
if let account = account, let credentials = try? account.retrieveCredentials(type: .basic) {
usernameTextField.stringValue = credentials.username
actionButton.title = NSLocalizedString("Update", comment: "Update")
signInTextField.stringValue = NSLocalizedString("Update your Feed Wrangler account credentials.", comment: "SignIn")
noAccountTextField.isHidden = true
createNewAccountButton.isHidden = true
} else {
actionButton.title = NSLocalizedString("Create", comment: "Create")
signInTextField.stringValue = NSLocalizedString("Sign in to your Feed Wrangler account.", comment: "SignIn")
}
enableAutofill()
usernameTextField.becomeFirstResponder()
}
// MARK: API
func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) {
self.hostWindow = hostWindow
hostWindow.beginSheet(window!, completionHandler: completion)
}
// MARK: Actions
@IBAction func cancel(_ sender: Any) {
hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel)
}
@IBAction func action(_ sender: Any) {
self.errorMessageLabel.stringValue = ""
guard !usernameTextField.stringValue.isEmpty && !passwordTextField.stringValue.isEmpty else {
self.errorMessageLabel.stringValue = NSLocalizedString("Username & password required.", comment: "Credentials Error")
return
}
guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .feedWrangler, username: usernameTextField.stringValue) else {
self.errorMessageLabel.stringValue = NSLocalizedString("There is already a FeedWrangler account with that username created.", comment: "Duplicate Error")
return
}
actionButton.isEnabled = false
progressIndicator.isHidden = false
progressIndicator.startAnimation(self)
let credentials = Credentials(type: .feedWranglerBasic, username: usernameTextField.stringValue, secret: passwordTextField.stringValue)
Account.validateCredentials(type: .feedWrangler, credentials: credentials) { [weak self] result in
guard let self = self else { return }
self.actionButton.isEnabled = true
self.progressIndicator.isHidden = true
self.progressIndicator.stopAnimation(self)
switch result {
case .success(let validatedCredentials):
guard let validatedCredentials = validatedCredentials else {
self.errorMessageLabel.stringValue = NSLocalizedString("Invalid email/password combination.", comment: "Credentials Error")
return
}
if self.account == nil {
self.account = AccountManager.shared.createAccount(type: .feedWrangler)
}
do {
try self.account?.removeCredentials(type: .feedWranglerBasic)
try self.account?.removeCredentials(type: .feedWranglerToken)
try self.account?.storeCredentials(credentials)
try self.account?.storeCredentials(validatedCredentials)
self.account?.refreshAll() { result in
switch result {
case .success:
break
case .failure(let error):
NSApplication.shared.presentError(error)
}
}
self.hostWindow?.endSheet(self.window!, returnCode: NSApplication.ModalResponse.OK)
} catch {
self.errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error")
}
case .failure:
self.errorMessageLabel.stringValue = NSLocalizedString("Network error. Try again later.", comment: "Credentials Error")
}
}
}
@IBAction func createAccountWithProvider(_ sender: Any) {
NSWorkspace.shared.open(URL(string: "https://feedwrangler.net/users/new")!)
}
// MARK: Autofill
func enableAutofill() {
if #available(macOS 11, *) {
usernameTextField.contentType = .username
passwordTextField.contentType = .password
}
}
}
|
478e38e9a9d25fc89b190ae74f10ad31
| 33.343066 | 156 | 0.750691 | false | false | false | false |
Binur/SubscriptionPrompt
|
refs/heads/master
|
SubscriptionPrompt/SlideCollectionViewCell.swift
|
mit
|
1
|
//
// SlideCollectionViewCell.swift
// SubscriptionPrompt
//
// Created by Binur Konarbayev on 4/29/16.
// Copyright © 2016 binchik. All rights reserved.
//
import UIKit
final class SlideCollectionViewCell: UICollectionViewCell {
lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
return imageView
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.setContentCompressionResistancePriority(1000, for: .vertical)
return label
}()
lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.setContentCompressionResistancePriority(1000, for: .vertical)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
private func setUp() {
setUpViews()
setUpConstraints()
}
private func setUpViews() {
let views: [UIView] = [imageView, titleLabel, subtitleLabel]
views.forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview($0)
}
}
private func setUpConstraints() {
[
NSLayoutConstraint(item: imageView, attribute: .top,
relatedBy: .equal, toItem: contentView,
attribute: .top, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: imageView, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: imageView, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: 0),
NSLayoutConstraint(item: titleLabel, attribute: .top,
relatedBy: .equal, toItem: imageView,
attribute: .bottom, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: titleLabel, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: titleLabel, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: -4),
NSLayoutConstraint(item: subtitleLabel, attribute: .top,
relatedBy: .equal, toItem: titleLabel,
attribute: .bottom, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: subtitleLabel, attribute: .leading,
relatedBy: .equal, toItem: contentView,
attribute: .leading, multiplier: 1,
constant: 4),
NSLayoutConstraint(item: subtitleLabel, attribute: .trailing,
relatedBy: .equal, toItem: contentView,
attribute: .trailing, multiplier: 1,
constant: -4),
NSLayoutConstraint(item: subtitleLabel, attribute: .bottom,
relatedBy: .equal, toItem: contentView,
attribute: .bottom, multiplier: 1,
constant: -4)
].forEach { $0.isActive = true }
}
}
extension SlideCollectionViewCell {
func setUp(withSlide slide: Slide) {
imageView.image = slide.image
titleLabel.text = slide.title
subtitleLabel.text = slide.subtitle
}
func setUp(withSlideStyle style: SlideStyle) {
backgroundColor = style.backgroundColor
titleLabel.font = style.titleFont
subtitleLabel.font = style.subtitleFont
titleLabel.textColor = style.titleColor
subtitleLabel.textColor = style.titleColor
}
}
|
b8388ecea3b44a5823b2852cfac2290c
| 34.10084 | 75 | 0.583912 | false | false | false | false |
jemartti/OnTheMap
|
refs/heads/master
|
OnTheMap/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// OnTheMap
//
// Created by Jacob Marttinen on 2/12/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
// MARK: - LoginViewController: UIViewController
class LoginViewController: UIViewController {
// MARK: Properties
var keyboardOnScreen = false
// MARK: Outlets
@IBOutlet weak var headerImageView: UIImageView!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: BorderedButton!
@IBOutlet weak var debugTextLabel: UILabel!
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
subscribeToNotification(.UIKeyboardWillShow, selector: #selector(keyboardWillShow))
subscribeToNotification(.UIKeyboardWillHide, selector: #selector(keyboardWillHide))
subscribeToNotification(.UIKeyboardDidShow, selector: #selector(keyboardDidShow))
subscribeToNotification(.UIKeyboardDidHide, selector: #selector(keyboardDidHide))
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.debugTextLabel.text = ""
unsubscribeFromAllNotifications()
}
// MARK: Login
@IBAction func loginPressed(_ sender: AnyObject) {
userTappedView(self)
if usernameTextField.text!.isEmpty || passwordTextField.text!.isEmpty {
alertUserOfFailure(message: "Both username and password are required.")
} else {
setUIEnabled(false)
createSession()
}
}
private func completeLogin() {
performUIUpdatesOnMain {
self.usernameTextField.text = ""
self.passwordTextField.text = ""
self.debugTextLabel.text = ""
self.setUIEnabled(true)
let controller = self.storyboard!.instantiateViewController(withIdentifier: "TabBarController") as! UITabBarController
self.present(controller, animated: true, completion: nil)
}
}
private func alertUserOfFailure( message: String) {
performUIUpdatesOnMain {
let alertController = UIAlertController(
title: "Login Failed",
message: message,
preferredStyle: UIAlertControllerStyle.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertActionStyle.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
self.setUIEnabled(true)
}
}
// MARK: Udacity
private func createSession() {
UdacityClient.sharedInstance().postSession(usernameTextField.text!, password: passwordTextField.text!) { (error) in
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
self.getUserData()
}
}
}
private func getUserData() {
UdacityClient.sharedInstance().getUserData() { (error) in
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
if let error = error {
self.alertUserOfFailure(message: error.localizedDescription)
} else {
self.completeLogin()
}
}
}
}
}
// MARK: - LoginViewController: UITextFieldDelegate
extension LoginViewController: UITextFieldDelegate {
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: Show/Hide Keyboard
func keyboardWillShow(_ notification: Notification) {
if !keyboardOnScreen {
view.frame.origin.y -= keyboardHeight(notification)
headerImageView.isHidden = true
}
}
func keyboardWillHide(_ notification: Notification) {
if keyboardOnScreen {
view.frame.origin.y += keyboardHeight(notification)
headerImageView.isHidden = false
}
}
func keyboardDidShow(_ notification: Notification) {
keyboardOnScreen = true
}
func keyboardDidHide(_ notification: Notification) {
keyboardOnScreen = false
}
private func keyboardHeight(_ notification: Notification) -> CGFloat {
let userInfo = (notification as NSNotification).userInfo
let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
return keyboardSize.cgRectValue.height
}
private func resignIfFirstResponder(_ textField: UITextField) {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
}
@IBAction func userTappedView(_ sender: AnyObject) {
resignIfFirstResponder(usernameTextField)
resignIfFirstResponder(passwordTextField)
}
}
// MARK: - LoginViewController (Configure UI)
private extension LoginViewController {
func setUIEnabled(_ enabled: Bool) {
usernameTextField.isEnabled = enabled
passwordTextField.isEnabled = enabled
loginButton.isEnabled = enabled
debugTextLabel.text = ""
debugTextLabel.isEnabled = enabled
// adjust login button alpha
if enabled {
loginButton.alpha = 1.0
} else {
loginButton.alpha = 0.5
}
}
func configureUI() {
// configure background gradient
let backgroundGradient = CAGradientLayer()
backgroundGradient.colors = [Constants.UI.LoginColorTop, Constants.UI.LoginColorBottom]
backgroundGradient.locations = [0.0, 1.0]
backgroundGradient.frame = view.frame
view.layer.insertSublayer(backgroundGradient, at: 0)
configureTextField(usernameTextField)
configureTextField(passwordTextField)
}
func configureTextField(_ textField: UITextField) {
let textFieldPaddingViewFrame = CGRect(x: 0.0, y: 0.0, width: 13.0, height: 0.0)
let textFieldPaddingView = UIView(frame: textFieldPaddingViewFrame)
textField.leftView = textFieldPaddingView
textField.leftViewMode = .always
textField.textColor = Constants.UI.OrangeColor
textField.attributedPlaceholder = NSAttributedString(string: textField.placeholder!, attributes: [NSForegroundColorAttributeName: Constants.UI.OrangeColor])
textField.delegate = self
}
}
// MARK: - LoginViewController (Notifications)
private extension LoginViewController {
func subscribeToNotification(_ notification: NSNotification.Name, selector: Selector) {
NotificationCenter.default.addObserver(self, selector: selector, name: notification, object: nil)
}
func unsubscribeFromAllNotifications() {
NotificationCenter.default.removeObserver(self)
}
}
|
5549ae758ab48bbf55f095cc2f96f58a
| 30.786026 | 164 | 0.631955 | false | false | false | false |
SwiftFMI/iOS_2017_2018
|
refs/heads/master
|
Upr/28.10.17/SecondTaskComplexSolution/SecondTaskComplexSolution/Model/Song.swift
|
apache-2.0
|
1
|
//
// Song.swift
// SecondTaskComplexSolution
//
// Created by Petko Haydushki on 31.10.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
class Song: NSObject {
var name = "";
var artistName = "";
var artworkImageName = "";
override init() {
super.init()
}
init(name : String,artist : String, artwork : String) {
self.name = name;
self.artistName = artist;
self.artworkImageName = artwork;
}
}
|
f048c76218c7dd972e115060e08e53f6
| 17.814815 | 59 | 0.580709 | false | false | false | false |
netguru/ResponseDetective
|
refs/heads/develop
|
ResponseDetective/Tests/Specs/RequestRepresentationSpec.swift
|
mit
|
1
|
//
// RequestRepresentationSpec.swift
//
// Copyright © 2016-2020 Netguru S.A. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
import Nimble
import ResponseDetective
import Quick
internal final class RequestRepresentationSpec: QuickSpec {
override func spec() {
describe("RequestRepresentation") {
context("after initializing with a request") {
let fixtureRequest = NSMutableURLRequest(
URL: URL(string: "https://httpbin.org/post")!,
HTTPMethod: "POST",
headerFields: [
"Content-Type": "application/json",
"X-Foo": "bar",
],
HTTPBody: try! JSONSerialization.data(withJSONObject: ["foo": "bar"], options: [])
)
let fixtureIdentifier = "1"
var sut: RequestRepresentation!
beforeEach {
sut = RequestRepresentation(identifier: fixtureIdentifier, request: fixtureRequest as URLRequest, deserializedBody: nil)
}
it("should have a correct identifier") {
expect(sut.identifier).to(equal(fixtureIdentifier))
}
it("should have a correct URLString") {
expect(sut.urlString).to(equal(fixtureRequest.url!.absoluteString))
}
it("should have a correct method") {
expect(sut.method).to(equal(fixtureRequest.httpMethod))
}
it("should have correct headers") {
expect(sut.headers).to(equal(fixtureRequest.allHTTPHeaderFields))
}
it("should have a correct body") {
expect(sut.body).to(equal(fixtureRequest.httpBody))
}
}
}
}
}
private extension NSMutableURLRequest {
convenience init(URL: Foundation.URL, HTTPMethod: String, headerFields: [String: String], HTTPBody: Data?) {
self.init(url: URL)
self.httpMethod = HTTPMethod
self.allHTTPHeaderFields = headerFields
self.httpBody = HTTPBody
}
}
|
14b771321330c8c0eadaea70dce52f18
| 22.381579 | 125 | 0.691615 | false | false | false | false |
PumpMagic/ostrich
|
refs/heads/master
|
gameboy/gameboy/Source/Memories/RAM.swift
|
mit
|
1
|
//
// RAM.swift
// ostrichframework
//
// Created by Ryan Conway on 4/4/16.
// Copyright © 2016 Ryan Conway. All rights reserved.
//
import Foundation
/// A random-access memory.
open class RAM: Memory, HandlesWrites {
var data: Array<UInt8>
/// An offset: specifies what memory location the first byte of the supplied data occupies
open let firstAddress: Address
open var lastAddress: Address {
return UInt16(UInt32(self.firstAddress) + UInt32(self.data.count) - 1)
}
open var addressRange: CountableClosedRange<Address> {
return self.firstAddress ... self.lastAddress
}
var addressRangeString: String {
return "[\(self.firstAddress.hexString), \(self.lastAddress.hexString)]"
}
public init(size: UInt16, fillByte: UInt8, firstAddress: Address) {
self.data = Array<UInt8>(repeating: fillByte, count: Int(size))
self.firstAddress = firstAddress
}
public convenience init(size: UInt16) {
self.init(size: size, fillByte: 0x00, firstAddress: 0x0000)
}
open func read(_ addr: Address) -> UInt8 {
if addr < self.firstAddress ||
Int(addr) > Int(self.firstAddress) + Int(self.data.count)
{
print("FATAL: attempt to access address \(addr.hexString) but our range is \(self.addressRangeString)")
exit(1)
}
return self.data[Int(addr - self.firstAddress)]
}
open func write(_ val: UInt8, to addr: Address) {
self.data[Int(addr - self.firstAddress)] = val
}
open func nonzeroes() -> String {
var nonzeroes: String = ""
for (index, datum) in self.data.enumerated() {
if datum != 0x00 {
nonzeroes += "\((firstAddress + UInt16(index)).hexString): \(datum.hexString) "
}
}
return nonzeroes
}
}
|
bec23d29301a060ef6241020ad954a13
| 28.984375 | 115 | 0.601876 | false | false | false | false |
wyzzarz/SwiftCollection
|
refs/heads/master
|
SwiftCollectionExample/SwiftCollectionExample/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// SwiftCollectionExample
//
// Copyright 2017 Warner Zee
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import SwiftCollection
/// `Document` sublcasses `SCDocument` and provides an additional field `name`.
///
/// Loading from persistent storage is updated for the `name` field.
class Document: SCDocument {
var name: String?
convenience init(id: SwiftCollection.Id, name: String) {
self.init(id: id)
self.name = name
}
override func load(propertyWithName name: String, currentValue: Any, potentialValue: Any, json: AnyObject) {
switch name {
case Keys.name: if let value = (json as? [String: Any])?[Keys.name] as? String { self.name = value }
default: super.load(propertyWithName: name, currentValue: currentValue, potentialValue: potentialValue, json: json)
}
}
}
extension Document.Keys {
static let name = "name"
}
/// `OrderedSet` provides a concrete implementation of `SCOrderedSet` for a collection of `Document`
/// objects.
///
/// A new persistent storage key is provided. And loading from persistent storage is performed
/// for documents in the collection.
class OrderedSet: SCOrderedSet<Document> {
override func storageKey() -> String {
return "OrderedSetExample"
}
override func load(jsonObject json: AnyObject) throws -> AnyObject? {
if let array = json as? [AnyObject] {
for item in array {
try? append(Document(json: item))
}
}
return json
}
}
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// create a new ordered set
let orderedSet = OrderedSet()
let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
// add documents to the collection
try? orderedSet.append(Document(id: 1, name: "First"))
try? orderedSet.append(Document(id: 2, name: "Second"))
try? orderedSet.append(Document(id: 3, name: "Third"))
tableView.dataSource = self
tableView.delegate = self
tableView.frame = UIEdgeInsetsInsetRect(self.view.frame, UIEdgeInsetsMake(20, 0, 0, 0))
self.view.addSubview(tableView)
DispatchQueue.main.async {
self.saveAndLoad()
}
}
/// An example to save the collection to persistent storage. And load saved data from persistent
/// storage.
func saveAndLoad() {
try? orderedSet.save(jsonStorage: .userDefaults) { (success) in
print("saved", success)
let anotherOrderedSet = OrderedSet()
try? anotherOrderedSet.load(jsonStorage: .userDefaults) { (success, json) in
print("loaded", success)
try? OrderedSet().remove(jsonStorage: .userDefaults, completion: nil)
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orderedSet.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "doc"
// get cell
var cell: UITableViewCell?
if let aCell = tableView.dequeueReusableCell(withIdentifier: cellId) { cell = aCell }
if cell == nil { cell = UITableViewCell(style: .value1, reuseIdentifier: cellId) }
// setup cell
let doc = orderedSet[orderedSet.index(orderedSet.startIndex, offsetBy: indexPath.row)]
cell?.textLabel?.text = doc.name
cell?.detailTextLabel?.text = String(doc.id)
return cell!
}
}
|
215d3eb60ab4bd094d3cf0fe382996f4
| 29.171642 | 119 | 0.690329 | false | false | false | false |
blokadaorg/blokada
|
refs/heads/main
|
ios/App/Model/StatsModel.swift
|
mpl-2.0
|
1
|
//
// This file is part of Blokada.
//
// 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 https://mozilla.org/MPL/2.0/.
//
// Copyright © 2020 Blocka AB. All rights reserved.
//
// @author Karol Gusak
//
import Foundation
struct Stats: Codable {
let allowed: UInt64
let denied: UInt64
let entries: [HistoryEntry]
}
struct HistoryEntry: Codable {
let name: String
let type: HistoryEntryType
let time: Date
let requests: UInt64
let device: String
let list: String?
}
enum HistoryEntryType: Int, Codable {
case whitelisted
case blocked
case passed
}
extension HistoryEntry: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(type)
hasher.combine(device)
}
}
extension HistoryEntry: Equatable {
static func == (lhs: HistoryEntry, rhs: HistoryEntry) -> Bool {
lhs.name == rhs.name && lhs.type == rhs.type && lhs.device == rhs.device
}
}
|
e946ec5152f6fad90b34ddddea206c61
| 21.854167 | 80 | 0.659982 | false | false | false | false |
ilyapuchka/SwiftNetworking
|
refs/heads/master
|
SwiftNetworking/Pagination.swift
|
mit
|
1
|
//
// Pagination.swift
// SwiftNetworking
//
// Created by Ilya Puchka on 11.09.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import Foundation
public protocol PaginationMetadata: JSONDecodable {
var page: Int {get}
var limit: Int {get}
var pages: Int {get}
init(page: Int, limit: Int, pages: Int)
}
extension PaginationMetadata {
func nextPage() -> Self? {
guard page < pages else { return nil }
return Self(page: page+1, limit: limit, pages: pages)
}
func prevPage() -> Self? {
guard page > 0 else { return nil }
return Self(page: page-1, limit: limit, pages: pages)
}
}
public protocol Pagination {
var metadata: PaginationMetadataType? {get}
typealias PaginationMetadataType: PaginationMetadata
init(metadata: PaginationMetadataType?)
}
extension Pagination {
public init(page: Int, limit: Int, pages: Int = 0) {
self.init(metadata: PaginationMetadataType(page: page, limit: limit, pages: pages))
}
public func nextPage() -> Self? {
guard let next = metadata?.nextPage() else { return nil }
return Self(metadata: next)
}
public func prevPage() -> Self? {
guard let prev = metadata?.prevPage() else { return nil }
return Self(metadata: prev)
}
}
public protocol AnyPagination: Pagination, JSONDecodable, APIResponseDecodable {
typealias Element: JSONDecodable
var items: [Element] {get}
init(items: [Element], metadata: PaginationMetadataType?)
static func paginationKey() -> String
static func itemsKey() -> String
}
extension AnyPagination {
public init?(jsonDictionary: JSONDictionary?) {
guard let
json = JSONObject(jsonDictionary),
items: [Element] = json.keyPath(Self.itemsKey()),
metadata: PaginationMetadataType = json.keyPath(Self.paginationKey())
else {
return nil
}
self.init(items: items, metadata: metadata)
}
}
extension AnyPagination {
public init?(apiResponseData: NSData) throws {
guard let jsonDictionary: JSONDictionary = try apiResponseData.decodeToJSON() else {
return nil
}
self.init(jsonDictionary: jsonDictionary)
}
}
public struct PaginationOf<T: JSONDecodable, M: PaginationMetadata>: AnyPagination {
public var items: [T]
public var metadata: M?
public init(items: [T] = [], metadata: M? = nil) {
self.items = items
self.metadata = metadata
}
public init(metadata: M?) {
self.init(items: [], metadata: metadata)
}
}
extension AnyPagination {
public static func paginationKey() -> String {
return "pagination"
}
public static func itemsKey() -> String {
return "items"
}
}
|
7461be6f4f17998a2dc672f3b1c2c23e
| 24.086957 | 92 | 0.623224 | false | false | false | false |
duycao2506/SASCoffeeIOS
|
refs/heads/master
|
SAS Coffee/Controller/KasperViewController.swift
|
gpl-3.0
|
1
|
//
// KasperViewController.swift
// SAS Coffee
//
// Created by Duy Cao on 8/30/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class KasperViewController: UIViewController, NVActivityIndicatorViewable, KasperObserverDelegate {
var activityData : ActivityData!
var backcomplete : (() -> Void)?
var continueCondition : ((Any, Any) -> Bool)?
@IBOutlet weak var notiViewHeightConstraint : NSLayoutConstraint?
@IBOutlet weak var notiTextview : UILabel?
var maxheightnoti = 36
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func actionBack (_sender: Any){
if let nav = self.navigationController {
if nav.viewControllers.first != self {
self.navigationController?.popViewController(animated: true)
}
}
dismiss(animated: true, completion: backcomplete)
}
func showNotification(){
if self.notiViewHeightConstraint != nil {
self.view.layoutIfNeeded()
self.notiViewHeightConstraint?.constant = CGFloat(maxheightnoti)
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
func hideNotfication(){
if self.notiViewHeightConstraint != nil {
self.view.layoutIfNeeded()
self.notiViewHeightConstraint?.constant = 0
UIView.animate(withDuration: 0.3, animations: {
self.view.layoutIfNeeded()
})
}
}
func callback(_ code: Int?, _ succ: Bool?, _ data: Any) {
}
}
|
ace8107c583bc61960570494b4f515f1
| 27.614458 | 106 | 0.625684 | false | false | false | false |
hsusmita/SHResponsiveLabel
|
refs/heads/master
|
SHResponsiveLabel/Source/Demo/ExpandableCell.swift
|
mit
|
1
|
//
// ExpandibleCell.swift
// SHResponsiveLabel
//
// Created by hsusmita on 11/08/15.
// Copyright (c) 2015 hsusmita.com. All rights reserved.
//
import UIKit
let kCollapseToken = "Read Less"
class ExpandableCell: UITableViewCell {
@IBOutlet weak var customLabel: SHResponsiveLabel!
var delegate : ExpandableCellDelegate?
override func awakeFromNib() {
let token = NSAttributedString(string: "...Read More",
attributes: [NSFontAttributeName:self.customLabel.font,
NSForegroundColorAttributeName:UIColor.brownColor(),
RLHighlightedBackgroundColorAttributeName:UIColor.blackColor(),
RLHighlightedForegroundColorAttributeName:UIColor.greenColor()])
let action = PatternTapResponder {(tappedString)-> (Void) in
self.delegate?.didTapOnMoreButton(self)
let messageString = "You have tapped token string"
}
customLabel.setAttributedTruncationToken(token, action: action)
}
func configureCell(text:String, shouldExpand:Bool) {
if shouldExpand {
//expand
let expandedString = text + kCollapseToken
let finalString = NSMutableAttributedString(string: expandedString)
let action = PatternTapResponder{(tappedString)-> (Void) in
self.delegate?.didTapOnMoreButton(self)
}
let range = NSMakeRange(count(text), count(kCollapseToken))
finalString.addAttributes([NSForegroundColorAttributeName:UIColor.redColor(),
RLTapResponderAttributeName:action], range: range)
finalString.addAttribute( NSFontAttributeName,value:customLabel.font, range: NSMakeRange(0,finalString.length))
// customLabel.numberOfLines = 0
// customLabel.attributedText = finalString
customLabel.customTruncationEnabled = false
customLabel.setAttributedTextWithTruncation(finalString, truncation: false)
}else {
// customLabel.numberOfLines = 4
// customLabel.text = text
customLabel.customTruncationEnabled = true
customLabel.setTextWithTruncation(text, truncation: true)
}
}
}
protocol ExpandableCellDelegate {
func didTapOnMoreButton(cell:ExpandableCell)
}
|
6ba859c652c17fbe153c0a7e9bdbf643
| 34.622951 | 118 | 0.720663 | false | false | false | false |
wscqs/QSWB
|
refs/heads/master
|
DSWeibo/DSWeibo/Classes/OAuth/OAuthViewController.swift
|
mit
|
1
|
//
// OAuthViewController.swift
// DSWeibo
//
// Created by xiaomage on 15/9/10.
// Copyright © 2015年 小码哥. All rights reserved.
//
import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController {
let WB_App_Key = "2058474898"
let WB_App_Secret = "a3ec3f8fa797fac21d702671a0cbfbf1"
let WB_redirect_uri = "https://wscqs.github.io/"
override func loadView() {
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 0.初始化导航条
navigationItem.title = "小码哥微博"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
// 1.获取未授权的RequestToken
// 要求SSL1.2
let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
let url = NSURL(string: urlStr)
let request = NSURLRequest(URL: url!)
webView.loadRequest(request)
}
func close()
{
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - 懒加载
private lazy var webView: UIWebView = {
let wv = UIWebView()
wv.delegate = self
return wv
}()
}
extension OAuthViewController: UIWebViewDelegate
{
// 返回ture正常加载 , 返回false不加载
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
{
// 1.判断是否是授权回调页面, 如果不是就继续加载
let urlStr = request.URL!.absoluteString
if !urlStr.hasPrefix(WB_redirect_uri)
{
// 继续加载
return true
}
// 2.判断是否授权成功
let codeStr = "code="
if request.URL!.query!.hasPrefix(codeStr)
{
// 授权成功
// 1.取出已经授权的RequestToken
let code = request.URL!.query?.substringFromIndex(codeStr.endIndex)
// 2.利用已经授权的RequestToken换取AccessToken
loadAccessToken(code!)
}else
{
// 取消授权
// 关闭界面
close()
}
return false
}
func webViewDidStartLoad(webView: UIWebView) {
// 提示用户正在加载
SVProgressHUD.showInfoWithStatus("正在加载...", maskType: SVProgressHUDMaskType.Black)
}
func webViewDidFinishLoad(webView: UIWebView) {
// 关闭提示
SVProgressHUD.dismiss()
}
/**
换取AccessToken
:param: code 已经授权的RequestToken
*/
private func loadAccessToken(code: String)
{
// 1.定义路径
let path = "oauth2/access_token"
// 2.封装参数
let params = ["client_id":WB_App_Key, "client_secret":WB_App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_redirect_uri]
// 3.发送POST请求
NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) -> Void in
// 1.字典转模型
let account = UserAccount(dict: JSON as! [String : AnyObject])
// 2.获取用户信息
account.loadUserInfo { (account, error) -> () in
if account != nil
{
account!.saveAccount()
// 去欢迎界面
NSNotificationCenter.defaultCenter().postNotificationName(XMGSwitchRootViewControllerKey, object: false)
return
}
SVProgressHUD.showInfoWithStatus("网络不给力", maskType: SVProgressHUDMaskType.Black)
}
}) { (_, error) -> Void in
print(error)
}
}
}
|
7de6012b01079247d0e24529b9743d82
| 27.700787 | 156 | 0.564883 | false | false | false | false |
Geor9eLau/WorkHelper
|
refs/heads/master
|
WorkoutHelper/HomePageViewController.swift
|
mit
|
1
|
//
// HomePageViewController.swift
// WorkoutHelper
//
// Created by George on 2016/12/26.
// Copyright © 2016年 George. All rights reserved.
//
import UIKit
class HomePageViewController: BaseViewController, iCarouselDataSource, iCarouselDelegate {
@IBOutlet weak var carousel: iCarousel!
// private lazy var colltectionView: UICollectionView = {
// let layout = UICollectionViewFlowLayout()
// layout.itemSize = CGSize(width: 70, height:90.0)
// layout.minimumLineSpacing = 5.0;
//
// layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20)
// let tmpCollectionView = UICollectionView(frame: CGRect(x: 0, y: 100, width: SCREEN_WIDTH , height: SCREEN_HEIGHT - 250), collectionViewLayout: layout)
// tmpCollectionView.delegate = self
// tmpCollectionView.dataSource = self
// tmpCollectionView.register(UINib.init(nibName: "ChooseCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
// tmpCollectionView.collectionViewLayout = layout
// tmpCollectionView.backgroundColor = UIColor.clear
// return tmpCollectionView
// }()
private var recordTf: UITextField = {
let tmp = UITextField(frame: CGRect(x: 20, y: SCREEN_HEIGHT - 200, width: SCREEN_WIDTH - 40, height: 150))
tmp.allowsEditingTextAttributes = false
tmp.isEnabled = false
return tmp
}()
private var dataSource: [BodyPart] = ALL_BODY_PART_CHOICES
override func viewDidLoad() {
super.viewDidLoad()
title = "Home Page"
carousel.type = .coverFlow
carousel.bounces = false
carousel.currentItemIndex = 1
// Do any additional setup after loading the view.
}
// MARK: - Private
private func setupUI() {
}
// MARK: - Event Handler
@IBAction func workoutBtnDidClicked(_ sender: UIButton) {
let motionVC = MotionViewController(part: dataSource[carousel.currentItemIndex])
motionVC.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(motionVC, animated: true)
}
// MARK: - iCarouselDataSource
func numberOfItems(in carousel: iCarousel) -> Int {
return dataSource.count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var itemView: CarouselItemView
let part = dataSource[index]
if (view as? CarouselItemView) != nil{
itemView = view as! CarouselItemView
} else {
//don't do anything specific to the index within
//this `if ... else` statement because the view will be
//recycled and used with other index values later
itemView = CarouselItemView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
}
itemView.imgView.image = UIImage(named: part.rawValue)
itemView.titleLbl.text = part.rawValue
return itemView
}
// MARK: - iCarouselDelegate
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
if (option == .spacing) {
return value * 1.1
}
return value
}
}
|
f698d587efeeda51cd660f774e0ea931
| 32.11 | 160 | 0.631833 | false | false | false | false |
ykay/twitter-with-menu
|
refs/heads/master
|
Twitter/TweetView.swift
|
mit
|
1
|
//
// TweetView.swift
// Twitter
//
// Created by Yuichi Kuroda on 10/10/15.
// Copyright © 2015 Yuichi Kuroda. All rights reserved.
//
import UIKit
class TweetView: UIView {
var nameLabel: UILabel!
var screennameLabel: UILabel!
var tweetTextLabel: UILabel!
var dateLabel: UILabel!
var favoriteLabel: UILabel!
var profileThumbImageView: UIImageView!
var favoriteImageView: UIImageView!
var retweetImageView: UIImageView!
var replyImageView: UIImageView!
var replyActionHandler: ((tweetId: String, tweetUserScreenname: String) -> ())?
var userProfileShowHandler: ((user: User) -> ())?
var tweet: Tweet! {
didSet {
nameLabel.text = tweet.user!.name
screennameLabel.text = "@\(tweet.user!.screenname)"
tweetTextLabel.text = tweet.text
dateLabel.text = tweet.createdAt?.description
profileThumbImageView.setImageWithURL(tweet.user!.profileImageUrl)
if tweet.favorited {
favoriteImageView.image = UIImage(named: "favorite_on.png")
favoriteLabel.textColor = UIColor(red:0.99, green:0.61, blue:0.16, alpha:1.0)
} else {
favoriteImageView.image = UIImage(named: "favorite_hover.png")
favoriteLabel.textColor = UIColor.lightGrayColor()
}
favoriteLabel.text = "\(tweet.favoriteCount)"
if tweet.user!.name == User.currentUser!.name {
retweetImageView.image = UIImage(named: "retweet.png")
} else {
if tweet.retweeted {
retweetImageView.image = UIImage(named: "retweet_on.png")
} else {
retweetImageView.image = UIImage(named: "retweet_hover.png")
}
}
/* Fade in code
profileThumbImageView.setImageWithURLRequest(NSURLRequest(URL: tweet.user!.profileImageUrl!), placeholderImage: nil,
success: { (request: NSURLRequest!, response: NSHTTPURLResponse!, image: UIImage!) -> Void in
let retrievedImage = image
UIView.transitionWithView(self.profileThumbImageView, duration: 2.0, options: UIViewAnimationOptions.TransitionCrossDissolve,
animations: { () -> Void in
self.profileThumbImageView.image = retrievedImage
},
completion: nil)
},
failure: { (request: NSURLRequest!, response: NSHTTPURLResponse!, error: NSError!) -> Void in
})*/
}
}
// Since super.init(coder) is failable, we must conform to that.
init?(_ coder: NSCoder?, frame: CGRect?) {
if let coder = coder {
super.init(coder: coder)
} else {
super.init(frame: frame ?? CGRectZero)
}
setupSubviews()
setupConstraints()
}
override convenience init(frame: CGRect) {
// Since we won't call the failable init(coder), we know this call will never fail, thus the '!' force unwrap is okay.
self.init(nil, frame: frame)!
}
required convenience init?(coder: NSCoder) {
self.init(coder, frame: nil)
}
func setupSubviews() {
nameLabel = UILabel()
nameLabel.font = UIFont.boldSystemFontOfSize(13.0)
nameLabel.textColor = Appearance.colorTwitterBlack
addSubview(nameLabel)
screennameLabel = UILabel()
screennameLabel.font = UIFont.systemFontOfSize(11.0)
screennameLabel.textColor = Appearance.colorTwitterDarkGray
addSubview(screennameLabel)
tweetTextLabel = UILabel()
tweetTextLabel.font = UIFont.systemFontOfSize(16)
tweetTextLabel.textColor = Appearance.colorTwitterBlack
tweetTextLabel.numberOfLines = 0
addSubview(tweetTextLabel)
dateLabel = UILabel()
dateLabel.font = screennameLabel.font
dateLabel.textColor = screennameLabel.textColor
addSubview(dateLabel)
favoriteLabel = UILabel()
favoriteLabel.font = UIFont.systemFontOfSize(10.0)
favoriteLabel.textColor = screennameLabel.textColor
addSubview(favoriteLabel)
profileThumbImageView = UIImageView()
addSubview(profileThumbImageView)
favoriteImageView = UIImageView()
addSubview(favoriteImageView)
retweetImageView = UIImageView()
addSubview(retweetImageView)
replyImageView = UIImageView()
replyImageView.image = UIImage(named: "reply_hover.png")
addSubview(replyImageView)
// Other initialization steps
profileThumbImageView.layer.cornerRadius = 10.0
profileThumbImageView.clipsToBounds = true
let userProfileTap = UITapGestureRecognizer(target: self, action: "onUserProfileTap")
userProfileTap.numberOfTapsRequired = 1
profileThumbImageView.userInteractionEnabled = true
profileThumbImageView.addGestureRecognizer(userProfileTap)
let retweetTap = UITapGestureRecognizer(target: self, action: "onRetweetTap")
retweetTap.numberOfTapsRequired = 1
retweetImageView.userInteractionEnabled = true
retweetImageView.addGestureRecognizer(retweetTap)
// Make favorite image tap-able.
let favoriteTap = UITapGestureRecognizer(target: self, action: "onFavoriteTap")
favoriteTap.numberOfTapsRequired = 1
favoriteImageView.userInteractionEnabled = true
favoriteImageView.addGestureRecognizer(favoriteTap)
let replyTap = UITapGestureRecognizer(target: self, action: "onReplyTap")
replyTap.numberOfTapsRequired = 1
replyImageView.userInteractionEnabled = true
replyImageView.addGestureRecognizer(replyTap)
}
func setupConstraints() {
nameLabel.translatesAutoresizingMaskIntoConstraints = false
screennameLabel.translatesAutoresizingMaskIntoConstraints = false
tweetTextLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.translatesAutoresizingMaskIntoConstraints = false
favoriteLabel.translatesAutoresizingMaskIntoConstraints = false
profileThumbImageView.translatesAutoresizingMaskIntoConstraints = false
favoriteImageView.translatesAutoresizingMaskIntoConstraints = false
retweetImageView.translatesAutoresizingMaskIntoConstraints = false
replyImageView.translatesAutoresizingMaskIntoConstraints = false
let views = [
"nameLabel":nameLabel,
"screennameLabel":screennameLabel,
"tweetTextLabel":tweetTextLabel,
"dateLabel":dateLabel,
"favoriteLabel":favoriteLabel,
"profileThumbImageView":profileThumbImageView,
"favoriteImageView":favoriteImageView,
"retweetImageView":retweetImageView,
"replyImageView":replyImageView,
]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(11)-[profileThumbImageView(65)]-(11)-[nameLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(8)-[profileThumbImageView(65)]-(8)-[tweetTextLabel]-(8)-[dateLabel]-(10)-[replyImageView(16)]-(>=8)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[tweetTextLabel]-(>=8)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: screennameLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: nameLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: tweetTextLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: profileThumbImageView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: dateLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: profileThumbImageView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(8)-[nameLabel]-(8)-[screennameLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(48)-[replyImageView(16)]-(48)-[retweetImageView(16)]-(48)-[favoriteImageView(16)]-(2)-[favoriteLabel]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[retweetImageView(16)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[favoriteImageView(16)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
addConstraint(NSLayoutConstraint(item: retweetImageView, attribute: .Top, relatedBy: .Equal, toItem: replyImageView, attribute: .Top, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: favoriteImageView, attribute: .Top, relatedBy: .Equal, toItem: replyImageView, attribute: .Top, multiplier: 1.0, constant: 0))
addConstraint(NSLayoutConstraint(item: favoriteLabel, attribute: .Top, relatedBy: .Equal, toItem: favoriteImageView, attribute: .Top, multiplier: 1.0, constant: 0))
}
func onRetweetTap() {
// Only retweet if not own tweet
if tweet.user!.name != User.currentUser!.name {
// Only allow retweeting if it hasn't been retweeted yet.
if !tweet.retweeted {
TwitterClient.sharedInstance.retweet(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
self.retweetImageView.image = UIImage(named: "retweet_on.png")
}
}
} else {
print("Can't retweet own tweet")
}
}
func onFavoriteTap() {
if tweet.favorited {
TwitterClient.sharedInstance.unfavorite(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
if let data = data {
self.tweet = Tweet(data)
}
}
} else {
TwitterClient.sharedInstance.favorite(tweet.id) { (data: [String:AnyObject]?, error: NSError?) -> Void in
if let data = data {
self.tweet = Tweet(data)
}
}
}
}
func onReplyTap() {
if let replyActionHandler = self.replyActionHandler {
replyActionHandler(tweetId: tweet.id, tweetUserScreenname: tweet.user!.screenname)
}
}
func onUserProfileTap() {
if let userProfileShowHandler = self.userProfileShowHandler {
userProfileShowHandler(user: tweet.user!)
}
}
}
|
07cce6ff7fe853eaaae5eb6e126c6534
| 40.429719 | 249 | 0.716654 | false | false | false | false |
RockyAo/RxSwift_learn
|
refs/heads/master
|
06-LoginDemo/06-LoginDemo/Service.swift
|
mit
|
1
|
//
// Service.swift
// 06-LoginDemo
//
// Created by Rocky on 2017/3/23.
// Copyright © 2017年 Rocky. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
let minCharacterCount = 6
let maxCharacterCount = 12
class ValidationService {
static let instance = ValidationService()
func validateUserName(_ userName:String) -> Observable<Result>{
if userName.characters.count == 0 {
return .just(.empty)
}
if userName.characters.count < minCharacterCount{
return .just(.faild(message:"账号至少\(minCharacterCount)个字符"))
}
if validateLocalUserName(userName) {
return .just(.faild(message:"用户名已存在"))
}
if userName.characters.count > maxCharacterCount {
return .just(.faild(message:"账号不能大于\(maxCharacterCount)个字符"))
}
return .just(.ok(message:"用户名可用"))
}
func validateLocalUserName(_ userName:String) -> Bool{
let filePath = NSHomeDirectory() + "/Documents/user.plist"
guard let userDictionary = NSDictionary(contentsOfFile: filePath) else {
return false
}
let usernameArray = userDictionary.allKeys as NSArray
if usernameArray.contains(userName) {
return true
} else {
return false
}
}
func validatePassword(_ password:String) -> Result {
if password.characters.count == 0 {
return .empty
}
if password.characters.count < minCharacterCount {
return .faild(message:"密码至少6位")
}
if password.characters.count > maxCharacterCount {
return .faild(message:"密码最多12位")
}
return .ok(message:"验证通过")
}
func validateRepeatPassword(_ password:String,_ repeatPassword:String) -> Result{
if repeatPassword.characters.count == 0 {
return .empty
}
if repeatPassword == password {
return .ok(message:"密码可用")
}
return .faild(message:"两次输入不一致")
}
func register(_ username:String,_ password:String) -> Observable<Result> {
let userdic = [username:password]
let filePath = NSHomeDirectory() + "/Documents/users.plist"
if (userdic as NSDictionary).write(toFile: filePath, atomically: true) {
return .just(.ok(message:"写入成功"))
}
return .just(.ok(message:"注册失败"))
}
}
|
f8397470c49e50b48bab40aa3e9f1edd
| 22.939655 | 85 | 0.529348 | false | false | false | false |
apple/swift-format
|
refs/heads/main
|
Sources/SwiftFormatRules/ValidateDocumentationComments.swift
|
apache-2.0
|
1
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import SwiftFormatCore
import SwiftSyntax
/// Documentation comments must be complete and valid.
///
/// "Command + Option + /" in Xcode produces a minimal valid documentation comment.
///
/// Lint: Documentation comments that are incomplete (e.g. missing parameter documentation) or
/// invalid (uses `Parameters` when there is only one parameter) will yield a lint error.
public final class ValidateDocumentationComments: SyntaxLintRule {
/// Identifies this rule as being opt-in. Accurate and complete documentation comments are
/// important, but this rule isn't able to handle situations where portions of documentation are
/// redundant. For example when the returns clause is redundant for a simple declaration.
public override class var isOptIn: Bool { return true }
public override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind {
return checkFunctionLikeDocumentation(
DeclSyntax(node), name: "init", signature: node.signature)
}
public override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind {
return checkFunctionLikeDocumentation(
DeclSyntax(node), name: node.identifier.text, signature: node.signature,
returnClause: node.signature.output)
}
private func checkFunctionLikeDocumentation(
_ node: DeclSyntax,
name: String,
signature: FunctionSignatureSyntax,
returnClause: ReturnClauseSyntax? = nil
) -> SyntaxVisitorContinueKind {
guard let declComment = node.docComment else { return .skipChildren }
guard let commentInfo = node.docCommentInfo else { return .skipChildren }
guard let params = commentInfo.parameters else { return .skipChildren }
// If a single sentence summary is the only documentation, parameter(s) and
// returns tags may be ommitted.
if commentInfo.oneSentenceSummary != nil && commentInfo.commentParagraphs!.isEmpty && params
.isEmpty && commentInfo.returnsDescription == nil
{
return .skipChildren
}
// Indicates if the documentation uses 'Parameters' as description of the
// documented parameters.
let hasPluralDesc = declComment.components(separatedBy: .newlines).contains {
$0.trimmingCharacters(in: .whitespaces).starts(with: "- Parameters")
}
validateThrows(
signature.throwsOrRethrowsKeyword, name: name, throwsDesc: commentInfo.throwsDescription, node: node)
validateReturn(
returnClause, name: name, returnDesc: commentInfo.returnsDescription, node: node)
let funcParameters = funcParametersIdentifiers(in: signature.input.parameterList)
// If the documentation of the parameters is wrong 'docCommentInfo' won't
// parse the parameters correctly. First the documentation has to be fix
// in order to validate the other conditions.
if hasPluralDesc && funcParameters.count == 1 {
diagnose(.useSingularParameter, on: node)
return .skipChildren
} else if !hasPluralDesc && funcParameters.count > 1 {
diagnose(.usePluralParameters, on: node)
return .skipChildren
}
// Ensures that the parameters of the documantation and the function signature
// are the same.
if (params.count != funcParameters.count) || !parametersAreEqual(
params: params, funcParam: funcParameters)
{
diagnose(.parametersDontMatch(funcName: name), on: node)
}
return .skipChildren
}
/// Ensures the function has a return documentation if it actually returns
/// a value.
private func validateReturn(
_ returnClause: ReturnClauseSyntax?,
name: String,
returnDesc: String?,
node: DeclSyntax
) {
if returnClause == nil && returnDesc != nil {
diagnose(.removeReturnComment(funcName: name), on: node)
} else if let returnClause = returnClause, returnDesc == nil {
if let returnTypeIdentifier = returnClause.returnType.as(SimpleTypeIdentifierSyntax.self),
returnTypeIdentifier.name.text == "Never"
{
return
}
diagnose(.documentReturnValue(funcName: name), on: returnClause)
}
}
/// Ensures the function has throws documentation if it may actually throw
/// an error.
private func validateThrows(
_ throwsOrRethrowsKeyword: TokenSyntax?,
name: String,
throwsDesc: String?,
node: DeclSyntax
) {
// If a function is marked as `rethrows`, it doesn't have any errors of its
// own that should be documented. So only require documentation for
// functions marked `throws`.
let needsThrowsDesc = throwsOrRethrowsKeyword?.tokenKind == .throwsKeyword
if !needsThrowsDesc && throwsDesc != nil {
diagnose(.removeThrowsComment(funcName: name), on: throwsOrRethrowsKeyword ?? node.firstToken)
} else if needsThrowsDesc && throwsDesc == nil {
diagnose(.documentErrorsThrown(funcName: name), on: throwsOrRethrowsKeyword)
}
}
}
/// Iterates through every parameter of paramList and returns a list of the
/// paramters identifiers.
fileprivate func funcParametersIdentifiers(in paramList: FunctionParameterListSyntax) -> [String] {
var funcParameters = [String]()
for parameter in paramList {
// If there is a label and an identifier, then the identifier (`secondName`) is the name that
// should be documented. Otherwise, the label and identifier are the same, occupying
// `firstName`.
guard let parameterIdentifier = parameter.secondName ?? parameter.firstName else {
continue
}
funcParameters.append(parameterIdentifier.text)
}
return funcParameters
}
/// Indicates if the parameters name from the documentation and the parameters
/// from the declaration are the same.
fileprivate func parametersAreEqual(params: [ParseComment.Parameter], funcParam: [String]) -> Bool {
for index in 0..<params.count {
if params[index].name != funcParam[index] {
return false
}
}
return true
}
extension Finding.Message {
public static func documentReturnValue(funcName: String) -> Finding.Message {
"document the return value of \(funcName)"
}
public static func removeReturnComment(funcName: String) -> Finding.Message {
"remove the return comment of \(funcName), it doesn't return a value"
}
public static func parametersDontMatch(funcName: String) -> Finding.Message {
"change the parameters of \(funcName)'s documentation to match its parameters"
}
public static let useSingularParameter: Finding.Message =
"replace the plural form of 'Parameters' with a singular inline form of the 'Parameter' tag"
public static let usePluralParameters: Finding.Message =
"""
replace the singular inline form of 'Parameter' tag with a plural 'Parameters' tag \
and group each parameter as a nested list
"""
public static func removeThrowsComment(funcName: String) -> Finding.Message {
"remove the 'Throws' tag for non-throwing function \(funcName)"
}
public static func documentErrorsThrown(funcName: String) -> Finding.Message {
"add a 'Throws' tag describing the errors thrown by \(funcName)"
}
}
|
92dec11315fb59f93d3c61d4ba3dd68a
| 38.947368 | 107 | 0.709618 | false | false | false | false |
designatednerd/GoCubs
|
refs/heads/master
|
GoCubs/Views/CubsGameCell.swift
|
mit
|
1
|
//
// CubsGameCell.swift
// GoCubs
//
// Created by Ellen Shapiro on 10/11/15.
// Copyright © 2015 Designated Nerd Software. All rights reserved.
//
import UIKit
class CubsGameCell: UITableViewCell {
static let identifier = "CubsGameCell"
// Use a static let so this only gets instantiated once across all cells.
private static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d"
return formatter
}()
@IBOutlet var dateLabel: UILabel!
@IBOutlet var vsLabel: UILabel!
@IBOutlet var primaryColorView: UIView!
@IBOutlet var secondaryColorView: UIView!
func configure(forGame game: CubsGame) {
self.dateLabel.text = CubsGameCell.dateFormatter.string(from: game.date as Date)
if game.opponent.isHomeTeam {
self.vsLabel.text = LocalizedString.versus(Team.Cubs.rawValue, homeTeam: game.opponent.name)
} else {
self.vsLabel.text = LocalizedString.versus(game.opponent.name, homeTeam: Team.Cubs.rawValue)
}
if game.result.type == .postponed {
self.vsLabel.alpha = 0.5
} else {
self.vsLabel.alpha = 1
}
self.primaryColorView.backgroundColor = game.opponent.team.primaryColor
self.secondaryColorView.backgroundColor = game.opponent.team.secondaryColor
}
//MARK: - Cell silliness
// Override these methods to prevent cell selection from futzing with
// the background color of the cell's color views.
override func setSelected(_ selected: Bool, animated: Bool) {
let primary = self.primaryColorView.backgroundColor
let secondary = self.secondaryColorView.backgroundColor
super.setSelected(selected, animated: animated)
self.primaryColorView.backgroundColor = primary
self.secondaryColorView.backgroundColor = secondary
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
let primary = self.primaryColorView.backgroundColor
let secondary = self.secondaryColorView.backgroundColor
super.setHighlighted(highlighted, animated: animated)
self.primaryColorView.backgroundColor = primary
self.secondaryColorView.backgroundColor = secondary
}
}
|
4bd53551697d2c9331e98f87d29c9be0
| 33.478261 | 104 | 0.670029 | false | false | false | false |
trujillo138/MyExpenses
|
refs/heads/master
|
MyExpenses/MyExpenses/Services/ModelController.swift
|
apache-2.0
|
1
|
//
// ModelController.swift
// MyExpenses
//
// Created by Tomas Trujillo on 5/22/17.
// Copyright © 2017 TOMApps. All rights reserved.
//
import Foundation
class ModelController {
//MARK: Properties
var user: User
private let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private var expensesURL: URL {
return documentsDirectoryURL.appendingPathComponent("Expenses").appendingPathExtension("plist")
}
//MARK: Model methods
func save(_ user: User) {
self.user = user
saveData()
}
//MARK: Loading and Saving
required init() {
user = User()
loadData()
}
private func loadData() {
guard let expenseModelPlist = NSDictionary.init(contentsOf: expensesURL) as? [String: AnyObject] else {
return
}
user = User(plist: expenseModelPlist)
}
private func saveData() {
let expenseDictionary = user.plistRepresentation as NSDictionary
expenseDictionary.write(to: expensesURL, atomically: true)
}
}
|
3ee24d2ab044c093f8a00543e44f924c
| 22.34 | 117 | 0.61868 | false | false | false | false |
Erickson0806/TableSearchwithUISearchController
|
refs/heads/master
|
Swift/TableSearch/Product.swift
|
apache-2.0
|
1
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The data model object describing the product displayed in both main and results tables.
*/
import Foundation
class Product: NSObject, NSCoding {
// MARK: Types
enum CoderKeys: String {
case nameKey
case typeKey
case yearKey
case priceKey
}
enum Hardware: String {
case iPhone = "iPhone"
case iPod = "iPod"
case iPodTouch = "iPod touch"
case iPad = "iPad"
case iPadMini = "iPad Mini"
case iMac = "iMac"
case MacPro = "Mac Pro"
case MacBookAir = "Mac Book Air"
case MacBookPro = "Mac Book Pro"
}
// MARK: Properties
let title: String
let hardwareType: String
let yearIntroduced: Int
let introPrice: Double
// MARK: Initializers
init(hardwareType: String, title: String, yearIntroduced: Int, introPrice: Double) {
self.hardwareType = hardwareType
self.title = title
self.yearIntroduced = yearIntroduced
self.introPrice = introPrice
}
// MARK: NSCoding
required init?(coder aDecoder: NSCoder) {
title = aDecoder.decodeObjectForKey(CoderKeys.nameKey.rawValue) as! String
hardwareType = aDecoder.decodeObjectForKey(CoderKeys.typeKey.rawValue) as! String
yearIntroduced = aDecoder.decodeIntegerForKey(CoderKeys.yearKey.rawValue)
introPrice = aDecoder.decodeDoubleForKey(CoderKeys.priceKey.rawValue)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(title, forKey: CoderKeys.nameKey.rawValue)
aCoder.encodeObject(hardwareType, forKey: CoderKeys.typeKey.rawValue)
aCoder.encodeInteger(yearIntroduced, forKey: CoderKeys.yearKey.rawValue)
aCoder.encodeDouble(introPrice, forKey: CoderKeys.priceKey.rawValue)
}
// MARK: Device Type Info
class var deviceTypeNames: [String] {
return [
Product.deviceTypeTitle,
Product.desktopTypeTitle,
Product.portableTypeTitle
]
}
class var deviceTypeTitle: String {
return NSLocalizedString("Device", comment:"Device type title")
}
class var desktopTypeTitle: String {
return NSLocalizedString("Desktop", comment:"Desktop type title")
}
class var portableTypeTitle: String {
return NSLocalizedString("Portable", comment:"Portable type title")
}
}
|
7657297762e39fd900fee24548e3a7c3
| 28.616279 | 89 | 0.655281 | false | false | false | false |
Bygo/BGChatBotMessaging-iOS
|
refs/heads/master
|
BGChatBotMessaging/Classes/BGMessagingOutgoingOptionsContainer.swift
|
mit
|
1
|
//
// BGMessagingOutgoingOptionsContainer.swift
// Pods
//
// Created by Nicholas Garfield on 17/6/16.
//
//
import UIKit
class BGMessagingOutgoingOptionsContainer: UIView {
var delegate: BGMessagingOutgoingOptionsContainerDelegate?
@IBOutlet var optionA: BGMessagingOutgoingOptionButton!
@IBOutlet var optionB: BGMessagingOutgoingOptionButton!
@IBOutlet var optionsHorizontalSpacingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionABottomLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBBottomLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionALeadingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBTrailingLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionACenterXLayoutConstraint: NSLayoutConstraint!
@IBOutlet var optionBCenterXLayoutConstraint: NSLayoutConstraint!
var layoutConfiguration: BGMessagingOutgoingOptionsLayoutConfiguration = .Horizontal {
didSet {
switch layoutConfiguration {
case .Vertical:
optionALeadingLayoutConstraint.active = false
optionBTrailingLayoutConstraint.active = false
optionsHorizontalSpacingLayoutConstraint.active = false
optionACenterXLayoutConstraint.active = true
optionBCenterXLayoutConstraint.active = true
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
optionBBottomLayoutConstraint.constant = 8.0 + optionA.bounds.height + 4.0 + optionB.bounds.height
case .Horizontal:
optionACenterXLayoutConstraint.active = false
optionBCenterXLayoutConstraint.active = false
optionsHorizontalSpacingLayoutConstraint.active = true
optionALeadingLayoutConstraint.active = true
optionBTrailingLayoutConstraint.active = true
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
optionBBottomLayoutConstraint.constant = 8.0 + optionB.bounds.height
}
layoutIfNeeded()
}
}
init() {
super.init(frame: CGRectZero)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configure() {
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = .clearColor()
userInteractionEnabled = true
configureOptions()
}
private func configureOptions() {
if optionA == nil {
optionA = BGMessagingOutgoingOptionButton()
addSubview(optionA)
optionALeadingLayoutConstraint = optionA.leadingAnchor.constraintEqualToAnchor(leadingAnchor)
optionALeadingLayoutConstraint.active = true
optionABottomLayoutConstraint = optionA.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: 8.0 + optionA.bounds.height)
optionABottomLayoutConstraint.active = true
optionA.topAnchor.constraintGreaterThanOrEqualToAnchor(topAnchor, constant: 8.0).active = true
optionACenterXLayoutConstraint = optionA.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
optionACenterXLayoutConstraint.active = false
optionA.addTarget(self, action: #selector(BGMessagingOutgoingOptionsContainer.optionAButtonTapped(_:)), forControlEvents: .TouchUpInside)
}
if optionB == nil {
optionB = BGMessagingOutgoingOptionButton()
addSubview(optionB)
optionBTrailingLayoutConstraint = optionB.trailingAnchor.constraintEqualToAnchor(trailingAnchor)
optionBTrailingLayoutConstraint.active = true
optionBBottomLayoutConstraint = optionB.bottomAnchor.constraintEqualToAnchor(bottomAnchor, constant: 8.0 + optionB.bounds.height)
optionBBottomLayoutConstraint.active = true
optionB.topAnchor.constraintGreaterThanOrEqualToAnchor(topAnchor, constant: 8.0).active = true
optionBCenterXLayoutConstraint = optionB.centerXAnchor.constraintEqualToAnchor(centerXAnchor)
optionBCenterXLayoutConstraint.active = false
optionB.addTarget(self, action: #selector(BGMessagingOutgoingOptionsContainer.optionBButtonTapped(_:)), forControlEvents: .TouchUpInside)
}
optionsHorizontalSpacingLayoutConstraint = optionB.leadingAnchor.constraintEqualToAnchor(optionA.trailingAnchor, constant: 4.0)
optionsHorizontalSpacingLayoutConstraint.active = true
layoutIfNeeded()
}
func showOptions() {
switch layoutConfiguration {
case .Horizontal:
if optionA.enabled {
optionABottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
if optionA.enabled && optionB.enabled {
optionBBottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
case .Vertical:
if optionA.enabled {
optionABottomLayoutConstraint.constant = -8.0 - optionB.bounds.height - 4.0
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
if optionA.enabled && optionB.enabled {
optionBBottomLayoutConstraint.constant = -8.0
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
}
}
func hideOptions() {
switch layoutConfiguration {
case .Horizontal:
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
optionBBottomLayoutConstraint.constant = 8.0 + optionB.bounds.height
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
case .Vertical:
optionBBottomLayoutConstraint.constant = 8.0 + optionA.bounds.height + 4.0 + optionB.bounds.height
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
optionABottomLayoutConstraint.constant = 8.0 + optionA.bounds.height
UIView.animateWithDuration(0.5, delay: 0.15, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: .CurveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
}
// MARK: - UI Actions
@IBAction func optionAButtonTapped(sender: BGMessagingOutgoingOptionButton) {
sender.selected = true
delegate?.didSelectOptionA(sender)
}
@IBAction func optionBButtonTapped(sender: BGMessagingOutgoingOptionButton) {
sender.selected = true
delegate?.didSelectOptionB(sender)
}
}
enum BGMessagingOutgoingOptionsLayoutConfiguration {
case Vertical
case Horizontal
}
protocol BGMessagingOutgoingOptionsContainerDelegate {
func didSelectOptionA(optionA: UIButton)
func didSelectOptionB(optionB: UIButton)
}
|
19307a5584cd7702b2a607b5889bb430
| 44.178378 | 156 | 0.662199 | false | true | false | false |
edwinbosire/YAWA
|
refs/heads/master
|
YAWA-Weather/Model/Forecast.swift
|
gpl-2.0
|
1
|
//
// Forecast.swift
// YAWA-Weather
//
// Created by edwin bosire on 15/06/2015.
// Copyright (c) 2015 Edwin Bosire. All rights reserved.
//
import Foundation
import CoreData
import UIKit
@objc(Forecast)
class Forecast: NSManagedObject {
@NSManaged var time: String
@NSManaged var temperature: NSNumber
@NSManaged var humidity: NSNumber
@NSManaged var precipitationProbability: NSNumber
@NSManaged var windSpeed: NSNumber
@NSManaged var windDirection: String
@NSManaged var summary: String
@NSManaged var icon: String
@NSManaged var weeklyForecast: NSSet
@NSManaged var city: City
class func createNewForecast() -> Forecast {
let forecast = NSEntityDescription.insertNewObjectForEntityForName("Forecast", inManagedObjectContext: StoreManager.sharedInstance.managedObjectContext!) as! Forecast
return forecast
}
class func forecastWithDictionary(weatherDictionary: NSDictionary) -> Forecast {
let forecast = Forecast.createNewForecast()
let currentWeather = weatherDictionary["currently"] as! NSDictionary
forecast.temperature = currentWeather["temperature"] as! Int
forecast.humidity = currentWeather["humidity"] as! Double
forecast.precipitationProbability = currentWeather["precipProbability"] as! Double
forecast.windSpeed = currentWeather["windSpeed"] as! Int
forecast.summary = currentWeather["summary"] as! String
forecast.icon = currentWeather["icon"] as! String
let myWeeklyForecast = Forecast.weeklyForecastFromDictionary(weatherDictionary)
let set = NSSet(array: myWeeklyForecast)
forecast.weeklyForecast = set
let windDirectionDegrees = currentWeather["windBearing"] as! Int
forecast.windDirection = forecast.windDirectionFromDegress(windDirectionDegrees)
let currentTimeIntVale = currentWeather["time"] as! Int
forecast.time = forecast.dateStringFromUnixTime(currentTimeIntVale)
return forecast
}
func image() -> UIImage {
return weatherIconFromString(icon)
}
class func weeklyForecastFromDictionary(weatherDictionary: NSDictionary) ->[Daily]{
var weeklyForcasts = [Daily]()
let weeklyWeather = weatherDictionary["daily"] as! NSDictionary
let weeklyForcast = weeklyWeather["data"] as! NSArray
for dailyDict in weeklyForcast {
let dailyForecast = Daily.dailyWithDictionary(dailyDict as! NSDictionary)
weeklyForcasts.append(dailyForecast)
}
return weeklyForcasts
}
func windDirectionFromDegress(degrees: Int) -> String {
switch degrees {
case (0...45):
return "North"
case (315...360):
return "North"
case (45...135):
return "East"
case (135...225):
return "South"
case (225...315):
return "West"
default:
return "Unknown"
}
}
func dateStringFromUnixTime(unixTime: Int) -> String {
let timeInSeconds = NSTimeInterval(unixTime)
let weatherDate = NSDate(timeIntervalSince1970: timeInSeconds)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d"
return dateFormatter.stringFromDate(weatherDate)
}
func dayOne() -> Daily {
return weeklyForecast.allObjects[0] as! Daily
}
func dayTwo() -> Daily {
return weeklyForecast.allObjects[1] as! Daily
}
func dayThree() -> Daily {
return weeklyForecast.allObjects[2] as! Daily
}
func dayFour() -> Daily {
return weeklyForecast.allObjects[3] as! Daily
}
func dayFive() -> Daily {
return weeklyForecast.allObjects[4] as! Daily
}
}
|
32d6114d9c0f5d87c451f4bc5ad49946
| 26.333333 | 168 | 0.738966 | false | false | false | false |
ustwo/mockingbird
|
refs/heads/master
|
Sources/SwaggerKit/Model/Endpoint+Kitura.swift
|
mit
|
1
|
//
// Endpoint.swift
// Mockingbird
//
// Created by Aaron McTavish on 20/12/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
import Kitura
extension Endpoint {
// MARK: - Properties
var handler: RouterHandler {
let summary = self.summary
return { request, response, next in
var responseText = summary
if !request.parameters.isEmpty {
var parametersList: [String] = []
for (key, value) in request.parameters {
parametersList.append("- " + key + ": " + value)
}
responseText += "\n\nParameters:\n" +
parametersList.joined(separator: "\n")
}
response.send(responseText)
next()
}
}
static private let kituraPathRegexString = "\\{([^\\{\\}\\s]+)\\}"
var kituraPath: String {
#if os(Linux)
let regexObj = try? NSRegularExpression(pattern: Endpoint.kituraPathRegexString,
options: [])
#else
let regexObj = try? NSRegularExpression(pattern: Endpoint.kituraPathRegexString)
#endif
guard let regex = regexObj else {
return ""
}
let pathString = NSMutableString(string: path)
let range = NSRange(location: 0, length:pathString.length)
// swiftlint:disable:next redundant_discardable_let
let _ = regex.replaceMatches(in: pathString,
options: [],
range: range,
withTemplate: ":$1")
#if os(Linux)
return pathString._bridgeToSwift()
#else
return pathString as String
#endif
}
// MARK: - Routing
func add(to router: Router) {
let path = kituraPath
switch method {
case .connect:
router.connect(path, handler: handler)
case .delete:
router.delete(path, handler: handler)
case .get:
router.get(path, handler: handler)
case .head:
router.head(path, handler: handler)
case .options:
router.options(path, handler: handler)
case .patch:
router.patch(path, handler: handler)
case .post:
router.post(path, handler: handler)
case .put:
router.put(path, handler: handler)
case .trace:
router.trace(path, handler: handler)
}
}
}
|
a3406556694f42f8d10a0691bd4949c4
| 28.083333 | 92 | 0.486032 | false | false | false | false |
gongmingqm10/DriftBook
|
refs/heads/master
|
DriftReading/DriftReading/CreateBookViewController.swift
|
mit
|
1
|
//
// CreateBookViewController.swift
// DriftReading
//
// Created by Ming Gong on 7/27/15.
// Copyright © 2015 gongmingqm10. All rights reserved.
//
import UIKit
class CreateBookViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
@IBOutlet weak var bookSearchBar: UISearchBar!
@IBOutlet weak var bookTableView: UITableView!
let doubanAPI = DoubanAPI()
let driftAPI = DriftAPI()
var books: [DoubanBook] = []
override func viewDidLoad() {
bookTableView.delegate = self
bookTableView.dataSource = self
bookSearchBar.delegate = self
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
doubanAPI.searchBooks(searchText, success: { (books) -> Void in
self.books = books
self.bookTableView.reloadData()
}) { (error) -> Void in
print(error.description)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return books.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 120
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = bookTableView.dequeueReusableCellWithIdentifier("DoubanTableCell", forIndexPath: indexPath) as! DoubanTableCell
let book = books[indexPath.row]
cell.populate(book)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let book = books[indexPath.row]
let alertController = UIAlertController(title: "提示", message: "确定将《\(book.name)》放漂吗?", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in
let user = DataUtils.sharedInstance.currentUser()
self.driftAPI.createDoubanBook(user.userId, book: book, success: { () -> Void in
self.navigationController?.popViewControllerAnimated(true)
}, failure: { (error) -> Void in
self.showErrorAlert()
})
}))
alertController.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
private func showErrorAlert() {
let alertController = UIAlertController(title: "提示", message: "图书添加失败,请稍后重试", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
|
8326f5a5ae89825f09afab4e2f98e4af
| 39.24 | 140 | 0.675613 | false | false | false | false |
AndreaMiotto/NASApp
|
refs/heads/master
|
NASApp/CollisionEventsTableViewController.swift
|
apache-2.0
|
1
|
//
// CollisionEventsTableViewController.swift
// NASApp
//
// Created by Andrea Miotto on 23/03/17.
// Copyright © 2017 Andrea Miotto. All rights reserved.
//
import UIKit
class CollisionEventsTableViewController: UITableViewController {
//----------------------
// MARK: - Variables
//----------------------
///It keeps track of the asteroids
var asteroids : [Asteroid] = []
//----------------------
// MARK: - View Fuctions
//----------------------
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Back", style: .done, target: nil, action: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//----------------------
// MARK: - Methods
//----------------------
/**This func will style the cell prperly */
func configureCell(cell: CollisionTableViewCell, withEntry entry: Asteroid) {
//setting the easy stuff
cell.nameLabel.text = entry.name
cell.dateLabel.text = entry.approachDate
if !entry.hazardous {
cell.hazardousLabel.isHidden = true
} else {
cell.hazardousLabel.isHidden = false
}
}
//----------------------
// MARK: - Table view data source
//----------------------
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return asteroids.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CollisionTableViewCell
let asteroid = self.asteroids[indexPath.row]
configureCell(cell: cell, withEntry: asteroid)
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "APPROACHING ASTEROIDS"
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
(view as! UITableViewHeaderFooterView).backgroundView?.backgroundColor = UIColor.black.withAlphaComponent(1)
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.white.withAlphaComponent(0.4)
(view as! UITableViewHeaderFooterView).textLabel?.font = UIFont(name: "Helvetica", size: 15)
}
//----------------------
// MARK: - Navigation
//----------------------
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showAsteroid" {
if let indexPath = self.tableView.indexPathForSelectedRow {
if let nextVC = segue.destination as? AsteroidDetailsTableViewController {
nextVC.asteroid = asteroids[indexPath.row]
}
}
}
}
}
|
4b724bd38ae633db314af09103fe086d
| 31.27551 | 116 | 0.59374 | false | false | false | false |
leschlogl/Programming-Contests
|
refs/heads/master
|
Hackerrank/30 Days of Code/day15.swift
|
mit
|
1
|
func insert(head: Node?, data: Int!) -> Node? {
if head == nil {
return Node(data: data)
} else if head!.next == nil {
head!.next = Node(data: data)
} else {
insert(head: head!.next, data: data)
}
return head
}
|
23c7eb608c95f4ee023930bdf03deaf4
| 16.6 | 47 | 0.503788 | false | false | false | false |
google/JacquardSDKiOS
|
refs/heads/main
|
JacquardSDK/Classes/Internal/IMUDataCollectionAPI/IMUModuleComands.swift
|
apache-2.0
|
1
|
// Copyright 2021 Google LLC
//
// 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
/// Command request to retrieve all the modules available in the device.
struct ListIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialList
let sessionListRequest = Google_Jacquard_Protocol_DataCollectionTrialListRequest()
request.Google_Jacquard_Protocol_DataCollectionTrialListRequest_trialList = sessionListRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialListResponse_trialList {
return .success(())
}
return .failure(CommandResponseStatus.errorAppUnknown)
}
}
struct IMUSessionNotificationSubscription: NotificationSubscription {
func extract(from outerProto: Any) -> IMUSessionInfo? {
guard let notification = outerProto as? Google_Jacquard_Protocol_Notification else {
jqLogger.assert(
"calling extract() with anything other than Google_Jacquard_Protocol_Notification is an error"
)
return nil
}
// Silently ignore other notifications.
guard notification.hasGoogle_Jacquard_Protocol_DataCollectionTrialListNotification_trialList
else {
return nil
}
let trial =
notification.Google_Jacquard_Protocol_DataCollectionTrialListNotification_trialList.trial
// If no trials are available, An empty session notification is sent by the tag.
if trial.hasTrialID {
let session = IMUSessionInfo(trial: trial)
return session
} else {
return nil
}
}
}
/// Command request to start IMU recording.
struct StartIMUSessionCommand: CommandRequest {
let sessionID: String
let campaignID: String
let groupID: String
let productID: String
let subjectID: String
init(
sessionID: String,
campaignID: String,
groupID: String,
productID: String,
subjectID: String
) {
self.sessionID = sessionID
self.campaignID = campaignID
self.groupID = groupID
self.productID = productID
self.subjectID = subjectID
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStart
var metaData = Google_Jacquard_Protocol_DataCollectionMetadata()
metaData.mode = .store
metaData.campaignID = campaignID
// The `trialID` is named as `sessionID` for the client app.
// `groupID` is introduced to replace `sessionID` for any public api's
metaData.sessionID = groupID
metaData.trialID = sessionID
metaData.subjectID = subjectID
metaData.productID = productID
var sessionStartRequest = Google_Jacquard_Protocol_DataCollectionStartRequest()
sessionStartRequest.metadata = metaData
request.Google_Jacquard_Protocol_DataCollectionStartRequest_start = sessionStartRequest
return request
}
func parseResponse(outerProto: Any)
-> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error>
{
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStartResponse_start {
return .success(
outerProto.Google_Jacquard_Protocol_DataCollectionStartResponse_start.dcStatus)
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to stop IMU recording.
struct StopIMUSessionCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStop
var sessionStopRequest = Google_Jacquard_Protocol_DataCollectionStopRequest()
sessionStopRequest.isError = true
request.Google_Jacquard_Protocol_DataCollectionStopRequest_stop = sessionStopRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionStopResponse_stop {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to get the current status of datacollection.
struct IMUDataCollectionStatusCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionStatus
let dcStatusRequest = Google_Jacquard_Protocol_DataCollectionStatusRequest()
request.Google_Jacquard_Protocol_DataCollectionStatusRequest_status = dcStatusRequest
return request
}
func parseResponse(
outerProto: Any
) -> Result<Google_Jacquard_Protocol_DataCollectionStatus, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
let dcStatus = outerProto.Google_Jacquard_Protocol_DataCollectionStatusResponse_status.dcStatus
return .success(dcStatus)
}
}
/// Command request to delete a session on the tag.
struct DeleteIMUSessionCommand: CommandRequest {
let session: IMUSessionInfo
init(session: IMUSessionInfo) {
self.session = session
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialDataErase
var deleteTrialRequest = Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest()
deleteTrialRequest.campaignID = session.campaignID
deleteTrialRequest.sessionID = session.groupID
deleteTrialRequest.trialID = session.sessionID
deleteTrialRequest.productID = session.productID
deleteTrialRequest.subjectID = session.subjectID
request.Google_Jacquard_Protocol_DataCollectionEraseTrialDataRequest_eraseTrialData =
deleteTrialRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseTrialDataResponse_eraseTrialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to delete all sessions on the tag.
struct DeleteAllIMUSessionsCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionDataErase
let deleteAllRequest = Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest()
request.Google_Jacquard_Protocol_DataCollectionEraseAllDataRequest_eraseAllData =
deleteAllRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionEraseAllDataResponse_eraseAllData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
/// Command request to retrieve session data.
struct RetreiveIMUSessionDataCommand: CommandRequest {
let session: IMUSessionInfo
let offset: UInt32
init(session: IMUSessionInfo, offset: UInt32) {
self.session = session
self.offset = offset
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .dataCollection
request.opcode = .dataCollectionTrialData
var sessionDataRequest = Google_Jacquard_Protocol_DataCollectionTrialDataRequest()
sessionDataRequest.campaignID = session.campaignID
sessionDataRequest.sessionID = session.groupID
sessionDataRequest.trialID = session.sessionID
sessionDataRequest.productID = session.productID
sessionDataRequest.subjectID = session.subjectID
sessionDataRequest.sensorID = 0
sessionDataRequest.offset = offset
request.Google_Jacquard_Protocol_DataCollectionTrialDataRequest_trialData = sessionDataRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard
let outerProto = outerProto as? Google_Jacquard_Protocol_Response
else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
if outerProto.hasGoogle_Jacquard_Protocol_DataCollectionTrialDataResponse_trialData {
return .success(())
}
return .failure(CommandResponseStatus.errorUnknown)
}
}
|
dedee7e256097cf1ae3beca6d0eea119
| 33.063694 | 104 | 0.751309 | false | false | false | false |
paulgriffiths/macvideopoker
|
refs/heads/master
|
VideoPoker/AppDelegate.swift
|
gpl-3.0
|
1
|
//
// AppDelegate.swift
//
// Application delegate class.
//
// Copyright (c) 2015 Paul Griffiths.
// Distributed under the terms of the GNU General Public License. <http://www.gnu.org/licenses/>
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var difficultyMenu: NSMenuItem?
@IBOutlet weak var easyMenu: NSMenuItem?
@IBOutlet weak var normalMenu: NSMenuItem?
private var mainWindowController: MainWindowController?
private let preferenceManager: PreferenceManager = PreferenceManager()
private var easyDifficulty = true {
didSet {
self.mainWindowController?.easyDifficulty = easyDifficulty
preferenceManager.easyDifficulty = easyDifficulty
easyMenu?.state = easyDifficulty ? NSOnState : NSOffState
normalMenu?.state = easyDifficulty ? NSOffState : NSOnState
}
}
// MARK: - NSApplicationDelegate methods
func applicationDidFinishLaunching(aNotification: NSNotification) {
let mainWindowController = MainWindowController()
mainWindowController.showWindow(self)
self.mainWindowController = mainWindowController
easyDifficulty = preferenceManager.easyDifficulty
}
// Terminate the app by the red button
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
// MARK: - Menu actions
@IBAction func difficultyMenuOptionChanged(sender: NSMenuItem) {
if let easyMenu = easyMenu, normalMenu = normalMenu {
switch sender {
case easyMenu:
easyDifficulty = true
case normalMenu:
easyDifficulty = false
default:
fatalError("Unrecognized difficulty menu selection")
}
}
}
@IBAction func newGameSelected(sender: NSMenuItem) {
self.mainWindowController?.resetGame()
}
}
|
4d157a9d02a003508e6b0d07986fa19f
| 30.057143 | 97 | 0.660074 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk
|
refs/heads/master
|
Sources/CoreAPI/CoreAPI_AuthVault.swift
|
mit
|
1
|
//
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2018 ShopGun. All rights reserved.
import Foundation
extension CoreAPI {
final class AuthVault {
// MARK: - Types
enum AuthRegenerationType: Equatable {
case create // destroy and recreate a new token
case renewOrCreate // just renew the current token's expiry (performs `create` if no token)
case reauthorize(LoginCredentials) // renew the current token the specified credentials (fails if no token)
}
typealias SignedRequestCompletion = ((Result<URLRequest, Error>) -> Void)
// MARK: Funcs
init(baseURL: URL, key: String, secret: String, tokenLife: Int = 7_776_000, urlSession: URLSession, dataStore: ShopGunSDKDataStore?) {
self.baseURL = baseURL
self.key = key
self.secret = secret
self.tokenLife = tokenLife
self.dataStore = dataStore
self.urlSession = urlSession
self.activeRegenerateTask = nil
// load clientId/authState from the store (if provided)
let storedAuth = AuthVault.loadFromDataStore(dataStore)
if let auth = storedAuth.auth {
// Apply stored auth if it exists
self.authState = .authorized(token: auth.token, user: auth.user, clientId: storedAuth.clientId)
} else if let legacyAuthState = AuthVault.loadLegacyAuthState() {
// load, apply & clear any legacy auth from the previous version of the SDK
self.authState = legacyAuthState
self.updateStore()
AuthVault.clearLegacyAuthState()
Logger.log("Loaded AuthState from Legacy cache", level: .debug, source: .CoreAPI)
} else {
// If no stored auth, or legacy auth to migrate, mark as unauthorized.
self.authState = .unauthorized(error: nil, clientId: storedAuth.clientId)
}
}
func regenerate(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) {
self.queue.async { [weak self] in
self?.regenerateOnQueue(type, completion: completion)
}
}
// Returns a new urlRequest that has been signed with the authToken
// If we are not authorized, or in the process of authorizing, then this can take some time to complete.
func signURLRequest(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) {
self.queue.async { [weak self] in
self?.signURLRequestOnQueue(urlRequest, completion: completion)
}
}
var authorizedUserDidChangeCallback: ((_ prev: AuthorizedUser?, _ new: AuthorizedUser?) -> Void)?
var additionalRequestParams: [String: String] = [:]
/// If we are authorized, and have an authorized user, then this is non-nil
var currentAuthorizedUser: AuthorizedUser? {
if case .authorized(_, let user, _) = self.authState, user != nil {
return user
} else {
return nil
}
}
func resetStoredAuthState() {
self.queue.async { [weak self] in
guard let s = self else { return }
AuthVault.clearLegacyAuthState()
AuthVault.updateDataStore(s.dataStore, data: nil)
s.authState = .unauthorized(error: nil, clientId: nil)
}
}
// MARK: - Private Types
enum AuthState {
case unauthorized(error: Error?, clientId: ClientIdentifier?) // we currently have no auth (TODO: `reason` enum insted of error?)
case authorized(token: String, user: AuthorizedUser?, clientId: ClientIdentifier?) // we have signed headers to return
}
// MARK: Private Vars
private let baseURL: URL
private let key: String
private let secret: String
private let tokenLife: Int
private weak var dataStore: ShopGunSDKDataStore?
private let urlSession: URLSession
private let queue = DispatchQueue(label: "ShopGunSDK.CoreAPI.AuthVault.Queue")
// if we are in the process of regenerating the token, this is set
private var activeRegenerateTask: (type: AuthRegenerationType, task: URLSessionTask)?
private var pendingSignedRequests: [(URLRequest, SignedRequestCompletion)] = []
private var authState: AuthState {
didSet {
// save the current authState to the store
updateStore()
// TODO: change to 'authStateDidChange', and trigger for _any_ change to the authState
guard let authDidChangeCallback = self.authorizedUserDidChangeCallback else { return }
var prevAuthUser: AuthorizedUser? = nil
if case .authorized(_, let user?, _) = oldValue {
prevAuthUser = user
}
if prevAuthUser?.person != currentAuthorizedUser?.person || prevAuthUser?.provider != currentAuthorizedUser?.provider {
authDidChangeCallback(prevAuthUser, currentAuthorizedUser)
}
}
}
var clientId: ClientIdentifier? {
switch self.authState {
case .authorized(_, _, let clientId),
.unauthorized(_, let clientId):
return clientId
}
}
var sessionToken: String? {
guard case let .authorized(token, _, _) = self.authState else { return nil }
return token
}
// MARK: Funcs
private func regenerateOnQueue(_ type: AuthRegenerationType, completion: ((Error?) -> Void)? = nil) {
// If we are in the process of doing a different kind of regen, cancel it
cancelActiveRegenerateTask()
var mutableCompletion = completion
// generate a request based on the regenerate type
let request: CoreAPI.Request<AuthSessionResponse>
switch (type, self.authState) {
case (.create, _),
(.renewOrCreate, .unauthorized):
request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife)
case (.renewOrCreate, .authorized):
request = AuthSessionResponse.renewRequest(clientId: self.clientId)
case (.reauthorize(let credentials), .authorized):
request = AuthSessionResponse.renewRequest(clientId: self.clientId, additionalParams: credentials.requestParams)
case (.reauthorize, .unauthorized):
// if we have no valid token at all when trying to reauthorize then just create
request = AuthSessionResponse.createRequest(clientId: self.clientId, apiKey: self.key, tokenLife: self.tokenLife)
// once completed, if we are authorized, then reauthorize with the credentials
mutableCompletion = { [weak self] (createError) in
self?.queue.async { [weak self] in
guard case .authorized? = self?.authState else {
DispatchQueue.main.async {
completion?(createError)
}
return
}
self?.regenerate(type, completion: completion)
}
}
}
var urlRequest = request.urlRequest(for: self.baseURL, additionalParameters: self.additionalRequestParams)
if case .authorized(let token, _, _) = self.authState,
request.requiresAuth == true {
urlRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret)
}
let task = self.urlSession.coreAPIDataTask(with: urlRequest) { [weak self] (authSessionResult: Result<AuthSessionResponse, Error>) -> Void in
self?.queue.async { [weak self] in
self?.activeRegenerateTaskCompleted(authSessionResult)
DispatchQueue.main.async {
mutableCompletion?(authSessionResult.getFailure())
}
}
}
self.activeRegenerateTask = (type: type, task: task)
task.resume()
}
private func signURLRequestOnQueue(_ urlRequest: URLRequest, completion: @escaping SignedRequestCompletion) {
// check if we are in the process of regenerating the token
// if so just save the completion handler to be run once regeneration finishes
guard self.activeRegenerateTask == nil else {
self.pendingSignedRequests.append((urlRequest, completion))
return
}
switch self.authState {
case .unauthorized(let authError, _):
if let authError = authError {
// unauthorized, with an error, so perform completion and forward the error
DispatchQueue.main.async {
completion(.failure(authError))
}
} else {
// unauthorized, without an error, so cache completion & start regenerating token
self.pendingSignedRequests.append((urlRequest, completion))
self.regenerate(.renewOrCreate)
}
case let .authorized(token, _, _):
// we are authorized, so sign the request and perform the completion handler
let signedRequest = urlRequest.signedForCoreAPI(withToken: token, secret: self.secret)
DispatchQueue.main.async {
completion(.success(signedRequest))
}
}
}
/// Save the current AuthState to the store
private func updateStore() {
guard let store = self.dataStore else { return }
switch self.authState {
case .unauthorized(_, nil):
AuthVault.updateDataStore(store, data: nil)
case let .unauthorized(_, clientId):
AuthVault.updateDataStore(store, data: StoreData(auth: nil, clientId: clientId))
case let .authorized(token, user, clientId):
AuthVault.updateDataStore(store, data: StoreData(auth: (token: token, user: user), clientId: clientId))
}
}
// If we are in the process of doing a different kind of regen, cancel it
private func cancelActiveRegenerateTask() {
self.activeRegenerateTask?.task.cancel()
self.activeRegenerateTask = nil
}
private func activeRegenerateTaskCompleted(_ result: Result<AuthSessionResponse, Error>) {
switch result {
case .success(let authSession):
Logger.log("Successfully updated authSession \(authSession)", level: .debug, source: .CoreAPI)
self.authState = .authorized(token: authSession.token, user: authSession.authorizedUser, clientId: authSession.clientId)
self.activeRegenerateTask = nil
// we are authorized, so sign the requests and perform the completion handlers
for (urlRequest, completion) in self.pendingSignedRequests {
let signedRequest = urlRequest.signedForCoreAPI(withToken: authSession.token, secret: self.secret)
DispatchQueue.main.async {
completion(.success(signedRequest))
}
}
case .failure(let cancelError as NSError)
where cancelError.domain == NSURLErrorDomain && cancelError.code == URLError.Code.cancelled.rawValue:
// if cancelled then ignore
break
case .failure(let regenError):
Logger.log("Failed to update authSession \(regenError)", level: .error, source: .CoreAPI)
let type = activeRegenerateTask?.type
self.activeRegenerateTask = nil
// we weren't creating, and the error isnt a network error, so try to just create the token.
if type != .create
&& (regenError as NSError).isNetworkError == false {
self.regenerateOnQueue(.create)
} else {
for (_, completion) in self.pendingSignedRequests {
DispatchQueue.main.async {
completion(.failure(regenError))
}
}
}
}
}
}
}
// MARK: -
extension CoreAPI.AuthVault {
/// The response from requests to the API's session endpoint
fileprivate struct AuthSessionResponse: Decodable {
var clientId: CoreAPI.ClientIdentifier
var token: String
var expiry: Date
var authorizedUser: CoreAPI.AuthorizedUser?
enum CodingKeys: String, CodingKey {
case clientId = "client_id"
case token = "token"
case expiry = "expires"
case provider = "provider"
case person = "user"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.clientId = try values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId)
self.token = try values.decode(String.self, forKey: .token)
if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .provider),
let person = try? values.decode(CoreAPI.Person.self, forKey: .person) {
self.authorizedUser = (person, provider)
}
let expiryString = try values.decode(String.self, forKey: .expiry)
if let expiryDate = CoreAPI.dateFormatter.date(from: expiryString) {
self.expiry = expiryDate
} else {
throw DecodingError.dataCorruptedError(forKey: .expiry, in: values, debugDescription: "Date string does not match format expected by formatter (\(String(describing: CoreAPI.dateFormatter.dateFormat))).")
}
}
// MARK: Response-generating requests
static func createRequest(clientId: CoreAPI.ClientIdentifier?, apiKey: String, tokenLife: Int) -> CoreAPI.Request<AuthSessionResponse> {
var params: [String: String] = [:]
params["api_key"] = apiKey
params["token_ttl"] = String(tokenLife)
params["clientId"] = clientId?.rawValue
return .init(path: "v2/sessions", method: .POST, requiresAuth: false, httpBody: params, timeoutInterval: 10)
}
static func renewRequest(clientId: CoreAPI.ClientIdentifier?, additionalParams: [String: String] = [:]) -> CoreAPI.Request<AuthSessionResponse> {
var params: [String: String] = additionalParams
params["clientId"] = clientId?.rawValue
return .init(path: "v2/sessions", method: .PUT, requiresAuth: true, httpBody: params, timeoutInterval: 10)
}
}
}
// MARK: - DataStore
extension CoreAPI.AuthVault {
fileprivate static let dataStoreKey = "ShopGunSDK.CoreAPI.AuthVault"
fileprivate static func updateDataStore(_ dataStore: ShopGunSDKDataStore?, data: CoreAPI.AuthVault.StoreData?) {
var authJSON: String? = nil
if let data = data,
let authJSONData: Data = try? JSONEncoder().encode(data) {
authJSON = String(data: authJSONData, encoding: .utf8)
}
dataStore?.set(value: authJSON, for: CoreAPI.AuthVault.dataStoreKey)
}
fileprivate static func loadFromDataStore(_ dataStore: ShopGunSDKDataStore?) -> CoreAPI.AuthVault.StoreData {
guard let authJSONData = dataStore?.get(for: CoreAPI.AuthVault.dataStoreKey)?.data(using: .utf8),
let auth = try? JSONDecoder().decode(CoreAPI.AuthVault.StoreData.self, from: authJSONData) else {
return .init(auth: nil, clientId: nil)
}
return auth
}
// The data to be saved/read from disk
fileprivate struct StoreData: Codable {
var auth: (token: String, user: CoreAPI.AuthorizedUser?)?
var clientId: CoreAPI.ClientIdentifier?
init(auth: (token: String, user: CoreAPI.AuthorizedUser?)?, clientId: CoreAPI.ClientIdentifier?) {
self.auth = auth
self.clientId = clientId
}
enum CodingKeys: String, CodingKey {
case authToken = "auth.token"
case authUserPerson = "auth.user.person"
case authUserProvider = "auth.user.provider"
case clientId = "clientId"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
if let token = try? values.decode(String.self, forKey: .authToken) {
let authorizedUser: CoreAPI.AuthorizedUser?
if let provider = try? values.decode(CoreAPI.AuthorizedUserProvider.self, forKey: .authUserProvider),
let person = try? values.decode(CoreAPI.Person.self, forKey: .authUserPerson) {
authorizedUser = (person, provider)
} else {
authorizedUser = nil
}
self.auth = (token: token, user: authorizedUser)
} else {
self.auth = nil
}
self.clientId = try? values.decode(CoreAPI.ClientIdentifier.self, forKey: .clientId)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encode(self.auth?.token, forKey: .authToken)
try? container.encode(self.auth?.user?.person, forKey: .authUserPerson)
try? container.encode(self.auth?.user?.provider, forKey: .authUserProvider)
try? container.encode(self.clientId, forKey: .clientId)
}
}
}
// MARK: -
extension URLRequest {
/// Generates a new URLRequest that includes the signed HTTPHeaders, given a token & secret
fileprivate func signedForCoreAPI(withToken token: String, secret: String) -> URLRequest {
// make an SHA256 Hex string
let hashString = (secret + token).sha256()
var signedRequest = self
signedRequest.setValue(token, forHTTPHeaderField: "X-Token")
signedRequest.setValue(hashString, forHTTPHeaderField: "X-Signature")
return signedRequest
}
}
// MARK: -
extension CoreAPI.LoginCredentials {
/// What are the request params that a specific loginCredential needs to send when reauthorizing
fileprivate var requestParams: [String: String] {
switch self {
case .logout:
return ["email": ""]
case let .shopgun(email, password):
return ["email": email,
"password": password]
case let .facebook(token):
return ["facebook_token": token]
}
}
}
|
fbed6178097b40f300049954c96d3e00
| 43.067982 | 219 | 0.567952 | false | false | false | false |
Bartlebys/Bartleby
|
refs/heads/master
|
Bartleby.xOS/core/Bartleby.swift
|
apache-2.0
|
1
|
//
// Bartleby.swift
// Bartleby
//
// Created by Benoit Pereira da Silva on 16/09/2015.
// Copyright © 2015 https://pereira-da-silva.com for Chaosmos SAS
// All rights reserved you can ask for a license.
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
//MARK: - Bartleby
// Bartleby's 1.0 approach is suitable for data set that can stored in memory.
open class Bartleby:NSObject,AliasResolution {
/// The standard singleton shared instance
open static let sharedInstance: Bartleby = {
let instance = Bartleby()
return instance
}()
static let b_version = "1.0"
static let b_release = "0"
open static let defaultLanguageCode = I18N.defaultLanguageCode
/// The version string of Bartleby framework
open static var versionString: String {
get {
return "\(self.b_version).\(self.b_release)"
}
}
// A unique run identifier that changes each time Bartleby is launched
open static let runUID: String=Bartleby.createUID()
// The configuration
public static var configuration: BartlebyConfiguration.Type=BartlebyDefaultConfiguration.self
// The crypto delegate
public static var cryptoDelegate: CryptoDelegate=NoCrypto()
// The File manager
// #TODO REMOVE BartlebyFileIO (simplification)
public static var fileManager: BartlebyFileIO=BFileManager()
/**
This method should be only used to cleanup in core unit test
*/
open func hardCoreCleanupForUnitTests() {
self._documents=[String:BartlebyDocument]()
}
/**
* When using ephemeralMode on registration Instance are marked ephemeral
*/
open static var ephemeral=false
open static var requestCounter=0
/**
Should be called on Init of the Document.
*/
open func configureWith(_ configuration: BartlebyConfiguration.Type) {
if configuration.DISABLE_DATA_CRYPTO {
// Use NoCrypto a neutral crypto delegate
Bartleby.cryptoDelegate=NoCrypto()
} else {
//Initialize the crypto delegate with the valid KEY & SALT
Bartleby.cryptoDelegate=CryptoHelper(salt: configuration.SHARED_SALT,keySize:configuration.KEY_SIZE)
}
// Store the configuration
Bartleby.configuration=configuration
// Ephemeral mode.
Bartleby.ephemeral=configuration.EPHEMERAL_MODE
// Configure the HTTP Manager
HTTPManager.configure()
}
override init() {
super.init()
}
// Bartleby's favourite
open static func please(_ message: String) -> String {
return "I would prefer not to!"
}
// MARK: -
// TODO: @md #crypto Check crypto key requirement
public static func isValidKey(_ key: String) -> Bool {
return key.count >= 32
}
// MARK: - Registries
// Each document is a stored separately
// Multiple documents can be openned at the same time
// and synchronized to different Servers.
// Bartleby supports multi-authentication and multi documents
/// Memory storage
fileprivate var _documents: [String:BartlebyDocument] = [String:BartlebyDocument]()
/**
Returns a document by its UID ( == document.metadata.persistentUID)
The SpaceUID is shared between multiple document.
- parameter UID: the uid of the document
- returns: the document
*/
open func getDocumentByUID(_ UID:UID) -> BartlebyDocument?{
if let document = self._documents[UID]{
return document
}
return nil
}
/**
Registers a document
- parameter document: the document
*/
open func declare(_ document: BartlebyDocument) {
self._documents[document.UID]=document
}
/**
Unloads the collections
- parameter documentUID: the target document UID
*/
open func forget(_ documentUID: UID) {
self._documents.removeValue(forKey: documentUID)
}
/**
Replaces the UID of a proxy Document
The proxy document is an instance that is created before to deserialize asynchronously the document Data
Should be exclusively used when re-openning an existing document.
- parameter documentProxyUID: the proxy UID
- parameter documentUID: the final UID
*/
open func replaceDocumentUID(_ documentProxyUID: UID, by documentUID: UID) {
if( documentProxyUID != documentUID) {
if let document=self._documents[documentProxyUID] {
self._documents[documentUID]=document
self._documents.removeValue(forKey: documentProxyUID)
}
}
}
/**
An UID generator compliant with MONGODB primary IDS constraints
- returns: the UID
*/
open static func createUID() -> UID {
// (!) NSUUID are not suitable for MONGODB as Primary Ids.
// We need to encode them we have choosen base64
let uid=UUID().uuidString
let utf8str = uid.data(using: Default.STRING_ENCODING)
return utf8str!.base64EncodedString(options: Data.Base64EncodingOptions(rawValue:0))
}
open static let startTime=CFAbsoluteTimeGetCurrent()
open static var elapsedTime:Double {
return CFAbsoluteTimeGetCurrent()-Bartleby.startTime
}
/**
Returns a random string of a given size.
- parameter len: the length
- parameter signs: the possible signs By default We exclude possibily confusing signs "oOiI01" to make random strings less ambiguous
- returns: the string
*/
open static func randomStringWithLength (_ len: UInt, signs: String="abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789") -> String {
var randomString = ""
for _ in (0 ..< len) {
let length = UInt32 (signs.count)
let rand = Int(arc4random_uniform(length))
let idx = signs.index(signs.startIndex, offsetBy: rand, limitedBy:signs.endIndex)
let c=signs[idx!]
randomString.append(c)
}
return randomString
}
// MARK: - Paths & URL
/**
Returns the search path directory
- parameter searchPath: the search Path
- returns: the path string
*/
open static func getSearchPath(_ searchPath: FileManager.SearchPathDirectory) -> String? {
let urls = FileManager.default.urls(for: searchPath, in: .userDomainMask)
if urls.count>0 {
let path = urls[0].path
return path
}
return nil
}
// MARK: - Maintenance
open func destroyLocalEphemeralInstances() {
for (dataSpaceUID, document) in self._documents {
document.log("Destroying EphemeralInstances on \(dataSpaceUID)", file:#file, function:#function, line:#line, category: Default.LOG_DEFAULT)
document.superIterate({ (element) in
if element.ephemeral {
document.delete(element)
}
})
}
}
//MARK: - Centralized ObjectList By UID
// this centralized dictionary allows to access to any referenced object by its UID
// to resolve externalReferences, cross reference, it simplify instance mobility from a Document to another, etc..
// future implementation may include extension for lazy Storage
fileprivate static var _instancesByUID=Dictionary<String, Collectible>()
// The number of registred object
open static var numberOfRegistredObject: Int {
get {
return _instancesByUID.count
}
}
/**
Registers an instance
- parameter instance: the Identifiable instance
*/
open static func register<T: Collectible>(_ instance: T) {
// Store the instance by its UID
self._instancesByUID[instance.UID]=instance
// Check if some deferred Ownership has been recorded
if let owneesUIDS = self._deferredOwnerships[instance.UID] {
/// This situation occurs for example
/// when the ownee has been triggered but not the owner
// or the deserialization of the ownee preceeds the owner
if let o=instance as? ManagedModel{
for owneeUID in owneesUIDS{
if let _ = Bartleby.registredManagedModelByUID(owneeUID){
// Add the owns entry
if !o.owns.contains(owneeUID){
o.owns.append(owneeUID)
}else{
print("### !")
}
}else{
print("----")
glog("Deferred ownership has failed to found \(owneeUID) for \(o.UID)", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
self._deferredOwnerships.removeValue(forKey: instance.UID)
}
}
/**
UnRegisters an instance
- parameter instance: the collectible instance
*/
open static func unRegister(_ instance: Collectible) {
self._instancesByUID.removeValue(forKey: instance.UID)
}
/**
UnRegisters an instance
- parameter instance: the collectible instance
*/
open static func unRegister(_ instances: [Collectible]) {
for instance in instances{
self._instancesByUID.removeValue(forKey: instance.UID)
}
}
/**
Returns the registred instance of by its UID
- parameter UID:
- returns: the instance
*/
open static func registredObjectByUID<T: Collectible>(_ UID: UID) throws-> T {
if let instance=self._instancesByUID[UID]{
if let casted=instance as? T{
return casted
}else{
throw DocumentError.instanceTypeMissMatch(found: instance.runTimeTypeName())
}
}
throw DocumentError.instanceNotFound
}
/// Returns a ManagedModel by its UID
/// Those instance are not casted.
/// You should most of the time use : `registredObjectByUID<T: Collectible>(_ UID: String) throws-> T`
/// - parameter UID:
/// - returns: the instance
open static func registredManagedModelByUID(_ UID: UID)-> ManagedModel? {
return try? Bartleby.registredObjectByUID(UID)
}
/// Returns a collection of ManagedModel by UIDs
/// Those instance are not casted.
/// You should most of the time use : `registredObjectByUID<T: Collectible>(_ UID: String) throws-> T`
/// - parameter UID:
/// - returns: the instance
open static func registredManagedModelByUIDs(_ UIDs: [UID])-> [ManagedModel]? {
return try? Bartleby.registredObjectsByUIDs(UIDs)
}
/// Returns the registred instance of by UIDs
///
/// - Parameter UIDs: the UIDs
/// - Returns: the registred Instances
open static func registredObjectsByUIDs<T: Collectible>(_ UIDs: [UID]) throws-> [T] {
var items=[T]()
for UID in UIDs{
items.append(try Bartleby.registredObjectByUID(UID))
}
return items
}
/**
Returns the instance by its UID
- parameter UID: needle
î
- returns: the instance
*/
open static func collectibleInstanceByUID(_ UID: UID) -> Collectible? {
return self._instancesByUID[UID]
}
/// Resolve the alias
///
/// - Parameter alias: the alias
/// - Returns: the reference
open static func instance(from alias:Alias)->Aliasable?{
return registredManagedModelByUID(alias.UID)
}
// MARK: - Deferred Ownwerships
/// If we receive a Instance that refers to an unexisting Owner
/// We store its missing entry is the deferredOwnerships dictionary
/// For future resolution (on registration)
/// [notAvailableOwnerUID][relatedOwnedUIDS]
fileprivate static var _deferredOwnerships=[UID:[UID]]()
/// Stores the ownee when the owner is not already available
/// This situation may occur on collection deserialization
/// when the owner is deserialized before the ownee.
///
/// - Parameters:
/// - ownee: the ownee
/// - ownerUID: the currently unavailable owner UID
open static func appendToDeferredOwnershipsList(_ ownee:Collectible,ownerUID:UID){
if self._deferredOwnerships.keys.contains(ownerUID) {
self._deferredOwnerships[ownerUID]!.append(ownee.UID)
}else{
self._deferredOwnerships[ownerUID]=[ownee.UID]
}
}
// MARK: - Report
/// Report the metrics to general endpoint calls (not clearly attached to a specific document)
///
/// - parameter metrics: the metrics
/// - parameter forURL: the concerned URL
open func report(_ metrics:Metrics,forURL:URL){
for( _ , document) in self._documents{
let s=document.baseURL.absoluteString
let us=forURL.absoluteString
if us.contains(s){
document.report(metrics)
}
}
}
// MARK: - Commit / Push Distribution (dynamic)
open static func markCommitted(_ instanceUID:UID){
if let instance=Bartleby.collectibleInstanceByUID(instanceUID){
instance.hasBeenCommitted()
}else{
glog("\(instanceUID) not found", file: #file, function: #function, line: #line, category: Default.LOG_WARNING, decorative: false)
}
}
}
|
6a4433ea4ea7e4dc962206aa33469cc5
| 29.441441 | 192 | 0.628588 | false | false | false | false |
fantast1k/Swiftent
|
refs/heads/master
|
Swiftent/Swiftent/Source/UIKit/UITextView+Contentable.swift
|
gpl-3.0
|
1
|
//
// UITextView+Contentable.swift
// Swiftent
//
// Created by Dmitry Fa[n]tastik on 26/08/2016.
// Copyright © 2016 Fantastik Solution. All rights reserved.
//
import UIKit
extension UITextView : Contentable {
public typealias Content = UITextViewContent
public func installContent(_ content: UITextViewContent) {
switch content.text {
case .Raw(let txt):
if let txt = txt {
self.text = txt
}
case .Attributed(let txt):
if let txt = txt {
self.attributedText = txt
}
}
}
}
|
13d85c90e56f82c9c28c57aa69ebd871
| 20.714286 | 62 | 0.570724 | false | false | false | false |
lucas34/SwiftQueue
|
refs/heads/master
|
Sources/SwiftQueue/Constraint+Retry.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2022 Lucas Nelaupe
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
internal final class JobRetryConstraint: SimpleConstraint, CodableConstraint {
/// Maximum number of authorised retried
internal var limit: Limit
required init(limit: Limit) {
self.limit = limit
}
convenience init?(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RetryConstraintKey.self)
if container.contains(.retryLimit) {
try self.init(limit: container.decode(Limit.self, forKey: .retryLimit))
} else { return nil }
}
func onCompletionFail(sqOperation: SqOperation, error: Error) {
switch limit {
case .limited(let value):
if value > 0 {
sqOperation.retryJob(actual: self, retry: sqOperation.handler.onRetry(error: error), origin: error)
} else {
sqOperation.onTerminate()
}
case .unlimited:
sqOperation.retryJob(actual: self, retry: sqOperation.handler.onRetry(error: error), origin: error)
}
}
private enum RetryConstraintKey: String, CodingKey {
case retryLimit
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RetryConstraintKey.self)
try container.encode(limit, forKey: .retryLimit)
}
}
fileprivate extension SqOperation {
func retryJob(actual: JobRetryConstraint, retry: RetryConstraint, origin: Error) {
func exponentialBackoff(initial: TimeInterval) -> TimeInterval {
currentRepetition += 1
return currentRepetition == 1 ? initial : initial * pow(2, Double(currentRepetition - 1))
}
func retryInBackgroundAfter(_ delay: TimeInterval) {
nextRunSchedule = Date().addingTimeInterval(delay)
dispatchQueue.runAfter(delay) { [weak actual, weak self] in
actual?.limit.decreaseValue(by: 1)
self?.run()
}
}
switch retry {
case .cancel:
lastError = SwiftQueueError.onRetryCancel(origin)
onTerminate()
case .retry(let after):
guard after > 0 else {
// Retry immediately
actual.limit.decreaseValue(by: 1)
self.run()
return
}
// Retry after time in parameter
retryInBackgroundAfter(after)
case .exponential(let initial):
retryInBackgroundAfter(exponentialBackoff(initial: initial))
case .exponentialWithLimit(let initial, let maxDelay):
retryInBackgroundAfter(min(maxDelay, exponentialBackoff(initial: initial)))
}
}
}
/// Behaviour for retrying the job
public enum RetryConstraint {
/// Retry after a certain time. If set to 0 it will retry immediately
case retry(delay: TimeInterval)
/// Will not retry, onRemoved will be called immediately
case cancel
/// Exponential back-off
case exponential(initial: TimeInterval)
/// Exponential back-off with max delay
case exponentialWithLimit(initial: TimeInterval, maxDelay: TimeInterval)
}
|
8acaf313cc87550813b8269a0cbd57b6
| 36.5 | 115 | 0.665731 | false | false | false | false |
AndrewBennet/readinglist
|
refs/heads/master
|
ReadingList/Views/BookTableHeader.swift
|
gpl-3.0
|
1
|
import Foundation
import UIKit
class BookTableHeader: UITableViewHeaderFooterView {
var orderable: Orderable?
weak var presenter: UITableViewController?
var onSortChanged: (() -> Void)?
var alertOrMenu: AlertOrMenu! {
didSet {
if #available(iOS 14.0, *) {
sortButton.showsMenuAsPrimaryAction = true
// Rebuild the menu each time alertOrMenu is reassigned
sortButton.menu = alertOrMenu.menu()
}
}
}
static let height: CGFloat = 50
@IBOutlet private weak var label: UILabel!
@IBOutlet private weak var sortButton: UIButton!
@IBOutlet private weak var numberBadgeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
if let descriptor = label.font.fontDescriptor.withDesign(.rounded) {
label.font = UIFont(descriptor: descriptor, size: label.font.pointSize)
}
numberBadgeLabel.font = .rounded(ofSize: numberBadgeLabel.font.pointSize, weight: .semibold)
}
@IBAction private func sortButtonTapped(_ sender: UIButton) {
if #available(iOS 14.0, *) {
assert(sender.showsMenuAsPrimaryAction)
return
}
let alert = alertOrMenu.actionSheet()
alert.popoverPresentationController?.setButton(sortButton)
presenter?.present(alert, animated: true, completion: nil)
}
func configure(labelText: String, badgeNumber: Int?, enableSort: Bool) {
label.text = labelText
sortButton.isEnabled = enableSort
if let badgeNumber = badgeNumber {
numberBadgeLabel.superview!.isHidden = false
numberBadgeLabel.text = "\(badgeNumber)"
} else {
numberBadgeLabel.superview!.isHidden = true
}
}
private func buildBookSortAlertOrMenu() -> AlertOrMenu {
guard let orderable = orderable else { preconditionFailure() }
let selectedSort = orderable.getSort()
return AlertOrMenu(title: "Choose Order", items: BookSort.allCases.filter { orderable.supports($0) }.map { sort in
AlertOrMenu.Item(title: sort == selectedSort ? "\(sort.description) ✓" : sort.description) { [weak self] in
if selectedSort == sort { return }
orderable.setSort(sort)
guard let `self` = self else { return }
// Rebuild the menu, so the tick is in the right place next time
if #available(iOS 14.0, *) {
self.alertOrMenu = self.buildBookSortAlertOrMenu()
}
self.onSortChanged?()
}
})
}
func configure(readState: BookReadState, bookCount: Int, enableSort: Bool) {
configure(labelText: "\(readState.description)", badgeNumber: bookCount, enableSort: enableSort)
orderable = .book(readState)
alertOrMenu = buildBookSortAlertOrMenu()
}
func configure(list: List, bookCount: Int, enableSort: Bool) {
configure(labelText: "\(bookCount) book\(bookCount == 1 ? "" : "s")", badgeNumber: nil, enableSort: enableSort)
orderable = .list(list)
alertOrMenu = buildBookSortAlertOrMenu()
}
}
|
b86d21f6804f52137828ff1f0fda37af
| 38.280488 | 122 | 0.625893 | false | true | false | false |
coffee-cup/solis
|
refs/heads/master
|
SunriseSunset/Sunline.swift
|
mit
|
1
|
//
// SunLine.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-05-18.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
class Sunline: UIView {
var line: UIView!
var timeLabel: UILabel!
var nameLabel: UILabel!
var parentView: UIView!
var topConstraint: NSLayoutConstraint!
var lineLeftConstraint: NSLayoutConstraint!
var lineRightConstraint: NSLayoutConstraint!
var nameLeftConstraint: NSLayoutConstraint!
var time: Date!
var colliding = false
let CollidingMinutesThreshhold = 12
let LineHorizontalPadding: CGFloat = 100
let NameHorizontalPadding: CGFloat = 20
let CollideAnimationDuration: TimeInterval = 0.25
override init (frame : CGRect) {
super.init(frame : frame)
}
convenience init () {
self.init(frame:CGRect.zero)
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
func createLine(_ parentView: UIView, type: SunType) {
self.parentView = parentView
DispatchQueue.main.async {
self.line = UIView()
self.timeLabel = UILabel()
self.nameLabel = UILabel()
self.translatesAutoresizingMaskIntoConstraints = false
self.line.translatesAutoresizingMaskIntoConstraints = false
self.timeLabel.translatesAutoresizingMaskIntoConstraints = false
self.nameLabel.translatesAutoresizingMaskIntoConstraints = false
parentView.addSubview(self)
self.addSubview(self.line)
self.addSubview(self.timeLabel)
self.addSubview(self.nameLabel)
// View Contraints
self.topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: parentView, attribute: .top, multiplier: 1, constant: 0)
let edgeConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": self])
NSLayoutConstraint.activate(edgeConstraints + [self.topConstraint])
// Line Constraints
self.lineLeftConstraint = NSLayoutConstraint(item: self.line!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
self.lineRightConstraint = NSLayoutConstraint(item: self.line!, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -self.LineHorizontalPadding)
let lineVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]|", options: [], metrics: nil, views: ["view": self.line!])
let lineHeightContraint = NSLayoutConstraint(item: self.line!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 1)
NSLayoutConstraint.activate([self.lineLeftConstraint, self.lineRightConstraint, lineHeightContraint] + lineVerticalConstraints)
// Name Constraints
self.nameLeftConstraint = NSLayoutConstraint(item: self.nameLabel!, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: self.NameHorizontalPadding)
let nameVerticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[view]-2-|", options: [], metrics: nil, views: ["view": self.nameLabel!])
NSLayoutConstraint.activate(nameVerticalConstraints + [self.nameLeftConstraint])
// Time Contstraints
let timeCenterConstraint = NSLayoutConstraint(item: self.timeLabel!, attribute: .centerY, relatedBy: .equal, toItem: self.line, attribute: .centerY, multiplier: 1, constant: 0)
let timeHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-10-|", options: [], metrics: nil, views: ["view": self.timeLabel!])
NSLayoutConstraint.activate(timeHorizontalConstraints + [timeCenterConstraint])
self.backgroundColor = UIColor.red
self.line.backgroundColor = type.lineColour
self.nameLabel.text = type.description.lowercased()
self.nameLabel.textColor = nameTextColour
self.nameLabel.font = fontTwilight
self.timeLabel.textColor = timeTextColour
self.timeLabel.text = "12:12"
self.timeLabel.font = fontDetail
self.nameLabel.addSimpleShadow()
self.timeLabel.addSimpleShadow()
self.isHidden = true
self.alpha = 0
}
}
func getTimeText(_ offset: TimeInterval) -> String {
let text = TimeFormatters.currentFormattedString(time, timeZone: TimeZones.currentTimeZone)
return text
}
// Animates the items in the sunline to avoid collision with now line
// Returns whether there will be a collision with now line
func animateAvoidCollision(_ offset: TimeInterval) -> Bool {
let offsetTime = Date().addingTimeInterval(offset)
let difference = abs(offsetTime.getDifferenceInMinutes(time))
if difference < CollidingMinutesThreshhold {
animateForCollision()
return true
} else {
animateToNormal()
}
return false
}
func animateForCollision() {
if !colliding {
// Fixes sunline overlap on iphone5 screens and smaller
let namePaddingFraction: CGFloat = parentView.frame.width < 375 ? 3 : 1
lineLeftConstraint.constant = LineHorizontalPadding
nameLeftConstraint.constant = LineHorizontalPadding + (NameHorizontalPadding / namePaddingFraction)
UIView.animate(withDuration: CollideAnimationDuration, delay: 0, options: UIView.AnimationOptions(), animations: {
self.layoutIfNeeded()
self.timeLabel.alpha = 0
}, completion: nil)
}
colliding = true
}
func animateToNormal() {
if colliding {
lineLeftConstraint.constant = 0
nameLeftConstraint.constant = NameHorizontalPadding
UIView.animate(withDuration: CollideAnimationDuration, delay: 0, options: UIView.AnimationOptions(), animations: {
self.layoutIfNeeded()
self.timeLabel.alpha = 1
}, completion: nil)
}
colliding = false
}
// Returns whether there will be a collision with now line
func updateTime(_ offset: TimeInterval = 0) -> Bool {
if time == nil {
return false
}
let timeText = getTimeText(offset)
let isCollision = animateAvoidCollision(offset)
DispatchQueue.main.async {
if self.time != nil {
self.timeLabel.text = timeText
}
}
return isCollision
}
func updateLine(_ time: Date, percent: Float, happens: Bool) {
DispatchQueue.main.async {
self.time = time
let _ = self.updateTime()
self.topConstraint.constant = self.parentView.frame.height * CGFloat(percent)
UIView.animate(withDuration: 0.5) {
self.parentView.layoutIfNeeded()
}
if happens {
self.isHidden = false
UIView.animate(withDuration: 0.5, delay: 1, options: UIView.AnimationOptions(), animations: {
self.alpha = 1
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, delay: 1, options: UIView.AnimationOptions(), animations: {
self.alpha = 0
}, completion: nil)
}
}
}
}
|
d0901724a22db27c31cb7737e3826427
| 40.936842 | 207 | 0.622741 | false | false | false | false |
cdmx/MiniMancera
|
refs/heads/master
|
miniMancera/Model/Option/WhistlesVsZombies/Strategy/MOptionWhistlesVsZombiesStrategyDefeated.swift
|
mit
|
1
|
import Foundation
class MOptionWhistlesVsZombiesStrategyDefeated:MGameStrategyMain<MOptionWhistlesVsZombies>
{
private var startingTime:TimeInterval?
private let kWait:TimeInterval = 3.5
init(model:MOptionWhistlesVsZombies)
{
let updateItems:[MGameUpdate<MOptionWhistlesVsZombies>] = [
model.player,
model.sonicBoom,
model.zombie,
model.points,
model.hud]
super.init(
model:model,
updateItems:updateItems)
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
super.update(elapsedTime:elapsedTime, scene:scene)
if let startingTime:TimeInterval = self.startingTime
{
let deltaTime:TimeInterval = elapsedTime - startingTime
if deltaTime > kWait
{
timeOut(scene:scene)
}
}
else
{
startingTime = elapsedTime
}
}
//MARK: private
private func timeOut(scene:ViewGameScene<MOptionWhistlesVsZombies>)
{
guard
let controller:COptionWhistlesVsZombies = scene.controller as? COptionWhistlesVsZombies
else
{
return
}
controller.showGameOver()
}
}
|
ecf81804564af8fc9cefc68e5a32b4f0
| 23.448276 | 99 | 0.569111 | false | false | false | false |
codefellows/sea-d40-iOS
|
refs/heads/master
|
Sample Code/Week2Filtering/ParseSwiftStarterProject/ParseStarterProject/FilterService.swift
|
mit
|
1
|
//
// FilterService.swift
// ParseStarterProject
//
// Created by Bradley Johnson on 8/12/15.
// Copyright (c) 2015 Parse. All rights reserved.
//
import UIKit
class FilterService {
class func sepiaImageFromOriginalImage(original : UIImage, context : CIContext) -> UIImage! {
let image = CIImage(image: original)
let filter = CIFilter(name: "CISepiaTone")
filter.setValue(image, forKey: kCIInputImageKey)
return filteredImageFromFilter(filter, context: context)
}
class func instantImageFromOriginalImage(original : UIImage,context : CIContext) -> UIImage! {
let image = CIImage(image: original)
let filter = CIFilter(name: "CIPhotoEffectInstant")
filter.setValue(image, forKey: kCIInputImageKey)
//set the vector for the colors
return filteredImageFromFilter(filter, context: context)
}
private class func filteredImageFromFilter(filter : CIFilter, context : CIContext) -> UIImage {
let outputImage = filter.outputImage
let extent = outputImage.extent()
let cgImage = context.createCGImage(outputImage, fromRect: extent)
return UIImage(CGImage: cgImage)!
}
}
|
7bfc1db1ef61f5a9e64191c27519d27b
| 28.820513 | 97 | 0.713672 | false | false | false | false |
YaxinCheng/Weather
|
refs/heads/master
|
Weather/WeatherStation.swift
|
apache-2.0
|
1
|
//
// WeatherStation.swift
// Weather
//
// Created by Yaxin Cheng on 2016-07-28.
// Copyright © 2016 Yaxin Cheng. All rights reserved.
//
import Foundation
import CoreLocation.CLLocation
import WeatherKit
struct WeatherStation {
let locationStorage: LocationStorage
fileprivate var weatherSource: WeatherKit.WeatherStation
static var sharedStation = WeatherStation()
var temperatureUnit: TemperatureUnit {
get {
return weatherSource.temperatureUnit
} set {
weatherSource.temperatureUnit = newValue
}
}
var speedUnit: SpeedUnit {
get {
return weatherSource.speedUnit
} set {
weatherSource.speedUnit = newValue
}
}
var distanceUnit: DistanceUnit {
get {
return weatherSource.distanceUnit
} set {
weatherSource.distanceUnit = newValue
}
}
var directionUnit: DirectionUnit {
get {
return weatherSource.directionUnit
} set {
weatherSource.directionUnit = newValue
}
}
fileprivate init() {
weatherSource = WeatherKit.WeatherStation()
locationStorage = LocationStorage()
let userDefault = UserDefaults.standard
temperatureUnit = userDefault.integer(forKey: "Temperature") == 1 ? .fahrenheit : .celsius
speedUnit = userDefault.integer(forKey: "Speed") == 1 ? .kmph : .mph
distanceUnit = userDefault.integer(forKey: "Distance") == 1 ? .km : .mi
directionUnit = userDefault.integer(forKey: "Direction") == 1 ? .degree : .direction
}
func all(_ completion: (Weather?, Error?) -> Void) {
let location: CLLocation?
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {
location = locationStorage.location
} else {
let error = WeatherError.notAuthorized("Location service of the weather app is blocked, please turn it on in the setting app")
completion(nil, error)
return
}
guard let currentLocation = location else {
let error = WeatherError.noAvailableLocation("Location is not available")
completion(nil, error)
return
}
let cityLoader = CityLoader()
cityLoader.locationParse(location: currentLocation) {
guard let JSON = $0, let city = City(from: JSON) else { return }
CityManager.sharedManager.currentCity = city
}
}
func all(for city: City, ignoreCache: Bool = false, completion: @escaping (Weather?, Error?) -> Void) {
weatherSource.weather(city: city.name, province: city.province, country: city.country, ignoreCache: ignoreCache) {
switch $0 {
case .success(let JSON):
guard let weather = Weather(with: JSON) else {
completion(nil, WeatherStationError.weatherLoadError)
return
}
if CityManager.sharedManager.isLocal {
self.saveForWidget(weather)
}
completion(weather, nil)
case .failure(let error):
completion(nil, error)
}
}
}
func forecast(_ completion: @escaping ([Forecast], Error?) -> Void) {
let location: CLLocation?
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse || CLLocationManager.authorizationStatus() == .authorizedAlways {
location = locationStorage.location
} else {
let error = WeatherError.notAuthorized("Location service of the weather app is blocked, please turn it on in the setting app")
completion([], error)
return
}
guard let currentLocation = location else {
let error = WeatherError.noAvailableLocation("Location is not available")
completion([], error)
return
}
weatherSource.forecast(location: currentLocation) {
switch $0 {
case .success(let JSONs):
let forecasts = JSONs.flatMap { Forecast(with: $0) }
if forecasts.count != 0 && CityManager.sharedManager.isLocal {
self.saveForWidget(forecasts.first!)
}
completion(forecasts, nil)
case .failure(let error):
completion([], error)
}
}
}
func forecast(for city: City, completion: @escaping ([Forecast], Error?) -> Void) {
weatherSource.forecast(city: city.name, province: city.province, country: city.country) {
switch $0 {
case .success(let JSONs):
let forecasts = JSONs.flatMap { Forecast(with: $0) }
if forecasts.count != 0 && CityManager.sharedManager.isLocal {
self.saveForWidget(forecasts.first!)
}
completion(forecasts, nil)
case .failure(let error):
completion([], error)
}
}
}
fileprivate func saveForWidget(_ weather: Weather) {
let userDefault = UserDefaults(suiteName: "group.NCGroup")
userDefault?.set(CityManager.sharedManager.currentCity?.name ?? "Local", forKey: "City")
userDefault?.set(weather.temprature, forKey: "Temperature")
userDefault?.set(weather.condition.rawValue, forKey: "Condition")
userDefault?.set(weather.humidity, forKey: "Humidity")
userDefault?.set(weather.condition.iconName, forKey: "Icon")
userDefault?.set(temperatureUnit.description, forKey: "unit")
}
fileprivate func saveForWidget(_ forecast: Forecast) {
let userDefault = UserDefaults(suiteName: "group.NCGroup")
userDefault?.set(forecast.highTemp, forKey: "highTemp")
userDefault?.set(forecast.lowTemp, forKey: "lowTemp")
}
func clearCache() {
weatherSource.clearCache()
}
}
enum WeatherStationError: Error {
case weatherLoadError
}
|
74405eeaf99807a429dd5dad715c7ae1
| 29.904192 | 134 | 0.715559 | false | false | false | false |
AmyKelly56/Assignment3
|
refs/heads/master
|
App/AlbumViewController.swift
|
mit
|
1
|
//
// AlbumViewController.swift
// App
//
// Created by Amy Kelly on 01/03/2017.
// Copyright © 2017 Amy Kelly. All rights reserved.
//
import UIKit
class AlbumViewController: UIViewController {
var album: Album?
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var albumCoverImageView: UIImageView!
@IBOutlet weak var descriptionTextView: UITextView!
func updateUI() {
let albumName = "\((album?.coverImageName)!)"
backgroundImageView?.image = UIImage(named: albumName)
albumCoverImageView?.image = UIImage(named: albumName)
let songList = ((album?.songs)! as NSArray).componentsJoined(by: ", ")
descriptionTextView.text = "\((album?.description)!)\n\n Songs: \n\(songList)"
}
override func viewDidLoad() {
super.viewDidLoad()
updateUI()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
backgroundImageView?.removeFromSuperview()
}
}
|
68cc4864bc00714b28b1e9eb489af55b
| 23.466667 | 86 | 0.619437 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/ViewRelated/QR Login/Coordinators/QRLoginCoordinator.swift
|
gpl-2.0
|
1
|
import UIKit
struct QRLoginCoordinator: QRLoginParentCoordinator {
enum QRLoginOrigin: String {
case menu
case deepLink = "deep_link"
}
let navigationController: UINavigationController
let origin: QRLoginOrigin
init(navigationController: UINavigationController = UINavigationController(), origin: QRLoginOrigin) {
self.navigationController = navigationController
self.origin = origin
configureNavigationController()
}
static func didHandle(url: URL) -> Bool {
guard
let token = QRLoginURLParser(urlString: url.absoluteString).parse(),
let source = UIApplication.shared.leafViewController
else {
return false
}
self.init(origin: .deepLink).showVerifyAuthorization(token: token, from: source)
return true
}
func showCameraScanningView(from source: UIViewController? = nil) {
pushOrPresent(scanningViewController(), from: source)
}
func showVerifyAuthorization(token: QRLoginToken, from source: UIViewController? = nil) {
let controller = QRLoginVerifyAuthorizationViewController()
controller.coordinator = QRLoginVerifyCoordinator(token: token,
view: controller,
parentCoordinator: self)
pushOrPresent(controller, from: source)
}
}
// MARK: - QRLoginParentCoordinator Child Coordinator Interactions
extension QRLoginCoordinator {
func dismiss() {
navigationController.dismiss(animated: true)
}
func didScanToken(_ token: QRLoginToken) {
showVerifyAuthorization(token: token)
}
func scanAgain() {
QRLoginCameraPermissionsHandler().checkCameraPermissions(from: navigationController, origin: origin) {
self.navigationController.setViewControllers([self.scanningViewController()], animated: true)
}
}
func track(_ event: WPAnalyticsEvent) {
self.track(event, properties: nil)
}
func track(_ event: WPAnalyticsEvent, properties: [AnyHashable: Any]? = nil) {
var props: [AnyHashable: Any] = ["origin": origin.rawValue]
guard let properties = properties else {
WPAnalytics.track(event, properties: props)
return
}
props.merge(properties) { (_, new) in new }
WPAnalytics.track(event, properties: props)
}
}
// MARK: - Private
private extension QRLoginCoordinator {
func configureNavigationController() {
navigationController.isNavigationBarHidden = true
navigationController.modalPresentationStyle = .fullScreen
}
func pushOrPresent(_ controller: UIViewController, from source: UIViewController?) {
guard source != nil else {
navigationController.pushViewController(controller, animated: true)
return
}
navigationController.setViewControllers([controller], animated: false)
source?.present(navigationController, animated: true)
}
private func scanningViewController() -> QRLoginScanningViewController {
let controller = QRLoginScanningViewController()
controller.coordinator = QRLoginScanningCoordinator(view: controller, parentCoordinator: self)
return controller
}
}
// MARK: - Presenting the QR Login Flow
extension QRLoginCoordinator {
/// Present the QR login flow starting with the scanning step
static func present(from source: UIViewController, origin: QRLoginOrigin) {
QRLoginCameraPermissionsHandler().checkCameraPermissions(from: source, origin: origin) {
QRLoginCoordinator(origin: origin).showCameraScanningView(from: source)
}
}
/// Display QR validation flow with a specific code, skipping the scanning step
/// and going to the validation flow
static func present(token: QRLoginToken, from source: UIViewController, origin: QRLoginOrigin) {
QRLoginCoordinator(origin: origin).showVerifyAuthorization(token: token, from: source)
}
}
|
5fcff0203d17765af24892e0f200299f
| 34.153846 | 110 | 0.676392 | false | false | false | false |
spacedrabbit/Swift-CatGram
|
refs/heads/master
|
The CatTasticals/CatViewerTableViewCell.swift
|
mit
|
1
|
//
// CatViewerTableViewCell.swift
// The CatTasticals
//
// Created by Louis Tur on 5/11/15.
// Copyright (c) 2015 Louis Tur. All rights reserved.
//
import UIKit
class CatViewerTableViewCell: PFTableViewCell {
@IBOutlet weak var catImageView:UIImageView?
@IBOutlet weak var catNameLabel:UILabel?
@IBOutlet weak var catVotesLabel:UILabel?
@IBOutlet weak var catCreditLabel:UILabel?
@IBOutlet weak var catPawIcon:UIImageView?
var parseObject:PFObject?
override func awakeFromNib() {
let gesture = UITapGestureRecognizer(target: self, action: Selector("onDoubleTap:"))
gesture.numberOfTapsRequired = 2
contentView.addGestureRecognizer(gesture)
catPawIcon?.hidden = true
super.awakeFromNib()
// Initialization code
}
func onDoubleTap(sender: AnyObject){
if (parseObject != nil){
if var votes:Int? = parseObject!.objectForKey("votes") as? Int{
votes!++
parseObject!.setObject(votes!, forKey: "votes")
parseObject!.saveInBackground()
catVotesLabel?.text = "\(votes!) votes"
}
}
catPawIcon?.hidden = false
catPawIcon?.alpha = 1.0
UIView.animateKeyframesWithDuration(1.0, delay: 1.0, options: nil, animations: {
self.catPawIcon?.alpha = 0
}, completion: {
(value:Bool) in
self.catPawIcon?.hidden = true
})
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
1341883a89395fb089898966d588c843
| 27.253968 | 92 | 0.58764 | false | false | false | false |
NeAres/1706C.C.
|
refs/heads/master
|
PDFMakers/PDFMakers/Customize Theme.swift
|
mit
|
1
|
//
// Customize Theme.swift
// PDFMakers
//
// Created by Arendelle on 2017/7/19.
// Copyright © 2017年 AdTech. All rights reserved.
//
import UIKit
func fitFileRead(fileDir:String, theme:Int) {
let themeImage = Bundle.main.path(forResource: "\(theme)", ofType: "png")
let image = UIImage(contentsOfFile: fileDir)!
if Double((image.cgImage?.width)!)/Double((image.cgImage?.height)!) > 2480.0/3508.0 {
let croppedWidth = Double((image.cgImage?.height)!) / 3508.0 * 2480.0
var themedImage = UIImage(contentsOfFile: themeImage!)
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
var croppedCGImage = image.cgImage?.cropping(to: CGRect(x: (Double((image.cgImage?.width)!) - croppedWidth) / 2.0, y: 0, width: croppedWidth, height: Double((image.cgImage?.height)!)))
var croppedUIImage = UIImage(cgImage: croppedCGImage!)
var blackMask = #imageLiteral(resourceName: "ZERO.png")
croppedUIImage.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
blackMask.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
themedImage?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
var finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: fileDir))
} catch {
print(error)
}
imageData = nil
finalDerivedImage = nil
croppedCGImage = nil
themedImage = nil
} else {
let croppedHeight = Double((image.cgImage?.width)!) / 2480.0 * 3508.0
var themedImage = UIImage(contentsOfFile: themeImage!)
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
var croppedCGImage = image.cgImage?.cropping(to: CGRect(x: 0, y: (Double((image.cgImage?.height)!) - croppedHeight) / 2.0, width: Double((image.cgImage?.width)!), height: croppedHeight))
var croppedUIImage = UIImage(cgImage: croppedCGImage!)
var blackMask = #imageLiteral(resourceName: "ZERO.png")
croppedUIImage.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
blackMask.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
themedImage?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
var finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
var imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: fileDir))
} catch {
print(error)
}
imageData = nil
finalDerivedImage = nil
croppedCGImage = nil
themedImage = nil
}
}
func enlongFile(fileInString:String) {
let image = UIImage(contentsOfFile: fileInString)
var image0 = UIImage()
if (image?.cgImage?.width)! > (image?.cgImage?.height)! {
image0 = UIImage(ciImage: (image?.ciImage?.applyingOrientation(Int32(UIImageOrientation.right.rawValue)))!)
}
var imageData = UIImageJPEGRepresentation(image0, 1.0)
do {
try imageData?.write(to: URL(fileURLWithPath: fileInString))
} catch {
print(error)
}
imageData = nil
}
func enlongImage(image:UIImage) -> UIImage {
if (image.cgImage?.width)! > (image.cgImage?.height)! {
return UIImage(cgImage: image.cgImage!, scale: 1.0, orientation: UIImageOrientation.right)
} else {
return image
}
}
func blurImage(cgImage:CGImage) -> UIImage {
return UIImage(cgImage: cgImage)
}
class CustomThemeManager {
func fitDirRead(fileDir:String) { //one for all, read every image, random select font, synth.
var allImages = [String]()
do {
try allImages = FileManager.default.contentsOfDirectory(atPath: fileDir)
} catch {
print(error)
}
let theme = arc4random()%10
let themeImage = Bundle.main.path(forResource: "\(theme)", ofType: "png")
for imageSingle in allImages {
if imageSingle == ".DS_Store" {
continue
}
let image = UIImage(contentsOfFile: (fileDir as NSString).appendingPathComponent(imageSingle))!
if Double((image.cgImage?.width)!)/Double((image.cgImage?.height)!) > 2480.0/3508.0 {
let croppedWidth = Double((image.cgImage?.height)!) / 3508.0 * 2480.0
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
let croppedCGImage = image.cgImage?.cropping(to: CGRect(x: (Double((image.cgImage?.width)!) - croppedWidth) / 2.0, y: 0, width: croppedWidth, height: Double((image.cgImage?.height)!)))
blurImage(cgImage: croppedCGImage!).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(contentsOfFile: themeImage!)?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
let finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print("x")
let imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: (fileDir as NSString).appendingPathComponent(imageSingle)))
} catch {
print(error)
}
} else {
let croppedHeight = Double((image.cgImage?.width)!) / 2480.0 * 3508.0
UIGraphicsBeginImageContext(CGSize(width: 2480, height: 3508))
let croppedCGImage = image.cgImage?.cropping(to: CGRect(x: 0, y: (Double((image.cgImage?.height)!) - croppedHeight) / 2.0, width: Double((image.cgImage?.width)!), height: croppedHeight))
blurImage(cgImage: croppedCGImage!).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(ciImage: CIImage(color: CIColor(red: 0, green: 0, blue: 0, alpha: 0.4))).draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
UIImage(contentsOfFile: themeImage!)?.draw(in: CGRect(x: 0, y: 0, width: 2480, height: 3508))
let finalDerivedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(finalDerivedImage!, 1.0)
do {
try imageData?.write(to: URL.init(fileURLWithPath: (fileDir as NSString).appendingPathComponent(imageSingle)))
} catch {
print(error)
}
}
}
}
}
|
a61886082922602d4501363d2be26471
| 47.746377 | 202 | 0.621674 | false | false | false | false |
WaterReporter/WaterReporter-iOS
|
refs/heads/master
|
WaterReporter/WaterReporter/NewReportGroupsTableViewController.swift
|
agpl-3.0
|
1
|
//
// NewReportGroupsTableViewController.swift
// Water-Reporter
//
// Created by Viable Industries on 11/15/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Alamofire
import Foundation
import Kingfisher
import SwiftyJSON
import UIKit
protocol NewReportGroupSelectorDelegate {
func sendGroups(groups: [String])
}
class NewReportGroupsTableViewController: UITableViewController, UINavigationControllerDelegate {
//
// MARK: @IBOutlets
//
@IBOutlet var viewActivityIndicator: UIView!
@IBAction func refreshTableView(refreshControl: UIRefreshControl) {
// If the view is not already refreshing, send a
// request to load all gorups
if (self.refreshControl?.refreshing == false) {
// Clear all groups currently listed
self.groups = []
// Attempt to load all groups again
self.attemptLoadUserGroups()
}
}
@IBAction func selectGroup(sender: UISwitch) {
if sender.on {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups.append(_organization_id_number)
print("addGroup::finished::tempGroups \(self.tempGroups)")
} else {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups = self.tempGroups.filter() {$0 != _organization_id_number}
print("removeGroup::finished::tempGroups \(self.tempGroups)")
}
}
@IBAction func dismissGroupSelector(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveGroupSelections(sender: UIBarButtonItem) {
if let del = delegate {
del.sendGroups(self.tempGroups)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
//
// MARK: Variables
//
var loadingView: UIView!
var groups: JSON?
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
var delegate: NewReportGroupSelectorDelegate?
var tempGroups: [String]!
//
// MARK: Overrides
//
override func viewDidLoad() {
super.viewDidLoad()
// Show loading symbol while Groups load
self.status("loading")
// Load all of the groups on WaterReporter.org
self.attemptLoadUserGroups()
print("self.tempGroups \(self.tempGroups)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//
// MARK: Statuses
//
func status(statusType: String) {
switch (statusType) {
case "loading":
// Create a view that covers the entire screen
self.loadingView = self.viewActivityIndicator
self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.view.addSubview(self.loadingView)
self.view.bringSubviewToFront(self.loadingView)
// Make sure that the Done button is disabled
self.navigationItem.rightBarButtonItem?.enabled = false
self.navigationItem.leftBarButtonItem?.enabled = false
// Hide table view separators
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
break
case "complete":
// Hide the loading view
self.loadingView.removeFromSuperview()
// Hide table view separators
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
// Make sure that the Done button is disabled
self.navigationItem.rightBarButtonItem?.enabled = true
self.navigationItem.leftBarButtonItem?.enabled = true
break
case "saving":
print("Saving groups page and dismiss modal")
break
case "doneLoadingWithError":
// Hide the loading view
self.loadingView.removeFromSuperview()
default:
break
}
}
//
// MARK: Table Overrides
//
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reportGroupTableViewCell", forIndexPath: indexPath) as! ReportGroupTableViewCell
//
// Assign the organization logo to the UIImageView
//
cell.imageViewGroupLogo.tag = indexPath.row
var organizationImageUrl:NSURL!
if let thisOrganizationImageUrl: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["picture"].string {
organizationImageUrl = NSURL(string: thisOrganizationImageUrl)
}
cell.imageViewGroupLogo.kf_indicatorType = .Activity
cell.imageViewGroupLogo.kf_showIndicatorWhenLoading = true
cell.imageViewGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: {
(image, error, cacheType, imageUrl) in
cell.imageViewGroupLogo.image = image
cell.imageViewGroupLogo.layer.cornerRadius = cell.imageViewGroupLogo.frame.size.width / 2
cell.imageViewGroupLogo.clipsToBounds = true
})
//
// Assign the organization name to the UILabel
//
if let thisOrganizationName: String = self.groups?["features"][indexPath.row]["properties"]["organization"]["properties"]["name"].string {
cell.labelGroupName.text = thisOrganizationName
}
// Assign existing groups to the group field
cell.switchSelectGroup.tag = indexPath.row
if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] {
if self.tempGroups.contains("\(_organization_id_number)") {
cell.switchSelectGroup.on = true
}
else {
cell.switchSelectGroup.on = false
}
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.groups == nil {
return 1
}
return (self.groups?["features"].count)!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72.0
}
//
// MARK: HTTP Request/Response Functionality
//
func buildRequestHeaders() -> [String: String] {
let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken")
return [
"Authorization": "Bearer " + (accessToken! as! String)
]
}
func attemptLoadUserGroups() {
// Set headers
let _headers = self.buildRequestHeaders()
if let userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber {
let GET_GROUPS_ENDPOINT = Endpoints.GET_USER_PROFILE + "\(userId)" + "/groups"
Alamofire.request(.GET, GET_GROUPS_ENDPOINT, headers: _headers, encoding: .JSON).responseJSON { response in
print("response.result \(response.result)")
switch response.result {
case .Success(let value):
print("Request Success: \(value)")
// Assign response to groups variable
self.groups = JSON(value)
// Tell the refresh control to stop spinning
self.refreshControl?.endRefreshing()
// Set status to complete
self.status("complete")
// Refresh the data in the table so the newest items appear
self.tableView.reloadData()
break
case .Failure(let error):
print("Request Failure: \(error)")
// Stop showing the loading indicator
self.status("doneLoadingWithError")
break
}
}
} else {
self.attemptRetrieveUserID()
}
}
func attemptRetrieveUserID() {
// Set headers
let _headers = self.buildRequestHeaders()
Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON)
.responseJSON { response in
switch response.result {
case .Success(let value):
let json = JSON(value)
if let data: AnyObject = json.rawValue {
NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID")
self.attemptLoadUserGroups()
}
case .Failure(let error):
print(error)
}
}
}
}
|
dfc9186bfa8a018c334e607864166b9a
| 32.445946 | 154 | 0.560808 | false | false | false | false |
hyouuu/Centa
|
refs/heads/master
|
Sources/App/Helpers/Helpers.swift
|
mit
|
1
|
//
// Helpers.swift
// Centa
//
// Created by Shawn Gong on 10/31/16.
//
//
import Foundation
import HTTP
/*
public func pr(
_ message: @autoclosure () -> String,
file: String = #file,
line: Int = #line)
{
// #if DEBUG
let msg = message()
print("\(file.lastPathComponent.stringByDeletingPathExtension):\(line): \(msg)")
// #endif
}
*/
// MARK: Short UID
func dbContainsUid(_ uid: String) -> Bool {
do {
if let _ = try Trip.query().filter(Prop.uid, uid).first() {
return true
}
if let _ = try User.query().filter(Prop.uid, uid).first() {
return true
}
} catch {
return false
}
return false
}
// 56 billion possibilities - should be sufficient for global use
public func genUid(len: Int = 6) -> String {
var uid = ""
repeat {
uid = randomStringWithLength(len: len)
} while dbContainsUid(uid)
return uid
}
// It chooses from 26 + 26 + 10 = 62 chars, so 62^len in possible outcomes.
// e.g. 62^8 = 218,340,105,584,896
// 62^16 = 4.76 e+28
public func randomStringWithLength(len: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString = ""
for _ in 0..<len {
let max = letters.count
var idx = 0
// Currently linux doesn't support arc4random https://bugs.swift.org/browse/SR-685
#if os(Linux)
idx = Int(random() % (max + 1))
#else
idx = Int(arc4random_uniform(UInt32(max)))
#endif
let index = letters.index(letters.startIndex, offsetBy: idx)
randomString += String(letters[index])
}
return randomString
}
|
25a7e9c753b18e05a5451fa9243364ea
| 22.186667 | 90 | 0.581369 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Components/SelectionScreen/Cells/SelectionItemTableViewCell.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxSwift
final class SelectionItemTableViewCell: UITableViewCell {
// MARK: - Injected
var presenter: SelectionItemViewPresenter! {
willSet {
disposeBag = DisposeBag()
}
didSet {
guard let presenter = presenter else { return }
switch presenter.thumb {
case .image(let content):
thumbImageView.set(content)
thumbLabel.content = .empty
thumbImageViewWidthConstraint.constant = 40
case .label(let content):
thumbLabel.content = content
thumbImageView.set(.empty)
thumbImageViewWidthConstraint.constant = 40
case .none:
thumbImageViewWidthConstraint.constant = 0.5
}
titleLabel.content = presenter.title
descriptionLabel.content = presenter.description
presenter.selectionImage
.bindAndCatch(to: selectionImageView.rx.content)
.disposed(by: disposeBag)
button.rx.tap
.bindAndCatch(to: presenter.tapRelay)
.disposed(by: disposeBag)
accessibility = presenter.accessibility
}
}
// MARK: - UI Properties
private let thumbImageView = UIImageView()
private let thumbLabel = UILabel()
private let stackView = UIStackView()
private let titleLabel = UILabel()
private let descriptionLabel = UILabel()
private let selectionImageView = UIImageView()
private let button = UIButton()
private var thumbImageViewWidthConstraint: NSLayoutConstraint!
// MARK: - Accessors
private var disposeBag = DisposeBag()
// MARK: - Setup
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
setup()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
presenter = nil
}
// MARK: - Setup
private func setup() {
contentView.addSubview(thumbImageView)
contentView.addSubview(thumbLabel)
contentView.addSubview(stackView)
contentView.addSubview(selectionImageView)
contentView.addSubview(button)
button.addTargetForTouchDown(self, selector: #selector(touchDown))
button.addTargetForTouchUp(self, selector: #selector(touchUp))
button.fillSuperview()
thumbImageView.layout(dimension: .height, to: 40)
thumbImageViewWidthConstraint = thumbImageView.layout(dimension: .width, to: 40)
thumbImageView.layoutToSuperview(.leading, offset: 24)
thumbImageView.layoutToSuperview(.centerY)
thumbImageView.layoutToSuperview(axis: .vertical, offset: 16, priority: .defaultHigh)
thumbLabel.layout(to: .leading, of: thumbImageView)
thumbLabel.layout(to: .trailing, of: thumbImageView)
thumbLabel.layout(to: .top, of: thumbImageView)
thumbLabel.layout(to: .bottom, of: thumbImageView)
stackView.layoutToSuperview(axis: .vertical, offset: 24)
stackView.layout(edge: .leading, to: .trailing, of: thumbImageView, offset: 16)
stackView.layout(edge: .trailing, to: .leading, of: selectionImageView, offset: -16)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 4
stackView.insertArrangedSubview(titleLabel, at: 0)
stackView.insertArrangedSubview(descriptionLabel, at: 1)
titleLabel.verticalContentHuggingPriority = .required
titleLabel.verticalContentCompressionResistancePriority = .required
descriptionLabel.verticalContentHuggingPriority = .required
descriptionLabel.verticalContentCompressionResistancePriority = .required
selectionImageView.layout(size: .init(edge: 20))
selectionImageView.layoutToSuperview(.trailing, offset: -24)
selectionImageView.layoutToSuperview(.centerY)
}
@objc
private func touchDown() {
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.contentView.backgroundColor = .hightlightedBackground
},
completion: nil
)
}
@objc
private func touchUp() {
UIView.animate(
withDuration: 0.2,
delay: 0,
options: .beginFromCurrentState,
animations: {
self.contentView.backgroundColor = .clear
},
completion: nil
)
}
}
|
33e383fa609488041d0c87539d951824
| 32.204082 | 93 | 0.638189 | false | false | false | false |
yotao/YunkuSwiftSDKTEST
|
refs/heads/master
|
YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/Digest.swift
|
mit
|
1
|
//
// Digest.swift
// SwiftDigest
//
// Created by Brent Royal-Gordon on 8/26/14.
// Copyright (c) 2014 Groundbreaking Software. All rights reserved.
//
import Foundation
import CommonCrypto
/// Digest is an immutable object representing a completed digest. Use the Digest
/// object to fetch the completed digest in various forms.
final public class Digest: Equatable, Comparable, Hashable {
/// The digest as a series of bytes.
public let bytes: [UInt8]
/// The digest as an NSData object.
public lazy var data: NSData = {
var temp = self.bytes
return NSData(bytes: &temp, length: temp.count)
}()
/// The digest as a hexadecimal string.
public lazy var hex: String = self.bytes.map { byte in byte.toHex() }.reduce("", +)
/// The digest as a base64-encoded String.
public func base64WithOptions(options: NSData.Base64EncodingOptions) -> String {
return data.base64EncodedString(options: options)
}
/// The digest as an NSData object of base64-encoded bytes.
public func base64DataWithOptions(options: NSData.Base64EncodingOptions) -> NSData {
return data.base64EncodedData(options: options) as NSData
}
/// Creates a Digest from an array of bytes. You should not normally need to
/// call this yourself.
public init(bytes: [UInt8]) {
self.bytes = bytes
}
/// Creates a Digest by copying the algorithm object and finish()ing it. You
/// should not normally need to call this yourself.
public convenience init<Algorithm: AlgorithmType>( algorithm: Algorithm) {
var algorithm = algorithm
self.init(bytes: algorithm.finish())
}
public lazy var hashValue: Int = {
// This should actually be a great hashValue for cryptographic digest
// algorithms, since each bit should contain as much entropy as
// every other.
var value: Int = 0
let usedBytes = self.bytes[0 ..< min(self.bytes.count, MemoryLayout<Int>.size)]
for byte in usedBytes {
value <<= 8
value &= Int(byte)
}
return value
}()
}
/// Tests if two digests are exactly equal.
public func == (lhs: Digest, rhs: Digest) -> Bool {
return lhs.bytes == rhs.bytes
}
/// Tests which digest is "less than" the other. Note that this comparison treats
/// shorter digests as "less than" longer digests; this should only occur if you
/// compare digests created by different algorithms.
public func < (lhs: Digest, rhs: Digest) -> Bool {
if lhs.bytes.count < rhs.bytes.count {
// rhs is a larger number
return true
}
if lhs.bytes.count > rhs.bytes.count {
// lhs is a larger number
return false
}
return lhs.bytes.lexicographicallyPrecedes(rhs.bytes)
}
|
e052db87aa96841c12e680cae05672e9
| 32.290698 | 88 | 0.646525 | false | false | false | false |
chatnuere/whatTheFete
|
refs/heads/master
|
What The Fête/People.swift
|
mit
|
1
|
//
// People.swift
// What The Fête
//
// Created by Pierre-Jean DUGUÉ on 17/12/2014.
// Copyright (c) 2014 Pierre-Jean DUGUÉ. All rights reserved.
//
import UIKit
class People: NSObject {
var people_id:Int!
var user_id:Int!
var event_id:Int!
var mark:String!
var markBibine:String!
var markDance:String!
var markDrague:String!
var markStyle:String!
var markVanne:String!
init( people_id:Int!,user_id:Int!,event_id:Int!, mark:String!, markBibine:String!, markDance:String!, markDrague:String!, markStyle:String!, markVanne:String! ) {
self.people_id = people_id
self.user_id = user_id
self.event_id = event_id
self.mark = mark
self.markBibine = markBibine
self.markDance = markDance
self.markDrague = markDrague
self.markStyle = markStyle
self.markVanne = markVanne
}
}
|
970f94444e8e886df51833d016594798
| 23.815789 | 167 | 0.611877 | false | false | false | false |
TMTBO/TTAMusicPlayer
|
refs/heads/master
|
TTAMusicPlayer/TTAMusicPlayer/Classes/MusicList/Controllers/MusicListViewController.swift
|
mit
|
1
|
//
// MusicListViewController.swift
// MusicPlayer
//
// Created by ys on 16/11/22.
// Copyright © 2016年 TobyoTenma. All rights reserved.
//
import UIKit
import MediaPlayer
class MusicListViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView?.rowHeight = 60 * kSCALEP
cells = ["music_list_cell" : MusicLisbleViewCell.self]
}
func item(at indexPaht : IndexPath) -> MPMediaItem {
return PlayerManager.shared.musics[indexPaht.row]
}
}
// MARK: - UITableViewController
extension MusicListViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return PlayerManager.shared.musics.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseCell = tableView.dequeueReusableCell(withIdentifier: "music_list_cell", for: indexPath)
guard let cell = reuseCell as? MusicLisbleViewCell else {
return reuseCell
}
cell.music = item(at: indexPath)
return cell
}
}
extension MusicListViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let playerVc = PlayerViewController()
playerVc.music = item(at: indexPath)
playerVc.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(playerVc, animated: true)
}
}
|
e3c4fcfcc2db086e4c20b0524a213844
| 30.46 | 109 | 0.696758 | false | false | false | false |
Nefuln/LNAddressBook
|
refs/heads/master
|
LNAddressBook/LNAddressBook/LNAddressBookUI/AddContact/view/LNContactHeaderFieldView.swift
|
mit
|
1
|
//
// LNContactHeaderFieldView.swift
// LNAddressBook
//
// Created by 浪漫满屋 on 2017/8/2.
// Copyright © 2017年 com.man.www. All rights reserved.
//
import UIKit
class LNContactHeaderFieldView: UIView {
public let textField: UITextField = {
let field = UITextField()
field.textColor = UIColor.black
return field
}()
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
layout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func initUI() {
addSubview(textField)
addSubview(line)
}
private func layout() {
textField.snp.makeConstraints { (make) in
make.top.right.equalTo(self)
make.left.equalTo(self.snp.left).offset(10)
make.bottom.equalTo(self.line.snp.top)
}
line.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
}
// MARK:- Private property
private let line: UIView = {
let line = UIView()
line.backgroundColor = UIColor.lightGray
return line
}()
}
|
024b4a7bf04f7086b0f33bf37c164c1d
| 22.240741 | 59 | 0.575299 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/CryptoAssets/Tests/BitcoinKitTests/Models/Accounts/KeyPair/BitcoinKeyPairDeriverTests.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
@testable import BitcoinKit
import TestKit
import XCTest
class BitcoinKeyPairDeriverTests: XCTestCase {
var subject: AnyBitcoinKeyPairDeriver!
override func setUp() {
super.setUp()
subject = AnyBitcoinKeyPairDeriver()
}
override func tearDown() {
subject = nil
super.tearDown()
}
func test_derive_passphrase() throws {
// Arrange
let expectedKeyPair = BitcoinKeyPair(
privateKey: BitcoinPrivateKey(
xpriv: "xprv9yiFNv3Esk6JkJH1xDggWsRVp37cNbd92qEsRVMRC2Z9eJXnCDjUmmwqL6CDMc7iQjdDibUw433staJVz6RENGEeWkciWQ4kYGV5vLgv1PE"
),
xpub: "xpub6ChbnRa8i7ebxnMV4FDgt1NEN4x6n4LzQ4AUDsm2kN68X6rvjm3jKaGKBQCSF4ZQ4T2ctoTtgME3uYb76ZhZ7BLNrtSQM9FXTja2cZMF8Xr"
)
let keyDerivationInput = BitcoinKeyDerivationInput(
mnemonic: MockWalletTestData.Bip39.mnemonic,
passphrase: MockWalletTestData.Bip39.passphrase
)
// Act
guard let result = try? subject.derive(input: keyDerivationInput).get() else {
XCTFail("Derivation failed")
return
}
// Assert
XCTAssertEqual(result, expectedKeyPair)
}
func test_derive_empty_passphrase() throws {
// Arrange
let expectedKeyPair = BitcoinKeyPair(
privateKey: BitcoinPrivateKey(
xpriv: "xprv9zDrURuhy9arxJ4tWiwnBXvcyNT88wvnSitdTnu3x6571yWTfqgyjY6TqVqhG26fy39JPdzb1VX6zXinGQtHi3Wys3qPwdkatg1KSWM2uHs"
),
xpub: "xpub6DDCswSboX9AAn9MckUnYfsMXQHcYQedowpEGBJfWRc5tmqcDP1EHLQwgmXFmkYvfhNigZqUHdWJUpf6t3ufdYrdUCHUrZUhgKj3diWoSm6"
)
let keyDerivationInput = BitcoinKeyDerivationInput(
mnemonic: MockWalletTestData.Bip39.mnemonic,
passphrase: MockWalletTestData.Bip39.emptyPassphrase
)
// Act
guard let result = try? subject.derive(input: keyDerivationInput).get() else {
XCTFail("Derivation failed")
return
}
// Assert
XCTAssertEqual(result, expectedKeyPair)
}
}
|
93f7a2df605ec773533fefd23365ae9f
| 31.893939 | 136 | 0.672041 | false | true | false | false |
EventsNetwork/Source
|
refs/heads/master
|
LetsTravel/TravelClient.swift
|
apache-2.0
|
1
|
//
// TravelClient.swift
// LetsTravel
//
// Created by TriNgo on 4/13/16.
// Copyright © 2016 TriNgo. All rights reserved.
//
import UIKit
import AFNetworking
let TravelClientSharedInstance = TravelClient()
class TravelClient: NSObject {
let BASE_URL = "http://school.naptiengame.net/user"
let functionSessionManager: AFHTTPSessionManager
class var sharedInstance: TravelClient {
get {
return TravelClientSharedInstance;
}
}
override init() {
self.functionSessionManager = AFHTTPSessionManager(baseURL: NSURL(string: BASE_URL))
self.functionSessionManager.requestSerializer = AFJSONRequestSerializer()
self.functionSessionManager.responseSerializer = AFJSONResponseSerializer()
}
private func fetchData(dictionary: NSDictionary) -> NSDictionary?
{
let statusCode = dictionary["code"] as! Int
if (statusCode != -1) {
return dictionary["data"] as? NSDictionary
}else {
return nil
}
}
private func fetchDataWithArray(dictionary: NSDictionary) -> [NSDictionary]?
{
let statusCode = dictionary["code"] as! Int
if (statusCode != -1) {
return dictionary["data"] as? [NSDictionary]
}else {
return nil
}
}
private func generateError(response: AnyObject) -> NSError {
let errorCode = (response as! NSDictionary)["code"] as! Int
let errorMessage = (response as! NSDictionary)["msg"] as! String
let error = NSError(domain: self.BASE_URL, code: errorCode, userInfo: ["error": errorMessage])
return error
}
// Login
func login(facebookId: String, fullName: String, avatarUrl: String, success: (User) -> (), failure: (NSError) -> ()) {
let postData = ["facebook_id":facebookId, "full_name":fullName, "avatar_url":avatarUrl]
let params = ["command": "U_LOGIN", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let userDictionary = self.fetchData(response as! NSDictionary)
if (userDictionary != nil) {
let user = User(dictionary: userDictionary!)
User.currentUser = user
success(user)
}else{
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
// Logout
func logout() {
User.currentUser = nil
NSNotificationCenter.defaultCenter().postNotificationName(User.userDidLogoutNotification, object: nil)
}
// Search places with category and province
func searchPlaceViaCategoryAndProvince(provinceId: Int, categoryId: String, placeName: String, success: ([Place]) -> (), failure: (NSError) -> ()) {
let postData = ["province_id":provinceId, "category_id":categoryId, "place_name":placeName]
let params = ["command": "U_PLACE_SEARCH_CATEGORY", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let placesDictionary = self.fetchDataWithArray(response as! NSDictionary)
if (placesDictionary != nil) {
let places = Place.getPlaces(placesDictionary!)
success(places)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get province list
func getProvinces(success: ([Province]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_PROVINCE_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let provinceDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (provinceDictionaries != nil) {
let provinces = Province.getProvinces(provinceDictionaries!)
success(provinces)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get categories list
func getCategories(success: ([Category]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_CATEGORY_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let categoryDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (categoryDictionaries != nil) {
let categories = Category.getCategories(categoryDictionaries!)
success(categories)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get hot tours
func getHotTours(success: ([Tour]) -> (), failure: (NSError) -> ()) {
let params = ["command": "U_TOUR_HOT_LIST", "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let tourDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (tourDictionaries != nil) {
let tours = Tour.getTours(tourDictionaries!)
success(tours)
} else {
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
// Get tour detail
func getTourDetail(tourId: Int, success: (Tour) -> (), failure: (NSError) -> ()) {
let postData = ["tour_id": tourId]
let params = ["command": "U_TOUR_DETAIL", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let tourDictionary = self.fetchData(response as! NSDictionary)
if (tourDictionary != nil) {
let tour = Tour(dictionary: tourDictionary!)
success(tour)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
// Get list my tour
func getMyTours(success: ([Tour]) -> (), failure: (NSError) -> ()) {
let token = User.currentUser?.token as! String
let params = ["command": "U_TOUR_MYSELF", "token" : token, "data" : ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task: NSURLSessionDataTask, response: AnyObject?) -> Void in
let tourDictionaries = self.fetchDataWithArray(response as! NSDictionary)
if (tourDictionaries != nil) {
let tours = Tour.getTours(tourDictionaries!)
success(tours)
} else {
failure(self.generateError(response!))
}
}, failure: { (task: NSURLSessionDataTask?, error: NSError) -> Void in
failure(error)
})
}
func createTour(tour: Tour, success: (Tour) -> (), failure: (NSError) -> ()) {
var postData = [String: AnyObject]()
postData["tour"] = ["start_time": tour.startTime ?? 0, "description": tour.desc ?? "", "province_id": tour.provinceId ?? 0]
var events = [[String: AnyObject]]()
for event in tour.tourEvents! {
events.append(["day" : event.dayOrder ?? 1, "place_id": event.place.placeId ?? 0])
}
postData["tour_events"] = events
let params = ["command": "U_TOUR_ADD", "data" : postData, "token": User.currentUser?.token ?? ""]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let responseDictionary = self.fetchData(response as! NSDictionary)
if let responseDictionary = responseDictionary {
if let tourId = responseDictionary["tour_id"] as? String {
tour.tourId = Int(tourId)
}
success(tour)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
func generateShareUrl(tour: Tour, success: (FBHostLink) -> (), failure: (NSError) -> ()) {
let postData = ["tour_id": tour.tourId ?? 0]
let params = ["command": "U_TOUR_GET_HOST_LINK", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let responseDictionary = self.fetchData(response as! NSDictionary)
if let responseDictionary = responseDictionary {
let hostLink = FBHostLink(dictionary: responseDictionary)
success(hostLink)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
func getPlaceDetail(placeId: Int, success: (Place) -> (), failure: (NSError) -> ()) {
let postData = ["place_id": placeId]
let params = ["command": "U_PLACE_DETAIL", "data" : postData]
self.functionSessionManager.POST(BASE_URL, parameters: params, progress: nil, success: { (task:NSURLSessionDataTask, response:AnyObject?) -> Void in
let placeDictionary = self.fetchData(response as! NSDictionary)
if (placeDictionary != nil) {
let place = Place(dictionary: placeDictionary!)
success(place)
} else {
failure(self.generateError(response!))
}
}, failure: { (task:NSURLSessionDataTask?, error:NSError) -> Void in
failure(error)
})
}
}
|
57111050425ac2ab071eba44647bd268
| 38.151625 | 158 | 0.583956 | false | false | false | false |
cp3hnu/PrivacyManager
|
refs/heads/master
|
PrivacyManagerDemo/PrivacyManagerDemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// PrivacyManagerDemo
//
// Created by CP3 on 17/4/13.
// Copyright © 2017年 CP3. All rights reserved.
//
import UIKit
import RxSwift
import CoreLocation
import PrivacyManager
import PrivacyPhoto
import PrivacyCamera
import PrivacyMicrophone
import PrivacyContact
import PrivacyLocation
import PrivacySpeech
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - 获取状态
let locationStatus = PrivacyManager.shared.locationStatus
print("locationStatus = ", locationStatus)
let cameraStatus = PrivacyManager.shared.cameraStatus
print("cameraStatus = ", cameraStatus)
let phoneStatus = PrivacyManager.shared.photoStatus
print("phoneStatus = ", phoneStatus)
let microphoneStatus = PrivacyManager.shared.microphoneStatus
print("microphoneStatus = ", microphoneStatus)
let contactStatus = PrivacyManager.shared.contactStatus
print("contactStatus = ", contactStatus)
// MARK: - UIViewController 请求权限 - 使用 UIViewcontroller 扩展方法 `privacyPermission`
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
PrivacyManager.shared.locationPermission(presenting: self, always: false, authorized: {
self.present("定位服务已授权")
})
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
_ = PrivacyManager.shared.rxLocations.subscribe(onNext: { locations in
print("locations", locations)
}, onError: { error in
print("error", error)
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
})
}
view.backgroundColor = UIColor.white
let button1 = UIButton()
button1.setTitle("相机", for: .normal)
button1.setTitleColor(UIColor.black, for: .normal)
_ = button1.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.cameraPermission(presenting: self, authorized: {
self.present("相机已授权")
})
}
)
let button2 = UIButton()
button2.setTitle("照片", for: .normal)
button2.setTitleColor(UIColor.black, for: .normal)
_ = button2.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.photoPermission(presenting: self, authorized: {
self.present("照片已授权")
})
}
)
let button3 = UIButton()
button3.setTitle("麦克风", for: .normal)
button3.setTitleColor(UIColor.black, for: .normal)
_ = button3.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.microphonePermission(presenting: self, authorized: {
self.present("麦克风已授权")
})
}
)
let button4 = UIButton()
button4.setTitle("语音识别", for: .normal)
button4.setTitleColor(UIColor.black, for: .normal)
_ = button4.rx.tap.subscribe(
onNext: { [weak self] _ in
guard let self = self else { return }
PrivacyManager.shared.speechPermission(presenting: self, authorized: {
self.present("语音识别已授权")
})
}
)
// MARK: - 使用 PrivacyManager 的 observable
let button5 = UIButton()
button5.setTitle("通讯录", for: .normal)
button5.setTitleColor(UIColor.black, for: .normal)
_ = button5.rx.tap
.flatMap{ () -> Observable<Bool> in
return PrivacyManager.shared.rxContactPermission
}
.subscribe(
onNext: { [weak self] granted in
if !granted {
self?.presentPrivacySetting(type: PermissionType.contact)
} else {
self?.present("通讯录已授权")
}
}
)
[button1, button2, button3, button4, button5].forEach { button in
button.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(button)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[button]-15-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button" : button]))
}
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-80-[button1(==40)]-40-[button2(==40)]-40-[button3(==40)]-40-[button4(==40)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: ["button1" : button1, "button2" : button2, "button3" : button3, "button4" : button4]))
button5.topAnchor.constraint(equalTo: button4.bottomAnchor, constant: 40).isActive = true
}
}
private extension ViewController {
func present(_ content: String) {
let alert = UIAlertController(title: content, message: "", preferredStyle: UIAlertController.Style.alert)
let action = UIAlertAction(title: "确定", style: UIAlertAction.Style.default, handler: nil)
alert.addAction(action)
alert.preferredAction = action
present(alert, animated: true, completion: nil)
}
}
|
bad0f79da87a800bbd0e40db9f5df819
| 35.928571 | 323 | 0.573061 | false | false | false | false |
haranicle/AlcatrazTour
|
refs/heads/master
|
AlcatrazTour/GithubClient.swift
|
mit
|
1
|
//
// GithubClient.swift
// AlcatrazTour
//
// Copyright (c) 2015年 haranicle. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Realm
import OAuthSwift
import SVProgressHUD
import JDStatusBarNotification
class GithubClient: NSObject {
// MARK: - Const
let alcatrazPackagesUrl = "https://raw.githubusercontent.com/supermarin/alcatraz-packages/master/packages.json"
let githubRepoUrl = "https://github.com"
let githubRepoApiUrl = "https://api.github.com/repos"
let githubStarApiUrl = "https://api.github.com/user/starred/"
let appScheme = "alcatraztour:"
// MARK: - Status
var isLoading = false
var loadCompleteCount:Int = 0
// MARK: - Create URL
func createRepoDetailUrl(repoUrl:String) -> String {
// create api url
var repoDetailUrl:String = repoUrl.stringByReplacingOccurrencesOfString(githubRepoUrl, withString: githubRepoApiUrl, options: [], range: nil)
// remove last "/"
if repoDetailUrl.hasSuffix("/") {
repoDetailUrl = repoDetailUrl[repoDetailUrl.startIndex..<repoDetailUrl.endIndex.advancedBy(-1)]
}
// remove last ".git"
if repoDetailUrl.hasSuffix(".git") {
repoDetailUrl = repoDetailUrl[repoDetailUrl.startIndex..<repoDetailUrl.endIndex.advancedBy(-4)]
}
return repoDetailUrl
}
// MARK: - OAuth
let githubOauthTokenKey = "githubTokenKey"
func isSignedIn()->Bool {
if let token = NSUserDefaults.standardUserDefaults().stringForKey(githubOauthTokenKey) {
return true
}
return false
}
func signOut() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(githubOauthTokenKey)
}
func requestOAuth(onSucceed:Void->Void, onFailed:NSError -> Void ){
let oauthswift = OAuth2Swift(
consumerKey: GithubKey["consumerKey"]!,
consumerSecret: GithubKey["consumerSecret"]!,
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
let oAuthTokenKey = githubOauthTokenKey
oauthswift.authorize_url_handler = LoginWebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "\(appScheme)//oauth-callback/github")!, scope: "user,repo,public_repo", state: "GITHUB", success: {
credential, response, parameters in
NSUserDefaults.standardUserDefaults().setObject(credential.oauth_token, forKey:oAuthTokenKey)
onSucceed()
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func oAuthToken() -> String? {
let token = NSUserDefaults.standardUserDefaults().stringForKey(githubOauthTokenKey)
if token == nil {
JDStatusBarNotification.showWithStatus("Not signed in.", dismissAfter: 3, styleName: JDStatusBarStyleError)
}
return token
}
// MARK: - Request
func requestPlugins(onSucceed:[Plugin] -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
Alamofire
.request(.GET, alcatrazPackagesUrl)
.validate(statusCode: 200..<400)
.responseJSON { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if let aResponseData: AnyObject = response.data {
var plugins:[Plugin] = []
let jsonData = JSON(aResponseData)
let jsonPlugins = jsonData["packages"]["plugins"].array
if let count = jsonPlugins?.count {
for i in 0 ..< count {
if let pluginParams = jsonPlugins?[i].object as? NSDictionary {
let plugin = Plugin()
plugin.setParams(pluginParams)
plugins.append(plugin)
}
}
}
onSucceed(plugins)
} else {
onFailed(response.request!, response.response, response.data, nil)
}
}
}
func requestRepoDetail(token:String, plugin:Plugin, onSucceed:(Plugin?, NSDictionary) -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
Alamofire
.request(Method.GET, createRepoDetailUrl(plugin.url), parameters: ["access_token": token])
.validate(statusCode: 200..<400)
.responseJSON { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if let aResponseData: AnyObject = response.data {
let jsonData = JSON(aResponseData)
if let pluginDetail = jsonData.object as? NSDictionary {
onSucceed(plugin, pluginDetail)
}
} else {
onFailed(response.request!, response.response, response.data, nil)
}
}
}
// MARK: - Processing Flow
func reloadAllPlugins(onComplete:NSError?->Void) {
if(isLoading) {
print("NOW LOADING!!")
return
}
print("START LOADING!!")
SVProgressHUD.showWithStatus("Loading list", maskType: SVProgressHUDMaskType.Black)
isLoading = true
loadCompleteCount = 0
// loading plugin list
let onSucceedRequestingPlugins = {[weak self] (plugins:[Plugin]) -> Void in
print("PLUGIN LIST LOAD COMPLETE!!")
SVProgressHUD.dismiss()
SVProgressHUD.showProgress(0, status: "Loading data", maskType: SVProgressHUDMaskType.Black)
// Dispatch Group
let group = dispatch_group_create()
var successCount = 0
// loading plugin details
let onSucceedRequestingRepoDetail = {[weak self] (plugin:Plugin?, pluginDetail:NSDictionary) -> Void in
plugin?.setDetails(pluginDetail)
if let p = plugin {
p.save()
}
successCount++
self?.updateProgress(plugins.count)
dispatch_group_leave(group)
}
let onFailed = {[weak self] (request:NSURLRequest, response:NSHTTPURLResponse?, responseData:AnyObject?, error:NSError?) -> Void in
self?.updateProgress(plugins.count)
dispatch_group_leave(group)
}
// start writing
RLMRealm.defaultRealm().beginWriteTransaction()
Plugin.deleteAll()
let token = self?.oAuthToken()
if token == nil {
return
}
for plugin in plugins {
dispatch_group_enter(group)
self?.requestRepoDetail(token!, plugin: plugin, onSucceed: onSucceedRequestingRepoDetail, onFailed: onFailed)
}
dispatch_group_notify(group, dispatch_get_main_queue(), {
// Yay!!! All done!!!
SVProgressHUD.dismiss()
self?.isLoading = false
do {
try RLMRealm.defaultRealm().commitWriteTransaction()
} catch {
fatalError()
}
print("successCount = \(successCount)")
print("plugins.count = \(plugins.count)")
onComplete(nil)
})
}
let onFailed = {[weak self] (request:NSURLRequest, response:NSHTTPURLResponse?, responseData:AnyObject?, error:NSError?) -> Void in
print("request = \(request)")
print("response = \(response)")
print("responseData = \(responseData)")
print("error = \(error?.description)")
self?.isLoading = false
SVProgressHUD.dismiss()
onComplete(error)
}
requestPlugins(onSucceedRequestingPlugins, onFailed: onFailed)
}
func updateProgress(pluginsCount:Int) {
self.loadCompleteCount++
SVProgressHUD.showProgress(Float(self.loadCompleteCount) / Float(pluginsCount) , status: "Loading data", maskType: SVProgressHUDMaskType.Black)
}
// MARK: - Staring
func checkIfStarredRepository(token:String, owner:String, repositoryName:String, onSucceed:(Bool) -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Request {
let apiUrl = githubStarApiUrl + owner + "/" + repositoryName
return Alamofire
.request(Method.GET, apiUrl, parameters: ["access_token": token])
.validate(statusCode: 204...404)
.responseString { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
if(response.response?.statusCode==204){
onSucceed(true)
return
}
if(response.response?.statusCode==404){
onSucceed(false)
return
}
onFailed(response.request!, response.response, response.data, nil)
}
}
func starRepository(token:String, isStarring:Bool, owner:String, repositoryName:String, onSucceed:() -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
let apiUrl = githubStarApiUrl + owner + "/" + repositoryName
let method = isStarring ? Method.PUT : Method.DELETE
Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = [
"Content-Length" : "0",
"Authorization" : "token \(token)"
]
Alamofire
.request(method, apiUrl, parameters: nil)
.validate(statusCode: 200..<400)
.responseString { response in
if let aError = response.result.error {
onFailed(response.request!, response.response, response.data, aError)
return
}
onSucceed()
}
}
func checkAndStarRepository(token:String, isStarring:Bool, owner:String, repositoryName:String, onSucceed:() -> Void, onFailed:(NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void){
checkIfStarredRepository(token, owner: owner, repositoryName: repositoryName, onSucceed: { (isStarred) -> Void in
if isStarring && isStarred {
JDStatusBarNotification.showWithStatus("Already starred.", dismissAfter: 3, styleName: JDStatusBarStyleWarning)
return
} else if !isStarring && !isStarred {
JDStatusBarNotification.showWithStatus("Already unstarred.", dismissAfter: 3, styleName: JDStatusBarStyleWarning)
return;
}
self.starRepository(token, isStarring: isStarring, owner: owner, repositoryName: repositoryName, onSucceed: { (responseObject) -> Void in
let action = isStarring ? "starred" : "unstarred"
JDStatusBarNotification.showWithStatus("Your \(action) \(repositoryName).", dismissAfter: 3, styleName: JDStatusBarStyleSuccess)
onSucceed()
}, onFailed: onFailed)
}, onFailed: onFailed)
}
}
|
f822d597a37396d29e0936350cd8bf09
| 37.924528 | 199 | 0.552997 | false | false | false | false |
Eonil/Editor
|
refs/heads/develop
|
Editor4/FileNavigatorMenuPalette.swift
|
mit
|
1
|
//
// FileNavigatorMenuPalette.swift
// Editor4
//
// Created by Hoon H. on 2016/05/25.
// Copyright © 2016 Eonil. All rights reserved.
//
import AppKit
struct FileNavigatorMenuPalette {
let context = MenuItemController(type: MenuItemTypeID.Submenu(.FileNavigator(.ContextMenuRoot)))
let showInFinder = menuItemWithAction(.showInFinder)
let showInTerminal = menuItemWithAction(.showInTerminal)
let createNewFolder = menuItemWithAction(.createNewFolder)
let createNewFile = menuItemWithAction(.createNewFile)
let delete = menuItemWithAction(.delete)
init() {
// Configure hierarchy here if needed.
context.subcontrollers = [
showInFinder,
showInTerminal,
separator(),
createNewFolder,
createNewFile,
separator(),
delete,
]
}
}
private func separator() -> MenuItemController {
return MenuItemController(type: .Separator)
}
//private func submenuContainerWithTitle(mainMenuSubmenuID: MainMenuSubmenuID) -> MenuItemController {
// let submenuID = FileNavigator(mainMenuSubmenuID)
// return MenuItemController(type: .Submenu(submenuID))
//}
private func menuItemWithAction(mainMenuCommand: FileNavigatorMenuCommand) -> MenuItemController {
let command = MenuCommand.fileNavigator(mainMenuCommand)
return MenuItemController(type: .MenuItem(command))
}
|
b053fc8bce5ab700fe3a616b1e1830b5
| 34.883721 | 126 | 0.650032 | false | false | false | false |
dschwartz783/MandelbrotSet
|
refs/heads/master
|
Sources/MandelbrotSet/main.swift
|
gpl-3.0
|
1
|
//
// main.swift
// MandelbrotSet
//
// Created by David Schwartz on 6/4/17.
// Copyright © 2017 DDS Programming. All rights reserved.
//
import Cocoa
class MandelbrotDrawClass {
let maxIterations = 50000
var Ox: Float80 = -2 {
willSet {
print("old Ox: \(Ox)")
}
didSet {
print("new Ox: \(Ox)")
}
}
var Oy: Float80 = -2 {
willSet {
print("old Oy: \(Oy)")
}
didSet {
print("new Oy: \(Oy)")
}
}
var Lx: Float80 = 4 {
willSet {
print("old Lx: \(Lx)")
}
didSet {
print("new Lx: \(Lx)")
}
}
var Ly: Float80 = 4 {
willSet {
print("old Ly: \(Ly)")
}
didSet {
print("new Ly: \(Ly)")
}
}
// let height = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
// let width = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
let rect: CGRect
var randomColorList: [Int: NSColor] = [:]
let saveThread = DispatchQueue(label: "savethread")
let cgContext = CGDisplayGetDrawingContext(CGMainDisplayID())!
let newContext: NSGraphicsContext
let drawQueue = DispatchQueue(label: "drawQueue")
init() {
for i in 0...maxIterations {
self.randomColorList[i] = NSColor(
calibratedRed: CGFloat(arc4random()) / CGFloat(UInt32.max),
green: CGFloat(arc4random()) / CGFloat(UInt32.max),
blue: CGFloat(arc4random()) / CGFloat(UInt32.max),
alpha: CGFloat(arc4random()) / CGFloat(UInt32.max))
}
newContext = NSGraphicsContext(cgContext: cgContext, flipped: false)
rect = CGDisplayBounds(CGMainDisplayID())
self.Ox = -(Lx / 2) * Float80(rect.width) / Float80(rect.height)
self.Lx = Ly * Float80(rect.width) / Float80(rect.height)
NSGraphicsContext.current = newContext
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "draw"), object: nil, queue: nil) { (aNotification) in
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomDec"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 2
self.Oy -= self.Ly / 2
self.Lx *= 2
self.Ly *= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomInc"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.Oy += self.Ly / 4
self.Lx /= 2
self.Ly /= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecX"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncX"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecY"), object: nil, queue: nil) { (aNotification) in
self.Oy -= self.Ly / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncY"), object: nil, queue: nil) { (aNotification) in
self.Oy += self.Ly / 4
self.draw()
}
}
func draw() {
self.drawQueue.async {
autoreleasepool {
let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes:nil,
pixelsWide:Int(self.rect.width),
pixelsHigh:Int(self.rect.height),
bitsPerSample:8,
samplesPerPixel:4,
hasAlpha:true,
isPlanar:false,
colorSpaceName:NSColorSpaceName.deviceRGB,
bitmapFormat:NSBitmapImageRep.Format.alphaFirst,
bytesPerRow:0,
bitsPerPixel:0
)!
let context = NSGraphicsContext(bitmapImageRep: offscreenRep)!
// NSGraphicsContext.current = context
let image = context.cgContext.makeImage()!
let nsImage = NSImage(cgImage: image, size: self.rect.size)
var rawTiff = nsImage.tiffRepresentation!
let bytes = rawTiff.withUnsafeMutableBytes { $0 }
DispatchQueue.concurrentPerform(iterations: Int(self.rect.width)) { (x) in
for y in 0..<Int(self.rect.height) {
let calcX = self.Ox + Float80(x) / Float80(self.rect.width) * self.Lx
let calcY = self.Oy + Float80(y) / Float80(self.rect.height) * self.Ly
let iterations = Mandelbrot.calculate(
x: calcX,
y: calcY,
i: self.maxIterations
)
let color = self.randomColorList[iterations]!
bytes[8 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.redComponent * CGFloat(UInt8.max))
bytes[9 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.greenComponent * CGFloat(UInt8.max))
bytes[10 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.blueComponent * CGFloat(UInt8.max))
bytes[11 + 4 * (y * Int(self.rect.width) + x)] = 0xff
}
}
let resultImage = NSImage(data: rawTiff)
DispatchQueue.main.sync {
resultImage?.draw(in: self.rect)
}
}
}
}
}
CGDisplayCapture(CGMainDisplayID())
let drawObject = MandelbrotDrawClass()
drawObject.draw()
RunLoop.current.add(generateKeyTracker(), forMode: .default)
RunLoop.current.run()
|
6f5298abb431ac657f326acb6cd2d54d
| 34.259459 | 146 | 0.503143 | false | false | false | false |
PureSwift/Bluetooth
|
refs/heads/master
|
Sources/BluetoothHCI/HCILEReadResolvingListSize.swift
|
mit
|
1
|
//
// HCILEReadResolvingListSize.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/15/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// LE Read Resolving List Size Command
///
/// This command is used to read the total number of address translation
/// entries in the resolving list that can be stored in the Controller.
func lowEnergyReadResolvingListSize(timeout: HCICommandTimeout = .default) async throws -> UInt8 {
let value = try await deviceRequest(HCILEReadResolvingListSize.self,
timeout: timeout)
return value.resolvingListSize
}
}
// MARK: - Return parameter
/// LE Read Resolving List Size Command
///
/// The command is used to read the total number of address translation entries
/// in the resolving list that can be stored in the Controller.
/// Note: The number of entries that can be stored is not fixed and
/// the Controller can change it at any time (e.g. because the memory
/// used to store the list can also be used for other purposes).
@frozen
public struct HCILEReadResolvingListSize: HCICommandReturnParameter {
public static let command = HCILowEnergyCommand.readResolvedListSize //0x002A
public static let length: Int = 1
public let resolvingListSize: UInt8 //Resolving_List_Size
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
self.resolvingListSize = data[0]
}
}
|
59e4fc7de15864eff6aecbcb04b94871
| 30.018868 | 102 | 0.677616 | false | false | false | false |
avito-tech/Marshroute
|
refs/heads/master
|
Example/NavigationDemo/VIPER/Advertisement/View/AdvertisementViewController.swift
|
mit
|
1
|
import UIKit
import Marshroute
final class AdvertisementViewController: BasePeekAndPopViewController, AdvertisementViewInput {
// MARK: - Private properties
private let advertisementView = AdvertisementView()
private let peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable
// MARK: - Init
init(
peekAndPopStateViewControllerObservable: PeekAndPopStateViewControllerObservable,
peekAndPopUtility: PeekAndPopUtility)
{
self.peekAndPopStateViewControllerObservable = peekAndPopStateViewControllerObservable
super.init(peekAndPopUtility: peekAndPopUtility)
subscribeForPeekAndPopStateChanges()
}
// MARK: - Lifecycle
override func loadView() {
view = advertisementView
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "recursion".localized, // to Recursion module
style: .plain,
target: self,
action: #selector(onRecursionButtonTap(_:))
)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
advertisementView.defaultContentInsets = defaultContentInsets
}
// MARK: - BasePeekAndPopViewController
override var peekSourceViews: [UIView] {
return advertisementView.peekSourceViews + [navigationController?.navigationBar].compactMap { $0 }
}
@available(iOS 9.0, *)
override func startPeekWith(
previewingContext: UIViewControllerPreviewing,
location: CGPoint)
{
if advertisementView.peekSourceViews.contains(previewingContext.sourceView) {
if let peekData = advertisementView.peekDataAt(
location: location,
sourceView: previewingContext.sourceView)
{
previewingContext.sourceRect = peekData.sourceRect
peekData.viewData.onTap()
}
} else {
super.startPeekWith(
previewingContext: previewingContext,
location: location
)
}
}
// MARK: - Private
@objc private func onRecursionButtonTap(_ sender: UIBarButtonItem) {
onRecursionButtonTap?(sender)
}
private func subscribeForPeekAndPopStateChanges() {
peekAndPopStateViewControllerObservable.addObserver(
disposableViewController: self,
onPeekAndPopStateChange: { [weak self] peekAndPopState in
switch peekAndPopState {
case .inPeek:
self?.onPeek?()
case .popped:
self?.onPop?()
case .interrupted:
break
}
}
)
}
// MARK: - AdvertisementViewInput
@nonobjc func setTitle(_ title: String?) {
self.title = title
}
func setPatternAssetName(_ assetName: String?) {
advertisementView.setPatternAssetName(assetName)
}
func setPlaceholderAssetName(_ assetName: String?) {
advertisementView.setPlaceholderAssetName(assetName)
}
func setBackgroundRGB(_ rgb: (red: Double, green: Double, blue: Double)?) {
advertisementView.setBackgroundRGB(rgb)
}
func setSimilarSearchResults(_ searchResults: [SearchResultsViewData]) {
advertisementView.setSimilarSearchResults(searchResults)
}
func setSimilarSearchResultsHidden(_ hidden: Bool) {
advertisementView.setSimilarSearchResultsHidden(hidden)
}
var onRecursionButtonTap: ((_ sender: AnyObject) -> ())?
var onPeek: (() -> ())?
var onPop: (() -> ())?
}
|
4b4f213f64cef21f5661aae4d6b238d7
| 30.719008 | 106 | 0.621678 | false | false | false | false |
groue/GRDB.swift
|
refs/heads/master
|
Tests/CombineExpectations/Recorder.swift
|
mit
|
1
|
#if canImport(Combine)
import Combine
import XCTest
/// A Combine subscriber which records all events published by a publisher.
///
/// You create a Recorder with the `Publisher.record()` method:
///
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// You can build publisher expectations from the Recorder. For example:
///
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public class Recorder<Input, Failure: Error>: Subscriber {
public typealias Input = Input
public typealias Failure = Failure
private enum RecorderExpectation {
case onInput(XCTestExpectation, remainingCount: Int)
case onCompletion(XCTestExpectation)
var expectation: XCTestExpectation {
switch self {
case let .onCompletion(expectation):
return expectation
case let .onInput(expectation, remainingCount: _):
return expectation
}
}
}
/// The recorder state
private enum State {
/// Publisher is not subscribed yet. The recorder may have an
/// expectation to fulfill.
case waitingForSubscription(RecorderExpectation?)
/// Publisher is subscribed. The recorder may have an expectation to
/// fulfill. It keeps track of all published elements.
case subscribed(Subscription, RecorderExpectation?, [Input])
/// Publisher is completed. The recorder keeps track of all published
/// elements and completion.
case completed([Input], Subscribers.Completion<Failure>)
var elementsAndCompletion: (elements: [Input], completion: Subscribers.Completion<Failure>?) {
switch self {
case .waitingForSubscription:
return (elements: [], completion: nil)
case let .subscribed(_, _, elements):
return (elements: elements, completion: nil)
case let .completed(elements, completion):
return (elements: elements, completion: completion)
}
}
var recorderExpectation: RecorderExpectation? {
switch self {
case let .waitingForSubscription(exp), let .subscribed(_, exp, _):
return exp
case .completed:
return nil
}
}
}
private let lock = NSLock()
private var state = State.waitingForSubscription(nil)
private var consumedCount = 0
/// The elements and completion recorded so far.
var elementsAndCompletion: (elements: [Input], completion: Subscribers.Completion<Failure>?) {
synchronized {
state.elementsAndCompletion
}
}
/// Use Publisher.record()
fileprivate init() { }
deinit {
if case let .subscribed(subscription, _, _) = state {
subscription.cancel()
}
}
private func synchronized<T>(_ execute: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try execute()
}
// MARK: - PublisherExpectation API
/// Registers the expectation so that it gets fulfilled when publisher
/// publishes elements or completes.
///
/// - parameter expectation: An XCTestExpectation.
/// - parameter includingConsumed: This flag controls how elements that were
/// already published at the time this method is called fulfill the
/// expectation. If true, all published elements fulfill the expectation.
/// If false, only published elements that are not consumed yet fulfill
/// the expectation. For example, the Prefix expectation uses true, but
/// the NextOne expectation uses false.
func fulfillOnInput(_ expectation: XCTestExpectation, includingConsumed: Bool) {
synchronized {
preconditionCanFulfillExpectation()
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let maxFulfillmentCount = includingConsumed
? elements.count
: elements.count - consumedCount
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
expectation.fulfill(count: fulfillmentCount)
let remainingCount = expectedFulfillmentCount - fulfillmentCount
if remainingCount > 0 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
state = .subscribed(subscription, exp, elements)
}
case .completed:
expectation.fulfill(count: expectedFulfillmentCount)
}
}
}
/// Registers the expectation so that it gets fulfilled when
/// publisher completes.
func fulfillOnCompletion(_ expectation: XCTestExpectation) {
synchronized {
preconditionCanFulfillExpectation()
switch state {
case .waitingForSubscription:
let exp = RecorderExpectation.onCompletion(expectation)
state = .waitingForSubscription(exp)
case let .subscribed(subscription, _, elements):
let exp = RecorderExpectation.onCompletion(expectation)
state = .subscribed(subscription, exp, elements)
case .completed:
expectation.fulfill()
}
}
}
/// Returns a value based on the recorded state of the publisher.
///
/// - parameter value: A function which returns the value, given the
/// recorded state of the publisher.
/// - parameter elements: All recorded elements.
/// - parameter completion: The eventual publisher completion.
/// - parameter remainingElements: The elements that were not consumed yet.
/// - parameter consume: A function which consumes elements.
/// - parameter count: The number of consumed elements.
/// - returns: The value
func value<T>(_ value: (
_ elements: [Input],
_ completion: Subscribers.Completion<Failure>?,
_ remainingElements: ArraySlice<Input>,
_ consume: (_ count: Int) -> ()) throws -> T)
rethrows -> T
{
try synchronized {
let (elements, completion) = state.elementsAndCompletion
let remainingElements = elements[consumedCount...]
return try value(elements, completion, remainingElements, { count in
precondition(count >= 0)
precondition(count <= remainingElements.count)
consumedCount += count
})
}
}
/// Checks that recorder can fulfill an expectation.
///
/// The reason this method exists is that a recorder can fulfill a single
/// expectation at a given time. It is a programmer error to wait for two
/// expectations concurrently.
///
/// This method MUST be called within a synchronized block.
private func preconditionCanFulfillExpectation() {
if let exp = state.recorderExpectation {
// We are already waiting for an expectation! Is it a programmer
// error? Recorder drops references to non-inverted expectations
// when they are fulfilled. But inverted expectations are not
// fulfilled, and thus not dropped. We can't quite know if an
// inverted expectations has expired yet, so just let it go.
precondition(exp.expectation.isInverted, "Already waiting for an expectation")
}
}
// MARK: - Subscriber
public func receive(subscription: Subscription) {
synchronized {
switch state {
case let .waitingForSubscription(exp):
state = .subscribed(subscription, exp, [])
default:
XCTFail("Publisher recorder is already subscribed")
}
}
subscription.request(.unlimited)
}
public func receive(_ input: Input) -> Subscribers.Demand {
return synchronized {
switch state {
case let .subscribed(subscription, exp, elements):
var elements = elements
elements.append(input)
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
assert(remainingCount > 0)
expectation.fulfill()
if remainingCount > 1 {
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
state = .subscribed(subscription, exp, elements)
} else {
state = .subscribed(subscription, nil, elements)
}
} else {
state = .subscribed(subscription, exp, elements)
}
return .unlimited
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
return .none
case .completed:
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
return .none
}
}
}
public func receive(completion: Subscribers.Completion<Failure>) {
synchronized {
switch state {
case let .subscribed(_, exp, elements):
if let exp = exp {
switch exp {
case let .onCompletion(expectation):
expectation.fulfill()
case let .onInput(expectation, remainingCount: remainingCount):
expectation.fulfill(count: remainingCount)
}
}
state = .completed(elements, completion)
case .waitingForSubscription:
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
case .completed:
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
}
}
}
}
// MARK: - Publisher Expectations
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension PublisherExpectations {
/// The type of the publisher expectation returned by `Recorder.completion`.
public typealias Completion<Input, Failure: Error> = Map<Recording<Input, Failure>, Subscribers.Completion<Failure>>
/// The type of the publisher expectation returned by `Recorder.elements`.
public typealias Elements<Input, Failure: Error> = Map<Recording<Input, Failure>, [Input]>
/// The type of the publisher expectation returned by `Recorder.last`.
public typealias Last<Input, Failure: Error> = Map<Elements<Input, Failure>, Input?>
/// The type of the publisher expectation returned by `Recorder.single`.
public typealias Single<Input, Failure: Error> = Map<Elements<Input, Failure>, Input>
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Recorder {
/// Returns a publisher expectation which waits for the timeout to expire,
/// or the recorded publisher to complete.
///
/// When waiting for this expectation, the publisher error is thrown if
/// the publisher fails before the expectation has expired.
///
/// Otherwise, an array of all elements published before the expectation
/// has expired is returned.
///
/// Unlike other expectations, `availableElements` does not make a test fail
/// on timeout expiration. It just returns the elements published so far.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testTimerPublishesIncreasingDates() throws {
/// let publisher = Timer.publish(every: 0.01, on: .main, in: .common).autoconnect()
/// let recorder = publisher.record()
/// let dates = try wait(for: recorder.availableElements, timeout: ...)
/// XCTAssertEqual(dates.sorted(), dates)
/// }
public var availableElements: PublisherExpectations.AvailableElements<Input, Failure> {
PublisherExpectations.AvailableElements(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time.
///
/// Otherwise, a [Subscribers.Completion](https://developer.apple.com/documentation/combine/subscribers/completion)
/// is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherCompletesWithSuccess() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let completion = try wait(for: recorder.completion, timeout: 1)
/// if case let .failure(error) = completion {
/// XCTFail("Unexpected error \(error)")
/// }
/// }
public var completion: PublisherExpectations.Completion<Input, Failure> {
recording.map { $0.completion }
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time, and the publisher
/// error is thrown if the publisher fails.
///
/// Otherwise, an array of published elements is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesArrayElements() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
/// }
public var elements: PublisherExpectations.Elements<Input, Failure> {
recording.map { recording in
if case let .failure(error) = recording.completion {
throw error
}
return recording.output
}
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, the publisher error is thrown if the
/// publisher fails.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherFinishesWithoutError() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// try wait(for: recorder.finished, timeout: 1)
/// }
///
/// This publisher expectation can be inverted:
///
/// // SUCCESS: no timeout, no error
/// func testPassthroughSubjectDoesNotFinish() throws {
/// let publisher = PassthroughSubject<String, Never>()
/// let recorder = publisher.record()
/// try wait(for: recorder.finished.inverted, timeout: 1)
/// }
public var finished: PublisherExpectations.Finished<Input, Failure> {
PublisherExpectations.Finished(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time, and the publisher
/// error is thrown if the publisher fails.
///
/// Otherwise, the last published element is returned, or nil if the publisher
/// completes before it publishes any element.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherPublishesLastElementLast() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// if let element = try wait(for: recorder.last, timeout: 1) {
/// XCTAssertEqual(element, "baz")
/// } else {
/// XCTFail("Expected one element")
/// }
/// }
public var last: PublisherExpectations.Last<Input, Failure> {
elements.map { $0.last }
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit one element, or to complete.
///
/// When waiting for this expectation, a `RecordingError.notEnoughElements`
/// is thrown if the publisher does not publish one element after last
/// waited expectation. The publisher error is thrown if the publisher fails
/// before publishing the next element.
///
/// Otherwise, the next published element is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfTwoElementsPublishesElementsInOrder() throws {
/// let publisher = ["foo", "bar"].publisher
/// let recorder = publisher.record()
///
/// var element = try wait(for: recorder.next(), timeout: 1)
/// XCTAssertEqual(element, "foo")
///
/// element = try wait(for: recorder.next(), timeout: 1)
/// XCTAssertEqual(element, "bar")
/// }
public func next() -> PublisherExpectations.NextOne<Input, Failure> {
PublisherExpectations.NextOne(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit `count` elements, or to complete.
///
/// When waiting for this expectation, a `RecordingError.notEnoughElements`
/// is thrown if the publisher does not publish `count` elements after last
/// waited expectation. The publisher error is thrown if the publisher fails
/// before publishing the next `count` elements.
///
/// Otherwise, an array of exactly `count` elements is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfThreeElementsPublishesTwoThenOneElement() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// var elements = try wait(for: recorder.next(2), timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
///
/// elements = try wait(for: recorder.next(1), timeout: 1)
/// XCTAssertEqual(elements, ["baz"])
/// }
///
/// - parameter count: The number of elements.
public func next(_ count: Int) -> PublisherExpectations.Next<Input, Failure> {
PublisherExpectations.Next(recorder: self, count: count)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to emit `maxLength` elements, or to complete.
///
/// When waiting for this expectation, the publisher error is thrown if the
/// publisher fails before `maxLength` elements are published.
///
/// Otherwise, an array of received elements is returned, containing at
/// most `maxLength` elements, or less if the publisher completes early.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayOfThreeElementsPublishesTwoFirstElementsWithoutError() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let elements = try wait(for: recorder.prefix(2), timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
/// }
///
/// This publisher expectation can be inverted:
///
/// // SUCCESS: no timeout, no error
/// func testPassthroughSubjectPublishesNoMoreThanSentValues() throws {
/// let publisher = PassthroughSubject<String, Never>()
/// let recorder = publisher.record()
/// publisher.send("foo")
/// publisher.send("bar")
/// let elements = try wait(for: recorder.prefix(3).inverted, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar"])
/// }
///
/// - parameter maxLength: The maximum number of elements.
public func prefix(_ maxLength: Int) -> PublisherExpectations.Prefix<Input, Failure> {
PublisherExpectations.Prefix(recorder: self, maxLength: maxLength)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError.notCompleted is
/// thrown if the publisher does not complete on time.
///
/// Otherwise, a [Record.Recording](https://developer.apple.com/documentation/combine/record/recording)
/// is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testArrayPublisherRecording() throws {
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
/// let recording = try wait(for: recorder.recording, timeout: 1)
/// XCTAssertEqual(recording.output, ["foo", "bar", "baz"])
/// if case let .failure(error) = recording.completion {
/// XCTFail("Unexpected error \(error)")
/// }
/// }
public var recording: PublisherExpectations.Recording<Input, Failure> {
PublisherExpectations.Recording(recorder: self)
}
/// Returns a publisher expectation which waits for the recorded publisher
/// to complete.
///
/// When waiting for this expectation, a RecordingError is thrown if the
/// publisher does not complete on time, or does not publish exactly one
/// element before it completes. The publisher error is thrown if the
/// publisher fails.
///
/// Otherwise, the single published element is returned.
///
/// For example:
///
/// // SUCCESS: no timeout, no error
/// func testJustPublishesExactlyOneElement() throws {
/// let publisher = Just("foo")
/// let recorder = publisher.record()
/// let element = try wait(for: recorder.single, timeout: 1)
/// XCTAssertEqual(element, "foo")
/// }
public var single: PublisherExpectations.Single<Input, Failure> {
elements.map { elements in
guard let element = elements.first else {
throw RecordingError.notEnoughElements
}
if elements.count > 1 {
throw RecordingError.tooManyElements
}
return element
}
}
}
// MARK: - Publisher + Recorder
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Publisher {
/// Returns a subscribed Recorder.
///
/// For example:
///
/// let publisher = ["foo", "bar", "baz"].publisher
/// let recorder = publisher.record()
///
/// You can build publisher expectations from the Recorder. For example:
///
/// let elements = try wait(for: recorder.elements, timeout: 1)
/// XCTAssertEqual(elements, ["foo", "bar", "baz"])
public func record() -> Recorder<Output, Failure> {
let recorder = Recorder<Output, Failure>()
subscribe(recorder)
return recorder
}
}
// MARK: - Convenience
extension XCTestExpectation {
fileprivate func fulfill(count: Int) {
for _ in 0..<count {
fulfill()
}
}
}
#endif
|
2cbfb5d7ec3a2a910c609846276da165
| 39.512397 | 126 | 0.596328 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Stats/Helpers/BottomScrollAnalyticsTracker.swift
|
gpl-2.0
|
1
|
import Foundation
// MARK: - BottomScrollAnalyticsTracker
final class BottomScrollAnalyticsTracker: NSObject {
private func captureAnalyticsEvent(_ event: WPAnalyticsStat) {
if let blogIdentifier = SiteStatsInformation.sharedInstance.siteID {
WPAppAnalytics.track(event, withBlogID: blogIdentifier)
} else {
WPAppAnalytics.track(event)
}
}
private func trackScrollToBottomEvent() {
captureAnalyticsEvent(.statsScrolledToBottom)
}
}
// MARK: - UIScrollViewDelegate
extension BottomScrollAnalyticsTracker: UIScrollViewDelegate {
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let targetOffsetY = Int(targetContentOffset.pointee.y)
let scrollViewContentHeight = scrollView.contentSize.height
let visibleScrollViewHeight = scrollView.bounds.height
let effectiveScrollViewHeight = Int(scrollViewContentHeight - visibleScrollViewHeight)
if targetOffsetY >= effectiveScrollViewHeight {
trackScrollToBottomEvent()
}
}
}
|
bb9a5ffeae831c36e62ed3859a46239a
| 31.222222 | 148 | 0.733621 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.