repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tjw/swift | stdlib/public/core/Join.swift | 2 | 6386 | //===--- Join.swift - Protocol and Algorithm for concatenation ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence that presents the elements of a base sequence of sequences
/// concatenated using a given separator.
@_fixed_layout // FIXME(sil-serialize-all)
public struct JoinedSequence<Base : Sequence> where Base.Element : Sequence {
public typealias Element = Base.Element.Element
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base
@usableFromInline // FIXME(sil-serialize-all)
internal var _separator: ContiguousArray<Element>
/// Creates an iterator that presents the elements of the sequences
/// traversed by `base`, concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // FIXME(sil-serialize-all)
public init<Separator : Sequence>(base: Base, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separator = ContiguousArray(separator)
}
}
extension JoinedSequence {
/// An iterator that presents the elements of the sequences traversed
/// by a base iterator, concatenated using a given separator.
@_fixed_layout // FIXME(sil-serialize-all)
public struct Iterator {
@usableFromInline // FIXME(sil-serialize-all)
internal var _base: Base.Iterator
@usableFromInline // FIXME(sil-serialize-all)
internal var _inner: Base.Element.Iterator?
@usableFromInline // FIXME(sil-serialize-all)
internal var _separatorData: ContiguousArray<Element>
@usableFromInline // FIXME(sil-serialize-all)
internal var _separator: ContiguousArray<Element>.Iterator?
@_frozen // FIXME(sil-serialize-all)
@usableFromInline // FIXME(sil-serialize-all)
internal enum JoinIteratorState {
case start
case generatingElements
case generatingSeparator
case end
}
@usableFromInline // FIXME(sil-serialize-all)
internal var _state: JoinIteratorState = .start
/// Creates a sequence that presents the elements of `base` sequences
/// concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // FIXME(sil-serialize-all)
public init<Separator: Sequence>(base: Base.Iterator, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separatorData = ContiguousArray(separator)
}
}
}
extension JoinedSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // FIXME(sil-serialize-all)
public mutating func next() -> Element? {
while true {
switch _state {
case .start:
if let nextSubSequence = _base.next() {
_inner = nextSubSequence.makeIterator()
_state = .generatingElements
} else {
_state = .end
return nil
}
case .generatingElements:
let result = _inner!.next()
if _fastPath(result != nil) {
return result
}
_inner = _base.next()?.makeIterator()
if _inner == nil {
_state = .end
return nil
}
if !_separatorData.isEmpty {
_separator = _separatorData.makeIterator()
_state = .generatingSeparator
}
case .generatingSeparator:
let result = _separator!.next()
if _fastPath(result != nil) {
return result
}
_state = .generatingElements
case .end:
return nil
}
}
}
}
extension JoinedSequence: Sequence {
/// Return an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // FIXME(sil-serialize-all)
public func makeIterator() -> Iterator {
return Iterator(base: _base.makeIterator(), separator: _separator)
}
@inlinable // FIXME(sil-serialize-all)
public func _copyToContiguousArray() -> ContiguousArray<Element> {
var result = ContiguousArray<Element>()
let separatorSize: Int = numericCast(_separator.count)
let reservation = _base._preprocessingPass {
() -> Int in
var r = 0
for chunk in _base {
r += separatorSize + chunk.underestimatedCount
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(numericCast(n))
}
if separatorSize == 0 {
for x in _base {
result.append(contentsOf: x)
}
return result
}
var iter = _base.makeIterator()
if let first = iter.next() {
result.append(contentsOf: first)
while let next = iter.next() {
result.append(contentsOf: _separator)
result.append(contentsOf: next)
}
}
return result
}
}
extension Sequence where Element : Sequence {
/// Returns the concatenated elements of this sequence of sequences,
/// inserting the given separator between each element.
///
/// This example shows how an array of `[Int]` instances can be joined, using
/// another `[Int]` instance as the separator:
///
/// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// let joined = nestedNumbers.joined(separator: [-1, -2])
/// print(Array(joined))
/// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"
///
/// - Parameter separator: A sequence to insert between each of this
/// sequence's elements.
/// - Returns: The joined sequence of elements.
@inlinable // FIXME(sil-serialize-all)
public func joined<Separator : Sequence>(
separator: Separator
) -> JoinedSequence<Self>
where Separator.Element == Element.Element {
return JoinedSequence(base: self, separator: separator)
}
}
// @available(*, deprecated, renamed: "JoinedSequence.Iterator")
public typealias JoinedIterator<T: Sequence> = JoinedSequence<T>.Iterator where T.Element: Sequence
| apache-2.0 | e6638020d108f448e7dc32dfe034a768 | 31.581633 | 99 | 0.643595 | 4.434722 | false | false | false | false |
raychrd/tada | tada/Event.swift | 1 | 5479 | //
// Event.swift
// tada
//
// Created by Ray on 15/1/24.
// Copyright (c) 2015年 Ray. All rights reserved.
//
import Foundation
import EventKit
import UIKit
var appDelegate:AppDelegate?
var isAccessToEventStoreGranted:Bool = true
var startDate=NSDate().dateByAddingTimeInterval(-60*60*24)
var endDate=NSDate().dateByAddingTimeInterval(60*60*24*30)
var status = false
var firstTime:String = ""
func getFirstTime()->String{
if appDelegate!.events.isEmpty{
let a = (appDelegate!.events[0] as EKReminder).startDateComponents.hour
var hour = String(a)
let b = (appDelegate!.events[0] as EKReminder).startDateComponents.minute
var minute = String(b)
if minute.hasSuffix("0") {
minute += "0"
}
firstTime = hour+":"+minute
}
return firstTime
}
func accessEventStore() {
appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
println("access 1")
if appDelegate!.eventStore == nil {
println("access 2")
appDelegate!.eventStore = EKEventStore()
println("access 3")
appDelegate!.eventStore!.requestAccessToEntityType(EKEntityTypeReminder, completion: {(granted,error) in
if !granted {
println("access 4")
println("Access to store not granted")
println(error.localizedDescription)
isAccessToEventStoreGranted = false
} else {
println("access 5")
println("Access granted")
isAccessToEventStoreGranted = true
}
})
}
}
func loadReminders() {
appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
appDelegate!.eventStore = EKEventStore()
println("loadReminders \(isAccessToEventStoreGranted)")
if isAccessToEventStoreGranted {
var calendars = appDelegate!.eventStore!.calendarsForEntityType(EKEntityTypeReminder)
var predicate = appDelegate!.eventStore!.predicateForRemindersInCalendars([])
appDelegate!.eventStore!.fetchRemindersMatchingPredicate(predicate) { reminders in
for reminder:EKReminder in reminders as [EKReminder] {
if reminder.creationDate!.compare(startDate) == .OrderedDescending && reminder.completed == false{
appDelegate!.events.append(reminder)
println(reminder.title)
println(reminder.completed)
println(reminder.calendarItemIdentifier)
/*
println(appDelegate!.events.count)
println(reminder.startDateComponents)
println(reminder.dueDateComponents)
println(reminder.alarms.description)
*/
status = false
}
}
println("load completed")
calSort()
}
}
}
func createReminder() {
appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
let reminder = EKReminder(eventStore: appDelegate!.eventStore)
let now = NSDate()
let cal = appDelegate!.eventStore!.calendarsForEntityType(EKEntityTypeReminder)
reminder.title = reminderText
reminder.calendar = appDelegate!.eventStore!.defaultCalendarForNewReminders()
/*
var todayComponents = NSDateComponents()
todayComponents.year = 2015
todayComponents.month = 1
todayComponents.day = 28
todayComponents.hour = 16
*/
//let todayDate = NSCalendar.currentCalendar().dateFromComponents(todayComponents)
//Reminders新建的提醒事项默认是没有startDateComponents和due这两个属性的 如果有闹钟的话 会新建startDateComponents和dueDate和alarm
reminder.startDateComponents = reminderTimeComponent
println(reminder.startDateComponents)
reminder.dueDateComponents = reminderTimeComponent
let todayDate:NSDate = NSCalendar.currentCalendar().dateFromComponents(reminderTimeComponent!)!
//就是看提醒时间
if setAlarm {
reminder.addAlarm(EKAlarm(absoluteDate: todayDate))
}
var error:NSError?
appDelegate!.eventStore!.saveReminder(reminder, commit:true, error: &error)
refreshEvents()
while(!status) {
}
status = false
}
func calSort() {
/*
sort(&appDelegate!.events,{(a:EKReminder,b:EKReminder) -> Bool in
let ad = NSCalendar.currentCalendar().dateFromComponents(a.startDateComponents)
let bd = NSCalendar.currentCalendar().dateFromComponents(b.startDateComponents)
if (ad!.compare(bd!)) == .OrderedAscending {
return false
} else {
return true
}
})
status = true
*/
/*
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"priority" ascending:YES] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors:sortDescriptors];
*/
status = true
}
func refreshEvents() -> Bool{
status = false
appDelegate!.events.removeAll(keepCapacity: true)
loadReminders()
while(!status){
}
return true
}
| mit | 7dab502ba10d8516c4e9f549c5e2fcb6 | 25.091787 | 114 | 0.626551 | 5.321182 | false | false | false | false |
yaslab/ZipArchive.swift | Sources/ZipArchive/ZipReaderFilter.swift | 1 | 2907 | import czlib
import ZipIO
public protocol ZipReaderFilter: InputStream {
init(_ base: InputStream, originalSize: Int)
}
// built-in filter
public final class StoreInputFilter: ZipReaderFilter {
public private(set) var crc: UInt = 0
private let base: InputStream
private let originalSize: Int
private var totalReadSize: Int
public init(_ base: InputStream, originalSize: Int) {
self.base = base
self.originalSize = originalSize
self.totalReadSize = 0
}
public func close() -> Bool {
return true
}
public func read(buffer: UnsafeMutableRawPointer, count: Int) -> Int {
let c = min(count, originalSize - totalReadSize)
if c < 0 {
return -1
}
let len = base.read(buffer: buffer, count: c)
if len > 0 {
crc = Zip.crc32(crc, buffer, len)
totalReadSize += len
}
return len
}
}
// built-in filter
public final class DeflateInputFilter: ZipReaderFilter {
public static let bufferSize = 1024
public private(set) var crc: UInt = 0
private var z: z_stream
private let base: InputStream
private var isStreamEnd: Bool
private let internalBuffer: UnsafeMutablePointer<UInt8>
private let internalBufferSize: Int
public init(_ base: InputStream, originalSize: Int) {
self.z = z_stream()
self.base = base
self.isStreamEnd = false
self.internalBufferSize = DeflateInputFilter.bufferSize
self.internalBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: internalBufferSize)
inflateInit2_(
&z,
-MAX_WBITS,
ZLIB_VERSION,
Int32(MemoryLayout<z_stream>.size)
)
}
deinit {
internalBuffer.deallocate()
inflateEnd(&z)
}
public func close() -> Bool {
return true
}
public func read(buffer: UnsafeMutableRawPointer, count: Int) -> Int {
if isStreamEnd {
return 0
}
z.next_out = buffer.assumingMemoryBound(to: Bytef.self)
z.avail_out = UInt32(count)
LOOP: while true {
if z.avail_in == 0 {
let len = base.read(buffer: internalBuffer, count: internalBufferSize)
if len < 0 {
return -1
}
z.next_in = internalBuffer
z.avail_in = UInt32(len)
}
let status = inflate(&z, Z_NO_FLUSH)
switch status {
case Z_STREAM_END:
isStreamEnd = true
break LOOP
case Z_OK:
if z.avail_out == 0 { break LOOP }
default:
return -1
}
}
let _count = count - Int(z.avail_out)
crc = Zip.crc32(crc, buffer, _count)
return _count
}
}
| mit | f5bfa73212d174132186b2ef00049b1f | 22.634146 | 96 | 0.560372 | 4.371429 | false | false | false | false |
stellaval/TravellersStory | TravellersStory/TravellersStory/CommunityTableViewController.swift | 1 | 2888 | //
// CommunityTableViewController.swift
// TravellersStory
//
// Created by Stella on 2/8/16.
// Copyright © 2016 Stella. All rights reserved.
//
import UIKit
class CommunityTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f6854748f53535dde33a363da115aa8a | 30.725275 | 157 | 0.680637 | 5.509542 | false | false | false | false |
bppr/Swiftest | src/Swiftest/Core/Expectations/Expectation.swift | 1 | 2494 | let defaultMessage = "expectation failed"
public class ExpectationResult : HasStatus {
public var subjectText = ""
public var assertions: [Assertion] = []
public let cursor: Cursor
public var status: Status {
if assertions.isEmpty { return .Pending }
for a in assertions {
if a.call() == a.reverse { return .Fail }
}
return .Pass
}
public var msg : String {
for a in assertions {
if a.call() == a.reverse {
let verb = a.reverse ? "not to" : "to"
return "expected \(subjectText) \(verb) \(a.msg)"
}
}
return defaultMessage
}
init(cursor: Cursor) { self.cursor = cursor }
init(cursor: Cursor, subjectText: String) {
self.cursor = cursor
self.subjectText = subjectText
}
func assert(assertion: Assertion) {
self.assertions.append(assertion)
}
}
public protocol Expectable {
var result : ExpectationResult { get }
}
public class Expectation<T, M:Matcher where M.SubjectType == T> : Expectable {
let subject: T?
public let result: ExpectationResult
public var to : M {
return M(subject: subject, callback: result.assert, reverse: false)
}
public var notTo : M {
return M(subject: subject, callback: result.assert, reverse: true)
}
public init(subject: T?, cursor: Cursor = nullCursor) {
self.subject = subject
self.result = ExpectationResult(
cursor: cursor,
subjectText: "\(subject)"
)
}
}
public class ArrayExpectation<T:Equatable> : Expectable {
let subject: [T]?
public let result: ExpectationResult
public var to : ArrayMatcher<T> {
return ArrayMatcher(subject: subject, callback: result.assert, reverse: false)
}
public var notTo : ArrayMatcher<T> {
return ArrayMatcher(subject: subject, callback: result.assert, reverse: true)
}
public init(subject: [T]?, cursor: Cursor = nullCursor) {
self.subject = subject
self.result = ExpectationResult(
cursor: cursor,
subjectText: "\(subject)"
)
}
}
public class DictionaryExpectation<K:Hashable, V:Equatable> : Expectable {
let subject: [K : V]?
public let result: ExpectationResult
public var to : DictionaryMatcher<K, V> {
return DictionaryMatcher(subject: subject, callback: result.assert, reverse: false)
}
public var notTo : DictionaryMatcher<K, V> {
return DictionaryMatcher(subject: subject, callback: result.assert, reverse: true)
}
public init(subject: [K : V]?, cursor: Cursor = nullCursor) {
self.subject = subject
self.result = ExpectationResult(
cursor: cursor,
subjectText: "\(subject)"
)
}
}
| mit | 550122c681bf10e96a0d2b5f34a6db6a | 22.752381 | 85 | 0.696872 | 3.343164 | false | false | false | false |
ChristianDeckert/CDTools | CDTools/UI/UIImage+CDTools.swift | 1 | 3324 | //
// UIImageView+CDTools.swift
//
//
// Created by Christian Deckert on 04.08.15.
// Copyright (c) 2015 Christian Deckert. All rights reserved.
//
import UIKit
import Foundation
typealias CoreImage = CIImage
public extension UIImage {
public func averageColor() -> UIColor? {
let rgba = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: 4)
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let info = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
if let context: CGContext = CGContext(data: rgba, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: info.rawValue) {
context.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1))
if rgba[3] > 0 {
let alpha: CGFloat = CGFloat(rgba[3]) / 255.0
let multiplier: CGFloat = alpha / 255.0
return UIColor(red: CGFloat(rgba[0]) * multiplier, green: CGFloat(rgba[1]) * multiplier, blue: CGFloat(rgba[2]) * multiplier, alpha: alpha)
} else {
return UIColor(red: CGFloat(rgba[0]) / 255.0, green: CGFloat(rgba[1]) / 255.0, blue: CGFloat(rgba[2]) / 255.0, alpha: CGFloat(rgba[3]) / 255.0)
}
}
return nil
}
public func darken(withColor color: UIColor = UIColor.black) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
guard let cgImage = self.cgImage else {
return self
}
guard let context = UIGraphicsGetCurrentContext() else {
return self
}
let area = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.scaleBy(x: 1, y: -1)
context.translateBy(x: 0, y: -area.size.height);
context.saveGState();
context.clip(to: area, mask: cgImage);
color.set()
context.fill(area);
context.restoreGState();
context.setBlendMode(CGBlendMode.multiply);
context.draw(cgImage, in: area);
let darkenedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return darkenedImage
}
public func brighten(byScale brightness: CGFloat = 0.5) -> UIImage? {
guard let inputCgImage = self.cgImage else {
return self
}
let inputImage = CoreImage(cgImage: inputCgImage)
guard let filter = CIFilter(name: "CIColorControls") else {
return self
}
let context = CIContext.init(options: nil)
filter.setValue(inputImage, forKey: kCIInputImageKey)
filter.setValue(brightness, forKey: kCIInputBrightnessKey)
guard let outputImage = filter.outputImage else {
return self
}
guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else {
return self
}
let brighterImage = UIImage(cgImage: cgImage)
return brighterImage
}
}
| mit | 6fe6619fbdc74cdc6ba143bef357b1f5 | 31.271845 | 163 | 0.572503 | 4.81042 | false | false | false | false |
Onetaway/iOS8-day-by-day | 12-healthkit/BodyTemple/BodyTemple/TabBarViewController.swift | 2 | 2355 | //
// Copyright 2014 Scott Logic
//
// 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 HealthKit
class TabBarViewController: UITabBarController {
var healthStore: HKHealthStore?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createAndPropagateHealthStore()
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
createAndPropagateHealthStore()
}
override func viewDidLoad() {
super.viewDidLoad()
requestAuthorisationForHealthStore()
}
private func createAndPropagateHealthStore() {
if self.healthStore == nil {
self.healthStore = HKHealthStore()
}
for vc in viewControllers {
if let healthStoreUser = vc as? HealthStoreUser {
healthStoreUser.healthStore = self.healthStore
}
}
}
private func requestAuthorisationForHealthStore() {
let dataTypesToWrite = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
]
let dataTypesToRead = [
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight),
HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMassIndex),
HKCharacteristicType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)
]
self.healthStore?.requestAuthorizationToShareTypes(NSSet(array: dataTypesToWrite),
readTypes: NSSet(array: dataTypesToRead), completion: {
(success, error) in
if success {
println("User completed authorisation request.")
} else {
println("The user cancelled the authorisation request. \(error)")
}
})
}
}
| apache-2.0 | 685760cc4d4c3da7934c53a8a705500a | 31.260274 | 101 | 0.729936 | 5.340136 | false | false | false | false |
peterlafferty/LuasLife | Carthage/Checkouts/Decodable/Tests/DecodableOperatorsTests.swift | 1 | 8842 | //
// DecodableOperatorsTests.swift
// Decodable
//
// Created by FJBelchi on 13/07/15.
// Copyright © 2015 anviking. All rights reserved.
//
import XCTest
@testable import Decodable
class DecodableOperatorsTests: XCTestCase {
// MARK: =>
func testDecodeAnyDecodableSuccess() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
let string = try! dictionary => KeyPath(key) as String
// then
XCTAssertEqual(string, value)
}
func testDecodeAnyDecodableDictionarySuccess() {
// given
let key = "key"
let value: NSDictionary = [key : "value"]
let dictionary: NSDictionary = [key: value]
// when
let result: NSDictionary = try! dictionary => KeyPath(key) as! NSDictionary
// then
XCTAssertEqual(result, value)
}
func testDecodeDictOfArraysSucess() {
// given
let key = "key"
let value: NSDictionary = ["list": [1, 2, 3]]
let dictionary: NSDictionary = [key: value]
// when
let result: [String: [Int]] = try! dictionary => KeyPath(key)
// then
XCTAssertEqual(result as NSDictionary, value)
}
// MARK: - Nested keys
func testDecodeNestedDictionarySuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key"
// then
XCTAssertEqual(result as? NSDictionary, value)
}
func testDecodeNestedDictionaryOptionalSuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key" as! [String : Any]
// then
XCTAssertEqual(result as NSDictionary, value)
}
// TODO: this does not compile with Swift 3
// func testDecodeNestedIntSuccess() {
// // given
// let value = 4
// let dictionary: NSDictionary = ["key1": ["key2": ["key3": value]]]
// // when
// let result: Int = try! dictionary => "key1" => "key2" => "key3"
// // then
// XCTAssertEqual(result, value)
// }
func testDecodeNestedDictionaryCastingSuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key" as! [String: String]
// then
XCTAssertEqual(result, value as! [String : String])
}
func testDecodeAnyDecodableOptionalSuccess() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
let string = try! dictionary => KeyPath(key) as String?
// then
XCTAssertEqual(string!, value)
}
func testDecodeAnyDecodableOptionalNilSuccess() {
// given
let key = "key"
let dictionary: NSDictionary = [key: NSNull()]
// when
let string = try! dictionary => KeyPath(key) as String?
// then
XCTAssertNil(string)
}
func testDecodeAnyDecodableOptionalTypeMismatchFailure() {
// given
let key = "key"
let dictionary: NSDictionary = [key: 2]
// when
do {
let a = try dictionary => KeyPath(key) as String?
print(a as Any)
XCTFail()
} catch let DecodingError.typeMismatch(_, actual, _) {
XCTAssertEqual(String(describing: actual), "_SwiftTypePreservingNSNumber")
} catch let error {
XCTFail("should not throw \(error)")
}
}
// MARK: - Nested =>? operators
// Should throw on typemismatch with correct metadata
func testDecodeNestedTypeMismatchFailure() {
let json: NSDictionary = ["user": ["followers": "not_an_integer"]]
do {
let _ : Int? = try json =>? "user" => "followers"
XCTFail("should throw")
} catch let DecodingError.typeMismatch(_, _, metadata) {
XCTAssertEqual(metadata.formattedPath, "user.followers")
} catch {
XCTFail("should not throw \(error)")
}
}
// Should currently (though really it shoult not) treat all keys as either optional or non-optional
func testDecodeNestedTypeReturnNilForSubobjectMissingKey() {
let json: NSDictionary = ["user": ["something_else": "test"]]
try! XCTAssertEqual(json =>? "user" =>? "followers", Optional<Int>.none)
}
// Sanity check
func testDecodeNestedTypeSuccess() {
let json: NSDictionary = ["user": ["followers": 3]]
try! XCTAssertEqual(json =>? "user" => "followers", 3)
}
// MARK: => Errors
/* //
func testDecodeNestedDictionaryCastingFailure() {
// given
let value: NSDictionary = ["apple" : 2]
let dictionary: NSDictionary = ["firstKey": ["secondKey": value]]
// when
do {
_ = try dictionary => "firstKey" => "secondKey" as [String: String]
XCTFail()
} catch DecodingError.typeMismatchError(_, Dictionary<String, String>.self, let info) {
// then
XCTAssertEqual(info.formattedPath, "firstKey.secondKey")
XCTAssertEqual(info.object as? NSDictionary, value)
} catch let error {
XCTFail("should not throw \(error)")
}
}
*/
func testDecodeAnyDecodableThrowMissingKeyException() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
do {
_ = try dictionary => "nokey" as String
} catch let DecodingError.missingKey(key, metadata) {
// then
XCTAssertEqual(key, "nokey")
XCTAssertEqual(metadata.path, [])
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSDictionary, dictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableThrowNoJsonObjectException() {
// given
let key = "key"
let noDictionary: NSString = "hello"
// when
do {
_ = try noDictionary => KeyPath(key) as String
} catch let DecodingError.typeMismatch(expected, actual, metadata) where expected == NSDictionary.self {
// then
XCTAssertTrue(true)
XCTAssertEqual(String(describing: actual), "__NSCFString")
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSString, (noDictionary))
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowMissingKeyException() {
// given
let key = "key"
let value: NSDictionary = [key : "value"]
let dictionary: NSDictionary = [key: value]
// when
do {
_ = try dictionary => "nokey"
} catch let DecodingError.missingKey(key, metadata) {
// then
XCTAssertEqual(key, "nokey")
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.path, [])
XCTAssertEqual(metadata.object as? NSDictionary, dictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowJSONNotObjectException() {
// given
let key = "key"
let noDictionary: NSString = "noDictionary"
// when
do {
_ = try noDictionary => KeyPath(key)
} catch let DecodingError.typeMismatch(expected, actual, metadata) where expected == NSDictionary.self {
// then
XCTAssertTrue(true)
XCTAssertEqual(String(describing: actual), "__NSCFString")
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSString, noDictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowTypeMismatchException() {
// given
let key = "key"
let dictionary: NSDictionary = [key: "value"]
// when
do {
_ = try dictionary => KeyPath(key)
} catch DecodingError.typeMismatch {
// then
XCTAssertTrue(true)
} catch let error {
XCTFail("should not throw \(error)")
}
}
}
| mit | 06d94c44969ffbedb9f34e00da59928e | 32.11236 | 112 | 0.564755 | 4.773758 | false | true | false | false |
blstream/StudyBox_iOS | Pods/Swifternalization/Swifternalization/SharedExpressionsProcessor.swift | 1 | 4523 | //
// ExpressionsProcessor.swift
// Swifternalization
//
// Created by Tomasz Szulc on 26/07/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Swifternalization contains some built-in country-related shared expressions.
Developer can create its own expressions in expressions.json file for
base and preferred languages.
The class is responsible for proper loading the built-in shared ones and
those loaded from project's files. It handles overriding of built-in and loads
those from Base and preferred language version.
It always load base expressions, then looking for language specific.
If in Base are some expressions that overrides built-ins, that's fine.
The class adds developer's custom expressions and adds only those of built-in
that are not contained in the Base.
The same is for preferred languages but also here what is important is that
at first preferred language file expressions are loaded, then if something
different is defined in Base it will be also loaded and then the built-in
expression that differs.
*/
class SharedExpressionsProcessor {
/**
Method takes expression for both Base and preferred language localizations
and also internally loads built-in expressions, combine them and returns
expressions for Base and prefered language.
:param: preferedLanguage A user device's language.
:param: preferedLanguageExpressions Expressions from expressions.json
:param: baseLanguageExpressions Expressions from base section of
expression.json.
:returns: array of shared expressions for Base and preferred language.
*/
class func processSharedExpression(preferedLanguage: CountryCode, preferedLanguageExpressions: [SharedExpression], baseLanguageExpressions: [SharedExpression]) -> [SharedExpression] {
/*
Get unique base expressions that are not presented in prefered language
expressions. Those from base will be used in a case when programmer
will ask for string localization and when there is no such expression
in prefered language section defined.
It means two things:
1. Programmer make this expression shared through prefered language
and this is good as base expression.
2. He forgot to define such expression for prefered language.
*/
let uniqueBaseExpressions = baseLanguageExpressions <! preferedLanguageExpressions
// Expressions from json files.
let loadedExpressions = uniqueBaseExpressions + preferedLanguageExpressions
// Load prefered language nad base built-in expressions. Get unique.
let prefBuiltInExpressions = loadBuiltInExpressions(preferedLanguage)
let baseBuiltInExpressions = SharedBaseExpression.allExpressions()
let uniqueBaseBuiltInExpressions = baseBuiltInExpressions <! prefBuiltInExpressions
// Unique built-in expressions made of base + prefered language.
let builtInExpressions = uniqueBaseBuiltInExpressions + prefBuiltInExpressions
/*
To get it done we must get only unique built-in expressions that are not
in loaded expressions.
*/
return loadedExpressions + (builtInExpressions <! loadedExpressions)
}
/**
Method loads built-in framework's built-in expressions for specific language.
:param: language A preferred user's language.
:returns: Shared expressions for specific language. If there is no
expression for passed language empty array is returned.
*/
private class func loadBuiltInExpressions(language: CountryCode) -> [SharedExpression] {
switch language {
case "pl": return SharedPolishExpression.allExpressions()
default: return []
}
}
}
infix operator <! {}
/**
"Get Unique" operator. It helps in getting unique shared expressions from two arrays.
Content of `lhs` array will be checked in terms on uniqueness. The operator does
check is there is any shared expression in `lhs` that is presented in `rhs`.
If element from `lhs` is not in `rhs` then this element is correct and is returned
in new array which is a result of this operation.
*/
func <! (lhs: [SharedExpression], rhs: [SharedExpression]) -> [SharedExpression] {
var result = lhs
if rhs.count > 0 {
result = lhs.filter({
let tmp = $0
return rhs.filter({$0.identifier == tmp.identifier}).count == 0
})
}
return result
}
| apache-2.0 | 95a398da3cfef685f607fa3d9f851851 | 41.271028 | 187 | 0.725846 | 5.076319 | false | false | false | false |
crazypoo/PTools | Pods/CryptoSwift/Sources/CryptoSwift/CS_BigInt/Comparable.swift | 2 | 1815 | //
// Comparable.swift
// CS.BigInt
//
// Created by Károly Lőrentey on 2016-01-03.
// Copyright © 2016-2017 Károly Lőrentey.
//
import Foundation
extension CS.BigUInt: Comparable {
//MARK: Comparison
/// Compare `a` to `b` and return an `NSComparisonResult` indicating their order.
///
/// - Complexity: O(count)
public static func compare(_ a: CS.BigUInt, _ b: CS.BigUInt) -> ComparisonResult {
if a.count != b.count { return a.count > b.count ? .orderedDescending : .orderedAscending }
for i in (0 ..< a.count).reversed() {
let ad = a[i]
let bd = b[i]
if ad != bd { return ad > bd ? .orderedDescending : .orderedAscending }
}
return .orderedSame
}
/// Return true iff `a` is equal to `b`.
///
/// - Complexity: O(count)
public static func ==(a: CS.BigUInt, b: CS.BigUInt) -> Bool {
return CS.BigUInt.compare(a, b) == .orderedSame
}
/// Return true iff `a` is less than `b`.
///
/// - Complexity: O(count)
public static func <(a: CS.BigUInt, b: CS.BigUInt) -> Bool {
return CS.BigUInt.compare(a, b) == .orderedAscending
}
}
extension CS.BigInt {
/// Return true iff `a` is equal to `b`.
public static func ==(a: CS.BigInt, b: CS.BigInt) -> Bool {
return a.sign == b.sign && a.magnitude == b.magnitude
}
/// Return true iff `a` is less than `b`.
public static func <(a: CS.BigInt, b: CS.BigInt) -> Bool {
switch (a.sign, b.sign) {
case (.plus, .plus):
return a.magnitude < b.magnitude
case (.plus, .minus):
return false
case (.minus, .plus):
return true
case (.minus, .minus):
return a.magnitude > b.magnitude
}
}
}
| mit | 2dd34b0527a7036b2ebc6ce6099189d0 | 27.730159 | 99 | 0.553039 | 3.709016 | false | false | false | false |
JohnSansoucie/MyProject2 | BlueCapKit/SerDe/NSDataExtensions.swift | 1 | 1663 | //
// NSDataExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 6/29/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
extension NSData : Serializable {
public class func fromString(value:String, encoding:NSStringEncoding = NSUTF8StringEncoding) -> NSData? {
return value.dataUsingEncoding(encoding).map{NSData(data:$0)}
}
public class func serialize<T>(value:T) -> NSData {
let values = [fromHostByteOrder(value)]
return NSData(bytes:values, length:sizeof(T))
}
public class func serialize<T>(values:[T]) -> NSData {
let littleValues = values.map{fromHostByteOrder($0)}
return NSData(bytes:littleValues, length:sizeof(T)*littleValues.count)
}
public class func serialize<T1, T2>(values:(T1, T2)) -> NSData {
let (values1, values2) = values
let data = NSMutableData()
data.setData(NSData.serialize(values1))
data.appendData(NSData.serialize(values2))
return data
}
public class func serialize<T1, T2>(values:([T1], [T2])) -> NSData {
let (values1, values2) = values
let data = NSMutableData()
data.setData(NSData.serialize(values1))
data.appendData(NSData.serialize(values2))
return data
}
public func hexStringValue() -> String {
var dataBytes = Array<Byte>(count:self.length, repeatedValue:0x0)
self.getBytes(&dataBytes, length:self.length)
var hexString = dataBytes.reduce(""){(out:String, dataByte:Byte) in
out + NSString(format:"%02lx", dataByte)
}
return hexString
}
}
| mit | 36ba8e9910aeef1ea74413ac272998dd | 30.980769 | 109 | 0.638004 | 3.968974 | false | false | false | false |
adamdahan/SwiftStructures | Source/Factories/HashTable.swift | 10 | 3595 | //
// HashTable.swift
// SwiftStructures
//
// Created by Wayne Bishop on 10/29/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
class HashTable {
private var buckets: Array<HashNode!>
//initialize the buckets with nil values
init(capacity: Int) {
self.buckets = Array<HashNode!>(count: capacity, repeatedValue:nil)
}
//add the key using the specified hash
func addWord(firstname: String, lastname: String) {
var hashindex: Int!
var fullname: String!
//create a hashvalue using the complete name
fullname = firstname + lastname
hashindex = self.createHash(fullname)
var childToUse: HashNode = HashNode()
var head: HashNode!
childToUse.firstname = firstname
childToUse.lastname = lastname
//check for an existing list
if buckets[hashindex] == nil {
buckets[hashindex] = childToUse
}
else {
println("a collision occured. implementing chaining..")
head = buckets[hashindex]
//append new item to the head of the list
childToUse.next = head
head = childToUse
//update the chained list
buckets[hashindex] = head
}
} //end function
//determine if the word is found in the hash table
func findWord(firstname: String, lastname: String) -> Bool! {
var hashindex: Int!
var fullname: String!
fullname = firstname + lastname
hashindex = self.createHash(fullname)
//determine if the value is present
if buckets[hashindex] == nil {
println("name not found in hash table..")
return false
}
//iterate through the list of items to find a match
else {
var current: HashNode! = buckets[hashindex]
while (current != nil) {
var hashName: String! = current.firstname + current.lastname
if (hashName == fullname) {
println("\(current.firstname) \(current.lastname) found in hash table..")
return true
}
println("searching for word through chained list..")
current = current.next
} //end while
} //end if
println("name not found in hash table..")
return false
}
//return the hash value to be used
func createHash(fullname: String) -> Int! {
var remainder: Int = 0
var divisor: Int = 0
for key in fullname.unicodeScalars {
//println("the ascii value of \(key) is \(key.value)..")
divisor += Int(key.value)
}
/*
note: modular math is used to calculate a hash value. The bucket count is used
as the dividend to ensure all possible outcomes are between 0 and 25. This is an example
of a simple but effective hash algorithm.
*/
remainder = divisor % buckets.count
return remainder - 1
}
} | mit | 23447df378e9411c328d43db57d2cca4 | 23.972222 | 96 | 0.497636 | 5.599688 | false | false | false | false |
qblu/ModelForm | ModelFormTests/PropertyTypeFormFields/IntTypeFormFieldSpec.swift | 1 | 4136 | //
// IntTypeFormFieldSpec.swift
// ModelForm
//
// Created by Rusty Zarse on 7/27/15.
// Copyright (c) 2015 LeVous. All rights reserved.
//
import Quick
import Nimble
import ModelForm
class IntTypeFormFieldSpec: QuickSpec {
override func spec() {
describe(".createFormField") {
context("When a number is passed as value") {
it("returns a UITextField with text as value") {
let field = IntTypeFormField().createFormField("someName", value: 6) as! UITextField
expect(field.text).to(equal("6"))
}
}
context("When a string is passed as value") {
it("creates a UITextField with empty text") {
let field = IntTypeFormField().createFormField("someName", value: "someValue") as! UITextField
expect(field.text).to(equal(""))
}
}
}
describe(".getValueFromFormField") {
context("When a text field is passed as formField") {
it("returns valid whole number as Int") {
let textField = UITextField()
textField.text = "99"
let (validationResult, value) = IntTypeFormField().getValueFromFormField(textField, forPropertyNamed: "doesnt_matter")
expect(validationResult.valid).to(beTrue())
expect((value as! Int)).to(equal(99))
}
}
context("When a switch field is passed as formField") {
it("returns 0 or 1 accordingly") {
let switchControl = UISwitch()
switchControl.on = true
let (validationResult, value) = IntTypeFormField().getValueFromFormField(switchControl, forPropertyNamed: "yep")
expect(validationResult.valid).to(beTrue())
expect((value as! Int)).to(equal(1))
switchControl.on = false
let (validationResult2, value2) = IntTypeFormField().getValueFromFormField(switchControl, forPropertyNamed: "hi ho")
expect(validationResult2.valid).to(beTrue())
expect((value2 as! Int)).to(equal(0))
}
}
}
describe(".updateValue(onFormField) ") {
context("When a whole number is given") {
it("sets the value and returns valid result") {
var textField = UITextField()
let validationResult = IntTypeFormField().updateValue(999, onFormField:textField, forPropertyNamed: "goofy")
expect(validationResult.valid).to(beTrue())
expect(textField.text).to(equal("999"))
}
}
pending("When a float number is given") {
it("sets the rounded value and returns invalid result") {
// not sure if this is even desirable. It requires a NumberFormatter and just not going to go that far today
var textField = UITextField()
let validationResult = IntTypeFormField().updateValue(99.9, onFormField:textField, forPropertyNamed: "goofy")
expect(validationResult.valid).to(beFalse())
expect(textField.text).to(equal("100"))
}
}
context("When a string is given") {
it("sets 0 and returns invalid result") {
var textField = UITextField()
let validationResult = IntTypeFormField().updateValue("whoa", onFormField:textField, forPropertyNamed: "goofy")
expect(validationResult.valid).to(beFalse())
expect(textField.text).to(equal(""))
}
}
}
}
}
| mit | cba7b2287fc5861054460076d67b905e | 38.018868 | 138 | 0.508221 | 5.760446 | false | false | false | false |
pollarm/HanekeSwift | Haneke/UIButton+Haneke.swift | 1 | 11891 | //
// UIButton+Haneke.swift
// Haneke
//
// Created by Joan Romano on 10/1/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension UIButton {
public var hnk_imageFormat : Format<UIImage> {
let bounds = self.bounds
assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.")
let contentRect = self.contentRect(forBounds: bounds)
let imageInsets = self.imageEdgeInsets
let scaleMode = self.contentHorizontalAlignment != UIControl.ContentHorizontalAlignment.fill || self.contentVerticalAlignment != UIControl.ContentVerticalAlignment.fill ? ImageResizer.ScaleMode.AspectFit : ImageResizer.ScaleMode.Fill
let imageSize = CGSize(width: contentRect.width - imageInsets.left - imageInsets.right, height: contentRect.height - imageInsets.top - imageInsets.bottom)
return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: scaleMode, allowUpscaling: scaleMode == ImageResizer.ScaleMode.AspectFit ? false : true)
}
public func hnk_setImageFromURL(_ URL: Foundation.URL, state: UIControl.State = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(URL: URL)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImage(_ image: UIImage, key: String, state: UIControl.State = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setImageFromFile(_ path: String, state: UIControl.State = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setImageFromFetcher(_ fetcher: Fetcher<UIImage>, state: UIControl.State = .normal, placeholder: UIImage? = nil, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())? = nil, success succeed: ((UIImage) -> ())? = nil){
self.hnk_cancelSetImage()
self.hnk_imageFetcher = fetcher
let didSetImage = self.hnk_fetchImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.setImage(placeholder, for: state)
}
}
public func hnk_cancelSetImage() {
if let fetcher = self.hnk_imageFetcher {
fetcher.cancelFetch()
self.hnk_imageFetcher = nil
}
}
// MARK: Internal Image
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_imageFetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.hnk_value as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func hnk_fetchImageForFetcher(_ fetcher : Fetcher<UIImage>, state : UIControl.State = .normal, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let format = format ?? self.hnk_imageFormat
let cache = Shared.imageCache
if cache.formats[format.name] == nil {
cache.addFormat(format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return }
strongSelf.hnk_imageFetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelImageForKey(fetcher.key) { return }
strongSelf.hnk_setImage(image, state: state, animated: animated, success: succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setImage(_ image : UIImage, state : UIControl.State, animated : Bool, success succeed : ((UIImage) -> ())?) {
self.hnk_imageFetcher = nil
if let succeed = succeed {
succeed(image)
} else if animated {
UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: {
self.setImage(image, for: state)
}, completion: nil)
} else {
self.setImage(image, for: state)
}
}
func hnk_shouldCancelImageForKey(_ key:String) -> Bool {
if self.hnk_imageFetcher?.key == key { return false }
Log.debug(message: "Cancelled set image for \((key as NSString).lastPathComponent)")
return true
}
// MARK: Background image
public var hnk_backgroundImageFormat : Format<UIImage> {
let bounds = self.bounds
assert(bounds.size.width > 0 && bounds.size.height > 0, "[\(Mirror(reflecting: self).description) \(#function)]: UIButton size is zero. Set its frame, call sizeToFit or force layout first. You can also set a custom format with a defined size if you don't want to force layout.")
let imageSize = self.backgroundRect(forBounds: bounds).size
return HanekeGlobals.UIKit.formatWithSize(imageSize, scaleMode: .Fill)
}
public func hnk_setBackgroundImageFromURL(_ URL : Foundation.URL, state : UIControl.State = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = NetworkFetcher<UIImage>(URL: URL)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setBackgroundImage(_ image : UIImage, key: String, state : UIControl.State = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, success: succeed)
}
public func hnk_setBackgroundImageFromFile(_ path: String, state : UIControl.State = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
let fetcher = DiskFetcher<UIImage>(path: path)
self.hnk_setBackgroundImageFromFetcher(fetcher, state: state, placeholder: placeholder, format: format, failure: fail, success: succeed)
}
public func hnk_setBackgroundImageFromFetcher(_ fetcher : Fetcher<UIImage>, state : UIControl.State = .normal, placeholder : UIImage? = nil, format : Format<UIImage>? = nil, failure fail : ((Error?) -> ())? = nil, success succeed : ((UIImage) -> ())? = nil) {
self.hnk_cancelSetBackgroundImage()
self.hnk_backgroundImageFetcher = fetcher
let didSetImage = self.hnk_fetchBackgroundImageForFetcher(fetcher, state: state, format : format, failure: fail, success: succeed)
if didSetImage { return }
if let placeholder = placeholder {
self.setBackgroundImage(placeholder, for: state)
}
}
public func hnk_cancelSetBackgroundImage() {
if let fetcher = self.hnk_backgroundImageFetcher {
fetcher.cancelFetch()
self.hnk_backgroundImageFetcher = nil
}
}
// MARK: Internal Background image
// See: http://stackoverflow.com/questions/25907421/associating-swift-things-with-nsobject-instances
var hnk_backgroundImageFetcher : Fetcher<UIImage>! {
get {
let wrapper = objc_getAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey) as? ObjectWrapper
let fetcher = wrapper?.hnk_value as? Fetcher<UIImage>
return fetcher
}
set (fetcher) {
var wrapper : ObjectWrapper?
if let fetcher = fetcher {
wrapper = ObjectWrapper(value: fetcher)
}
objc_setAssociatedObject(self, &HanekeGlobals.UIKit.SetBackgroundImageFetcherKey, wrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func hnk_fetchBackgroundImageForFetcher(_ fetcher: Fetcher<UIImage>, state: UIControl.State = .normal, format: Format<UIImage>? = nil, failure fail: ((Error?) -> ())?, success succeed : ((UIImage) -> ())?) -> Bool {
let format = format ?? self.hnk_backgroundImageFormat
let cache = Shared.imageCache
if cache.formats[format.name] == nil {
cache.addFormat(format)
}
var animated = false
let fetch = cache.fetch(fetcher: fetcher, formatName: format.name, failure: {[weak self] error in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return }
strongSelf.hnk_backgroundImageFetcher = nil
fail?(error)
}
}) { [weak self] image in
if let strongSelf = self {
if strongSelf.hnk_shouldCancelBackgroundImageForKey(fetcher.key) { return }
strongSelf.hnk_setBackgroundImage(image, state: state, animated: animated, success: succeed)
}
}
animated = true
return fetch.hasSucceeded
}
func hnk_setBackgroundImage(_ image: UIImage, state: UIControl.State, animated: Bool, success succeed: ((UIImage) -> ())?) {
self.hnk_backgroundImageFetcher = nil
if let succeed = succeed {
succeed(image)
} else if animated {
UIView.transition(with: self, duration: HanekeGlobals.UIKit.SetImageAnimationDuration, options: .transitionCrossDissolve, animations: {
self.setBackgroundImage(image, for: state)
}, completion: nil)
} else {
self.setBackgroundImage(image, for: state)
}
}
func hnk_shouldCancelBackgroundImageForKey(_ key: String) -> Bool {
if self.hnk_backgroundImageFetcher?.key == key { return false }
Log.debug(message: "Cancelled set background image for \((key as NSString).lastPathComponent)")
return true
}
}
| apache-2.0 | cbb822515a99e94962095625de350e11 | 49.816239 | 286 | 0.628963 | 4.83374 | false | false | false | false |
Brandon-J-Campbell/codemash | AutoLayoutSession/demos/demo6/codemash/ContainerViewController.swift | 4 | 6005 | //
// ContainerViewController.swift
// codemash
//
// Created by Brandon Campbell on 12/5/16.
// Copyright © 2016 Brandon Campbell. All rights reserved.
//
import Foundation
import UIKit
class ContainerRow {
var tabName : String?
var items = Array<ContainerRow>()
convenience init(withTabName: String) {
self.init()
self.tabName = withTabName
}
convenience init(items: Array<ContainerRow>) {
self.init()
self.items = items
}
}
class ContainerCell : UICollectionViewCell {
var viewController : ScheduleTableViewController?
static func cellIdentifier() -> String {
return "ContainerCell"
}
static func cell(forCollectionView collectionView: UICollectionView, indexPath: IndexPath, tabName: String) -> ContainerCell {
let cell : ContainerCell = collectionView.dequeueReusableCell(withReuseIdentifier: ContainerCell.cellIdentifier(), for: indexPath) as! ContainerCell
return cell
}
}
class ContainerViewController : UICollectionViewController {
var data = Dictionary<String, Array<Session>>()
var sessions : Array<Session> = Array<Session>.init()
var sections = Array<ContainerRow>()
override func viewDidLoad() {
super.viewDidLoad()
/*
let urlSession = URLSession.shared
urlSession.dataTask(with: URL.init(string: "https://speakers.codemash.org/api/SessionsData/")!, completionHandler: { (data, response, error) -> Void in
if let HTTPResponse = response as? HTTPURLResponse {
let statusCode = HTTPResponse.statusCode
if(data == nil || error != nil || statusCode != 200) {
print(error.debugDescription)
} else {
do {
let convertedString = String(data: data!, encoding: String.Encoding.utf8) // the data will be converted to the string
print(convertedString!)
let array : Array<Any?> = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments]) as! Array<Any?>
for dict : Dictionary<String, Any> in array as! Array<Dictionary<String, Any>> {
let session = Session.parse(fromDictionary: dict)
self.sessions.append(session)
}
} catch {
print(error.localizedDescription)
}
DispatchQueue.main.async {
self.setupSections()
}
}
}
}).resume()
*/
var rawSessions = Array<Session>.init()
if let url = Bundle.main.url(forResource: "SessionsData", withExtension: "json") {
if let data = NSData(contentsOf: url) {
do {
let array : Array<Any?> = try JSONSerialization.jsonObject(with: data as Data, options: [.allowFragments]) as! Array<Any?>
for dict : Dictionary<String, Any> in array as! Array<Dictionary<String, Any>> {
let session = Session.parse(fromDictionary: dict)
rawSessions.append(session)
}
} catch {
print("Error!! Unable to parse SessionsData.json")
}
}
print("Error!! Unable to load SessionsData.json")
}
self.sessions = rawSessions.sorted()
self.setupSections()
}
func setupSections() {
var sections : Array<ContainerRow> = []
var rows : Array<ContainerRow> = []
let dayFormatter = DateFormatter.init()
dayFormatter.dateFormat = "EEEE"
for session in self.sessions {
let day = dayFormatter.string(from: session.startTime)
if data[day] == nil {
data[day] = Array<Session>()
rows.append(ContainerRow.init(withTabName: day))
}
data[day]?.append(session)
}
sections.append(ContainerRow.init(items: rows))
self.sections = sections
self.collectionView?.reloadData()
}
}
extension ContainerViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let section = self.sections[section]
return section.items.count
}
}
extension ContainerViewController {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = self.sections[indexPath.section]
let row = section.items[indexPath.row]
let cell = ContainerCell.cell(forCollectionView: collectionView, indexPath: indexPath, tabName: row.tabName!)
if (cell.viewController == nil) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "ScheduleTableViewController") as! ScheduleTableViewController
cell.viewController = vc
self.addChildViewController(vc)
cell.addSubview((vc.view)!)
vc.view.frame = cell.bounds
vc.view.autoresizingMask = [ .flexibleWidth, .flexibleHeight ]
}
cell.viewController?.sessions = data[row.tabName!]!
return cell
}
}
extension ContainerViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
}
| mit | 6a70f223ff5776558bd032a70b553f63 | 35.387879 | 160 | 0.585443 | 5.370304 | false | false | false | false |
ikesyo/Swiftz | SwiftzTests/ReaderSpec.swift | 2 | 2815 | //
// ReaderSpec.swift
// Swiftz
//
// Created by Matthew Purland on 11/25/15.
// Copyright © 2015 TypeLift. All rights reserved.
//
import XCTest
import Swiftz
import SwiftCheck
class ReaderSpec : XCTestCase {
func testReader() {
func addOne() -> Reader<Int, Int> {
return asks { $0 + 1 }
}
func hello() -> Reader<String, String> {
return asks { "Hello \($0)" }
}
func bye() -> Reader<String, String> {
return asks { "Goodbye \($0)!" }
}
func helloAndGoodbye() -> Reader<String, String> {
return asks { hello().runReader($0) + " and " + bye().runReader($0) }
}
XCTAssert(addOne().runReader(1) == 2)
let input = "Matthew"
let helloReader = hello()
let modifiedHelloReader = helloReader.local({ "\($0) - Local"})
XCTAssert(helloReader.runReader(input) == "Hello \(input)")
XCTAssert(modifiedHelloReader.runReader(input) == "Hello \(input) - Local")
let byeReader = bye()
let modifiedByeReader = byeReader.local({ $0 + " - Local" })
XCTAssert(byeReader.runReader(input) == "Goodbye \(input)!")
XCTAssert(modifiedByeReader.runReader(input) == "Goodbye \(input) - Local!")
let result = hello() >>- { $0.runReader(input) }
XCTAssert(result == "Hello \(input)")
let result2 = bye().runReader(input)
XCTAssert(result2 == "Goodbye \(input)!")
let helloAndGoodbyeReader = helloAndGoodbye()
XCTAssert(helloAndGoodbyeReader.runReader(input) == "Hello \(input) and Goodbye \(input)!")
let lengthResult = runReader(reader { (environment: String) -> Int in
return environment.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
})("Banana")
XCTAssert(lengthResult == 6)
let length : String -> Int = { $0.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) }
let lengthResult2 = runReader(reader(length))("Banana")
XCTAssert(lengthResult2 == 6)
// Ask
let lengthResult3 = (reader { 1234 } >>- runReader)?()
XCTAssert(lengthResult3 == 1234)
let lengthResult4 = hello() >>- runReader
XCTAssert(lengthResult4?("Matthew") == "Hello Matthew")
// Asks
let lengthResult5 = runReader(asks(length))("Banana")
XCTAssert(lengthResult5 == 6)
let lengthReader = runReader(reader(asks))(length)
let lengthResult6 = lengthReader.runReader("Banana")
XCTAssert(lengthResult6 == 6)
// >>-
let lengthResult7 = (asks(length) >>- runReader)?("abc")
XCTAssert(lengthResult7 == .Some(3))
}
}
| bsd-3-clause | 10d34899809074fafa5479c8839e38c4 | 33.317073 | 99 | 0.566098 | 4.53871 | false | false | false | false |
TheTekton/Malibu | Sources/Encoding/MultipartFormEncoder.swift | 1 | 863 | import Foundation
struct MultipartFormEncoder: ParameterEncoding {
// MARK: - ParameterEncoding
func encode(_ parameters: [String: AnyObject]) throws -> Data? {
let string = buildMultipartString(parameters, boundary: boundary)
guard let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
throw MalibuError.invalidParameter
}
return data
}
// MARK: - Helpers
func buildMultipartString(_ parameters: [String: AnyObject], boundary: String) -> String {
var string = ""
let components = QueryBuilder().buildComponents(parameters: parameters)
for (key, value) in components {
string += "--\(boundary)\r\n"
string += "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
string += "\(value)\r\n"
}
string += "--\(boundary)--\r\n"
return string
}
}
| mit | 14c3c0bc70303209d07b31283cc25b7f | 25.151515 | 96 | 0.65701 | 4.251232 | false | false | false | false |
andykkt/BFWControls | BFWControls/Modules/Binding/Controller/Binding.swift | 1 | 2305 | //
// Binding.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 4/07/2016.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
class Binding: NSObject {
// MARK: - Variables
@IBOutlet var view: UIView? {
didSet {
updateBinding()
}
}
@IBInspectable var plist: String? {
didSet {
updateBinding()
}
}
@IBInspectable var viewKeyPath: String? = "text" {
didSet {
updateBinding()
}
}
@IBInspectable var variable: String? {
didSet {
updateBinding()
}
}
private static var rootBindingDict = [String: [String: AnyObject]]()
fileprivate var bindingDict: [String: AnyObject]? {
get {
var bindingDict: [String: AnyObject]?
if let plist = plist {
if let dict = Binding.rootBindingDict[plist] {
bindingDict = dict
} else {
if let path = Bundle.main.path(forResource: plist, ofType: "plist"),
let plistDict = NSDictionary(contentsOfFile: path) as? [String: AnyObject]
{
bindingDict = plistDict
Binding.rootBindingDict[plist] = bindingDict
}
}
}
return bindingDict
}
}
// MARK: - Functions
private func updateBinding() {
if let view = view,
let keyPath = viewKeyPath,
let variable = variable,
let bindingDict = bindingDict,
let value = bindingDict[variable]
{
let string = String(describing: value)
view.setValue(string, forKeyPath: keyPath)
if let textField = view as? UITextField,
viewKeyPath == "text"
{
textField.delegate = self
}
}
}
}
extension Binding: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
if var bindingDict = bindingDict, let variable = variable {
bindingDict[variable] = textField.text as AnyObject?
}
}
}
| mit | 0b908913c93b4531475853b031ed68a6 | 24.6 | 98 | 0.518229 | 5.052632 | false | false | false | false |
GrouponChina/groupon-up | Groupon UP/Groupon UP/MenuViewController.swift | 1 | 4607 | //
// MenuViewController.swift
// Groupon UP
//
// Created by Robert Xue on 11/21/15.
// Copyright © 2015 Chang Liu. All rights reserved.
//
import UIKit
import Parse
import ParseUI
class MenuViewController: BaseViewController {
private var _tableView: UITableView!
private var _userProfileScreen: ProfileViewController!
private var _ordersScreen: OrderViewController!
private var _browseScreen: BrowseViewController!
private var _upNotificationsScreen: UPListViewController!
private var _viewControllers: [UIViewController]!
override func addSubviews() {
view.addSubview(tableView)
}
override func addLayouts() {
tableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(snp_topLayoutGuideBottom)
make.bottom.equalTo(snp_bottomLayoutGuideTop)
make.left.equalTo(view)
make.right.equalTo(view)
}
}
override func initializeUI() {
if let hamburgerVC = (navigationController ?? self).parentViewController as? HamburgerViewController where viewControllers.count > 0 {
hamburgerVC.centerViewController = viewControllers[1]
}
automaticallyAdjustsScrollViewInsets = false
}
}
extension MenuViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewControllers.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell
let reuseId = "command cell"
if let reuseCell = tableView.dequeueReusableCellWithIdentifier(reuseId) {
cell = reuseCell
} else {
cell = UITableViewCell(style: .Default, reuseIdentifier: reuseId)
}
cell.layoutMargins = UIEdgeInsetsZero
cell.preservesSuperviewLayoutMargins = false
cell.separatorInset = UIEdgeInsetsZero
switch indexPath.row {
case 0:
// Profile cell
cell.textLabel?.text = "PROFILE"
case 1:
// Browse Deals
cell.textLabel?.text = "DEALS"
case 2:
// Home timeline
cell.textLabel?.text = "MY GROUPON"
case 3:
// Home timeline
cell.textLabel?.text = "GROUPON UP"
default:
break
}
return cell
}
}
extension MenuViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if let hamburgerVC = (navigationController ?? self).parentViewController as? HamburgerViewController {
hamburgerVC.centerViewController = viewControllers[indexPath.row]
hamburgerVC.closeLeftView()
}
}
}
extension MenuViewController {
var tableView: UITableView {
if _tableView == nil {
let v = UITableView()
v.dataSource = self
v.delegate = self
v.tableFooterView = UIView()
_tableView = v
}
return _tableView
}
var viewControllers: [UIViewController] {
if _viewControllers == nil {
_viewControllers = [
MenuEnabledNavigationViewController(rootViewController: userProfileScreen),
MenuEnabledNavigationViewController(rootViewController: browseScreen),
MenuEnabledNavigationViewController(rootViewController: ordersScreen),
MenuEnabledNavigationViewController(rootViewController: upNotificationsScreen)
]
}
return _viewControllers
}
var userProfileScreen: ProfileViewController {
if _userProfileScreen == nil {
let s = ProfileViewController()
_userProfileScreen = s
}
return _userProfileScreen
}
var ordersScreen: OrderViewController {
if _ordersScreen == nil {
let s = OrderViewController()
_ordersScreen = s
}
return _ordersScreen
}
var browseScreen: BrowseViewController {
if _browseScreen == nil {
_browseScreen = BrowseViewController()
}
return _browseScreen
}
var upNotificationsScreen: UPListViewController {
if _upNotificationsScreen == nil {
let s = UPListViewController()
_upNotificationsScreen = s
}
return _upNotificationsScreen
}
}
| apache-2.0 | bee8d566f5f249ab2d6ef2cf55364c15 | 31.20979 | 142 | 0.634824 | 5.651534 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Nodes/Generators/Noise/Pink Noise/AKPinkNoise.swift | 1 | 3221 | //
// AKPinkNoise.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Faust-based pink noise generator
///
/// - parameter amplitude: Amplitude. (Value between 0-1).
///
public class AKPinkNoise: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKPinkNoiseAudioUnit?
internal var token: AUParameterObserverToken?
private var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Amplitude. (Value between 0-1).
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this noise node
///
/// - parameter amplitude: Amplitude. (Value between 0-1).
///
public init(amplitude: Double = 1) {
self.amplitude = amplitude
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x70696e6b /*'pink'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKPinkNoiseAudioUnit.self,
asComponentDescription: description,
name: "Local AKPinkNoise",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPinkNoiseAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.amplitude = Float(amplitude)
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | c841ff1a0ed103483fcf126c781b64df | 28.281818 | 87 | 0.620615 | 5.323967 | false | false | false | false |
iOSTestApps/firefox-ios | Client/Frontend/Home/ReaderPanel.swift | 1 | 21475 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Storage
import ReadingList
import Shared
private struct ReadingListTableViewCellUX {
static let RowHeight: CGFloat = 86
static let ActiveTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
static let DimmedTextColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.44)
static let ReadIndicatorWidth: CGFloat = 12 // image width
static let ReadIndicatorHeight: CGFloat = 12 // image height
static let ReadIndicatorTopOffset: CGFloat = 36.75 // half of the cell - half of the height of the asset
static let ReadIndicatorLeftOffset: CGFloat = 18
static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest
static let TitleLabelFont = UIFont.systemFontOfSize(15, weight: UIFontWeightMedium)
static let TitleLabelTopOffset: CGFloat = 14 - 4
static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16
static let TitleLabelRightOffset: CGFloat = -40
static let HostnameLabelFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight)
static let HostnameLabelBottomOffset: CGFloat = 11
static let DeleteButtonBackgroundColor = UIColor(rgb: 0xef4035)
static let DeleteButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight)
static let DeleteButtonTitleColor = UIColor.whiteColor()
static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
static let MarkAsReadButtonBackgroundColor = UIColor(rgb: 0x2193d1)
static let MarkAsReadButtonTitleFont = UIFont.systemFontOfSize(15, weight: UIFontWeightLight)
static let MarkAsReadButtonTitleColor = UIColor.whiteColor()
static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
// Localizable strings
static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item")
static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read")
static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread")
}
private struct ReadingListPanelUX {
// Welcome Screen
static let WelcomeScreenTopPadding: CGFloat = 16
static let WelcomeScreenPadding: CGFloat = 10
static let WelcomeScreenHeaderFont = UIFont.boldSystemFontOfSize(14)
static let WelcomeScreenHeaderTextColor = UIColor.darkGrayColor()
static let WelcomeScreenItemFont = UIFont.systemFontOfSize(14, weight: UIFontWeightLight)
static let WelcomeScreenItemTextColor = UIColor.lightGrayColor()
static let WelcomeScreenItemWidth = 220
static let WelcomeScreenItemOffset = -20
static let WelcomeScreenCircleWidth = 40
static let WelcomeScreenCircleOffset = 20
static let WelcomeScreenCircleSpacer = 10
}
class ReadingListTableViewCell: SWTableViewCell {
var title: String = "Example" {
didSet {
titleLabel.text = title
updateAccessibilityLabel()
}
}
var url: NSURL = NSURL(string: "http://www.example.com")! {
didSet {
hostnameLabel.text = simplifiedHostnameFromURL(url)
updateAccessibilityLabel()
}
}
var unread: Bool = true {
didSet {
readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")
titleLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
hostnameLabel.textColor = unread ? ReadingListTableViewCellUX.ActiveTextColor : ReadingListTableViewCellUX.DimmedTextColor
markAsReadButton.setTitle(unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText, forState: UIControlState.Normal)
markAsReadAction.name = markAsReadButton.titleLabel!.text
updateAccessibilityLabel()
}
}
private let deleteAction: UIAccessibilityCustomAction
private let markAsReadAction: UIAccessibilityCustomAction
let readStatusImageView: UIImageView!
let titleLabel: UILabel!
let hostnameLabel: UILabel!
let deleteButton: UIButton!
let markAsReadButton: UIButton!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
readStatusImageView = UIImageView()
titleLabel = UILabel()
hostnameLabel = UILabel()
deleteButton = UIButton()
markAsReadButton = UIButton()
deleteAction = UIAccessibilityCustomAction()
markAsReadAction = UIAccessibilityCustomAction()
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clearColor()
separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0)
layoutMargins = UIEdgeInsetsZero
preservesSuperviewLayoutMargins = false
contentView.addSubview(readStatusImageView)
readStatusImageView.contentMode = UIViewContentMode.ScaleAspectFit
readStatusImageView.snp_makeConstraints { (make) -> () in
make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth)
make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight)
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset)
}
contentView.addSubview(titleLabel)
titleLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
titleLabel.numberOfLines = 2
titleLabel.font = ReadingListTableViewCellUX.TitleLabelFont
titleLabel.snp_makeConstraints { (make) -> () in
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset)
make.left.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset)
make.right.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec
}
contentView.addSubview(hostnameLabel)
hostnameLabel.textColor = ReadingListTableViewCellUX.ActiveTextColor
hostnameLabel.numberOfLines = 1
hostnameLabel.font = ReadingListTableViewCellUX.HostnameLabelFont
hostnameLabel.snp_makeConstraints { (make) -> () in
make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)
make.left.right.equalTo(self.titleLabel)
}
deleteButton.backgroundColor = ReadingListTableViewCellUX.DeleteButtonBackgroundColor
deleteButton.titleLabel?.font = ReadingListTableViewCellUX.DeleteButtonTitleFont
deleteButton.titleLabel?.textColor = ReadingListTableViewCellUX.DeleteButtonTitleColor
deleteButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
deleteButton.titleLabel?.textAlignment = NSTextAlignment.Center
deleteButton.setTitle(ReadingListTableViewCellUX.DeleteButtonTitleText, forState: UIControlState.Normal)
deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
deleteButton.titleEdgeInsets = ReadingListTableViewCellUX.DeleteButtonTitleEdgeInsets
deleteAction.name = deleteButton.titleLabel!.text
deleteAction.target = self
deleteAction.selector = "deleteActionActivated"
rightUtilityButtons = [deleteButton]
markAsReadButton.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor
markAsReadButton.titleLabel?.font = ReadingListTableViewCellUX.MarkAsReadButtonTitleFont
markAsReadButton.titleLabel?.textColor = ReadingListTableViewCellUX.MarkAsReadButtonTitleColor
markAsReadButton.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
markAsReadButton.titleLabel?.textAlignment = NSTextAlignment.Center
markAsReadButton.setTitle(ReadingListTableViewCellUX.MarkAsReadButtonTitleText, forState: UIControlState.Normal)
markAsReadButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
markAsReadButton.titleEdgeInsets = ReadingListTableViewCellUX.MarkAsReadButtonTitleEdgeInsets
markAsReadAction.name = markAsReadButton.titleLabel!.text
markAsReadAction.target = self
markAsReadAction.selector = "markAsReadActionActivated"
leftUtilityButtons = [markAsReadButton]
accessibilityCustomActions = [deleteAction, markAsReadAction]
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
private func simplifiedHostnameFromURL(url: NSURL) -> String {
let hostname = url.host ?? ""
for prefix in prefixesToSimplify {
if hostname.hasPrefix(prefix) {
return hostname.substringFromIndex(advance(hostname.startIndex, count(prefix)))
}
}
return hostname
}
@objc private func markAsReadActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerLeftUtilityButtonWithIndex: 0)
return true
}
@objc private func deleteActionActivated() -> Bool {
self.delegate?.swipeableTableViewCell?(self, didTriggerRightUtilityButtonWithIndex: 0)
return true
}
private func updateAccessibilityLabel() {
if let hostname = hostnameLabel.text,
title = titleLabel.text {
let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.")
let string = "\(title), \(unreadStatus), \(hostname)"
var label: AnyObject
if !unread {
// mimic light gray visual dimming by "dimming" the speech by reducing pitch
let lowerPitchString = NSMutableAttributedString(string: string as String)
lowerPitchString.addAttribute(UIAccessibilitySpeechAttributePitch, value: NSNumber(float: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch), range: NSMakeRange(0, lowerPitchString.length))
label = NSAttributedString(attributedString: lowerPitchString)
} else {
label = string
}
// need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this
// see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple
// also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly...
setValue(label, forKey: "accessibilityLabel")
}
}
}
class ReadingListEmptyStateView: UIView {
convenience init() {
self.init(frame: CGRectZero)
}
}
class ReadingListPanel: UITableViewController, HomePanel, SWTableViewCellDelegate {
weak var homePanelDelegate: HomePanelDelegate? = nil
var profile: Profile!
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverview()
private var records: [ReadingListClientRecord]?
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "firefoxAccountChanged:", name: NotificationFirefoxAccountChanged, object: nil)
}
required init!(coder aDecoder: NSCoder!) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = ReadingListTableViewCellUX.RowHeight
tableView.separatorInset = UIEdgeInsetsZero
tableView.layoutMargins = UIEdgeInsetsZero
tableView.separatorColor = UIConstants.SeparatorColor
tableView.registerClass(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell")
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
view.backgroundColor = UIConstants.PanelBackgroundColor
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
// If no records have been added yet, we display the empty state
if records?.count == 0 {
tableView.scrollEnabled = false
view.addSubview(emptyStateOverlayView)
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
func firefoxAccountChanged(notification: NSNotification) {
if notification.name == NotificationFirefoxAccountChanged {
let prevNumberOfRecords = records?.count
if let result = profile.readingList?.getAvailableRecords() where result.isSuccess {
records = result.successValue
if records?.count == 0 {
tableView.scrollEnabled = false
if emptyStateOverlayView.superview == nil {
view.addSubview(emptyStateOverlayView)
}
} else {
if prevNumberOfRecords == 0 {
tableView.scrollEnabled = true
emptyStateOverlayView.removeFromSuperview()
}
}
self.tableView.reloadData()
}
}
}
private func createEmptyStateOverview() -> UIView {
let overlayView = UIView(frame: tableView.bounds)
overlayView.backgroundColor = UIColor.whiteColor()
// Unknown why this does not work with autolayout
overlayView.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
let containerView = UIView()
overlayView.addSubview(containerView)
let logoImageView = UIImageView(image: UIImage(named: "ReadingListEmptyPanel"))
containerView.addSubview(logoImageView)
logoImageView.snp_makeConstraints({ (make) -> Void in
make.centerX.equalTo(containerView)
make.top.equalTo(containerView)
})
let welcomeLabel = UILabel()
containerView.addSubview(welcomeLabel)
welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL")
welcomeLabel.textAlignment = NSTextAlignment.Center
welcomeLabel.font = ReadingListPanelUX.WelcomeScreenHeaderFont
welcomeLabel.textColor = ReadingListPanelUX.WelcomeScreenHeaderTextColor
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp_makeConstraints({ (make) -> Void in
make.centerX.equalTo(containerView)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth)
make.top.equalTo(logoImageView.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
})
let readerModeLabel = UILabel()
containerView.addSubview(readerModeLabel)
readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL")
readerModeLabel.font = ReadingListPanelUX.WelcomeScreenItemFont
readerModeLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readerModeLabel.numberOfLines = 0
readerModeLabel.snp_makeConstraints({ (make) -> Void in
make.top.equalTo(welcomeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
})
let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle"))
containerView.addSubview(readerModeImageView)
readerModeImageView.snp_makeConstraints({ (make) -> Void in
make.centerY.equalTo(readerModeLabel)
make.right.equalTo(welcomeLabel.snp_right)
})
let readingListLabel = UILabel()
containerView.addSubview(readingListLabel)
readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL")
readingListLabel.font = ReadingListPanelUX.WelcomeScreenItemFont
readingListLabel.textColor = ReadingListPanelUX.WelcomeScreenItemTextColor
readingListLabel.numberOfLines = 0
readingListLabel.snp_makeConstraints({ (make) -> Void in
make.top.equalTo(readerModeLabel.snp_bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.left.equalTo(welcomeLabel.snp_left)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
})
let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle"))
containerView.addSubview(readingListImageView)
readingListImageView.snp_makeConstraints({ (make) -> Void in
make.centerY.equalTo(readingListLabel)
make.right.equalTo(welcomeLabel.snp_right)
})
containerView.snp_makeConstraints({ (make) -> Void in
// Let the container wrap around the content
make.top.equalTo(overlayView.snp_top).offset(20)
make.bottom.equalTo(readingListLabel.snp_bottom)
make.left.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenItemOffset)
make.right.equalTo(welcomeLabel).offset(ReadingListPanelUX.WelcomeScreenCircleOffset)
// And then center it in the overlay view that sits on top of the UITableView
make.centerX.equalTo(overlayView)
})
return overlayView
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records?.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ReadingListTableViewCell", forIndexPath: indexPath) as! ReadingListTableViewCell
cell.delegate = self
if let record = records?[indexPath.row] {
cell.title = record.title
cell.url = NSURL(string: record.url)!
cell.unread = record.unread
}
return cell
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerLeftUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell {
cell.hideUtilityButtonsAnimated(true)
if let indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.updateRecord(record, unread: !record.unread) where result.isSuccess {
// TODO This is a bit odd because the success value of the update is an optional optional Record
if let successValue = result.successValue, updatedRecord = successValue {
records?[indexPath.row] = updatedRecord
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
}
}
func swipeableTableViewCell(cell: SWTableViewCell!, didTriggerRightUtilityButtonWithIndex index: Int) {
if let cell = cell as? ReadingListTableViewCell, indexPath = tableView.indexPathForCell(cell), record = records?[indexPath.row] {
if let result = profile.readingList?.deleteRecord(record) where result.isSuccess {
records?.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
// reshow empty state if no records left
if records?.count == 0 {
view.addSubview(emptyStateOverlayView)
}
}
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let record = records?[indexPath.row], encodedURL = ReaderModeUtils.encodeURL(NSURL(string: record.url)!) {
// Reading list items are closest in concept to bookmarks.
let visitType = VisitType.Bookmark
homePanelDelegate?.homePanel(self, didSelectURL: encodedURL, visitType: visitType)
}
}
}
| mpl-2.0 | b1595e6a3b610de19a1ebcb8a61aae54 | 48.710648 | 333 | 0.707427 | 5.862681 | false | false | false | false |
codefellows/sea-d40-iOS | Sample Code/Week3Github/GithubClient/GithubClient/AppDelegate.swift | 1 | 2666 | //
// AppDelegate.swift
// GithubClient
//
// Created by Bradley Johnson on 8/17/15.
// Copyright (c) 2015 CF. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if let token = KeychainService.loadToken() {
} else {
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
if let loginVC = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as? LoginViewController {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
window?.rootViewController = loginVC
}
}
GithubService.createFileOnRepo()
return true
}
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
println(url)
AuthService.exchangeCodeInURL(url)
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 81ebe7512e4aa2456ec806970d88b0a5 | 39.393939 | 281 | 0.750563 | 5.385859 | false | false | false | false |
k0nserv/SwiftTracer-Core | Sources/Math/Vector.swift | 1 | 2382 | //
// Vector.swift
// SwiftTracer
//
// Created by Hugo Tunius on 09/08/15.
// Copyright © 2015 Hugo Tunius. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
public struct Vector : Equatable {
public let x: Double
public let y: Double
public let z: Double
public init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
public func dot(_ other: Vector) -> Double {
return x * other.x + y * other.y + z * other.z
}
public func cross(_ other: Vector) -> Vector {
let x0 = y * other.z - z * other.y
let y0 = z * other.x - x * other.z
let z0 = x * other.y - y * other.x
return Vector(x: x0, y: y0, z: z0)
}
public func length() -> Double {
return sqrt(dot(self))
}
public func normalize() -> Vector {
let l = length()
if l == 0 {
return Vector(x: 0.0, y: 0.0, z: 0.0)
}
return Vector(x: (x / l), y: (y / l), z: (z / l))
}
public func reflect(_ normal: Vector) -> Vector {
return self - normal * 2 * self.dot(normal)
}
func fuzzyEquals(_ other: Vector) -> Bool {
var result = true
result = result && abs(x - other.x) < 0.001
result = result && abs(y - other.y) < 0.001
result = result && abs(z - other.z) < 0.001
return result
}
}
public func ==(left: Vector, right: Vector) -> Bool {
return left.x == right.x &&
left.y == right.y &&
left.z == right.z
}
public func -(left: Vector, right: Vector) -> Vector {
return newVector(left: left, right: right) {
$0 - $1
}
}
public func +(left: Vector, right: Vector) -> Vector {
return newVector(left: left, right: right) {
$0 + $1
}
}
public func *(left: Vector, right: Vector) -> Vector {
return newVector(left: left, right: right) {
$0 * $1
}
}
public prefix func -(left: Vector) -> Vector {
return left * -1
}
public func *(left: Vector, right: Double) -> Vector {
return Vector(x: left.x * right, y: left.y * right, z: left.z * right)
}
private func newVector(left: Vector, right: Vector, closure: (Double, Double) -> Double) -> Vector {
return Vector(x: closure(left.x, right.x), y: closure(left.y, right.y), z: closure(left.z, right.z))
}
| mit | ae3df76b6eaf5c73992ed322d1cfba9a | 22.574257 | 104 | 0.544309 | 3.213225 | false | false | false | false |
exponent/exponent | ios/vendored/sdk43/@stripe/stripe-react-native/ios/StripeSdk.swift | 2 | 39112 | import PassKit
import Stripe
@objc(ABI43_0_0StripeSdk)
class StripeSdk: ABI43_0_0RCTEventEmitter, STPApplePayContextDelegate, STPBankSelectionViewControllerDelegate, UIAdaptivePresentationControllerDelegate {
public var cardFieldView: CardFieldView? = nil
public var cardFormView: CardFormView? = nil
var merchantIdentifier: String? = nil
private var paymentSheet: PaymentSheet?
private var paymentSheetFlowController: PaymentSheet.FlowController?
var urlScheme: String? = nil
var applePayCompletionCallback: STPIntentClientSecretCompletionBlock? = nil
var applePayRequestResolver: ABI43_0_0RCTPromiseResolveBlock? = nil
var applePayRequestRejecter: ABI43_0_0RCTPromiseRejectBlock? = nil
var applePayCompletionRejecter: ABI43_0_0RCTPromiseRejectBlock? = nil
var confirmApplePayPaymentResolver: ABI43_0_0RCTPromiseResolveBlock? = nil
var confirmPaymentResolver: ABI43_0_0RCTPromiseResolveBlock? = nil
var confirmPaymentClientSecret: String? = nil
var shippingMethodUpdateHandler: ((PKPaymentRequestShippingMethodUpdate) -> Void)? = nil
var shippingContactUpdateHandler: ((PKPaymentRequestShippingContactUpdate) -> Void)? = nil
override func supportedEvents() -> [String]! {
return ["onDidSetShippingMethod", "onDidSetShippingContact"]
}
@objc override static func requiresMainQueueSetup() -> Bool {
return false
}
@objc(initialise:resolver:rejecter:)
func initialise(params: NSDictionary, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) -> Void {
let publishableKey = params["publishableKey"] as! String
let appInfo = params["appInfo"] as! NSDictionary
let stripeAccountId = params["stripeAccountId"] as? String
let params3ds = params["threeDSecureParams"] as? NSDictionary
let urlScheme = params["urlScheme"] as? String
let merchantIdentifier = params["merchantIdentifier"] as? String
if let params3ds = params3ds {
configure3dSecure(params3ds)
}
self.urlScheme = urlScheme
STPAPIClient.shared.publishableKey = publishableKey
STPAPIClient.shared.stripeAccount = stripeAccountId
let name = ABI43_0_0RCTConvert.nsString(appInfo["name"]) ?? ""
let partnerId = ABI43_0_0RCTConvert.nsString(appInfo["partnerId"]) ?? ""
let version = ABI43_0_0RCTConvert.nsString(appInfo["version"]) ?? ""
let url = ABI43_0_0RCTConvert.nsString(appInfo["url"]) ?? ""
STPAPIClient.shared.appInfo = STPAppInfo(name: name, partnerId: partnerId, version: version, url: url)
self.merchantIdentifier = merchantIdentifier
resolve(NSNull())
}
@objc(initPaymentSheet:resolver:rejecter:)
func initPaymentSheet(params: NSDictionary, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) -> Void {
var configuration = PaymentSheet.Configuration()
if params["applePay"] as? Bool == true {
if let merchantIdentifier = self.merchantIdentifier, let merchantCountryCode = params["merchantCountryCode"] as? String {
configuration.applePay = .init(merchantId: merchantIdentifier,
merchantCountryCode: merchantCountryCode)
} else {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "Either merchantIdentifier or merchantCountryCode is missing"))
return
}
}
if let merchantDisplayName = params["merchantDisplayName"] as? String {
configuration.merchantDisplayName = merchantDisplayName
}
if let customerId = params["customerId"] as? String {
if let customerEphemeralKeySecret = params["customerEphemeralKeySecret"] as? String {
if (!Errors.isEKClientSecretValid(clientSecret: customerEphemeralKeySecret)) {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`customerEphemeralKeySecret` format does not match expected client secret formatting."))
return
}
configuration.customer = .init(id: customerId, ephemeralKeySecret: customerEphemeralKeySecret)
}
}
if #available(iOS 13.0, *) {
if let style = params["style"] as? String {
configuration.style = Mappers.mapToUserInterfaceStyle(style)
}
}
func handlePaymentSheetFlowControllerResult(result: Result<PaymentSheet.FlowController, Error>, stripeSdk: StripeSdk?) {
switch result {
case .failure(let error):
resolve(Errors.createError("Failed", error as NSError))
case .success(let paymentSheetFlowController):
self.paymentSheetFlowController = paymentSheetFlowController
if let paymentOption = stripeSdk?.paymentSheetFlowController?.paymentOption {
let option: NSDictionary = [
"label": paymentOption.label,
"image": paymentOption.image.pngData()?.base64EncodedString() ?? ""
]
resolve(Mappers.createResult("paymentOption", option))
} else {
resolve(Mappers.createResult("paymentOption", nil))
}
}
}
if let paymentIntentClientSecret = params["paymentIntentClientSecret"] as? String {
if (!Errors.isPIClientSecretValid(clientSecret: paymentIntentClientSecret)) {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`secret` format does not match expected client secret formatting."))
return
}
if params["customFlow"] as? Bool == true {
PaymentSheet.FlowController.create(paymentIntentClientSecret: paymentIntentClientSecret,
configuration: configuration) { [weak self] result in
handlePaymentSheetFlowControllerResult(result: result, stripeSdk: self)
}
} else {
self.paymentSheet = PaymentSheet(paymentIntentClientSecret: paymentIntentClientSecret, configuration: configuration)
resolve([])
}
} else if let setupIntentClientSecret = params["setupIntentClientSecret"] as? String {
if (!Errors.isSetiClientSecretValid(clientSecret: setupIntentClientSecret)) {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "`secret` format does not match expected client secret formatting."))
return
}
if params["customFlow"] as? Bool == true {
PaymentSheet.FlowController.create(setupIntentClientSecret: setupIntentClientSecret,
configuration: configuration) { [weak self] result in
handlePaymentSheetFlowControllerResult(result: result, stripeSdk: self)
}
} else {
self.paymentSheet = PaymentSheet(setupIntentClientSecret: setupIntentClientSecret, configuration: configuration)
resolve([])
}
} else {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "You must provide either paymentIntentClientSecret or setupIntentClientSecret"))
}
}
@objc(confirmPaymentSheetPayment:rejecter:)
func confirmPaymentSheetPayment(resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) -> Void {
DispatchQueue.main.async {
if (self.paymentSheetFlowController != nil) {
self.paymentSheetFlowController?.confirm(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController()) { paymentResult in
switch paymentResult {
case .completed:
resolve([])
self.paymentSheetFlowController = nil
case .canceled:
resolve(Errors.createError(PaymentSheetErrorType.Canceled.rawValue, "The payment has been canceled"))
case .failed(let error):
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, error.localizedDescription))
}
}
} else {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "No payment sheet has been initialized yet"))
}
}
}
@objc(presentPaymentSheet:rejecter:)
func presentPaymentSheet(resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) -> Void {
DispatchQueue.main.async {
if let paymentSheetFlowController = self.paymentSheetFlowController {
paymentSheetFlowController.presentPaymentOptions(from:
findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController())
) {
if let paymentOption = self.paymentSheetFlowController?.paymentOption {
let option: NSDictionary = [
"label": paymentOption.label,
"image": paymentOption.image.pngData()?.base64EncodedString() ?? ""
]
resolve(Mappers.createResult("paymentOption", option))
} else {
resolve(Mappers.createResult("paymentOption", nil))
}
}
} else if let paymentSheet = self.paymentSheet {
paymentSheet.present(from:
findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController())
) { paymentResult in
switch paymentResult {
case .completed:
resolve([])
self.paymentSheet = nil
case .canceled:
resolve(Errors.createError(PaymentSheetErrorType.Canceled.rawValue, "The payment has been canceled"))
case .failed(let error):
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, error as NSError))
}
}
} else {
resolve(Errors.createError(PaymentSheetErrorType.Failed.rawValue, "No payment sheet has been initialized yet"))
}
}
}
@objc(createTokenForCVCUpdate:resolver:rejecter:)
func createTokenForCVCUpdate(cvc: String?, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
guard let cvc = cvc else {
resolve(Errors.createError("Failed", "You must provide CVC"))
return;
}
STPAPIClient.shared.createToken(forCVCUpdate: cvc) { (token, error) in
if error != nil || token == nil {
resolve(Errors.createError("Failed", error?.localizedDescription ?? ""))
} else {
let tokenId = token?.tokenId
resolve(["tokenId": tokenId])
}
}
}
@objc(confirmSetupIntent:data:options:resolver:rejecter:)
func confirmSetupIntent (setupIntentClientSecret: String, params: NSDictionary,
options: NSDictionary, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String)
guard let paymentMethodType = type else {
resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "You must provide paymentMethodType"))
return
}
var paymentMethodParams: STPPaymentMethodParams?
let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView)
do {
paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType)
} catch {
resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error.localizedDescription))
return
}
guard paymentMethodParams != nil else {
resolve(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Unhandled error occured"))
return
}
let setupIntentParams = STPSetupIntentConfirmParams(clientSecret: setupIntentClientSecret)
setupIntentParams.paymentMethodParams = paymentMethodParams
if let urlScheme = urlScheme {
setupIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme)
}
let paymentHandler = STPPaymentHandler.shared()
paymentHandler.confirmSetupIntent(setupIntentParams, with: self) { status, setupIntent, error in
switch (status) {
case .failed:
resolve(Errors.createError(ConfirmSetupIntentErrorType.Failed.rawValue, error))
break
case .canceled:
if let lastError = setupIntent?.lastSetupError {
resolve(Errors.createError(ConfirmSetupIntentErrorType.Canceled.rawValue, lastError))
} else {
resolve(Errors.createError(ConfirmSetupIntentErrorType.Canceled.rawValue, "The payment has been canceled"))
}
break
case .succeeded:
let intent = Mappers.mapFromSetupIntent(setupIntent: setupIntent!)
resolve(Mappers.createResult("setupIntent", intent))
@unknown default:
resolve(Errors.createError(ConfirmSetupIntentErrorType.Unknown.rawValue, error))
break
}
}
}
@objc(updateApplePaySummaryItems:errorAddressFields:resolver:rejecter:)
func updateApplePaySummaryItems(summaryItems: NSArray, errorAddressFields: [NSDictionary], resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
if (shippingMethodUpdateHandler == nil && shippingContactUpdateHandler == nil) {
resolve(Errors.createError(ApplePayErrorType.Failed.rawValue, "You can use this method only after either onDidSetShippingMethod or onDidSetShippingContact events emitted"))
return
}
var paymentSummaryItems: [PKPaymentSummaryItem] = []
if let items = summaryItems as? [[String : Any]] {
for item in items {
let label = item["label"] as? String ?? ""
let amount = NSDecimalNumber(string: item["amount"] as? String ?? "")
let type = Mappers.mapToPaymentSummaryItemType(type: item["type"] as? String)
paymentSummaryItems.append(PKPaymentSummaryItem(label: label, amount: amount, type: type))
}
}
var shippingAddressErrors: [Error] = []
for item in errorAddressFields {
let field = item["field"] as! String
let message = item["message"] as? String ?? field + " error"
shippingAddressErrors.append(PKPaymentRequest.paymentShippingAddressInvalidError(withKey: field, localizedDescription: message))
}
shippingMethodUpdateHandler?(PKPaymentRequestShippingMethodUpdate.init(paymentSummaryItems: paymentSummaryItems))
shippingContactUpdateHandler?(PKPaymentRequestShippingContactUpdate.init(errors: shippingAddressErrors, paymentSummaryItems: paymentSummaryItems, shippingMethods: []))
self.shippingMethodUpdateHandler = nil
self.shippingContactUpdateHandler = nil
resolve([])
}
@objc(openApplePaySetup:rejecter:)
func openApplePaySetup(resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) -> Void {
let library = PKPassLibrary.init()
if (library.responds(to: #selector(PKPassLibrary.openPaymentSetup))) {
library.openPaymentSetup()
resolve([])
} else {
resolve(Errors.createError("Failed", "Cannot open payment setup"))
}
}
func applePayContext(_ context: STPApplePayContext, didSelect shippingMethod: PKShippingMethod, handler: @escaping (PKPaymentRequestShippingMethodUpdate) -> Void) {
self.shippingMethodUpdateHandler = handler
sendEvent(withName: "onDidSetShippingMethod", body: ["shippingMethod": Mappers.mapFromShippingMethod(shippingMethod: shippingMethod)])
}
func applePayContext(_ context: STPApplePayContext, didSelectShippingContact contact: PKContact, handler: @escaping (PKPaymentRequestShippingContactUpdate) -> Void) {
self.shippingContactUpdateHandler = handler
sendEvent(withName: "onDidSetShippingContact", body: ["shippingContact": Mappers.mapFromShippingContact(shippingContact: contact)])
}
func applePayContext(_ context: STPApplePayContext, didCreatePaymentMethod paymentMethod: STPPaymentMethod, paymentInformation: PKPayment, completion: @escaping STPIntentClientSecretCompletionBlock) {
self.applePayCompletionCallback = completion
let address = paymentMethod.billingDetails?.address?.line1?.split(whereSeparator: \.isNewline)
if (address?.indices.contains(0) == true) {
paymentMethod.billingDetails?.address?.line1 = String(address?[0] ?? "")
}
if (address?.indices.contains(1) == true) {
paymentMethod.billingDetails?.address?.line2 = String(address?[1] ?? "")
}
let method = Mappers.mapFromPaymentMethod(paymentMethod)
self.applePayRequestResolver?(Mappers.createResult("paymentMethod", method))
self.applePayRequestRejecter = nil
}
@objc(confirmApplePayPayment:resolver:rejecter:)
func confirmApplePayPayment(clientSecret: String, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
self.applePayCompletionRejecter = reject
self.confirmApplePayPaymentResolver = resolve
self.applePayCompletionCallback?(clientSecret, nil)
}
func applePayContext(_ context: STPApplePayContext, didCompleteWith status: STPPaymentStatus, error: Error?) {
switch status {
case .success:
applePayCompletionRejecter = nil
applePayRequestRejecter = nil
confirmApplePayPaymentResolver?([])
break
case .error:
let message = "Payment not completed"
applePayCompletionRejecter?(ApplePayErrorType.Failed.rawValue, message, nil)
applePayRequestRejecter?(ApplePayErrorType.Failed.rawValue, message, nil)
applePayCompletionRejecter = nil
applePayRequestRejecter = nil
break
case .userCancellation:
let message = "The payment has been canceled"
applePayCompletionRejecter?(ApplePayErrorType.Canceled.rawValue, message, nil)
applePayRequestRejecter?(ApplePayErrorType.Canceled.rawValue, message, nil)
applePayCompletionRejecter = nil
applePayRequestRejecter = nil
break
@unknown default:
let message = "Payment not completed"
applePayCompletionRejecter?(ApplePayErrorType.Unknown.rawValue, message, nil)
applePayRequestRejecter?(ApplePayErrorType.Unknown.rawValue, message, nil)
applePayCompletionRejecter = nil
applePayRequestRejecter = nil
}
}
@objc(isApplePaySupported:rejecter:)
func isApplePaySupported(resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
let isSupported = StripeAPI.deviceSupportsApplePay()
resolve(isSupported)
}
@objc(handleURLCallback:resolver:rejecter:)
func handleURLCallback(url: String?, resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock, rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
guard let url = url else {
resolve(false)
return;
}
let urlObj = URL(string: url)
if (urlObj == nil) {
resolve(false)
} else {
DispatchQueue.main.async {
let stripeHandled = StripeAPI.handleURLCallback(with: urlObj!)
resolve(stripeHandled)
}
}
}
@objc(presentApplePay:resolver:rejecter:)
func presentApplePay(params: NSDictionary,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock) {
if (merchantIdentifier == nil) {
reject(ApplePayErrorType.Failed.rawValue, "You must provide merchantIdentifier", nil)
return
}
if (params["jcbEnabled"] as? Bool == true) {
StripeAPI.additionalEnabledApplePayNetworks = [.JCB]
}
guard let summaryItems = params["cartItems"] as? NSArray else {
reject(ApplePayErrorType.Failed.rawValue, "You must provide the items for purchase", nil)
return
}
guard let country = params["country"] as? String else {
reject(ApplePayErrorType.Failed.rawValue, "You must provide the country", nil)
return
}
guard let currency = params["currency"] as? String else {
reject(ApplePayErrorType.Failed.rawValue, "You must provide the payment currency", nil)
return
}
self.applePayRequestResolver = resolve
self.applePayRequestRejecter = reject
let merchantIdentifier = self.merchantIdentifier ?? ""
let paymentRequest = StripeAPI.paymentRequest(withMerchantIdentifier: merchantIdentifier, country: country, currency: currency)
let requiredShippingAddressFields = params["requiredShippingAddressFields"] as? NSArray ?? NSArray()
let requiredBillingContactFields = params["requiredBillingContactFields"] as? NSArray ?? NSArray()
let shippingMethods = params["shippingMethods"] as? NSArray ?? NSArray()
paymentRequest.requiredShippingContactFields = Set(requiredShippingAddressFields.map {
Mappers.mapToPKContactField(field: $0 as! String)
})
paymentRequest.requiredBillingContactFields = Set(requiredBillingContactFields.map {
Mappers.mapToPKContactField(field: $0 as! String)
})
paymentRequest.shippingMethods = Mappers.mapToShippingMethods(shippingMethods: shippingMethods)
var paymentSummaryItems: [PKPaymentSummaryItem] = []
if let items = summaryItems as? [[String : Any]] {
for item in items {
let label = item["label"] as? String ?? ""
let amount = NSDecimalNumber(string: item["amount"] as? String ?? "")
let type = Mappers.mapToPaymentSummaryItemType(type: item["type"] as? String)
paymentSummaryItems.append(PKPaymentSummaryItem(label: label, amount: amount, type: type))
}
}
paymentRequest.paymentSummaryItems = paymentSummaryItems
if let applePayContext = STPApplePayContext(paymentRequest: paymentRequest, delegate: self) {
DispatchQueue.main.async {
applePayContext.presentApplePay(completion: nil)
}
} else {
reject(ApplePayErrorType.Failed.rawValue, "Payment not completed", nil)
}
}
func configure3dSecure(_ params: NSDictionary) {
let threeDSCustomizationSettings = STPPaymentHandler.shared().threeDSCustomizationSettings
let uiCustomization = Mappers.mapUICustomization(params)
threeDSCustomizationSettings.uiCustomization = uiCustomization
}
@objc(createPaymentMethod:options:resolver:rejecter:)
func createPaymentMethod(
params: NSDictionary,
options: NSDictionary,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
) -> Void {
let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String)
guard let paymentMethodType = type else {
resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, "You must provide paymentMethodType"))
return
}
var paymentMethodParams: STPPaymentMethodParams?
let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView)
do {
paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType)
} catch {
resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, error.localizedDescription))
return
}
guard let params = paymentMethodParams else {
resolve(Errors.createError(NextPaymentActionErrorType.Unknown.rawValue, "Unhandled error occured"))
return
}
STPAPIClient.shared.createPaymentMethod(with: params) { paymentMethod, error in
if let createError = error {
resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, createError.localizedDescription))
return
}
if let paymentMethod = paymentMethod {
let method = Mappers.mapFromPaymentMethod(paymentMethod)
resolve(Mappers.createResult("paymentMethod", method))
}
}
}
@objc(createToken:resolver:rejecter:)
func createToken(
params: NSDictionary,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
) -> Void {
let address = params["address"] as? NSDictionary
if let type = params["type"] as? String {
if (type != "Card") {
resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, type + " type is not supported yet"))
}
}
guard let cardParams = cardFieldView?.cardParams ?? cardFormView?.cardParams else {
resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, "Card details not complete"))
return
}
let cardSourceParams = STPCardParams()
cardSourceParams.number = cardParams.number
cardSourceParams.cvc = cardParams.cvc
cardSourceParams.expMonth = UInt(truncating: cardParams.expMonth ?? 0)
cardSourceParams.expYear = UInt(truncating: cardParams.expYear ?? 0)
cardSourceParams.address = Mappers.mapToAddress(address: address)
cardSourceParams.name = params["name"] as? String
STPAPIClient.shared.createToken(withCard: cardSourceParams) { token, error in
if let token = token {
resolve(Mappers.createResult("token", Mappers.mapFromToken(token: token)))
} else {
resolve(Errors.createError(CreateTokenErrorType.Failed.rawValue, error?.localizedDescription))
}
}
}
@objc(handleCardAction:resolver:rejecter:)
func handleCardAction(
paymentIntentClientSecret: String,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
){
let paymentHandler = STPPaymentHandler.shared()
paymentHandler.handleNextAction(forPayment: paymentIntentClientSecret, with: self, returnURL: nil) { status, paymentIntent, handleActionError in
switch (status) {
case .failed:
resolve(Errors.createError(NextPaymentActionErrorType.Failed.rawValue, handleActionError))
break
case .canceled:
if let lastError = paymentIntent?.lastPaymentError {
resolve(Errors.createError(NextPaymentActionErrorType.Canceled.rawValue, lastError))
} else {
resolve(Errors.createError(NextPaymentActionErrorType.Canceled.rawValue, "The payment has been canceled"))
}
break
case .succeeded:
if let paymentIntent = paymentIntent {
resolve(Mappers.createResult("paymentIntent", Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent)))
}
break
@unknown default:
resolve(Errors.createError(NextPaymentActionErrorType.Unknown.rawValue, "Cannot complete payment"))
break
}
}
}
@objc(confirmPayment:data:options:resolver:rejecter:)
func confirmPayment(
paymentIntentClientSecret: String,
params: NSDictionary,
options: NSDictionary,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
) -> Void {
self.confirmPaymentResolver = resolve
self.confirmPaymentClientSecret = paymentIntentClientSecret
let paymentMethodId = params["paymentMethodId"] as? String
let paymentIntentParams = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret)
if let setupFutureUsage = params["setupFutureUsage"] as? String {
paymentIntentParams.setupFutureUsage = Mappers.mapToPaymentIntentFutureUsage(usage: setupFutureUsage)
}
let type = Mappers.mapToPaymentMethodType(type: params["type"] as? String)
guard let paymentMethodType = type else {
resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "You must provide paymentMethodType"))
return
}
if (paymentMethodType == STPPaymentMethodType.FPX) {
let testOfflineBank = params["testOfflineBank"] as? Bool
if (testOfflineBank == false || testOfflineBank == nil) {
payWithFPX(paymentIntentClientSecret)
return
}
}
if paymentMethodId != nil {
paymentIntentParams.paymentMethodId = paymentMethodId
} else {
var paymentMethodParams: STPPaymentMethodParams?
var paymentMethodOptions: STPConfirmPaymentMethodOptions?
let factory = PaymentMethodFactory.init(params: params, cardFieldView: cardFieldView, cardFormView: cardFormView)
do {
paymentMethodParams = try factory.createParams(paymentMethodType: paymentMethodType)
paymentMethodOptions = try factory.createOptions(paymentMethodType: paymentMethodType)
} catch {
resolve(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error.localizedDescription))
return
}
guard paymentMethodParams != nil else {
resolve(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Unhandled error occured"))
return
}
paymentIntentParams.paymentMethodParams = paymentMethodParams
paymentIntentParams.paymentMethodOptions = paymentMethodOptions
paymentIntentParams.shipping = Mappers.mapToShippingDetails(shippingDetails: params["shippingDetails"] as? NSDictionary)
}
if let urlScheme = urlScheme {
paymentIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme)
}
let paymentHandler = STPPaymentHandler.shared()
paymentHandler.confirmPayment(paymentIntentParams, with: self, completion: onCompleteConfirmPayment)
}
@objc(retrievePaymentIntent:resolver:rejecter:)
func retrievePaymentIntent(
clientSecret: String,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
) -> Void {
STPAPIClient.shared.retrievePaymentIntent(withClientSecret: clientSecret) { (paymentIntent, error) in
guard error == nil else {
if let lastPaymentError = paymentIntent?.lastPaymentError {
resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, lastPaymentError))
} else {
resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, error?.localizedDescription))
}
return
}
if let paymentIntent = paymentIntent {
resolve(Mappers.createResult("paymentIntent", Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent)))
} else {
resolve(Errors.createError(RetrievePaymentIntentErrorType.Unknown.rawValue, "Failed to retrieve the PaymentIntent"))
}
}
}
@objc(retrieveSetupIntent:resolver:rejecter:)
func retrieveSetupIntent(
clientSecret: String,
resolver resolve: @escaping ABI43_0_0RCTPromiseResolveBlock,
rejecter reject: @escaping ABI43_0_0RCTPromiseRejectBlock
) -> Void {
STPAPIClient.shared.retrieveSetupIntent(withClientSecret: clientSecret) { (setupIntent, error) in
guard error == nil else {
if let lastSetupError = setupIntent?.lastSetupError {
resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, lastSetupError))
} else {
resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, error?.localizedDescription))
}
return
}
if let setupIntent = setupIntent {
resolve(Mappers.createResult("setupIntent", Mappers.mapFromSetupIntent(setupIntent: setupIntent)))
} else {
resolve(Errors.createError(RetrieveSetupIntentErrorType.Unknown.rawValue, "Failed to retrieve the SetupIntent"))
}
}
}
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Canceled.rawValue, "FPX Payment has been canceled"))
}
func payWithFPX(_ paymentIntentClientSecret: String) {
let vc = STPBankSelectionViewController.init(bankMethod: .FPX)
vc.delegate = self
DispatchQueue.main.async {
vc.presentationController?.delegate = self
let share = UIApplication.shared.delegate
share?.window??.rootViewController?.present(vc, animated: true)
}
}
func bankSelectionViewController(_ bankViewController: STPBankSelectionViewController, didCreatePaymentMethodParams paymentMethodParams: STPPaymentMethodParams) {
guard let clientSecret = confirmPaymentClientSecret else {
confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, "Missing paymentIntentClientSecret"))
return
}
let paymentIntentParams = STPPaymentIntentParams(clientSecret: clientSecret)
paymentIntentParams.paymentMethodParams = paymentMethodParams
if let urlScheme = urlScheme {
paymentIntentParams.returnURL = Mappers.mapToReturnURL(urlScheme: urlScheme)
}
let paymentHandler = STPPaymentHandler.shared()
bankViewController.dismiss(animated: true)
paymentHandler.confirmPayment(paymentIntentParams, with: self, completion: onCompleteConfirmPayment)
}
func onCompleteConfirmPayment(status: STPPaymentHandlerActionStatus, paymentIntent: STPPaymentIntent?, error: NSError?) {
self.confirmPaymentClientSecret = nil
switch (status) {
case .failed:
confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Failed.rawValue, error))
break
case .canceled:
let statusCode: String
if (paymentIntent?.status == STPPaymentIntentStatus.requiresPaymentMethod) {
statusCode = ConfirmPaymentErrorType.Failed.rawValue
} else {
statusCode = ConfirmPaymentErrorType.Canceled.rawValue
}
if let lastPaymentError = paymentIntent?.lastPaymentError {
confirmPaymentResolver?(Errors.createError(statusCode, lastPaymentError))
} else {
confirmPaymentResolver?(Errors.createError(statusCode, "The payment has been canceled"))
}
break
case .succeeded:
if let paymentIntent = paymentIntent {
let intent = Mappers.mapFromPaymentIntent(paymentIntent: paymentIntent)
confirmPaymentResolver?(Mappers.createResult("paymentIntent", intent))
}
break
@unknown default:
confirmPaymentResolver?(Errors.createError(ConfirmPaymentErrorType.Unknown.rawValue, "Cannot complete the payment"))
break
}
}
}
func findViewControllerPresenter(from uiViewController: UIViewController) -> UIViewController {
// Note: creating a UIViewController inside here results in a nil window
// This is a bit of a hack: We traverse the view hierarchy looking for the most reasonable VC to present from.
// A VC hosted within a SwiftUI cell, for example, doesn't have a parent, so we need to find the UIWindow.
var presentingViewController: UIViewController =
uiViewController.view.window?.rootViewController ?? uiViewController
// Find the most-presented UIViewController
while let presented = presentingViewController.presentedViewController {
presentingViewController = presented
}
return presentingViewController
}
extension StripeSdk: STPAuthenticationContext {
func authenticationPresentingViewController() -> UIViewController {
return findViewControllerPresenter(from: UIApplication.shared.delegate?.window??.rootViewController ?? UIViewController())
}
}
| bsd-3-clause | 6c58bd5751cb83e5e51c93133adcdf12 | 48.446271 | 216 | 0.648829 | 5.568337 | false | false | false | false |
seanooi/Yapper | Yapper/BuyerCollectionViewCell.swift | 1 | 1101 | //
// BuyerCollectionViewCell.swift
// CarousellChat
//
// Created by Sean Ooi on 7/29/15.
// Copyright (c) 2015 Sean Ooi. All rights reserved.
//
import UIKit
class BuyerCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var dateLabel: UILabel?
@IBOutlet weak var messageLabel: UILabel?
@IBOutlet weak var bubbleImageView: UIImageView?
var bubbleImage: UIImage!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
bubbleImage = UIImage(named: "BuyerBubble")?.resizableImageWithCapInsets(UIEdgeInsets(top: 10, left: 10, bottom: 38, right: 25), resizingMode: .Stretch)
}
override func layoutSubviews() {
super.layoutSubviews()
bubbleImageView?.image = bubbleImage
dateLabel?.font = UIFont.systemFontOfSize(8)
messageLabel?.font = UIFont.systemFontOfSize(12)
messageLabel?.numberOfLines = 0
}
}
| mit | 97000dd2e226dc2bab72f544a285be0f | 25.853659 | 160 | 0.648501 | 4.493878 | false | false | false | false |
a2/MessagePack.swift | Tests/MessagePackTests/StringTests.swift | 1 | 3462 | import Foundation
import XCTest
@testable import MessagePack
class StringTests: XCTestCase {
static var allTests = {
return [
("testLiteralConversion", testLiteralConversion),
("testPackFixstr", testPackFixstr),
("testUnpackFixstr", testUnpackFixstr),
("testUnpackFixstrEmpty", testUnpackFixstrEmpty),
("testPackStr8", testPackStr8),
("testUnpackStr8", testUnpackStr8),
("testPackStr16", testPackStr16),
("testUnpackStr16", testUnpackStr16),
("testPackStr32", testPackStr32),
("testUnpackStr32", testUnpackStr32),
]
}()
func testLiteralConversion() {
var implicitValue: MessagePackValue
implicitValue = "Hello, world!"
XCTAssertEqual(implicitValue, .string("Hello, world!"))
implicitValue = MessagePackValue(extendedGraphemeClusterLiteral: "Hello, world!")
XCTAssertEqual(implicitValue, .string("Hello, world!"))
implicitValue = MessagePackValue(unicodeScalarLiteral: "Hello, world!")
XCTAssertEqual(implicitValue, .string("Hello, world!"))
}
func testPackFixstr() {
let packed = Data([0xad, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21])
XCTAssertEqual(pack(.string("Hello, world!")), packed)
}
func testUnpackFixstr() {
let packed = Data([0xad, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked?.value, .string("Hello, world!"))
XCTAssertEqual(unpacked?.remainder.count, 0)
}
func testUnpackFixstrEmpty() {
let packed = Data([0xa0])
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked?.value, .string(""))
XCTAssertEqual(unpacked?.remainder.count, 0)
}
func testPackStr8() {
let string = String(repeating: "*", count: 0x20)
XCTAssertEqual(pack(.string(string)), Data([0xd9, 0x20]) + string.data(using: .utf8)!)
}
func testUnpackStr8() {
let string = String(repeating: "*", count: 0x20)
let packed = Data([0xd9, 0x20]) + string.data(using: .utf8)!
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked?.value, .string(string))
XCTAssertEqual(unpacked?.remainder.count, 0)
}
func testPackStr16() {
let string = String(repeating: "*", count: 0x1000)
XCTAssertEqual(pack(.string(string)), [0xda, 0x10, 0x00] + string.data(using: .utf8)!)
}
func testUnpackStr16() {
let string = String(repeating: "*", count: 0x1000)
let packed = Data([0xda, 0x10, 0x00]) + string.data(using: .utf8)!
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked?.value, .string(string))
XCTAssertEqual(unpacked?.remainder.count, 0)
}
func testPackStr32() {
let string = String(repeating: "*", count: 0x10000)
XCTAssertEqual(pack(.string(string)), Data([0xdb, 0x00, 0x01, 0x00, 0x00]) + string.data(using: .utf8)!)
}
func testUnpackStr32() {
let string = String(repeating: "*", count: 0x10000)
let packed = Data([0xdb, 0x00, 0x01, 0x00, 0x00]) + string.data(using: .utf8)!
let unpacked = try? unpack(packed)
XCTAssertEqual(unpacked?.value, .string(string))
XCTAssertEqual(unpacked?.remainder.count, 0)
}
}
| mit | af24ee958e12335f78c46b73a81448ea | 35.0625 | 112 | 0.623339 | 3.698718 | false | true | false | false |
joseph-zhong/CommuterBuddy-iOS | SwiftSideMenu/MyMenuTableViewController.swift | 1 | 3975 | //
// MyMenuTableViewController.swift
// SwiftSideMenu
//
// Created by Evgeny Nazarov on 29.09.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
class MyMenuTableViewController: UITableViewController {
var selectedMenuItem : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Customize apperance of table view
tableView.contentInset = UIEdgeInsetsMake(64.0, 0, 0, 0) //
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor.clear
tableView.scrollsToTop = false
// Preserve selection between presentations
self.clearsSelectionOnViewWillAppear = false
tableView.selectRow(at: IndexPath(row: selectedMenuItem, section: 0), animated: false, scrollPosition: .middle)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "CELL")
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "CELL")
cell!.backgroundColor = UIColor.clear
cell!.textLabel?.textColor = UIColor.darkGray
let selectedBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
selectedBackgroundView.backgroundColor = UIColor.gray.withAlphaComponent(0.2)
cell!.selectedBackgroundView = selectedBackgroundView
}
cell!.textLabel?.text = "ViewController #\((indexPath as NSIndexPath).row+1)"
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("did select row: \((indexPath as NSIndexPath).row)")
if ((indexPath as NSIndexPath).row == selectedMenuItem) {
return
}
selectedMenuItem = (indexPath as NSIndexPath).row
//Present new view controller
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main",bundle: nil)
var destViewController : UIViewController
switch ((indexPath as NSIndexPath).row) {
case 0:
destViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController1")
break
case 1:
destViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController2")
break
case 2:
destViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController3")
break
default:
destViewController = mainStoryboard.instantiateViewController(withIdentifier: "ViewController4")
break
}
sideMenuController()?.setContentViewController(destViewController)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | 185d0b41233d4a1b98db8172968193f7 | 35.805556 | 138 | 0.656101 | 5.646307 | false | false | false | false |
ksco/swift-algorithm-club-cn | Bucket Sort/Tests/Tests.swift | 1 | 2410 | //
// TestTests.swift
// TestTests
//
// Created by Barbara Rodeker on 4/5/16.
// Copyright © 2016 Barbara M. Rodeker. All rights reserved.
//
import XCTest
class TestTests: XCTestCase {
var smallArray: [Int]?
let total = 400
let maximum = 1000
var largeArray: [Int]?
var sparsedArray: [Int]?
override func setUp() {
super.setUp()
smallArray = [8,3,33,0,12,8,2,18]
largeArray = [Int]()
for _ in 0..<total {
largeArray!.append( random() % maximum )
}
sparsedArray = [Int]()
sparsedArray = [10,400,1500,500]
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSmallArray() {
let results = performBucketSort(smallArray!, totalBuckets: 3)
XCTAssert(isSorted(results))
}
func testBigArray() {
let results = performBucketSort(largeArray!, totalBuckets: 8)
XCTAssert(isSorted(results))
}
func testSparsedArray() {
let results = performBucketSort(sparsedArray!, totalBuckets: 3)
XCTAssert(isSorted(results))
}
// MARK: Private functions
private func performBucketSort(elements: [Int], totalBuckets: Int) -> [Int] {
let value = (elements.maxElement()?.toInt())! + 1
let capacityRequired = Int( ceil( Double(value) / Double(totalBuckets) ) )
var buckets = [Bucket<Int>]()
for _ in 0..<totalBuckets {
buckets.append(Bucket<Int>(capacity: capacityRequired))
}
let results = bucketSort(smallArray!, distributor: RangeDistributor(), sorter: InsertionSorter(), buckets: buckets)
return results
}
func isSorted(array: [Int]) -> Bool {
var index = 0
var sorted = true
while index < (array.count - 1) && sorted {
if (array[index] > array[index+1]) {
sorted = false
}
index += 1
}
return sorted
}
}
//////////////////////////////////////
// MARK: Extensions
//////////////////////////////////////
extension Int: IntConvertible, Sortable {
public func toInt() -> Int {
return self
}
}
| mit | 42412f810236029d9e8046cfe60984b9 | 23.581633 | 123 | 0.536737 | 4.461111 | false | true | false | false |
kristopherjohnson/kjchess | kjchess/Position_after_coordinateMove.swift | 1 | 2506 | //
// Position_after_coordinateMove.swift
// kjchess
//
// Copyright © 2017 Kristopher Johnson. All rights reserved.
//
extension Position {
/// Return position after applying specified move in coordinate notation.
///
/// - parameter coordinateMove: A string like "e2e4" or "e7e8q"
///
/// - returns: Resulting `Position`.
///
/// - throws: `ChessError` if the move string doesn't have valid syntax or does not identify a legal move from this position.
public func after(coordinateMove: String) throws -> Position {
var newPosition = self
let move = try newPosition.find(coordinateMove: coordinateMove)
_ = newPosition.apply(move)
return newPosition
}
/// Return position after applying specified moves in coordinate notation.
///
/// - parameter coordinateMoves: A sequence of strings like "e2e4" or "e7e8q"
///
/// - returns: Resulting `Position`.
///
/// - throws: `ChessError` if any of the move strings doesn't have valid syntax or does not identify a legal move.
public func after(coordinateMoves: String...) throws -> Position {
var result = self
for move in coordinateMoves {
result = try result.after(coordinateMove: move)
}
return result
}
/// Get the full `Move` for the given coordinate move string.
///
/// - parameter coordinateMove: A string like "e2e4" or "e7e8q"
///
/// - returns: The `Move`.
///
/// - throws: `ChessError` if the move string doesn't have valid syntax or does not identify a legal move from this position.
public mutating func find(coordinateMove: String) throws -> Move {
guard let (from, to, promotedKind) = parseCoordinateMove(coordinateMove) else {
throw ChessError.invalidCoordinateMove(move: coordinateMove)
}
// TODO: Add an overload legalMoves(from: Location)
// that only considers moves by the piece at that location.
let moves = legalMoves().filter {
$0.from == from && $0.to == to
}
if moves.count == 1 {
return moves[0]
}
if let promotedKind = promotedKind {
let moves = moves.filter {
$0.promotedKind == promotedKind
}
if moves.count == 1 {
return moves[0]
}
}
throw ChessError.noMatchingCoordinateMoves(from: from, to: to, promotedKind: promotedKind)
}
}
| mit | c08b3554a1eeba4f2046012e22d5f58d | 33.791667 | 129 | 0.613972 | 4.38704 | false | false | false | false |
mlgoogle/wp | wp/Scenes/Share/RechageVC/FullBankInfomationVC.swift | 1 | 2282 | //
// FullBankInfomationVC.swift
// wp
//
// Created by sum on 2017/1/6.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
import SVProgressHUD
//进入输入手机号界面
let pushInputPhone:String = "pushInputPhone"
//pushInputPhone
class FullBankInfomationVC: BaseTableViewController {
// 银行卡号
@IBOutlet weak var bankNumber: UITextField!
// 支行地址
@IBOutlet weak var branceAddress: UITextField!
// 持卡人姓名
@IBOutlet weak var name: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
title = "输入银行卡信息"
}
deinit {
ShareModel.share().shareData.removeAll()
}
@IBAction func nextInputPhone(_ sender: Any) {
if checkTextFieldEmpty([name,bankNumber,branceAddress]){
if !onlyInputTheNumber(bankNumber.text!) {
SVProgressHUD.showErrorMessage(ErrorMessage: "输入正确的银行卡号", ForDuration: 1, completion: {})
return
}
didRequest()
return
}
}
//MARK: 网络请求
override func didRequest() {
let param = BankNameParam()
param.cardNo = bankNumber.text!
AppAPIHelper.user().getBankName(param: param, complete: { [weak self](result) -> ()? in
if let object = result{
let bankId : Int = object["bankId"] as! Int
ShareModel.share().shareData["cardNo"] = (self?.bankNumber.text!)!
ShareModel.share().shareData["branchBank"] = (self?.branceAddress.text!)!
ShareModel.share().shareData["name"] = (self?.name.text!)!
ShareModel.share().shareData["bankName"] = object["bankName"] as? String
ShareModel.share().shareData["bankId"] = "\(bankId)"
self?.performSegue(withIdentifier: pushInputPhone, sender: nil)
}
return nil
}, error: errorBlockFunc())
}
func onlyInputTheNumber(_ string: String) -> Bool {
let numString = "[0-9]*"
let predicate = NSPredicate(format: "SELF MATCHES %@", numString)
let number = predicate.evaluate(with: string)
return number
}
}
| apache-2.0 | 886925da38b30add3a5701d530d0cda5 | 30.357143 | 102 | 0.588155 | 4.278752 | false | false | false | false |
Yurssoft/QuickFile | Pods/SwiftMessages/SwiftMessages/PhysicsAnimation.swift | 2 | 5581 | //
// PhysicsAnimation.swift
// SwiftMessages
//
// Created by Timothy Moose on 6/14/17.
// Copyright © 2017 SwiftKick Mobile. All rights reserved.
//
import UIKit
public class PhysicsAnimation: NSObject, Animator {
public enum Placement {
case top
case center
case bottom
}
public var placement: Placement = .center
public weak var delegate: AnimationDelegate?
weak var messageView: UIView?
weak var containerView: UIView?
var context: AnimationContext?
public override init() {}
init(delegate: AnimationDelegate) {
self.delegate = delegate
}
public func show(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.addObserver(self, selector: #selector(adjustMargins), name: Notification.Name.UIDeviceOrientationDidChange, object: nil)
install(context: context)
showAnimation(context: context, completion: completion)
}
public func hide(context: AnimationContext, completion: @escaping AnimationCompletion) {
NotificationCenter.default.removeObserver(self)
if panHandler?.isOffScreen ?? false {
context.messageView.alpha = 0
panHandler?.state?.stop()
}
let view = context.messageView
self.context = context
CATransaction.begin()
CATransaction.setCompletionBlock {
view.alpha = 1
view.transform = CGAffineTransform.identity
completion(true)
}
UIView.animate(withDuration: 0.15, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: {
view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: nil)
UIView.animate(withDuration: 0.15, delay: 0, options: [.beginFromCurrentState, .curveEaseIn, .allowUserInteraction], animations: {
view.alpha = 0
}, completion: nil)
CATransaction.commit()
}
func install(context: AnimationContext) {
let view = context.messageView
let container = context.containerView
messageView = view
containerView = container
self.context = context
view.translatesAutoresizingMaskIntoConstraints = false
container.addSubview(view)
switch placement {
case .center:
NSLayoutConstraint(item: view, attribute: .centerY, relatedBy: .equal, toItem: container, attribute: .centerY, multiplier: 1, constant: 0).isActive = true
case .top:
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: container, attribute: .top, multiplier: 1, constant: 0).isActive = true
case .bottom:
NSLayoutConstraint(item: container, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0).isActive = true
}
// Important to layout now in order to get the right safe area insets
container.layoutIfNeeded()
adjustMargins()
NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: container, attribute: .leading, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: container, attribute: .trailing, multiplier: 1, constant: 0).isActive = true
container.layoutIfNeeded()
installInteractive(context: context)
}
@objc public func adjustMargins() {
guard let adjustable = messageView as? MarginAdjustable & UIView,
let container = containerView,
let context = context else { return }
var top: CGFloat = 0
var bottom: CGFloat = 0
switch placement {
case .top:
top += adjustable.topAdjustment(container: container, context: context)
case .bottom:
bottom += adjustable.bottomAdjustment(container: container, context: context)
case .center:
break
}
adjustable.preservesSuperviewLayoutMargins = false
if #available(iOS 11, *) {
var margins = adjustable.directionalLayoutMargins
margins.top = top
margins.bottom = bottom
adjustable.directionalLayoutMargins = margins
} else {
var margins = adjustable.layoutMargins
margins.top = top
margins.bottom = bottom
adjustable.layoutMargins = margins
}
}
func showAnimation(context: AnimationContext, completion: @escaping AnimationCompletion) {
let view = context.messageView
view.alpha = 0.25
view.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
CATransaction.begin()
CATransaction.setCompletionBlock {
completion(true)
}
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: {
view.transform = CGAffineTransform.identity
}, completion: nil)
UIView.animate(withDuration: 0.15, delay: 0, options: [.beginFromCurrentState, .curveLinear, .allowUserInteraction], animations: {
view.alpha = 1
}, completion: nil)
CATransaction.commit()
}
var panHandler: PhysicsPanHandler?
func installInteractive(context: AnimationContext) {
guard context.interactiveHide else { return }
panHandler = PhysicsPanHandler(context: context, animator: self)
}
}
| mit | be90b7c7a39c67f3fcaa3477d2e1e25e | 39.143885 | 192 | 0.656452 | 5.105215 | false | false | false | false |
lightsprint09/LADVSwift | LADVSwift/Performance+JSONDecodeable.swift | 1 | 892 | //
// Lsitung+JSONDecodeable.swift
// Leichatletik
//
// Created by Lukas Schmidt on 28.01.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
extension Performance: JSONCodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
location = try decoder.decode("ort")
disciplin = Disciplin(dlvID: try decoder.decode("disziplin"))
let valueString: String = try decoder.decode("leistung")
value = valueString.replacingOccurrences(of: ",", with: ".")
dateText = try decoder.decode("datum")
let isPersonalBestString: String? = try decoder.decode("personalbest")
isPersonalBest = isPersonalBestString == "true"
let indoorString: String? = try decoder.decode("halle")
indoor = indoorString == "true"
wind = try decoder.decode("wind")
}
}
| mit | f0fa22f5484a6ffe162b4f6fa5ec0b36 | 33.269231 | 78 | 0.662177 | 3.907895 | false | false | false | false |
Instagram/IGListKit | Examples/Examples-tvOS/IGListKitExamples/ViewControllers/NestedAdapterViewController.swift | 1 | 1530 | /*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import UIKit
final class NestedAdapterViewController: UIViewController, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
let data: [Any] = [
"Most Recent",
10,
"Recently Watched",
16,
"New Arrivals",
20
]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = .clear
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return data as! [ListDiffable]
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
if object is Int {
return HorizontalSectionController()
}
return LabelSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil }
}
| mit | 2cddff1d85ab214e5e1e4e01c9048d7b | 25.37931 | 109 | 0.666667 | 5.368421 | false | false | false | false |
lgp123456/tiantianTV | douyuTV/douyuTV/Classes/Me/Controller/XTMeViewController.swift | 1 | 5548 | //
// XTMeViewController.swift
// douyuTV
//
// Created by 李贵鹏 on 16/8/24.
// Copyright © 2016年 李贵鹏. All rights reserved.
//
import UIKit
class XTMeViewController: UIViewController {
private let tableID = "tableCell"
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var heaerView: UIView!
var loginView : XTLoginView?
override func viewDidLoad() {
super.viewDidLoad()
//添加顶部的view
addHeaderView()
//取消系统设置的内边距
automaticallyAdjustsScrollViewInsets = false
//注册cell
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: tableID)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XTMeViewController.loginBtnClick), name: "loginClick", object: nil)
tableView.bounces = false
//接收快速登录的通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XTMeViewController.qqFastLogin), name: "qqLogin", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(XTMeViewController.sinaFastLogin), name: "sinaLogin", object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//改变状态栏的颜色
UIApplication.sharedApplication().statusBarStyle = .LightContent
//隐藏导航条
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//改变状态栏的颜色
UIApplication.sharedApplication().statusBarStyle = .Default
//显示导航条
navigationController?.setNavigationBarHidden(false, animated: animated)
}
}
// MARK: - 第三方登录按钮
extension XTMeViewController {
@objc private func qqFastLogin(){
loginClick(UMShareToQQ)
}
@objc private func sinaFastLogin(){
self.loginView?.removeFromSuperview()
loginClick(UMShareToSina)
}
private func loginClick(platformName : String) {
// 1.获取平台
let snsPlatform = UMSocialSnsPlatformManager.getSocialPlatformWithName(platformName)
// 2.进行三方登录
snsPlatform.loginClickHandler(self, UMSocialControllerService.defaultControllerService(), true, { (response : UMSocialResponseEntity?) -> Void in
// 1.对response进行校验
guard let response = response else {
return
}
// 2.判断响应码是否是正确
guard response.responseCode == UMSResponseCodeSuccess else {
return
}
// 3.获取用户登录的信息(uid/accessToken(昵称/头像))
guard let snsAccount = UMSocialAccountManager.socialAccountDictionary()[snsPlatform.platformName] as? UMSocialAccountEntity else {
return
}
print("uid:\(snsAccount.usid) 昵称:\(snsAccount.userName) 头像地址:\(snsAccount.iconURL) accessToken:\(snsAccount.accessToken)")
})
}
}
// MARK:- 登陆按钮点击
extension XTMeViewController {
func loginBtnClick(){
//添加loginView
let loginView = XTLoginView.loadLoginInView()
self.loginView = loginView
loginView.center = CGPoint(x: XTScreenW * 0.5 , y: XTScreenH * 0.5)
// loginView.bounds.size = CGSize(width: 0, height: 0)
loginView.transform = CGAffineTransformMakeScale(0, 0);
UIApplication.sharedApplication().keyWindow?.addSubview(loginView)
//执行动画
UIView.animateWithDuration(0.25) {
loginView.transform = CGAffineTransformIdentity
loginView.bounds.size = CGSize(width: XTScreenW, height: XTScreenH)
// loginView.center = CGPoint(x: XTScreenW * 0.5 , y: XTScreenH * 0.5)
}
}
}
// MARK:- 添加顶部View
extension XTMeViewController {
func addHeaderView(){
//添加headerView
let headerXibView = XTHeaderView.loadHeaderView()
headerXibView.frame = self.heaerView.bounds
heaerView.addSubview(headerXibView)
}
}
// MARK:- UITableView数据源方法
extension XTMeViewController : UITableViewDataSource {
//tableview有多少组
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
//每一组有多少行
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
//每个cell的内容
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tableID)
// cell?.selectionStyle = .None
cell?.accessoryType = .DisclosureIndicator
cell?.textLabel?.text = "开播提醒"
cell?.imageView?.image = UIImage(named: "image_my_settings_18x18_")
return cell!
}
//设置组的头部间距
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
if (section == 0) {
return 15;
}
return 5
}
//设置组的尾部间距
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 10
}
} | mit | 23515a94ed14927bd3981f1be92842cf | 31.767296 | 153 | 0.645421 | 4.823148 | false | false | false | false |
withcopper/CopperKit | CopperKit/UILabel+Copper.swift | 1 | 880 | //
// UILabel+Copper.swift
// CopperKit
//
// Created by Doug Williams on 5/28/16.
// Copyright © 2016 Doug Williams. All rights reserved.
//
import UIKit
extension UILabel {
public func boldRange(range: Range<String.Index>) {
if let text = self.attributedText {
let attr = NSMutableAttributedString(attributedString: text)
let start = text.string.startIndex.distanceTo(range.startIndex)
let length = range.startIndex.distanceTo(range.endIndex)
attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(self.font!.pointSize)], range: NSMakeRange(start, length))
self.attributedText = attr
}
}
public func boldSubstring(substr: String) {
let range = self.text?.rangeOfString(substr)
if let r = range {
boldRange(r)
}
}
} | mit | 9a0c7ddacab201665eb0ded367a94ed3 | 28.333333 | 139 | 0.639363 | 4.439394 | false | false | false | false |
jotaninwater/yeahbuoy | YeahBuoy/BuoyManager.swift | 1 | 11759 | //
// BuoyManager.swift
// YeahBuoy
//
// Created by Jonathan Domasig on 7/13/16.
// Copyright © 2016 Jonathan Domasig. All rights reserved.
//
import Foundation
protocol BuoyModifiedDelegate {
func buoyModified()
}
/**
Manages all the buoy data.
*/
class BuoyManager: NSObject, NSXMLParserDelegate, BuoyModifiedDelegate {
var buoys = [String:Buoy]() // All our buoys.
var favoriteBuoys = [Buoy]() // Just our favorite buoys.
// Parsing variables.
private var currentBuoy:Buoy? = nil // Buoy used for parsing.
private var currentElement:String = ""
private var parser = NSXMLParser()
private var currentString:String = ""
/*
iOS blocks this because it's not using https
http://stackoverflow.com/questions/31254725/transport-security-has-blocked-a-cleartext-http
You have to set the NSAllowsArbitraryLoads key to YES under NSAppTransportSecurity dictionary in your .plist file.
*/
// The rss feed we are grabbing the data from.
var rssUrl:String = Settings.instance.getFeedUrl()
override init() {
super.init()
}
/**
Get a flat list of buoys for display.
TODO: Can be optimized instead of doing alot of loops
*/
func getBuoys(favorites:Bool, searchText:String) -> [Buoy] {
var retBuoys = [Buoy]()
let filteredBuoys = buoys.filter({
var search = true
var favorite = true
if !searchText.isEmpty {
search = $0.1.name.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
search = search || ($0.1.stationid.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil)
}
if favorites {
favorite = $0.1.favorite
}
return search && favorite && $0.1.show
})
// Now just make it into a flat
for (stationid, buoy) in filteredBuoys {
retBuoys += [buoy]
}
return retBuoys
}
/**
Sync the data with the servers
*/
func syncData() {
// Let's hide everyone.
for (stationid, buoy) in buoys {
buoy.show = false
}
// Reget our url because it may have changed.
rssUrl = Settings.instance.getFeedUrl()
// Load our local data first.
loadData()
let rssNUrl: NSURL = NSURL(string: self.rssUrl)!
self.parser = NSXMLParser(contentsOfURL: rssNUrl)!
self.parser.delegate = self
let success:Bool = self.parser.parse()
if !success {
}
}
// Let's parse our NOAA information.
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.currentElement=elementName
self.currentString = "" // Reset our current string.
switch elementName {
case "item": // This is our station
self.currentBuoy = Buoy(buoyDelegate: self)
break
default:
break // Place holder because compiler is comlaing.
}
//print("Element's name is \(elementName)")
//print("Element's attributes are \(attributeDict)")
}
/**
Store our current string.
*/
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
self.currentString += string
}
/**
The end of our element, so lets do things.
*/
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
var stationid:Int = 0;
// We don't even have a buoy, so let's jump out.
if (self.currentBuoy == nil) {
return
}
switch elementName {
case "item":
if self.currentBuoy!.isValid() {
if (self.buoys[self.currentBuoy!.stationid] != nil) {
// One exists so lets do a copy
self.currentBuoy?.copyPeristent(self.buoys[self.currentBuoy!.stationid]!)
}
self.currentBuoy!.show = true // Show us
self.buoys[self.currentBuoy!.stationid] = self.currentBuoy // Finally store us.
}
else {
NSLog("Invalid buoy: %@", self.currentBuoy!.name)
}
break
case "title":
self.currentBuoy!.name = self.currentString
// Let's parse out the station id from the title.
let titleArray = self.currentString.characters.split{$0 == " "}.map(String.init)
// Huge assumption that all titles are formated the same.
if titleArray.count >= 2 {
self.currentBuoy!.stationid = titleArray[1].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// Do some cleaning up of the name.
self.currentBuoy!.name = self.currentBuoy!.name.stringByReplacingOccurrencesOfString(self.currentBuoy!.stationid + " - ", withString: "")
self.currentBuoy!.name = self.currentBuoy!.name.stringByReplacingOccurrencesOfString("Station", withString: "")
self.currentBuoy!.name = self.currentBuoy!.name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
break
case "description":
// The description contains all our values so have to parse it out.
// It's another huge assumption that the formating will be the same.
// First split it by <strong>
let lines = self.currentString.componentsSeparatedByString("<strong>")
for line in lines {
// Now we need to split it by type and value.
let pairs = line.componentsSeparatedByString("</strong>")
if pairs.count >= 2 {
let type:String = pairs[0].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
var value:String = pairs[1].stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
value = value.stringByReplacingOccurrencesOfString("<br />", withString: "") // Strip out our html line break.
// TODO: Convert HTML entities.
switch type {
case "Wind Direction:":
value = value.stringByReplacingOccurrencesOfString("°", withString: "\u{00B0}") // Convert degrees
self.currentBuoy!.windDirection = value
break
case "Wind Speed:":
self.currentBuoy!.windSpeed = value
break
case "Significant Wave Height:":
self.currentBuoy!.waveSignificant = value
break
case "Dominant Wave Period:":
self.currentBuoy!.waveDominentPeriod = value
break
case "Average Period:":
self.currentBuoy!.waveAveragePeriod = value
break
case "Mean Wave Direction:":
value = value.stringByReplacingOccurrencesOfString("°", withString: "\u{00B0}") // Convert degrees
self.currentBuoy!.waveDirection = value
break
case "Water Temperature:":
value = value.stringByReplacingOccurrencesOfString("°", withString: "\u{00B0}") // Convert degrees
self.currentBuoy!.waterTemp = value
break
default:
break
}
}
}
break
case "georss:point":
self.currentBuoy!.longlat = self.currentString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
break
default:
break
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
NSLog("failure error: %@", parseError)
}
// MARK: NSCoding
/**
Load data from local store.
*/
func loadData() {
if NSFileManager.defaultManager().fileExistsAtPath(Buoy.ArchiveURL.path!) {
self.buoys = (NSKeyedUnarchiver.unarchiveObjectWithFile(Buoy.ArchiveURL.path!) as? [String:Buoy])!
}
//self.buoys = loadBuoys
}
/**
Save our favorites.
*/
func saveData() {
let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(buoys, toFile: Buoy.ArchiveURL.path!)
if !isSuccessfulSave {
NSLog("Failed to save buoys...")
}
}
/**
Just get our list of favorite buoys.
TODO: Optimize by not just brute forcing
*/
//func getBuoys(favorites:Bool) -> [
// MARK: BuoyModifiedProtocol
func buoyModified() {
// We are just going to save everything.
saveData()
}
}
/* --------------------------------------------------------------------------------------------------- */
// Sample item element from the noaa xml.
/*<item>
<pubDate>Thu, 14 Jul 2016 15:30:47 +0000</pubDate>
<title>Station 44025 - LONG ISLAND - 30 NM SOUTH OF ISLIP, NY</title>
<description><![CDATA[
<strong>July 14, 2016 10:50 am EDT</strong><br />
<strong>Location:</strong> 40.251N 73.164W or 17 nautical miles NNW of search location of 40N 73W.<br />
<strong>Wind Direction:</strong> S (180°)<br />
<strong>Wind Speed:</strong> 12 knots<br />
<strong>Wind Gust:</strong> 16 knots<br />
<strong>Significant Wave Height:</strong> 3 ft<br />
<strong>Dominant Wave Period:</strong> 4 sec<br />
<strong>Average Period:</strong> 4.0 sec<br />
<strong>Mean Wave Direction:</strong> SSE (160°)<br />
<strong>Atmospheric Pressure:</strong> 29.91 in (1013.0 mb)<br />
<strong>Pressure Tendency:</strong> -0.02 in (-0.6 mb)<br />
<strong>Air Temperature:</strong> 74°F (23.4°C)<br />
<strong>Water Temperature:</strong> 72°F (22.1°C)<br />
]]></description>
<link>http://www.ndbc.noaa.gov/station_page.php?station=44025</link>
<guid isPermaLink="false">NDBC-44025-20160714145000</guid>
<georss:point>40.251 -73.164</georss:point>
</item>
*/
/* --------------------------------------------------------------------------------------------------- */ | gpl-3.0 | f1d6905faa5c0395e8dd598b9ab54bf6 | 36.094637 | 173 | 0.517945 | 5.05503 | false | false | false | false |
lixiangzhou/ZZSwiftTool | ZZSwiftTool/ZZSwiftTool/ZZExtension/ZZUIExtension/UIView+ZZExtension.swift | 1 | 3883 | //
// UIView+ZZExtension.swift
// ZZSwiftTool
//
// Created by lixiangzhou on 2017/3/10.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
public extension UIView {
/// view所在的UIViewController
var zz_controller: UIViewController? {
var responder = next
while responder != nil {
if responder!.isKind(of: UIViewController.self) {
return responder as? UIViewController
}
responder = responder?.next
}
return nil
}
/// 移除所有子控件
func zz_removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
public extension UIView {
/// 设置圆形
func zz_setCircle() {
zz_setCorner(radius: min(bounds.width, bounds.height) * 0.5, masksToBounds: true)
}
/// 设置圆角
func zz_setCorner(radius: CGFloat, masksToBounds: Bool) {
layer.cornerRadius = radius
layer.masksToBounds = masksToBounds
}
/// 设置边宽及颜色
///
/// - parameter color: 边框颜色
/// - parameter width: 边框宽度
func zz_setBorder(color: UIColor, width: CGFloat) {
layer.borderColor = color.cgColor
layer.borderWidth = width
}
}
public extension UIView {
/// 添加子控件
///
/// - parameter subview: 子控件
///
/// - returns: 添加的子控件
func zz_add(subview: UIView) -> UIView {
addSubview(subview)
return subview
}
/// 添加子控件
///
/// - parameter subview: 子控件
/// - parameter frame: 子控件的frame
///
/// - returns: 添加的子控件
func zz_add(subview: UIView, frame: CGRect) -> UIView {
addSubview(subview)
subview.frame = frame
return subview
}
}
public extension UIView {
/// nib 加载控件
///
/// - parameter nibName: nib 文件名
///
/// - returns: nib 文件中对应的第一个对象
static func zz_loadFrom(nibName: String) -> UIView? {
return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).first as? UIView
}
/// nib 加载控件,nib 文件名和View类名一致
static func zz_loadFromNib() -> UIView? {
let nibName = NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last!
return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).first as? UIView
}
}
public extension UIView {
/// view生成的对应的图片
func zz_snapshotImage() -> UIImage {
return zz_cropImage(inRect: bounds)
}
/// 在指定区域截取图像
///
/// - parameter inRect: 截取图像的区域
///
/// - returns: 截取的图像
func zz_cropImage(inRect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0)
UIRectClip(inRect)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
public extension UIView {
var zz_x: CGFloat {
get {
return frame.origin.x
}
set {
frame.origin.x = newValue
}
}
var zz_y: CGFloat {
get {
return frame.origin.y
}
set {
frame.origin.y = newValue
}
}
var zz_width: CGFloat {
get {
return frame.width
}
set {
frame.size.width = newValue
}
}
var zz_height: CGFloat {
get {
return frame.height
}
set {
frame.size.height = newValue
}
}
}
| mit | bb2228e22a9ee873a740a05377ae213e | 21.546584 | 110 | 0.555647 | 4.373494 | false | false | false | false |
Faifly/FFActionSheet | FFActionSheet/FFActionSheet/FFActionSheet.swift | 1 | 7592 | //
// FFActionSheet.swift
// FFActionSheet
//
// Created by Ihor Embaievskyi on 9/21/16.
// Copyright © 2016 Faifly. All rights reserved.
//
import UIKit
public class FFActionSheetItem: NSObject
{
open var text : String!
open var image : UIImage? = nil
open var backgroundColor : UIColor? = .white
open var font : UIFont? = .systemFont(ofSize: 14.0)
open var fontColor : UIColor? = .black
open var tag : Int = 0
open var buttonImageEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 15.0)
open var buttonTitleEdgeInsets = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 0.0, right: 10.0)
}
public class FFActionSheet: UIViewController
{
// MARK: Properties
open var backgroundColor : UIColor = .white
open var itemHeight : CGFloat = 45.0
open var highlitedColor : UIColor = .lightGray
open var handler: ((_ index: Int) -> ())?
open var dimViewAlpha = 0.5
private var dimView = UIView()
private var dimWindow: UIWindow?
// MARK: Init
public init(titles: [String])
{
super.init(nibName: nil, bundle: nil)
let items = titles.map { (title) -> FFActionSheetItem in
let item = FFActionSheetItem()
item.text = title
return item
}
self.setupViewsPosition(views: self.createViews(items: items))
}
public init(items: [FFActionSheetItem])
{
super.init(nibName: nil, bundle: nil)
self.setupViewsPosition(views: self.createViews(items: items))
}
public init(views : [UIView])
{
super.init(nibName: nil, bundle: nil)
self.setupViewsPosition(views: views)
}
required public init?(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
// MARK: Create Views
func createViews(items: [FFActionSheetItem]) -> [UIView]
{
var views = [UIView]()
for item in items
{
let view = UIView()
view.layer.cornerRadius = 10.0
view.backgroundColor = item.backgroundColor
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.clipsToBounds = true
button.layer.cornerRadius = 10.0
button.titleLabel?.font = item.font
button.setTitle(item.text, for: .normal)
button.setTitleColor(item.fontColor, for: .normal)
button.setBackgroundImage(self.createImage(color: self.highlitedColor, size: self.view.bounds.size), for: .highlighted)
button.backgroundColor = .clear
button.tag = item.tag
button.addTarget(self, action: #selector(onButtonTap), for: .touchUpInside)
view.addSubview(button)
if item.image != nil
{
var buttonImage = UIImage()
buttonImage = item.image!
button.imageView?.contentMode = .scaleAspectFit
button.setImage(buttonImage, for: .normal)
button.setImage(buttonImage, for: .highlighted)
button.imageEdgeInsets = item.buttonImageEdgeInsets
button.titleEdgeInsets = item.buttonTitleEdgeInsets
}
self.setupConstraints(item: button, toItem: view, horizontalConstant: 0.0, topConstant: 0.0, bottomConstant: 0.0)
views.append(view)
}
return views
}
// MARK: Setup views
func setupViewsPosition(views : [UIView])
{
var count = 0;
for view in views.reversed()
{
view.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view)
self.setupConstraints(item: view, toItem: self.view, horizontalConstant: 10.0, bottomConstant: -(self.itemHeight * CGFloat(count) * 1.15 + 5), heightConstant: self.itemHeight)
count = count + 1
}
}
// MARK: Setup constraints
func setupConstraints(item: AnyObject, toItem: AnyObject, horizontalConstant: CGFloat, topConstant: CGFloat? = nil, bottomConstant: CGFloat, heightConstant: CGFloat? = nil)
{
let rightConstraint = NSLayoutConstraint(item: item, attribute: .right, relatedBy: .equal, toItem: toItem, attribute: .right, multiplier: 1, constant: -(horizontalConstant))
toItem.addConstraint(rightConstraint)
let leftConstraint = NSLayoutConstraint(item: item, attribute: .left, relatedBy: .equal, toItem: toItem, attribute: .left, multiplier: 1, constant: horizontalConstant)
toItem.addConstraint(leftConstraint)
if topConstant != nil
{
let topConstraint = NSLayoutConstraint(item: item, attribute: .top, relatedBy: .equal, toItem: toItem, attribute: .top, multiplier: 1, constant: topConstant!)
toItem.addConstraint(topConstraint)
}
let bottomConstraint = NSLayoutConstraint(item: item, attribute: .bottom, relatedBy: .equal, toItem: toItem, attribute: .bottom, multiplier: 1, constant: bottomConstant)
toItem.addConstraint(bottomConstraint)
if heightConstant != nil
{
let heightConstraint = NSLayoutConstraint(item: item, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightConstant!)
toItem.addConstraint(heightConstraint)
}
}
// MARK: Button action
func onButtonTap(sender: UIButton!)
{
if let buttonHandler = self.handler
{
buttonHandler(sender.tag)
}
self.dismiss()
}
public func dismiss()
{
UIView.animate(withDuration: 0.25, animations: {
self.dimView.alpha = 0.0
}) {[weak self] (complete) in
self?.dimView.removeFromSuperview()
}
self.dimWindow = nil
self.dismiss(animated: true, completion: nil)
}
// MARK: Create Image
func createImage(color: UIColor, size: CGSize) -> UIImage
{
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
// MARK: Show Action Sheet
public func showActionSheet(from viewController: UIViewController)
{
self.dimWindow = UIWindow(frame: UIScreen.main.bounds)
self.dimWindow!.rootViewController = UIViewController()
let topWindow = UIApplication.shared.windows.last
self.dimWindow!.windowLevel = topWindow!.windowLevel + 1
self.dimView = UIView(frame: (dimWindow?.frame)!)
self.dimView.backgroundColor = .black
self.dimView.alpha = 0.0
dimWindow?.addSubview(self.dimView)
UIView.animate(withDuration: 0.25, animations: {[unowned self] () -> Void in
self.dimView.alpha = CGFloat(self.dimViewAlpha)
})
self.dimWindow?.makeKeyAndVisible()
self.dimWindow?.rootViewController?.present(self, animated: true, completion: nil)
}
}
| mit | 1a74be05710326e40e01315a8132c54d | 32.888393 | 187 | 0.600053 | 4.859795 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/Autocomplete/IssueAutocomplete.swift | 1 | 2585 | //
// IssueAutocomplete.swift
// Freetime
//
// Created by Ryan Nystrom on 7/14/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import GitHubAPI
import Squawk
final class IssueAutocomplete: AutocompleteType {
private struct Issue {
let number: Int
let title: String
}
private let client: Client
private let owner: String
private let repo: String
private var cachedResults = [String: [Issue]]()
private var results = [Issue]()
init(client: Client, owner: String, repo: String) {
self.client = client
self.owner = owner
self.repo = repo
}
// MARK: AutocompleteType
var prefix: String {
return "#"
}
var resultsCount: Int {
return results.count
}
func configure(cell: AutocompleteCell, index: Int) {
let result = results[index]
cell.configure(state: .issue(number: result.number, title: result.title))
}
func search(word: String, completion: @escaping (Bool) -> Void) {
if let cached = cachedResults[word] {
self.results = cached
completion(cached.count > 0)
return
}
// search gql for term or number
client.query(
IssueAutocompleteQuery(query: "repo:\(owner)/\(repo) \(word)", page_size: 20),
result: { $0 },
completion: { [weak self] result in
switch result {
case .failure(let error):
Squawk.show(error: error)
completion(false)
case .success(let data):
guard let strongSelf = self else { return }
strongSelf.results.removeAll()
for node in data.search.nodes ?? [] {
let issue: Issue?
if let asIssue = node?.asIssue {
issue = Issue(number: asIssue.number, title: asIssue.title)
} else if let asPR = node?.asPullRequest {
issue = Issue(number: asPR.number, title: asPR.title)
} else {
issue = nil
}
if let issue = issue {
strongSelf.results.append(issue)
}
}
completion(strongSelf.results.count > 0)
}
})
}
func accept(index: Int) -> String? {
return prefix + "\(results[index].number)"
}
var highlightAttributes: [NSAttributedStringKey: Any]? { return nil }
}
| mit | 78fcbb8b85401d7b7935d3a272f92e51 | 27.086957 | 90 | 0.533282 | 4.672694 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/ArticlePlaceView.swift | 1 | 22980 | import UIKit
import WMF
#if OSM
import Mapbox
#else
import MapKit
#endif
protocol ArticlePlaceViewDelegate: NSObjectProtocol {
func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView)
}
class ArticlePlaceView: MapAnnotationView {
static let smallDotImage = #imageLiteral(resourceName: "places-dot-small")
static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium")
static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque")
static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium")
static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque")
static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium")
static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque")
static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large")
static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque")
static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ")
static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium")
static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large")
static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium")
static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large")
public weak var delegate: ArticlePlaceViewDelegate?
var imageView: UIView!
private var imageImageView: UIImageView!
private var imageImagePlaceholderView: UIImageView!
private var imageOutlineView: UIView!
private var imageBackgroundView: UIView!
private var selectedImageView: UIView!
private var selectedImageImageView: UIImageView!
private var selectedImageImagePlaceholderView: UIImageView!
private var selectedImageOutlineView: UIView!
private var selectedImageBackgroundView: UIView!
private var dotView: UIView!
private var groupView: UIView!
private var countLabel: UILabel!
private var dimension: CGFloat!
private var collapsedDimension: CGFloat!
var groupDimension: CGFloat!
var imageDimension: CGFloat!
var selectedImageButton: UIButton!
private var alwaysShowImage = false
private let selectionAnimationDuration = 0.3
private let springDamping: CGFloat = 0.5
private let crossFadeRelativeHalfDuration: TimeInterval = 0.1
private let alwaysRasterize = true // set this or rasterize on animations, not both
private let rasterizeOnAnimations = false
override func setup() {
selectedImageView = UIView()
imageView = UIView()
selectedImageImageView = UIImageView()
imageImageView = UIImageView()
if #available(iOS 11.0, *) {
selectedImageImageView.accessibilityIgnoresInvertColors = true
imageImageView.accessibilityIgnoresInvertColors = true
}
countLabel = UILabel()
dotView = UIView()
groupView = UIView()
imageOutlineView = UIView()
selectedImageOutlineView = UIView()
imageBackgroundView = UIView()
selectedImageBackgroundView = UIView()
selectedImageButton = UIButton()
imageImagePlaceholderView = UIImageView()
selectedImageImagePlaceholderView = UIImageView()
let scale = ArticlePlaceView.mediumDotImage.scale
let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage
let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage
let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage
let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage
let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage
let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage
collapsedDimension = ArticlePlaceView.smallDotImage.size.width
groupDimension = ArticlePlaceView.mediumDotImage.size.width
dimension = largeOpaqueDotOutlineImage.size.width
imageDimension = mediumOpaqueDotOutlineImage.size.width
let gravity = kCAGravityBottomRight
isPlaceholderHidden = false
frame = CGRect(x: 0, y: 0, width: dimension, height: dimension)
dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension)
dotView.layer.contentsGravity = gravity
dotView.layer.contentsScale = scale
dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage
dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height)
addSubview(dotView)
groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension)
groupView.layer.contentsGravity = gravity
groupView.layer.contentsScale = scale
groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage
addSubview(groupView)
imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension)
imageView.layer.rasterizationScale = scale
addSubview(imageView)
imageBackgroundView.frame = imageView.bounds
imageBackgroundView.layer.contentsGravity = gravity
imageBackgroundView.layer.contentsScale = scale
imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage
imageView.addSubview(imageBackgroundView)
imageImagePlaceholderView.frame = imageView.bounds
imageImagePlaceholderView.contentMode = .center
imageImagePlaceholderView.image = mediumPlaceholderImage
imageView.addSubview(imageImagePlaceholderView)
var inset: CGFloat = 3.5
var imageViewFrame = UIEdgeInsetsInsetRect(imageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset))
imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset)
imageImageView.frame = imageViewFrame
imageImageView.contentMode = .scaleAspectFill
imageImageView.layer.masksToBounds = true
imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5
imageImageView.backgroundColor = UIColor.white
imageView.addSubview(imageImageView)
imageOutlineView.frame = imageView.bounds
imageOutlineView.layer.contentsGravity = gravity
imageOutlineView.layer.contentsScale = scale
imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage
imageView.addSubview(imageOutlineView)
selectedImageView.bounds = bounds
selectedImageView.layer.rasterizationScale = scale
addSubview(selectedImageView)
selectedImageBackgroundView.frame = selectedImageView.bounds
selectedImageBackgroundView.layer.contentsGravity = gravity
selectedImageBackgroundView.layer.contentsScale = scale
selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage
selectedImageView.addSubview(selectedImageBackgroundView)
selectedImageImagePlaceholderView.frame = selectedImageView.bounds
selectedImageImagePlaceholderView.contentMode = .center
selectedImageImagePlaceholderView.image = largePlaceholderImage
selectedImageView.addSubview(selectedImageImagePlaceholderView)
inset = imageDimension > 40 ? 3.5 : 5.5
imageViewFrame = UIEdgeInsetsInsetRect(selectedImageView.bounds, UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset))
imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset)
selectedImageImageView.frame = imageViewFrame
selectedImageImageView.contentMode = .scaleAspectFill
selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5
selectedImageImageView.layer.masksToBounds = true
selectedImageImageView.backgroundColor = UIColor.white
selectedImageView.addSubview(selectedImageImageView)
selectedImageOutlineView.frame = selectedImageView.bounds
selectedImageOutlineView.layer.contentsGravity = gravity
selectedImageOutlineView.layer.contentsScale = scale
selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage
selectedImageView.addSubview(selectedImageOutlineView)
selectedImageButton.frame = selectedImageView.bounds
selectedImageButton.accessibilityTraits = UIAccessibilityTraitNone
selectedImageView.addSubview(selectedImageButton)
countLabel.frame = groupView.bounds
countLabel.textColor = UIColor.white
countLabel.textAlignment = .center
countLabel.font = UIFont.boldSystemFont(ofSize: 16)
groupView.addSubview(countLabel)
prepareForReuse()
super.setup()
updateLayout()
update(withArticlePlace: annotation as? ArticlePlace)
}
func set(alwaysShowImage: Bool, animated: Bool) {
self.alwaysShowImage = alwaysShowImage
let scale = collapsedDimension/imageDimension
let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale)
let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale)
if alwaysShowImage {
loadImage()
imageView.alpha = 0
imageView.isHidden = false
dotView.alpha = 1
dotView.isHidden = false
imageView.transform = imageViewScaleDownTransform
dotView.transform = CGAffineTransform.identity
} else {
dotView.transform = dotViewScaleUpTransform
imageView.transform = CGAffineTransform.identity
imageView.alpha = 1
imageView.isHidden = false
dotView.alpha = 0
dotView.isHidden = false
}
let transforms = {
if alwaysShowImage {
self.imageView.transform = CGAffineTransform.identity
self.dotView.transform = dotViewScaleUpTransform
} else {
self.imageView.transform = imageViewScaleDownTransform
self.dotView.transform = CGAffineTransform.identity
}
}
let fadesIn = {
if alwaysShowImage {
self.imageView.alpha = 1
} else {
self.dotView.alpha = 1
}
}
let fadesOut = {
if alwaysShowImage {
self.dotView.alpha = 0
} else {
self.imageView.alpha = 0
}
}
if (animated && rasterizeOnAnimations) {
self.imageView.layer.shouldRasterize = true
}
let done = {
if (animated && self.rasterizeOnAnimations) {
self.imageView.layer.shouldRasterize = false
}
guard let articlePlace = self.annotation as? ArticlePlace else {
return
}
self.updateDotAndImageHiddenState(with: articlePlace.articles.count)
}
if animated {
if alwaysShowImage {
UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil)
UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut)
}) { (didFinish) in
done()
}
} else {
UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms)
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut)
}) { (didFinish) in
done()
}
}
} else {
transforms()
fadesIn()
fadesOut()
done()
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
guard superview != nil else {
selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside)
return
}
selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside)
}
@objc func selectedImageViewWasTapped(_ sender: UIButton) {
delegate?.articlePlaceViewWasTapped(self)
}
var zPosition: CGFloat = 1 {
didSet {
guard !isSelected else {
return
}
layer.zPosition = zPosition
}
}
var isPlaceholderHidden: Bool = true {
didSet {
selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden
imageImagePlaceholderView.isHidden = isPlaceholderHidden
imageImageView.isHidden = !isPlaceholderHidden
selectedImageImageView.isHidden = !isPlaceholderHidden
}
}
private var shouldRasterize = false {
didSet {
imageView.layer.shouldRasterize = shouldRasterize
selectedImageView.layer.shouldRasterize = shouldRasterize
}
}
private var isImageLoaded = false
func loadImage() {
guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else {
return
}
if alwaysRasterize {
shouldRasterize = false
}
isPlaceholderHidden = false
isImageLoaded = true
let article = articlePlace.articles[0]
if let thumbnailURL = article.thumbnailURL {
imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in
if self.alwaysRasterize {
self.shouldRasterize = true
}
}, success: {
self.selectedImageImageView.image = self.imageImageView.image
self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect
self.isPlaceholderHidden = true
if self.alwaysRasterize {
self.shouldRasterize = true
}
})
}
}
func update(withArticlePlace articlePlace: ArticlePlace?) {
let articleCount = articlePlace?.articles.count ?? 1
switch articleCount {
case 0:
zPosition = 1
isPlaceholderHidden = false
imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more")
accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles")
case 1:
zPosition = 1
isImageLoaded = false
if isSelected || alwaysShowImage {
loadImage()
}
accessibilityLabel = articlePlace?.articles.first?.displayTitle
default:
zPosition = 2
let countString = "\(articleCount)"
countLabel.text = countString
accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group\n{{Identical|Article}}"), countString)
}
updateDotAndImageHiddenState(with: articleCount)
}
func updateDotAndImageHiddenState(with articleCount: Int) {
switch articleCount {
case 0:
fallthrough
case 1:
imageView.isHidden = !alwaysShowImage
dotView.isHidden = alwaysShowImage
groupView.isHidden = true
default:
imageView.isHidden = true
dotView.isHidden = true
groupView.isHidden = false
}
}
#if OSM
override var annotation: MGLAnnotation? {
didSet {
guard isSetup, let articlePlace = annotation as? ArticlePlace else {
return
}
update(withArticlePlace: articlePlace)
}
}
#else
override var annotation: MKAnnotation? {
didSet {
guard isSetup, let articlePlace = annotation as? ArticlePlace else {
return
}
update(withArticlePlace: articlePlace)
}
}
#endif
override func prepareForReuse() {
super.prepareForReuse()
if alwaysRasterize {
shouldRasterize = false
}
isPlaceholderHidden = false
isImageLoaded = false
delegate = nil
imageImageView.wmf_reset()
selectedImageImageView.wmf_reset()
countLabel.text = nil
set(alwaysShowImage: false, animated: false)
setSelected(false, animated: false)
alpha = 1
transform = CGAffineTransform.identity
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
guard let place = annotation as? ArticlePlace, place.articles.count == 1 else {
selectedImageView.alpha = 0
return
}
let dotScale = collapsedDimension/dimension
let imageViewScale = imageDimension/dimension
let scale = alwaysShowImage ? imageViewScale : dotScale
let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale)
let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale)
let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale)
layer.zPosition = 3
if selected {
loadImage()
selectedImageView.transform = selectedImageViewScaleDownTransform
dotView.transform = CGAffineTransform.identity
imageView.transform = CGAffineTransform.identity
selectedImageView.alpha = 0
imageView.alpha = 1
dotView.alpha = 1
} else {
selectedImageView.transform = CGAffineTransform.identity
dotView.transform = dotViewScaleUpTransform
imageView.transform = imageViewScaleUpTransform
selectedImageView.alpha = 1
imageView.alpha = 0
dotView.alpha = 0
}
let transforms = {
if selected {
self.selectedImageView.transform = CGAffineTransform.identity
self.dotView.transform = dotViewScaleUpTransform
self.imageView.transform = imageViewScaleUpTransform
} else {
self.selectedImageView.transform = selectedImageViewScaleDownTransform
self.dotView.transform = CGAffineTransform.identity
self.imageView.transform = CGAffineTransform.identity
}
}
let fadesIn = {
if selected {
self.selectedImageView.alpha = 1
} else {
self.imageView.alpha = 1
self.dotView.alpha = 1
}
}
let fadesOut = {
if selected {
self.imageView.alpha = 0
self.dotView.alpha = 0
} else {
self.selectedImageView.alpha = 0
}
}
if (animated && rasterizeOnAnimations) {
shouldRasterize = true
}
let done = {
if (animated && self.rasterizeOnAnimations) {
self.shouldRasterize = false
}
if !selected {
self.layer.zPosition = self.zPosition
}
}
if animated {
let duration = 2*selectionAnimationDuration
if selected {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil)
UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut)
}) { (didFinish) in
done()
}
} else {
UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms)
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut)
}) { (didFinish) in
done()
}
}
} else {
transforms()
fadesIn()
fadesOut()
done()
}
}
func updateLayout() {
let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height)
selectedImageView.center = center
imageView.center = center
dotView.center = center
groupView.center = center
}
override var frame: CGRect {
didSet {
guard isSetup else {
return
}
updateLayout()
}
}
override var bounds: CGRect {
didSet {
guard isSetup else {
return
}
updateLayout()
}
}
}
| mit | 450c83e798a49b447673bde5c436ada5 | 41.010969 | 280 | 0.644778 | 6.242869 | false | false | false | false |
ForrestAlfred/firefox-ios | ClientTests/MockProfile.swift | 4 | 4236 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
public class MockSyncManager: SyncManager {
public func syncClients() -> SyncResult { return deferResult(.Completed) }
public func syncClientsThenTabs() -> SyncResult { return deferResult(.Completed) }
public func syncHistory() -> SyncResult { return deferResult(.Completed) }
public func syncLogins() -> SyncResult { return deferResult(.Completed) }
public func beginTimedSyncs() {}
public func endTimedSyncs() {}
public func onAddedAccount() -> Success {
return succeed()
}
public func onRemovedAccount(account: FirefoxAccount?) -> Success {
return succeed()
}
}
public class MockTabQueue: TabQueue {
public func addToQueue(tab: ShareItem) -> Success {
return succeed()
}
public func getQueuedTabs() -> Deferred<Result<Cursor<ShareItem>>> {
return deferResult(ArrayCursor<ShareItem>(data: []))
}
public func clearQueuedTabs() -> Success {
return succeed()
}
}
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
func shutdown() {
if dbCreated {
db.close()
}
}
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "mock.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = {
return SQLiteHistory(db: self.db)
}()
var favicons: Favicons {
return self.places
}
lazy var queue: TabQueue = {
return MockTabQueue()
}()
var history: protocol<BrowserHistory, SyncableHistory> {
return self.places
}
lazy var syncManager: SyncManager = {
return MockSyncManager()
}()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
return SQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
lazy var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
private lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var logins: protocol<BrowserLogins, SyncableLogins> = {
return MockLogins(files: self.files)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
func getClients() -> Deferred<Result<[RemoteClient]>> {
return deferResult([])
}
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> {
return deferResult(0)
}
func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
}
} | mpl-2.0 | dfa0b1ab3793b5f2eb43570f9028f67a | 25.647799 | 99 | 0.650142 | 4.948598 | false | false | false | false |
skumaringuva/TipCalc | TipCalculator/TipCalculator/ViewController.swift | 1 | 3708 | //
// ViewController.swift
// TipCalculator
//
// Created by SheshuKumar Inguva on 3/12/17.
// Copyright © 2017 Atal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var TipLabel: UILabel!
@IBOutlet weak var TotalLabel: UILabel!
@IBOutlet weak var BillField: UITextField!
@IBOutlet weak var TipSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
self.BillField.becomeFirstResponder()
// Do any additional setup after loading the view, typically from a nib.
let defaultIndex = Utils.getDefaultTipPercentageIndex()
TipSegmentedControl.selectedSegmentIndex = defaultIndex
//TipLabel.text = formatCurrencyNumber(Utils.getLastBillAmount());
self.BillField.text = String(Utils.getLastBillAmount())
calulateBill()
//TotalLabel.text = formatCurrencyNumber(0.0)
}
func animateViews(){
/*
UIView.animate(withDuration:0.8, delay: 0.0,
// Autoreverse runs the animation backwards and Repeat cycles the animation indefinitely.
options: [.autoreverse, .repeat], animations: { () -> Void in
self.TotalLabel.transform = CGAffineTransform(translationX: 0, y: 10)
}, completion: nil)
*/
UIView.animate(withDuration:0.8, delay: 0.0,
// Autoreverse runs the animation backwards and Repeat cycles the animation indefinitely.
options: [.autoreverse, .repeat], animations: { () -> Void in
self.TipLabel.transform = CGAffineTransform(translationX: 5, y: 0)
}, completion: nil)
}
func scaleTotal(_ factor:Double){
UIView.animate(withDuration:0.4, delay: 0.0,
options: [],
animations: { () -> Void in
self.TotalLabel.transform = CGAffineTransform(scaleX: CGFloat(1.0 + (factor )), y: CGFloat(1.0 + (factor)))
}, completion: nil)
}
func formatCurrencyNumber(_ number:Double)->String{
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale.current;
numberFormatter.numberStyle = .currency
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
let result = (numberFormatter.string(from: (NSNumber(value:number))))!;
return result;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func calulateBill(){
let tipValues = [0.1,0.2,0.3];
let bill = Double(BillField.text!) ?? 0;
let tip = tipValues[TipSegmentedControl.selectedSegmentIndex]*bill ;
let totalBill = bill+tip;
TipLabel.text = formatCurrencyNumber(tip);
TotalLabel.text = formatCurrencyNumber( totalBill);
scaleTotal(tipValues[TipSegmentedControl.selectedSegmentIndex])
Utils.saveLasBillAmount(bill)
animateViews()
}
@IBAction func BillEntered(_ sender: AnyObject) {
calulateBill()
}
@IBAction func TipPercentChanged(_ sender: UISegmentedControl) {
}
@IBAction func tapOutside(_ sender: Any) {
// Dismiss keyboard
print("Dismiss keyboard")
view.endEditing(true);
animateViews()
}
}
| apache-2.0 | bfdcd35533bc9b40182a443e03cfde07 | 30.151261 | 131 | 0.60642 | 4.995957 | false | false | false | false |
mzp/OctoEye | Sources/OctoEye/DataSource/PagingRepositories.swift | 1 | 1927 | //
// PagingRepositories.swift
// Tests
//
// Created by mzp on 2017/08/11.
// Copyright © 2017 mzp. All rights reserved.
//
import BrightFutures
import ReactiveSwift
import Result
internal class PagingRepositories {
typealias Pipe<Value> = (Signal<Value, AnyError>, Signal<Value, AnyError>.Observer)
private let (cursorSignal, cursorObserver): Pipe<String?> = Signal<String?, AnyError>.pipe()
let (eventSignal, eventObserver): Pipe<PagingEvent> = Signal<PagingEvent, AnyError>.pipe()
init() {
}
// MARK: - repositories
private var repositories: [RepositoryObject] = []
var count: Int {
return repositories.count
}
subscript(index: Int) -> RepositoryObject {
return repositories[index]
}
func clear() {
repositories = []
}
// MARK: - cursor
private var currentCursor: String?
var cursor: Signal<String?, AnyError> {
return cursorSignal.skipRepeats { $0 == $1 }
}
func invokePaging() {
cursorObserver.send(value: currentCursor)
}
// MARK: - observe result
func observe<T>(signal: Signal<T, AnyError>,
fetch: @escaping (T) -> Future<([RepositoryObject], String?), AnyError>) {
signal
.flatMap(.concat) { value -> SignalProducer<([RepositoryObject], String?), AnyError> in
self.eventObserver.send(value: .loading)
return SignalProducer(fetch(value))
}
.observeResult { result in
switch result {
case .success(let repositories, let cursor):
self.currentCursor = cursor
self.repositories.append(contentsOf: repositories)
self.eventObserver.send(value: .completed)
case .failure(let error):
self.eventObserver.send(error: error)
}
}
}
}
| mit | cc4e291631c4cf3e4f34f227d94d0ba5 | 28.181818 | 99 | 0.592939 | 4.585714 | false | false | false | false |
pavelpark/GitHubClone | GitHubClone/GitHubAuthControllerViewController.swift | 1 | 1338 | //
// GitHubAuthControllerViewController.swift
// GitHubClone
//
// Created by Pavel Parkhomey on 4/3/17.
// Copyright © 2017 Pavel Parkhomey. All rights reserved.
//
import UIKit
class GitHubAuthControllerViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
hasToken()
}
@IBOutlet weak var logInButton: UIButton!
func hasToken() {
if UserDefaults.standard.getAccessToken() == nil {
print("Please Log In")
logInButton.isEnabled = true
logInButton.isHidden = false
} else {
print("Already Logged In")
logInButton.isHidden = true
logInButton.isEnabled = false
}
}
@IBAction func printTokenPressed(_ sender: Any) {
}
@IBAction func logInButtonPressed(_ sender: Any) {
// hasToken()
let parameters = ["scope" : "email,user,repo"]
GitHub.shared.oAuthRequestWith(parameters: parameters)
}
func dismissAuthController() {
self.view.removeFromSuperview()
self.removeFromParentViewController()
}
}
| mit | 950daaa861ec25630b2fe8adf946c9bb | 22.875 | 62 | 0.605086 | 5.045283 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Banking | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/Dashboard/DashboardViewController.swift | 1 | 13258 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
/**
* A custom UIViewController used to display a user's account and business information
*/
class DashboardViewController: HatchUIViewController {
/// Label showing the estimated spending amount
@IBOutlet weak var estimatedSpendingAmountLabel: UILabel!
/// Container for the estimated available green view
@IBOutlet weak var bottomView: UIView!
/// Username UILabel
@IBOutlet weak var usernameLabel: UILabel!
/// Greetings UILabel
@IBOutlet weak var greetingLabel: UILabel!
/// Spendings UITableView
@IBOutlet weak var spendingsTableView: UITableView!
/// Accounts UITableView
@IBOutlet weak var accountsTableView: UITableView!
/// Custom UIPageControl
@IBOutlet weak var hatchPageControl: HatchPageControl!
/// Height constraint for the accounts UITableView
@IBOutlet weak var accountsTableViewHeightConstraint: NSLayoutConstraint!
/// Height constraint for the spendings UITableView
@IBOutlet weak var spendingTableViewHeightConstraint: NSLayoutConstraint!
/// Available amount for all accounts UILabel
@IBOutlet weak var availableAmountLabel: UILabel!
/// Total amount for all accounts UILabel
@IBOutlet weak var totalAccountAmountLabel: UILabel!
/// The current BusinessViewController in the UIPageViewController
var businessViewController: BusinessViewController!
/// The array of businesses for the user
var businesses: [Business]! = []
/// The current business being display
var business: Business! = Business()
/// Value for the account cell hieght in the UITableView. Used to calculate the total height of the DashboardViewController.
var accountCellHeight: CGFloat!
/// Value for the height of the view without the UITableViews. Used to calculate the total height of the DashboardViewController.
var viewHeightWithoutTableViews: CGFloat!
/// PageViewController for the businesses
var pageBusinessViewController: UIPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
MILLoadViewManager.sharedInstance.show()
hatchPageControl.useGreenDots()
greetingLabel.text = Utils.getRandomGreeting()
DashboardDataManager.sharedInstance.getDashboardData(dashboardDataReturned)
viewHeightWithoutTableViews = bottomView.bottom - (accountsTableViewHeightConstraint.constant + spendingTableViewHeightConstraint.constant)
accountCellHeight = accountsTableViewHeightConstraint.constant
}
/**
Updates the accounts and spendings when a user selects a new business
- parameter index: The index of the array of businesses that the user has moved to
*/
func updateAccounts(index: Int) {
business = businesses[index]
self.hatchPageControl.setCurrentPageIndex(index)
accountsTableView.reloadData()
spendingsTableView.reloadData()
let totalAccountAmount = Utils.getAccountsTotal(business.accounts)
let spendingTotal = Utils.getAccountsTotal(business.spendings)
let availableAmount = totalAccountAmount - spendingTotal
Utils.setUpViewKern(self.view)
totalAccountAmountLabel.attributedText = Utils.getPriceAttributedString(LocalizationUtils.localizeCurrency(totalAccountAmount), dollarSize: 38, centSize: 23, color: totalAccountAmountLabel.textColor)
availableAmountLabel.attributedText = Utils.getPriceAttributedString(LocalizationUtils.localizeCurrency(availableAmount), dollarSize: 38, centSize: 23, color: availableAmountLabel.textColor)
estimatedSpendingAmountLabel.attributedText = Utils.getPriceAttributedString(LocalizationUtils.localizeCurrency(spendingTotal), dollarSize: 38, centSize: 23, color: estimatedSpendingAmountLabel.textColor)
let accountsTableHeight = business.accounts.count.toFloat.toCGFloat * accountCellHeight
let spendingsTableHeight = business.spendings.count.toFloat.toCGFloat * accountCellHeight
accountsTableViewHeightConstraint.constant = accountsTableHeight
spendingTableViewHeightConstraint.constant = spendingsTableHeight
let height = viewHeightWithoutTableViews + accountsTableHeight + spendingsTableHeight
(parentViewController as! ContainerDashboardViewController).setHeight(height)
MILLoadViewManager.sharedInstance.hide()
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "pageSegue") {
pageBusinessViewController = segue.destinationViewController as! UIPageViewController
pageBusinessViewController.dataSource = self
pageBusinessViewController.delegate = self
pageBusinessViewController.view.backgroundColor = UIColor.greenHatch()
let startingViewController = self.businessViewControllerAtIndex(0)
pageBusinessViewController.setViewControllers([startingViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
}
}
// MARK: Dashboard Data
/**
This is the callback method that is passed to the DashboardDataManager that is triggered on success/failure of the getDashboardData method.
- parameter success: True if data retrieval was successful
*/
func dashboardDataReturned(success: Bool, businesses: [Business]!){
if (success){
MQALogger.log("dashboardDataReturned success")
usernameLabel.text = LoginDataManager.sharedInstance.currentUser.firstName.uppercaseString + "!"
self.businesses = businesses
business = businesses.first
businessViewController.businessNameLabel.text = business.name
businessViewController.logoImageView.image = UIImage(named: business.imageName)
self.hatchPageControl.numberOfPages = businesses.count
let startingViewController = self.businessViewControllerAtIndex(DashboardDataManager.sharedInstance.businessIndex)
pageBusinessViewController.setViewControllers([startingViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
self.updateAccounts(DashboardDataManager.sharedInstance.businessIndex)
DashboardDataManager.sharedInstance.businessIndex = 0
} else {
MQALogger.log("dashboardDataReturned failure")
}
}
}
extension DashboardViewController: UITableViewDataSource {
/**
Delegate method to set the number of rows for the accounts or spending table.
- parameter tableView:
- parameter section:
- returns:
*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView.tag == 0 {
return business.accounts.count
}else{
return business.spendings.count
}
}
/**
Delegate method to create the cell for the accounts or spending table.
- parameter tableView: <#tableView description#>
- parameter indexPath: <#indexPath description#>
- returns: <#return value description#>
*/
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("accountCell") as! AccountViewCell
var account : Account
if tableView.tag == 0 {
account = business.accounts[indexPath.row]
}else{
account = business.spendings[indexPath.row]
}
cell.nameLabel.text = account.accountName
Utils.setUpViewKern(cell)
cell.amountLabel.attributedText = Utils.getPriceAttributedString(LocalizationUtils.localizeCurrency(account.balance.toDouble), dollarSize: 38, centSize: 23, color: UIColor.darkGrayTextHatch())
return cell
}
}
extension DashboardViewController: UITableViewDelegate {
/**
Delegate method to show a account transactions when an account is tapped
- parameter tableView:
- parameter indexPath:
*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var segueAccount : Account!
if tableView.tag == 0 {
let segueAccount = business.accounts[indexPath.row]
if segueAccount.hasTransactions {
let transactionsViewController = UIStoryboard(name: "Dashboard", bundle: nil).instantiateViewControllerWithIdentifier("TransactionViewController") as! TransactionsViewController
transactionsViewController.account = segueAccount
self.navigationController?.pushViewController(transactionsViewController, animated: true)
} else if segueAccount.accountName.uppercaseString == "GOALS" {
goToGoalsFromDashboard()
}
}else{
let segueAccount = business.spendings[indexPath.row]
if segueAccount.accountName.uppercaseString == "GOALS" {
goToGoalsFromDashboard()
}
}
}
/**
Goes to goal from dashboard to show back button
*/
func goToGoalsFromDashboard(){
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
MenuViewController.transition(mainStoryboard)
WL.sharedInstance().sendActionToJS("changePage", withData: ["route":""]);
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.hybridViewController.fromGoals = true
appDelegate.hybridViewController.isFirstInstance = true
}
}
extension DashboardViewController: UIPageViewControllerDataSource {
/**
This method must be implemented since DashboardViewController uses UIPageViewControllerDataSource. It will return the viewcontroller to be shown before whichever viewcontroller is currently being shown
- parameter pageViewController:
- parameter viewController:
- returns:
*/
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?{
var index = (viewController as! BusinessViewController).pageIndex as Int
if ((index == 0) || (index == NSNotFound)) {
return nil
}
index--
return self.businessViewControllerAtIndex(index)
}
/**
This method must be implemented since DashboardViewController uses UIPageViewControllerDataSource. It will return the viewcontroller to be shown after whichever viewcontroller is currently being shown
- parameter pageViewController:
- parameter viewController:
- returns:
*/
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?{
var index = (viewController as! BusinessViewController).pageIndex as Int
if ((index == self.businesses.count-1) || (index == NSNotFound)) {
return nil
}
index++
return self.businessViewControllerAtIndex(index)
}
func businessViewControllerAtIndex(index: Int) -> BusinessViewController? {
let dashboardStoryboard = UIStoryboard(name: "Dashboard", bundle: nil)
businessViewController = dashboardStoryboard.instantiateViewControllerWithIdentifier("BusinessViewController") as! BusinessViewController
if ((self.businesses.count != 0) && (index < self.businesses.count)) {
let business = businesses[index]
businessViewController.businessName = business.name
businessViewController.logoImage = UIImage(named: business.imageName)
businessViewController.pageIndex = index
}else{
businessViewController.pageIndex = 0
}
return businessViewController
}
}
extension DashboardViewController: UIPageViewControllerDelegate {
/**
This method should update the hatchPageControl's current page (shows correct dot based on page being shown). This also signals when to update the accounts and spendings.
- parameter pageViewController:
- parameter finished:
- parameter previousViewControllers:
- parameter completed:
*/
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if !completed {
return
}
self.hatchPageControl.setCurrentPageIndex((pageViewController.viewControllers!.last as! BusinessViewController).pageIndex)
self.updateAccounts((pageViewController.viewControllers!.last as! BusinessViewController).pageIndex)
}
}
| epl-1.0 | fd7e0479352e0a085cdda3a730f2a937 | 41.902913 | 212 | 0.707551 | 5.913024 | false | false | false | false |
GeekSpeak/GeekSpeak-Show-Timer | TimerViewsGear/RingPoint.swift | 2 | 2062 | import UIKit
import AngleGear
open class RingPoint: NSObject {
open let x: CGFloat
open let y: CGFloat
public init( x: CGFloat,
y: CGFloat) {
self.x = x
self.y = y
}
public override init() {
self.x = CGFloat(0)
self.y = CGFloat(0)
}
open var point: CGPoint {
return CGPoint(x: self.x, y: self.y)
}
open func subtract(_ point: RingPoint) -> RingPoint {
return RingPoint(x: x - point.x,
y: y - point.y)
}
open func add(_ point: RingPoint) -> RingPoint {
return RingPoint( x: x + point.x,
y: y + point.y)
}
open func scale(_ multiple: CGFloat) -> RingPoint {
return RingPoint(x: x * multiple,
y: y * multiple)
}
open func distance(_ point: RingPoint) -> CGFloat {
return sqrt((x - point.x)*(x - point.x) +
(y - point.y)*(y - point.y))
}
open func angleBetweenPoint( _ point: RingPoint, fromMutualCenter center: RingPoint)
-> TauAngle {
let selfAngle = type(of: self).angleFrom2Points(self,center)
let otherAngle = type(of: self).angleFrom2Points(point,center)
return selfAngle - otherAngle
}
open func angleFromCenter(_ center: RingPoint) -> TauAngle {
return type(of: self).angleFrom2Points(self,center)
}
open class func angleFrom2Points(_ point1: RingPoint, _ point2: RingPoint)
-> TauAngle {
let dx = point1.x - point2.x
let dy = point1.y - point2.y
let radian = atan2(dy,dx)
return TauAngle(radian)
}
open func ringRadialPointUsingCenter(_ center: RingPoint) -> RingRadialPoint {
let angle = angleFromCenter(center)
let radius = distance(center)
return RingRadialPoint(center: center,
radius: radius,
angle: angle )
}
open override var description: String {
return "x: \(x) y: \(y))"
}
}
| mit | 66962f80130d8ac8689051757e6eafea | 26.131579 | 85 | 0.550436 | 3.883239 | false | false | false | false |
zixun/GodEye | Core/SystemEye/Classes/CPU.swift | 1 | 7172 | //
// CPU.swift
// Pods
//
// Created by zixun on 2016/12/5.
//
//
import Foundation
private let HOST_CPU_LOAD_INFO_COUNT : mach_msg_type_number_t =
UInt32(MemoryLayout<host_cpu_load_info_data_t>.size / MemoryLayout<integer_t>.size)
/// CPU Class
open class CPU: NSObject {
//--------------------------------------------------------------------------
// MARK: OPEN PROPERTY
//--------------------------------------------------------------------------
/// Number of physical cores on this machine.
public static var physicalCores: Int {
get {
return Int(System.hostBasicInfo.physical_cpu)
}
}
/// Number of logical cores on this machine. Will be equal to physicalCores
/// unless it has hyper-threading, in which case it will be double.
public static var logicalCores: Int {
get {
return Int(System.hostBasicInfo.logical_cpu)
}
}
//--------------------------------------------------------------------------
// MARK: OPEN FUNCTIONS
//--------------------------------------------------------------------------
/// Get CPU usage of hole system (system, user, idle, nice). Determined by the delta between
/// the current and last call.
public static func systemUsage() -> (system: Double,
user: Double,
idle: Double,
nice: Double) {
let load = self.hostCPULoadInfo
let userDiff = Double(load.cpu_ticks.0 - loadPrevious.cpu_ticks.0)
let sysDiff = Double(load.cpu_ticks.1 - loadPrevious.cpu_ticks.1)
let idleDiff = Double(load.cpu_ticks.2 - loadPrevious.cpu_ticks.2)
let niceDiff = Double(load.cpu_ticks.3 - loadPrevious.cpu_ticks.3)
let totalTicks = sysDiff + userDiff + niceDiff + idleDiff
let sys = sysDiff / totalTicks * 100.0
let user = userDiff / totalTicks * 100.0
let idle = idleDiff / totalTicks * 100.0
let nice = niceDiff / totalTicks * 100.0
loadPrevious = load
return (sys, user, idle, nice)
}
/// Get CPU usage of application,get from all thread
public class func applicationUsage() -> Double {
let threads = self.threadBasicInfos()
var result : Double = 0.0
threads.forEach { (thread:thread_basic_info) in
if self.flag(thread) {
result += Double.init(thread.cpu_usage) / Double.init(TH_USAGE_SCALE);
}
}
return result * 100
}
//--------------------------------------------------------------------------
// MARK: PRIVATE PROPERTY
//--------------------------------------------------------------------------
/// previous load of cpu
private static var loadPrevious = host_cpu_load_info()
static var hostCPULoadInfo: host_cpu_load_info {
get {
var size = HOST_CPU_LOAD_INFO_COUNT
var hostInfo = host_cpu_load_info()
let result = withUnsafeMutablePointer(to: &hostInfo) {
$0.withMemoryRebound(to: integer_t.self, capacity: Int(size)) {
host_statistics(System.machHost, HOST_CPU_LOAD_INFO, $0, &size)
}
}
#if DEBUG
if result != KERN_SUCCESS {
fatalError("ERROR - \(#file):\(#function) - kern_result_t = "
+ "\(result)")
}
#endif
return hostInfo
}
}
//--------------------------------------------------------------------------
// MARK: PRIVATE FUNCTION
//--------------------------------------------------------------------------
private class func flag(_ thread:thread_basic_info) -> Bool {
let foo = thread.flags & TH_FLAGS_IDLE
let number = NSNumber.init(value: foo)
return !Bool.init(number)
}
private class func threadActPointers() -> [thread_act_t] {
var threads_act = [thread_act_t]()
var threads_array: thread_act_array_t? = nil
var count = mach_msg_type_number_t()
let result = task_threads(mach_task_self_, &(threads_array), &count)
guard result == KERN_SUCCESS else {
return threads_act
}
guard let array = threads_array else {
return threads_act
}
for i in 0..<count {
threads_act.append(array[Int(i)])
}
let krsize = count * UInt32.init(MemoryLayout<thread_t>.size)
let kr = vm_deallocate(mach_task_self_, vm_address_t(array.pointee), vm_size_t(krsize));
return threads_act
}
private class func threadBasicInfos() -> [thread_basic_info] {
var result = [thread_basic_info]()
var thinfo : thread_info_t = thread_info_t.allocate(capacity: Int(THREAD_INFO_MAX))
var thread_info_count = UnsafeMutablePointer<mach_msg_type_number_t>.allocate(capacity: 128)
var basic_info_th: thread_basic_info_t? = nil
for act_t in self.threadActPointers() {
thread_info_count.pointee = UInt32(THREAD_INFO_MAX);
let kr = thread_info(act_t ,thread_flavor_t(THREAD_BASIC_INFO),thinfo, thread_info_count);
if (kr != KERN_SUCCESS) {
return [thread_basic_info]();
}
basic_info_th = withUnsafePointer(to: &thinfo.pointee, { (ptr) -> thread_basic_info_t in
let int8Ptr = unsafeBitCast(ptr, to: thread_basic_info_t.self)
return int8Ptr
})
if basic_info_th != nil {
result.append(basic_info_th!.pointee)
}
}
return result
}
//TODO: this function is used for get cpu usage of all thread,and this is in developing
private class func threadIdentifierInfos() -> [thread_identifier_info] {
var result = [thread_identifier_info]()
var thinfo : thread_info_t = thread_info_t.allocate(capacity: Int(THREAD_INFO_MAX))
var thread_info_count = UnsafeMutablePointer<mach_msg_type_number_t>.allocate(capacity: 128)
var identifier_info_th: thread_identifier_info_t? = nil
for act_t in self.threadActPointers() {
thread_info_count.pointee = UInt32(THREAD_INFO_MAX);
let kr = thread_info(act_t ,thread_flavor_t(THREAD_IDENTIFIER_INFO),thinfo, thread_info_count);
if (kr != KERN_SUCCESS) {
return [thread_identifier_info]();
}
identifier_info_th = withUnsafePointer(to: &thinfo.pointee, { (ptr) -> thread_identifier_info_t in
let int8Ptr = unsafeBitCast(ptr, to: thread_identifier_info_t.self)
return int8Ptr
})
if identifier_info_th != nil {
result.append(identifier_info_th!.pointee)
}
}
return result
}
}
| mit | 4d2555c7e4fe77968d3183e36c98b16b | 36.94709 | 110 | 0.506693 | 4.435374 | false | false | false | false |
narner/AudioKit | Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Stereo Field Limiter.xcplaygroundpage/Contents.swift | 1 | 1081 | //: ## Stereo Field Limiter
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
var player = try AKAudioPlayer(file: file)
player.looping = true
var limitedOutput = AKStereoFieldLimiter(player)
AudioKit.output = limitedOutput
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Stereo Field Limiter")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop") { button in
let node = limitedOutput
node.isStarted ? node.stop() : node.play()
button.title = node.isStarted ? "Stop" : "Start"
})
addView(AKSlider(property: "Amount", value: limitedOutput.amount) { sliderValue in
limitedOutput.amount = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| mit | 3e5e45ca5e403b988c7379e805e1e0a2 | 26.025 | 96 | 0.708603 | 4.523013 | false | false | false | false |
haldun/MapleBacon | Library/MapleBacon/MapleBacon/Storage/DiskStorage.swift | 2 | 4509 | //
// Copyright (c) 2015 Zalando SE. All rights reserved.
//
import UIKit
public class DiskStorage: Storage {
let fileManager: NSFileManager = {
return NSFileManager.defaultManager()
}()
let storageQueue: dispatch_queue_t = {
dispatch_queue_create("de.zalando.MapleBacon.Storage", DISPATCH_QUEUE_SERIAL)
}()
let storagePath: String
public var maxAge: NSTimeInterval = 60 * 60 * 24 * 7
public class var sharedStorage: DiskStorage {
struct Singleton {
static let instance = DiskStorage()
}
return Singleton.instance
}
public convenience init() {
self.init(name: "default")
}
public init(name: String) {
let paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)
storagePath = (paths.first as! NSString).stringByAppendingPathComponent("de.zalando.MapleBacon.\(name)")
fileManager.createDirectoryAtPath(storagePath, withIntermediateDirectories: true, attributes: nil, error: nil)
}
public func storeImage(image: UIImage, var data: NSData?, forKey key: String) {
dispatch_async(storageQueue) {
if (data == nil) {
data = UIImagePNGRepresentation(image)
}
self.fileManager.createFileAtPath(self.defaultStoragePath(forKey: key), contents: data!, attributes: nil)
self.pruneStorage()
}
}
public func pruneStorage() {
dispatch_async(storageQueue) {
if let directoryURL = NSURL(fileURLWithPath: self.storagePath, isDirectory: true),
let enumerator = self.fileManager.enumeratorAtURL(directoryURL,
includingPropertiesForKeys: [NSURLIsDirectoryKey, NSURLContentModificationDateKey],
options: .SkipsHiddenFiles,
errorHandler: nil) {
self.deleteExpiredFiles(self.expiredFiles(usingEnumerator: enumerator))
}
}
}
private func expiredFiles(usingEnumerator enumerator: NSDirectoryEnumerator) -> [NSURL] {
let expirationDate = NSDate(timeIntervalSinceNow: -maxAge)
var expiredFiles = [NSURL]()
while let fileURL = enumerator.nextObject() as? NSURL {
if self.isDirectory(fileURL) {
enumerator.skipDescendants()
continue
}
if let modificationDate = self.modificationDate(fileURL) {
if modificationDate.laterDate(expirationDate) == expirationDate {
expiredFiles.append(fileURL)
}
}
}
return expiredFiles
}
private func isDirectory(fileURL: NSURL) -> Bool {
var isDirectoryResource: AnyObject?
fileURL.getResourceValue(&isDirectoryResource, forKey: NSURLIsDirectoryKey, error: nil)
if let isDirectory = isDirectoryResource as? NSNumber {
return isDirectory.boolValue
}
return false
}
private func modificationDate(fileURL: NSURL) -> NSDate? {
var modificationDateResource: AnyObject?
fileURL.getResourceValue(&modificationDateResource, forKey: NSURLContentModificationDateKey, error: nil)
return modificationDateResource as? NSDate
}
private func deleteExpiredFiles(files: [NSURL]) {
for file in files {
fileManager.removeItemAtURL(file, error: nil)
}
}
public func image(forKey key: String) -> UIImage? {
if let data = NSData(contentsOfFile: defaultStoragePath(forKey: key)) {
return UIImage.imageWithCachedData(data)
}
return nil
}
private func defaultStoragePath(forKey key: String) -> String {
return storagePath(forKey: key, inPath: storagePath)
}
private func storagePath(forKey key: String, inPath path: String) -> String {
return (path as NSString).stringByAppendingPathComponent(key.MD5())
}
public func removeImage(forKey key: String) {
dispatch_async(storageQueue) {
self.fileManager.removeItemAtPath(self.defaultStoragePath(forKey: key), error: nil)
return
}
}
public func clearStorage() {
dispatch_async(storageQueue) {
self.fileManager.removeItemAtPath(self.storagePath, error: nil)
self.fileManager.createDirectoryAtPath(self.storagePath, withIntermediateDirectories: true, attributes: nil,
error: nil)
}
}
}
| mit | 60d23e54f933e98f901c5c36f8635a3a | 33.953488 | 120 | 0.640275 | 5.292254 | false | false | false | false |
Quanhua-Guan/HQPhotoLock | PhotoLock/Controllers/ChangePasswordViewController.swift | 2 | 5634 | //
// AuthenticationViewController.swift
// PhotoLock
//
// Created by 泉华 官 on 14/12/28.
// Copyright (c) 2014年 CQMH. All rights reserved.
//
import UIKit
private let alpha = 0.06 as CGFloat
private let showColor = UIColor(red: 252.0 / 255.0, green: 72.0 / 255.0, blue: 72.0 / 255.0, alpha: 0.70)
class ChangePasswordViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var saveButton: UIBarButtonItem!
var isInputingOldPassword = true
var passwords: [Bool]!
var passwordsInput: [Bool]!
var user: User!
override func viewDidLoad() {
super.viewDidLoad()
self.saveButton.enabled = false
let results = DBMasterKey.findInTable(User.self, whereField: "username", equalToValue: "root")!
user = results.firstObject as! User
user.password = (user.password as NSString).AES256DecryptWithKey(passwordForEncryptPassword)
passwords = [Bool]()
passwordsInput = [Bool]()
for (i, flag) in enumerate(user.password) {
passwordsInput.append(false)
passwords.append(flag == "0" ? false : true)
containerView.viewWithTag(9000 + i + 1)?.backgroundColor = UIColor.randomColor(alpha: alpha)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
var title = NSLocalizedString("Old Password", comment: "")
var message = NSLocalizedString("Please enter your old password", comment: "")
if self.isInputingOldPassword {
title = NSLocalizedString("Old Password", comment: "")
message = NSLocalizedString("Please enter your old password", comment: "")
} else {
title = NSLocalizedString("New Password", comment: "")
message = NSLocalizedString("Please enter your new password", comment: "")
}
let otherButtonsTitle = [NSLocalizedString("OK", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: nil,
otherButtonTitles: otherButtonsTitle) { (alertView, index) -> Void in
alertView.dismissWithClickedButtonIndex(index, animated: true)
self.isInputingOldPassword = true
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func passwordInputChanged(sender: UIButton) {
let index = sender.tag - 9000 - 1// 0...27
passwordsInput[index] = !passwordsInput[index]
sender.backgroundColor = passwordsInput[index] ? showColor : UIColor.randomColor(alpha: alpha)
if self.isInputingOldPassword {
self.checkPassword()
}
}
func checkPassword() {
for i in 0..<passwords.count {
if passwords[i] != passwordsInput[i] {
return;
}
}
let title = NSLocalizedString("New Password", comment: "")
let message = NSLocalizedString("Please enter your new password", comment: "")
let otherButtonsTitle = [NSLocalizedString("OK", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: nil,
otherButtonTitles: otherButtonsTitle) {[unowned self] (alertView, index) -> Void in
alertView.dismissWithClickedButtonIndex(index, animated: true)
self.isInputingOldPassword = false
self.saveButton.enabled = true
for i in 1...self.passwords.count {
self.passwordsInput[i - 1] = false
self.containerView.viewWithTag(9000 + i)?.backgroundColor = UIColor.randomColor(alpha: alpha)
}
}
}
@IBAction func savePassword(sender: UIBarButtonItem) {
let title = NSLocalizedString("Tip", comment: "")
let message = NSLocalizedString("Do you remember your new passwod?", comment: "")
let cancelTitle = NSLocalizedString("NO, Wait!", comment: "")
let otherButtonsTitle = [NSLocalizedString("YES, Save it!", comment: "")]
UIAlertView.showWithTitle(title,
message:message,
style: UIAlertViewStyle.Default,
cancelButtonTitle: cancelTitle,
otherButtonTitles: otherButtonsTitle) {[unowned self] (alertView, index) -> Void in
if index == 0 {
// do nothing
} else if index == 1 {
var password = ""
for flag in self.passwordsInput {
if flag {
password += "1"
} else {
password += "0"
}
}
self.user.password = (password as NSString).AES256EncryptWithKey(passwordForEncryptPassword)
DBMasterKey.update(self.user)
// 更新验证视图的密码
authenticationViewController.updatePassword(self.passwordsInput)
// 退出
alertView.dismissWithClickedButtonIndex(index, animated: true)
self.navigationController?.popViewControllerAnimated(true)
}
}
}
}
| mit | 8b4087f003af448090b0a326a2811f2e | 37.916667 | 113 | 0.582084 | 5.193698 | false | false | false | false |
wireapp/wire-ios-data-model | Source/ManagedObjectContext/NSManagedObjectContext+LastNotificationID.swift | 1 | 1986 | //
// Wire
// Copyright (C) 2021 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
private let lastUpdateEventIDKey = "LastUpdateEventID"
@objc public protocol ZMLastNotificationIDStore {
var zm_lastNotificationID: UUID? { get set }
var zm_hasLastNotificationID: Bool { get }
}
extension NSManagedObjectContext: ZMLastNotificationIDStore {
public var zm_lastNotificationID: UUID? {
get {
guard
let uuidString = self.persistentStoreMetadata(forKey: lastUpdateEventIDKey) as? String,
let uuid = UUID(uuidString: uuidString)
else {
return nil
}
return uuid
}
set (newValue) {
if
let value = newValue,
let previousValue = zm_lastNotificationID,
value.isType1UUID &&
previousValue.isType1UUID &&
previousValue.compare(withType1: value) != .orderedAscending {
return
}
Logging.eventProcessing.debug("Setting zm_lastNotificationID = \( newValue?.transportString() ?? "nil" )")
self.setPersistentStoreMetadata(newValue?.uuidString, key: lastUpdateEventIDKey)
}
}
public var zm_hasLastNotificationID: Bool {
return zm_lastNotificationID != nil
}
}
| gpl-3.0 | fd2f3b0936035f7d2456670b022be629 | 31.032258 | 118 | 0.65005 | 4.683962 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/UI/Views/Progress Indicators/ProgressIndicatorView.swift | 1 | 2720 | //
// ProgressIndicatorView.swift
// YourGoals
//
// Created by André Claaßen on 27.10.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import UIKit
import PNChart
enum ProgressIndicatorViewMode {
case normal
case mini
}
/// a circle progress indicator
class ProgressIndicatorView: UIView {
var viewMode = ProgressIndicatorViewMode.normal
var progressView:PieProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
self.backgroundColor = UIColor.clear
self.progressView = PieProgressView(frame: self.bounds)
self.addSubview(progressView)
}
func setProgress(progress:Double, progressIndicator:ProgressIndicator) {
let color = calculateColor(fromIndicator: progressIndicator)
self.progressView.progressTintColor = color
self.progressView.trackTintColor = color
self.progressView.fillColor = color.withAlphaComponent(0.3)
self.progressView.progress = CGFloat(progress)
}
/// show the progress of the goal as a colored circle
/// - Parameters:
/// - goal: the goal
/// - date: calculation of progress for this date
/// - manager: a manager to retrieve actual data from the core data sotre
/// - Throws: core data exception
func setProgress(forGoal goal:Goal, forDate date: Date, withBackburned backburnedGoals:Bool, manager: GoalsStorageManager) throws {
let calculator = GoalProgressCalculator(manager: manager)
let progress = try calculator.calculateProgress(forGoal: goal, forDate: date, withBackburned: backburnedGoals)
self.setProgress(progress: progress.progress, progressIndicator: progress.indicator)
}
/// convert the progress indicator to a traffic color
///
/// - Parameter progressIndicator: the progress indicator
/// - Returns: a color represnetation the state of the progress
func calculateColor(fromIndicator progressIndicator: ProgressIndicator) -> UIColor {
switch progressIndicator {
case .met:
return UIColor.green
case .ahead:
return UIColor.blue
case .onTrack:
return UIColor.green
case .lagging:
return UIColor.orange
case .behind:
return UIColor.red
case .notStarted:
return UIColor.lightGray
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
}
| lgpl-3.0 | 31d3e7db8f98268334fcc52034c6c23c | 29.852273 | 135 | 0.648987 | 5.037106 | false | false | false | false |
apple/swift-experimental-string-processing | Tests/Prototypes/PEG/Printing.swift | 1 | 2518 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
@testable import _StringProcessing
extension PEGCore.Instruction: InstructionProtocol {
var operandPC: InstructionAddress? { self.pc }
}
extension PEG.VM.Code.Instruction: InstructionProtocol {
// No chaining for us
var operandPC: InstructionAddress? { nil }
}
extension PEGCore: TracedProcessor {
var isAcceptState: Bool { state == .accept }
var isFailState: Bool { state == .fail }
var currentPosition: Input.Index { current.pos }
var currentPC: InstructionAddress { current.pc }
}
extension PEGCore.Thread: CustomStringConvertible {
var description: String {
"(pc: \(pc), pos: \(pos))"
}
}
extension PEGCore.Instruction: CustomDebugStringConvertible, CustomStringConvertible {
var description: String {
switch self {
case .nop: return "<nop>"
case .consume(let i): return "<eat \(i)>"
case .match(let e): return "<match '\(e)'>"
case .matchPredicate(let s): return "<match predicate \(String(describing: s))>"
case .branch(let to): return "<branch to: \(to)>"
case .condBranch(let condition, let to):
return "<cond br \(condition) to: \(to)>"
case .call(let f): return "<call \(f)>"
case .ret: return "<ret>"
case .save(let restoringAt): return "<save restoringAt: \(restoringAt)>"
case .accept: return "<accept>"
case .fail: return "<fail>"
case .abort: return "<abort>"
case .comment(let s): return "/* \(s) */"
case .clear: return "<clear>"
case .restore: return "<restore>"
case .push(let pc): return "<push \(pc)>"
case .pop: return "<pop>"
case .assert(let e, let r):
return "<assert \(r) = \(e)>"
case .assertPredicate(let p, let r):
return "<assert predicate \(r) = \(String(describing: p))>"
case .matchHook(let p):
return "<match hook \(String(describing: p))>"
case .assertHook(let p, let r):
return "<assert hook \(r) = \(String(describing: p))>"
}
}
var debugDescription: String { description }
}
extension PEGCore: CustomStringConvertible {
public var description: String {
fatalError()
}
}
| apache-2.0 | 04423c533d76f7a8d0f79a51a414a5c0 | 31.282051 | 86 | 0.614376 | 4.067851 | false | false | false | false |
kinetic-fit/sensors-swift | SwiftySensorsExample/SensorListViewController.swift | 1 | 1727 | //
// SensorListViewController.swift
// SwiftySensorsExample
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import UIKit
import SwiftySensors
class SensorListViewController: UITableViewController {
fileprivate var sensors: [Sensor] = []
override func viewDidLoad() {
super.viewDidLoad()
SensorManager.instance.onSensorDiscovered.subscribe(with: self) { [weak self] sensor in
guard let s = self else { return }
if !s.sensors.contains(sensor) {
s.sensors.append(sensor)
s.tableView.reloadData()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sensors = SensorManager.instance.sensors
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sensors.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sensorCell = tableView.dequeueReusableCell(withIdentifier: "SensorCell")!
let sensor = sensors[indexPath.row]
sensorCell.textLabel?.text = sensor.peripheral.name
return sensorCell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let sensorDetails = segue.destination as? SensorDetailsViewController {
guard let indexPath = tableView.indexPathForSelectedRow else { return }
if indexPath.row >= sensors.count { return }
sensorDetails.sensor = sensors[indexPath.row]
}
}
}
| mit | e558023339e658696c555173c9bf74f2 | 30.381818 | 109 | 0.650058 | 4.974063 | false | false | false | false |
rkreutz/TableAdapter | TableAdapter/TableAdapter.swift | 1 | 6558 | //
// TableAdapter.swift
// TableAdapter
//
// Created by Rodrigo Kreutz on 9/28/17.
// Copyright © 2017 Rodrigo Kreutz. All rights reserved.
//
import UIKit
public protocol TableAdapterDelegate {
func didUpdateData(updatedIndexes: [IndexPath], insertedIndexes: [IndexPath], deletedIndexes: [IndexPath], insertedSections: IndexSet?, deletedSections: IndexSet?)
func didSelect(item: TableItem, at indexPath: IndexPath)
}
open class TableAdapter: NSObject {
public var data: [(section: TableSection?, items: [TableItem])] {
didSet {
var insertIndexes: [IndexPath] = []
var updateIndexes: [IndexPath] = []
for y in 0..<self.data.count {
guard y < oldValue.count else {
insertIndexes.append(contentsOf: (0..<self.data[y].items.count).map({ IndexPath(row: $0, section: y) }))
continue
}
for x in 0..<self.data[y].items.count {
guard x < oldValue[y].items.count else {
insertIndexes.append(IndexPath(row: x, section: y))
continue
}
if self.data[y].items[x].hashValue != oldValue[y].items[x].hashValue {
updateIndexes.append(IndexPath(row: x, section: y))
}
}
}
var deleteIndexes: [IndexPath] = []
for y in 0..<oldValue.count {
guard y < self.data.count else {
deleteIndexes.append(contentsOf: (0..<oldValue[y].items.count).map({ IndexPath(row: $0, section: y) }))
continue
}
for x in 0..<oldValue[y].items.count {
guard x < self.data[y].items.count else {
deleteIndexes.append(IndexPath(row: x, section: y))
continue
}
}
}
var deleteSections: IndexSet?
var insertSections: IndexSet?
if oldValue.count > self.data.count {
deleteSections = IndexSet(integersIn: self.data.count..<oldValue.count)
} else if oldValue.count < self.data.count {
insertSections = IndexSet(integersIn: oldValue.count..<self.data.count)
}
self.delegate?.didUpdateData(updatedIndexes: updateIndexes, insertedIndexes: insertIndexes, deletedIndexes: deleteIndexes, insertedSections: insertSections, deletedSections: deleteSections)
}
}
fileprivate var lastIndexSelected: IndexPath? {
didSet {
guard
let index = self.lastIndexSelected,
index.section < self.data.count,
index.row < self.data[index.section].items.count
else { return }
self.delegate?.didSelect(item: self.data[index.section].items[index.row], at: index)
}
}
public var delegate: TableAdapterDelegate?
public init(withItems items: [TableItem], delegate: TableAdapterDelegate?) {
self.data = [(nil, items)]
self.delegate = delegate
super.init()
}
public init(withData data: [(TableSection?, [TableItem])], delegate: TableAdapterDelegate?) {
self.data = data
self.delegate = delegate
super.init()
}
}
// MARK: - UITableViewDataSource
extension TableAdapter: UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section < data.count else { return 0 }
return data[section].items.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard indexPath.section < self.data.count, indexPath.row < self.data[indexPath.section].items.count else { return UITableViewCell() }
let item = self.data[indexPath.section].items[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: item.cellIdentifier, for: indexPath)
item.configure(cell: cell)
return cell
}
}
// MARK: - UITableViewDelegate
extension TableAdapter: UITableViewDelegate {
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard
section < self.data.count,
let sectionItem = self.data[section].section,
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: sectionItem.headerIdentifier)
else { return nil }
sectionItem.configure(headerView: view)
return view
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section < self.data.count, let sectionItem = self.data[section].section else { return 0 }
return sectionItem.headerHeight
}
public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard
section < self.data.count,
let sectionItem = self.data[section].section,
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: sectionItem.footerIdentifier)
else { return nil }
sectionItem.configure(footerView: view)
return view
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard section < self.data.count, let sectionItem = self.data[section].section else { return 0 }
return sectionItem.footerHeight
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard indexPath.section < self.data.count, indexPath.row < self.data[indexPath.section].items.count else { return }
self.lastIndexSelected = indexPath
}
public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
guard indexPath.section < self.data.count, indexPath.row < self.data[indexPath.section].items.count else { return nil }
let item = self.data[indexPath.section].items[indexPath.row]
return item.editActions
}
}
| mit | af6e24dd4894e0894de85af9a9ebb1bd | 39.226994 | 201 | 0.6079 | 5.016832 | false | false | false | false |
labi3285/QXConsMaker | QXConsMaker/BasicLayoutVc.swift | 1 | 1680 | //
// BasicLayoutVc.swift
// QXAutoLayoutDemo
//
// Created by Richard.q.x on 16/5/9.
// Copyright © 2016年 labi3285_lab. All rights reserved.
//
import UIKit
class BasicLayoutVc: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.white
let SuperV = view!
let scale: CGFloat = 1
let A = NewSharp(title: "A", inView: view)
let B = NewSharp(title: "B", inView: A)
let C = NewSharp(title: "C", inView: A)
let D = NewSharp(title: "D", inView: A)
let T1 = NewText(text: "ABCDEFGHIJKLMNOPQRSTUVWZ", inView: view)
let T2 = NewText(text: "ABCDEFG", inView: view)
A.LEFT.EQUAL(SuperV).OFFSET(20).MAKE()
A.RIGHT.EQUAL(SuperV).OFFSET(-20).MAKE()
A.TOP.EQUAL(SuperV).OFFSET(100).MAKE()
A.BOTTOM.EQUAL(SuperV).OFFSET(-20).MAKE()
B.CENTER_X.EQUAL(A).MAKE(scale)
B.CENTER_Y.EQUAL(A).MAKE(scale)
B.WIDTH.EQUAL(100).MAKE(scale)
B.HEIGHT.EQUAL(B).WIDTH.MAKE(scale)
T1.LEFT.EQUAL(A).OFFSET(10).MAKE(scale)
T1.TOP.EQUAL(A).OFFSET(100).MAKE(scale)
T2.LEFT.EQUAL(T1).RIGHT.OFFSET(10).MAKE(scale)
T2.RIGHT.LESS_THAN_OR_EQUAL(A).OFFSET(-10).MAKE(scale)
T2.CENTER_Y.EQUAL(T1).MAKE(scale)
C.LEFT.EQUAL(A).MAKE()
C.WIDTH.EQUAL(A).RATIO(0.5).MAKE(scale)
C.HEIGHT.EQUAL(100).MAKE(scale)
C.TOP.EQUAL(B).BOTTOM.MAKE(scale)
D.WIDTH.EQUAL(100).MAKE()
D.LEFT.EQUAL(A).RIGHT.RATIO(0.5).MAKE(scale)
D.TOP.EQUAL(C).BOTTOM.MAKE()
}
}
| apache-2.0 | 822158a07ef38d6bd72f901ff36da8b8 | 27.913793 | 72 | 0.563506 | 3.176136 | false | false | false | false |
BearchInc/Transporter | Transporter/TPTransferTask.swift | 6 | 2254 | //
// TPTransferTask.swift
// Example
//
// Created by Le VanNghia on 3/27/15.
// Copyright (c) 2015 Le VanNghia. All rights reserved.
//
import Foundation
// TODO
/*
- header configuration
- parameter
- resume
- suspend
- cancel
*/
public class TPTransferTask : TPTask {
public var method: TPMethod = .GET
public var HTTPShouldUsePipelining = false
public var HTTPShouldHandleCookies = true
public var allowsCellularAccess = true
public var params: [String: AnyObject]?
public var headers: [String: String]?
public var completionHandler: TransferCompletionHandler?
var url: String
var request: NSMutableURLRequest?
var totalBytes: Int64 = 0
var session: NSURLSession?
var responseData: NSData?
var jsonData: AnyObject? {
if let reponseData = responseData {
return NSJSONSerialization.JSONObjectWithData(reponseData, options: .AllowFragments, error: nil)
}
return nil
}
var error: NSError?
var failed: Bool {
return error != nil
}
public init(url: String, params: [String: AnyObject]? = nil) {
self.url = url
self.params = params
super.init()
}
func setup() {
let requestUrl = NSURL(string: url)!
let request = NSMutableURLRequest(URL: requestUrl)
request.HTTPMethod = method.rawValue
request.HTTPShouldUsePipelining = HTTPShouldUsePipelining
request.HTTPShouldHandleCookies = HTTPShouldHandleCookies
request.allowsCellularAccess = allowsCellularAccess
// append header
if let headers = headers {
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
}
// append http body
if let params = params {
if method == .GET {
let query = queryStringFromParams(params)
let newUrl = url.stringByAppendingString("?\(query)")
request.URL = NSURL(string: newUrl)
}
}
self.request = request
}
public func completed(handler: TransferCompletionHandler) -> Self {
completionHandler = handler
return self
}
} | mit | a3ba457d468574cd14558ff1584884ff | 26.839506 | 108 | 0.621118 | 4.997783 | false | false | false | false |
colemancda/DemoPeripheral | Sources/Peripheral/SunXi.swift | 1 | 1380 | //
// SunXi.swift
//
//
// Created by Alsey Coleman Miller on 6/7/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
/// GPIO for SunXi (e.g. OrangePi) hardware.
///
/// - SeeAlso: [SunXi Wiki](http://linux-sunxi.org/GPIO)
public struct SunXiGPIO: CustomStringConvertible, Equatable {
// MARK: - Properties
public var letter: Letter
public var pin: UInt
// MARK: - Initialization
public init(letter: Letter, pin: UInt) {
self.letter = letter
self.pin = pin
}
// MARK: - Computed Properties
public var description: String {
return pinName
}
public var pinName: String {
return "P" + "\(letter)" + "\(pin)"
}
public var gpioPin: Int {
return (letter.rawValue * 32) + Int(pin)
}
}
// MARK: - Equatable
public func == (lhs: SunXiGPIO, rhs: SunXiGPIO) -> Bool {
return lhs.letter == rhs.letter && lhs.pin == rhs.pin
}
// MARK: - Supporting Types
public extension SunXiGPIO {
public enum Letter: Int {
case A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
}
}
// MARK: - Extensions
public extension GPIO {
convenience init(sunXi: SunXiGPIO) {
self.init(name: sunXi.pinName, id: sunXi.gpioPin)
}
} | mit | 9d39248fd1674355b2b73e3ea95efde1 | 18.43662 | 89 | 0.544598 | 3.526854 | false | false | false | false |
24/ios-o2o-c | gxc/OpenSource/PullRefresh/RefreshBaseView.swift | 1 | 5537 | //
// RefreshBaseView.swift
// RefreshExample
//
// Created by SunSet on 14-6-23.
// Copyright (c) 2014 zhaokaiyuan. All rights reserved.
//
import UIKit
//控件的刷新状态
enum RefreshState {
case Pulling // 松开就可以进行刷新的状态
case Normal // 普通状态
case Refreshing // 正在刷新中的状态
case WillRefreshing
}
//控件的类型
enum RefreshViewType {
case TypeHeader // 头部控件
case TypeFooter // 尾部控件
}
let RefreshLabelTextColor:UIColor = UIColor(red: 150.0/255, green: 150.0/255.0, blue: 150.0/255.0, alpha: 1)
class RefreshBaseView: UIView {
// 父控件
var scrollView:UIScrollView!
var scrollViewOriginalInset:UIEdgeInsets!
// 内部的控件
var statusLabel:UILabel!
var arrowImage:UIImageView!
var activityView:UIActivityIndicatorView!
//回调
var beginRefreshingCallback:(()->Void)?
// 交给子类去实现 和 调用
var oldState:RefreshState?
var State:RefreshState = RefreshState.Normal{
willSet{
}
didSet{
}
}
func setState(newValue:RefreshState){
if self.State != RefreshState.Refreshing {
scrollViewOriginalInset = self.scrollView.contentInset;
}
if self.State == newValue {
return
}
switch newValue {
case .Normal:
self.arrowImage.hidden = false
self.activityView.stopAnimating()
break
case .Pulling:
break
case .Refreshing:
self.arrowImage.hidden = true
activityView.startAnimating()
beginRefreshingCallback!()
break
default:
break
}
}
//控件初始化
override init(frame: CGRect) {
super.init(frame: frame)
//状态标签
statusLabel = UILabel()
statusLabel.autoresizingMask = UIViewAutoresizing.FlexibleWidth
statusLabel.font = UIFont.boldSystemFontOfSize(13)
statusLabel.textColor = RefreshLabelTextColor
statusLabel.backgroundColor = UIColor.clearColor()
statusLabel.textAlignment = NSTextAlignment.Center
self.addSubview(statusLabel)
//箭头图片
arrowImage = UIImageView(image: UIImage(named: "arrow.png"))
arrowImage.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin
self.addSubview(arrowImage)
//状态标签
activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
activityView.bounds = self.arrowImage.bounds
activityView.autoresizingMask = self.arrowImage.autoresizingMask
self.addSubview(activityView)
//自己的属性
self.autoresizingMask = UIViewAutoresizing.FlexibleWidth
self.backgroundColor = UIColor.clearColor()
//设置默认状态
self.State = RefreshState.Normal;
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//箭头
let arrowX:CGFloat = self.frame.size.width * 0.5 * 0.5
self.arrowImage.center = CGPointMake(arrowX, self.frame.size.height * 0.5)
//指示器
self.activityView.center = self.arrowImage.center
}
override func willMoveToSuperview(newSuperview: UIView!) {
super.willMoveToSuperview(newSuperview)
// 旧的父控件
if (self.superview != nil) {
self.superview?.removeObserver(self, forKeyPath: RefreshContentSize, context: nil)
}
// 新的父控件
if (newSuperview != nil) {
newSuperview.addObserver(self, forKeyPath: RefreshContentOffset, options: NSKeyValueObservingOptions.New, context: nil)
var rect:CGRect = self.frame
// 设置宽度 位置
rect.size.width = newSuperview.frame.size.width
rect.origin.x = 0
self.frame = frame;
//UIScrollView
scrollView = newSuperview as UIScrollView
scrollViewOriginalInset = scrollView.contentInset;
}
}
//显示到屏幕上
override func drawRect(rect: CGRect) {
superview?.drawRect(rect);
if self.State == RefreshState.WillRefreshing {
self.State = RefreshState.Refreshing
}
}
// 刷新相关
// 是否正在刷新
func isRefreshing()->Bool{
return RefreshState.Refreshing == self.State;
}
// 开始刷新
func beginRefreshing(){
// self.State = RefreshState.Refreshing;
if (self.window != nil) {
self.State = RefreshState.Refreshing;
} else {
//不能调用set方法
State = RefreshState.WillRefreshing;
super.setNeedsDisplay()
}
}
//结束刷新
func endRefreshing(){
let delayInSeconds:Double = 0.3
var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayInSeconds));
dispatch_after(popTime, dispatch_get_main_queue(), {
self.State = RefreshState.Normal;
})
}
}
| mit | b98c8d6dc0f548b4222aa5a6884037e9 | 25.654822 | 131 | 0.592078 | 5.015282 | false | false | false | false |
SPECURE/rmbt-ios-client | Sources/QOSHTTPProxyTest.swift | 1 | 3144 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************************************/
import Foundation
///
class QOSHTTPProxyTest: QOSTest {
fileprivate let PARAM_URL = "url"
fileprivate let PARAM_RANGE = "range"
fileprivate let PARAM_DOWNLOAD_TIMEOUT = "download_timeout"
fileprivate let PARAM_CONNECTION_TIMEOUT = "conn_timeout"
//
/// The download timeout in nano seconds of the http proxy test (optional) (provided by control server)
var downloadTimeout: UInt64 = 10_000_000_000 // default download timeout value
/// The connection timeout in nano seconds of the http proxy test (optional) (provided by control server)
var connectionTimeout: UInt64 = 5_000_000_000 // default connection timeout value
/// The url of the http proxy test (provided by control server)
var url: String?
/// The range of the http proxy test (optional) (provided by control server)
var range: String?
//
///
override var description: String {
return super.description + ", [downloadTimeout: \(downloadTimeout), connectionTimeout: \(connectionTimeout), url: \(String(describing: url)), range: \(String(describing: range))]"
}
//
///
override init(testParameters: QOSTestParameters) {
// url
if let url = testParameters[PARAM_URL] as? String {
// TODO: length check on url?
self.url = url
}
// range
if let range = testParameters[PARAM_RANGE] as? String {
self.range = range
}
// downloadTimeout
if let downloadTimeoutString = testParameters[PARAM_DOWNLOAD_TIMEOUT] as? NSString {
let downloadTimeout = downloadTimeoutString.longLongValue
if downloadTimeout > 0 {
self.downloadTimeout = UInt64(downloadTimeout)
}
}
// connectionTimeout
if let connectionTimeoutString = testParameters[PARAM_CONNECTION_TIMEOUT] as? NSString {
let connectionTimeout = connectionTimeoutString.longLongValue
if connectionTimeout > 0 {
self.connectionTimeout = UInt64(connectionTimeout)
}
}
super.init(testParameters: testParameters)
// set timeout
self.timeout = max(downloadTimeout, connectionTimeout)
}
///
override func getType() -> QosMeasurementType! {
return .HttpProxy
}
}
| apache-2.0 | bb75b4e3629e6ce4b0f0ca438a2cdfe4 | 33.549451 | 187 | 0.618639 | 5.054662 | false | true | false | false |
spritekitbook/flappybird-swift | Chapter 8/Start/FloppyBird/FloppyBird/GameOverScene.swift | 2 | 2054 | //
// GameOverScene.swift
// FloppyBird
//
// Created by Jeremy Novak on 9/24/16.
// Copyright © 2016 SpriteKit Book. All rights reserved.
//
import SpriteKit
class GameOverScene: SKScene {
// MARK: - Private class constants
private let cloudController = CloudController()
private let hills = Hills()
private let ground = Ground()
private let retryButton = RetryButton()
// MARK: - Private class variables
private var lastUpdateTime:TimeInterval = 0.0
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
}
convenience init(size: CGSize, score: Int) {
self.init(size: size)
setup(score: score)
}
override func didMove(to view: SKView) {
}
// MARK: - Setup
private func setup(score: Int) {
self.backgroundColor = Colors.colorFrom(rgb: Colors.sky)
self.addChild(cloudController)
self.addChild(hills)
self.addChild(ground)
self.addChild(retryButton)
let scoreBoard = Scoreboard(score: score)
self.addChild(scoreBoard)
}
// MARK: - Update
override func update(_ currentTime: TimeInterval) {
let delta = currentTime - lastUpdateTime
lastUpdateTime = currentTime
cloudController.update(delta: delta)
}
// MARK: - Touch Events
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let touchLocation = touch.location(in: self)
if retryButton.contains(touchLocation) {
loadScene()
}
}
// MARK: - Load Scene
private func loadScene() {
let scene = GameScene(size: kViewSize)
let transition = SKTransition.fade(with: SKColor.black, duration: 0.5)
self.view?.presentScene(scene, transition: transition)
}
}
| apache-2.0 | 00b8e1e7992661f63a26e8998a5efb18 | 24.987342 | 79 | 0.605943 | 4.532009 | false | false | false | false |
YoungGary/Sina | Sina/Sina/Classes/Home首页/PhotoBrower/BrowerTransitionAnimation.swift | 1 | 4124 | //
// BrowerTransitionAnimation.swift
// Sina
//
// Created by YOUNG on 16/9/24.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
//定义协议 弹出
protocol AnimationPresentedDelegate : NSObjectProtocol{
func startRect(indexPath : NSIndexPath) -> CGRect
func endRect(indexPath : NSIndexPath) -> CGRect
func imageView(indexPath : NSIndexPath) -> UIImageView
}
//定义dismiss的协议
protocol AnimationDismissDelegate : NSObjectProtocol {
func indexPathForDimissView() -> NSIndexPath
func imageViewForDimissView() -> UIImageView
}
class BrowerTransitionAnimation: NSObject {
var isPresented :Bool = false
//定义代理属性
var presentedDelegate : AnimationPresentedDelegate?
var dismissDelegate : AnimationDismissDelegate?
var indexPath : NSIndexPath?
}
extension BrowerTransitionAnimation : UIViewControllerTransitioningDelegate{
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = true
return self
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresented = false
return self
}
}
extension BrowerTransitionAnimation : UIViewControllerAnimatedTransitioning{
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if isPresented == true {//model
//nil 检验
guard let presentedDelegate = presentedDelegate, indexPath = indexPath else {
return
}
// UITransitionContextFromViewKey, and UITransitionContextToViewKey
let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)!
transitionContext.containerView()?.addSubview(presentedView)
// 获取执行动画的imageView
let startRect = presentedDelegate.startRect(indexPath)
let imageView = presentedDelegate.imageView(indexPath)
transitionContext.containerView()?.addSubview(imageView)
imageView.frame = startRect
//执行动画
presentedView.alpha = 0.0
transitionContext.containerView()?.backgroundColor = UIColor.blackColor()
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
imageView.frame = presentedDelegate.endRect(indexPath)
}, completion: { (_) in
imageView.removeFromSuperview()
presentedView.alpha = 1.0
transitionContext.containerView()?.backgroundColor = UIColor.clearColor()
transitionContext.completeTransition(true)
})
}else{//dismiss
// nil值校验
guard let dismissDelegate = dismissDelegate, presentedDelegate = presentedDelegate else {
return
}
// 1.取出消失的View
let dismissView = transitionContext.viewForKey(UITransitionContextFromViewKey)
dismissView?.removeFromSuperview()
// 2.获取执行动画的ImageView
let imageView = dismissDelegate.imageViewForDimissView()
transitionContext.containerView()?.addSubview(imageView)
let indexPath = dismissDelegate.indexPathForDimissView()
// 3.执行动画
UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
imageView.frame = presentedDelegate.startRect(indexPath)
}) { (_) -> Void in
transitionContext.completeTransition(true)
}
}
}
}
| apache-2.0 | 5c7f05b2826a925ec3d56642addae394 | 33.09322 | 217 | 0.653492 | 6.807107 | false | false | false | false |
bolshedvorsky/swift-corelibs-foundation | TestFoundation/TestNotification.swift | 11 | 1848 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNotification : XCTestCase {
static var allTests: [(String, (TestNotification) -> () throws -> Void)] {
return [
("test_customReflection", test_customReflection),
]
}
func test_customReflection() {
let someName = "somenotifname"
let targetObject = NSObject()
let userInfo = ["hello": "world", "indexThis": 350] as [AnyHashable: Any]
let notif = Notification(name: Notification.Name(rawValue: someName), object: targetObject, userInfo: userInfo)
let mirror = notif.customMirror
XCTAssertEqual(mirror.displayStyle, .class)
XCTAssertNil(mirror.superclassMirror)
var children = Array(mirror.children).makeIterator()
let firstChild = children.next()
let secondChild = children.next()
let thirdChild = children.next()
XCTAssertEqual(firstChild?.label, "name")
XCTAssertEqual(firstChild?.value as? String, someName)
XCTAssertEqual(secondChild?.label, "object")
XCTAssertEqual(secondChild?.value as? NSObject, targetObject)
XCTAssertEqual(thirdChild?.label, "userInfo")
XCTAssertEqual((thirdChild?.value as? [AnyHashable: Any])?["hello"] as? String, "world")
XCTAssertEqual((thirdChild?.value as? [AnyHashable: Any])?["indexThis"] as? Int, 350)
}
}
| apache-2.0 | a3a01059d199ea122264897125453102 | 32 | 119 | 0.675325 | 4.551724 | false | true | false | false |
AutomationStation/BouncerBuddy | BouncerBuddyV6/BouncerBuddy/HomeModel.swift | 3 | 2825 | //
// HomeModel.swift
// BouncerBuddy
//
// Created by Sha Wu on 16/3/7.
// Copyright © 2016年 Sheryl Hong. All rights reserved.
//
import Foundation
protocol HomeModelProtocal: class {
func itemsDownloaded(items: NSArray)
}
class HomeModel: NSObject, NSURLSessionDataDelegate {
//properties
weak var delegate: HomeModelProtocal!
var data : NSMutableData = NSMutableData()
let urlPath: String = "https://cgi.soic.indiana.edu/~hong43/blacklistconn.php"
func downloadItems() {
let url: NSURL = NSURL(string: urlPath)!
var session: NSURLSession!
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithURL(url)
task.resume()
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
self.data.appendData(data);
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded")
self.parseJSON()
}
}
func parseJSON() {
var jsonResult: NSMutableArray = NSMutableArray()
do{
jsonResult = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions.AllowFragments) as! NSMutableArray
} catch let error as NSError {
print(error)
}
var jsonElement: NSDictionary = NSDictionary()
let bannedlist: NSMutableArray = NSMutableArray()
for(var i = 0; i < jsonResult.count; i++)
{
jsonElement = jsonResult[i] as! NSDictionary
let banned = BannedModel()
//the following insures none of the JsonElement values are nil through optional binding
if let name = jsonElement["name"] as? String,
let gender = jsonElement["gender"] as? String,
let notes = jsonElement["notes"] as? String
{
banned.name = name
banned.gender = gender
banned.notes = notes
}
bannedlist.addObject(banned)
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.delegate.itemsDownloaded(bannedlist)
})
}
}
| apache-2.0 | f10529a69f51c281f1cdfa47eb5af120 | 26.666667 | 142 | 0.546421 | 5.522505 | false | false | false | false |
xiaozhuxiong121/PGDatePicker | SwiftDemo/SwiftDemo/ViewController.swift | 1 | 5698 | //
// ViewController.swift
// SwiftDemo
//
// Created by piggybear on 2017/10/25.
// Copyright © 2017年 piggybear. All rights reserved.
//
import UIKit
import PGDatePicker
class ViewController: UIViewController {
@IBAction func yearHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
datePickerManager.isShadeBackground = true
datePickerManager.style = .alertTopButton
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .year
self.present(datePickerManager, animated: false, completion: nil)
// datePicker.minimumDate = NSDate.setYear(2015)
// datePicker.maximumDate = NSDate.setYear(2020)
}
@IBAction func yearAndMonthHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
datePickerManager.isShadeBackground = true
datePickerManager.style = .alertBottomButton
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerType = .type1
datePicker.datePickerMode = .yearAndMonth
self.present(datePickerManager, animated: false, completion: nil)
// datePicker.minimumDate = NSDate.setYear(2015, month: 5)
// datePicker.maximumDate = NSDate.setYear(2020, month: 10)
}
@IBAction func dateHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.isHiddenMiddleText = false;
datePicker.datePickerType = .type2;
datePicker.datePickerMode = .date
self.present(datePickerManager, animated: false, completion: nil)
// datePicker.minimumDate = NSDate.setYear(2015, month: 5, day: 10)
// datePicker.maximumDate = NSDate.setYear(2020, month: 10, day: 20)
}
@IBAction func dateHourMinuteHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .dateHourMinute
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func dateHourMinuteSecondHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .dateHourMinuteSecond
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func timeHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .time
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func timeAndSecondHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .timeAndSecond
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func dateAndTimeHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .dateAndTime
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func titleHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
datePickerManager.titleLabel.text = "PGDatePicker"
let datePicker = datePickerManager.datePicker!
datePicker.delegate = self
datePicker.datePickerMode = .date
self.present(datePickerManager, animated: false, completion: nil)
}
@IBAction func styleHandler(_ sender: Any) {
let datePickerManager = PGDatePickManager()
let datePicker = datePickerManager.datePicker!
self.present(datePickerManager, animated: false, completion: nil)
datePicker.delegate = self
datePickerManager.titleLabel.text = "PGDatePicker"
//设置头部的背景颜色
datePickerManager.headerViewBackgroundColor = UIColor.orange
//设置半透明背景
datePickerManager.isShadeBackground = true
//设置线条的颜色
datePicker.lineBackgroundColor = UIColor.red
//设置选中行的字体颜色
datePicker.textColorOfSelectedRow = UIColor.red
//设置未选中行的字体颜色
datePicker.textColorOfOtherRow = UIColor.black
//设置取消按钮的字体颜色
datePickerManager.cancelButtonTextColor = UIColor.black
//设置取消按钮的字
datePickerManager.cancelButtonText = "Cancel"
//设置取消按钮的字体大小
datePickerManager.cancelButtonFont = UIFont.boldSystemFont(ofSize: 17)
//设置确定按钮的字体颜色
datePickerManager.confirmButtonTextColor = UIColor.red
//设置确定按钮的字
datePickerManager.confirmButtonText = "Sure"
//设置确定按钮的字体大小
datePickerManager.confirmButtonFont = UIFont.boldSystemFont(ofSize: 17)
datePicker.datePickerMode = .date
}
}
extension ViewController: PGDatePickerDelegate {
func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
print("dateComponents = ", dateComponents)
}
}
| mit | fd8002d34e53245ccee2c42f8c9b21d9 | 37.914894 | 97 | 0.684345 | 4.912265 | false | false | false | false |
digitwolf/SwiftFerrySkill | Sources/Ferry/Models/SpaceForArrivalTerminals.swift | 1 | 2602 | //
// SpaceForArrivalTerminals.swift
// FerrySkill
//
// Created by Shakenova, Galiya on 3/3/17.
//
//
import Foundation
import SwiftyJSON
public class SpaceForArrivalTerminals {
public var terminalID : Int? = 0
public var terminalName : String? = ""
public var vesselID : Int? = 0
public var vesselName : String? = ""
public var displayReservableSpace : Bool? = false
public var reservableSpaceCount : Int? = 0
public var reservableSpaceHexColor : String? = ""
public var displayDriveUpSpace : Bool? = false
public var driveUpSpaceCount : Int? = 0
public var driveUpSpaceHexColor : String? = ""
public var maxSpaceCount : Int? = 0
public var arrivalTerminalIDs: [Int] = []
init() {
}
public init(_ json: JSON) {
terminalID = json["TerminalID"].intValue
terminalName = json["TerminalName"].stringValue
vesselName = json["VesselName"].stringValue
vesselID = json["VesselID"].intValue
displayReservableSpace = json["DisplayReservableSpace"].boolValue
reservableSpaceCount = json["ReservableSpaceCount"].intValue
reservableSpaceHexColor = json["ReservableSpaceHexColor"].stringValue
displayDriveUpSpace = json["DisplayDriveUpSpace"].boolValue
driveUpSpaceCount = json["DriveUpSpaceCount"].intValue
driveUpSpaceHexColor = json["DriveUpSpaceHexColor"].stringValue
maxSpaceCount = json["MaxSpaceCount"].intValue
for terminal in json["ArrivalTerminalIDs"].arrayValue {
arrivalTerminalIDs.append(terminal.intValue)
}
}
public func toJson() -> JSON {
var json = JSON([])
json["TerminalID"].intValue = terminalID!
json["TerminalName"].stringValue = terminalName!
json["VesselName"].stringValue = vesselName!
json["VesselID"].intValue = vesselID!
json["DisplayReservableSpace"].boolValue = displayReservableSpace!
json["ReservableSpaceCount"].intValue = reservableSpaceCount!
json["ReservableSpaceHexColor"].stringValue = reservableSpaceHexColor!
json["DisplayDriveUpSpace"].boolValue = displayDriveUpSpace!
json["DriveUpSpaceCount"].intValue = driveUpSpaceCount!
json["DriveUpSpaceHexColor"].stringValue = driveUpSpaceHexColor!
json["MaxSpaceCount"].intValue = maxSpaceCount!
var terminals: [Int] = []
for terminal in arrivalTerminalIDs {
terminals.append(terminal)
}
json["ArrivalTerminalIDs"] = JSON(terminals)
return json
}
}
| apache-2.0 | 5b296b64fa7cb8f0aca585abe295bad7 | 36.710145 | 78 | 0.669101 | 4.463122 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainComponentLibrary/Sources/Examples/Utilities/NavigationLinkProvider.swift | 1 | 2140 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainComponentLibrary
import SwiftUI
public typealias NavigationLinkProviderList = [String: [NavigationLinkProvider]]
public struct NavigationLinkProvider: Hashable {
public static func == (lhs: NavigationLinkProvider, rhs: NavigationLinkProvider) -> Bool {
lhs.title == rhs.title
}
private let view: AnyView
private let title: String
public init<Content: View>(view: Content, title: String? = nil) {
self.title = title ?? String(describing: type(of: view))
self.view = AnyView(view.primaryNavigation(title: self.title))
}
public func hash(into hasher: inout Hasher) {
hasher.combine(title)
}
@ViewBuilder
public static func sections(for data: NavigationLinkProviderList) -> some View {
ForEach(Array(data.keys.sorted()), id: \.self) { key in
if let dict = data[key] {
Section(header: SectionHeader(title: key)) {
links(for: dict)
}
}
}
}
@ViewBuilder
public static func links(for dict: [NavigationLinkProvider]) -> some View {
ForEach(dict, id: \.self) { linkable in
NavigationLinkView(
title: linkable.title,
view: linkable.view
)
}
}
}
private struct NavigationLinkView<LinkableView: View>: View {
@State var isActive = false
let title: String
let view: LinkableView
var body: some View {
VStack(spacing: 0) {
PrimaryRow(title: title) { isActive = true }
.background(
PrimaryNavigationLink(
destination: ZStack { view }
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.semantic.background.ignoresSafeArea()),
isActive: $isActive,
label: { EmptyView() }
)
)
PrimaryDivider()
}
.listRowInsets(EdgeInsets())
}
}
| lgpl-3.0 | e32c2433c2e2553d64dc7962e023fee6 | 29.126761 | 94 | 0.568022 | 4.883562 | false | false | false | false |
fitpay/fitpay-ios-sdk | FitpaySDK/Rest/Models/Commit/Enums/SyncInitiator.swift | 1 | 267 | import Foundation
public enum SyncInitiator: String, Serializable {
case platform = "PLATFORM"
case notification = "NOTIFICATION"
case webHook = "WEB_HOOK"
case eventStream = "EVENT_STREAM"
case notDefined = "NOT DEFINED"
}
| mit | 528a5edb2f271036f4e03f39ba8d1bd1 | 28.666667 | 49 | 0.64794 | 4.045455 | false | false | false | false |
Authman2/Pix | Pix/NetworkingStorage.swift | 1 | 3550 | //
// NetworkingStorage.swift
// PlanIt
//
// Created by Adeola Uthman on 2/25/17.
// Copyright © 2017 Miguel Guerrero. All rights reserved.
//
import Foundation
import UIKit
import Firebase
/** This extension handles media storage. */
public extension Networking {
/**
Takes a UIImage as the input and saves it into the Firebase storage under the folder (userID)/imageID.
@parameters: {
- img: The UIImage that is to be saved.
- toUser: The user who needs to have the photo saved to.
- success: When the image is successfully saved.
- failure: When there is an error saving the image.
}
*/
public static func saveImageToFirebase(img: UIImage, toUser: User, success: (()->Void)?, failure: (()->Void)?) {
let ref = storageRef.child("\(toUser.uid)/\(toUser.profilePicName!).jpg");
let data = UIImageJPEGRepresentation(img, 100) as NSData?;
let _ = ref.put(data! as Data, metadata: nil) { (metaData, error) in
if error == nil {
fireRef.child("Users").child(toUser.uid).setValue(toUser.toDictionary(), withCompletionBlock: { (err: Error?, ref: FIRDatabaseReference) in
if err == nil {
// Run the success block
if let s = success {
s();
}
} else {
// Also run the failure block if it can't save to the database.
if let fail = failure {
fail();
}
}
});
} else {
// Run the failure block.
if let fail = failure {
fail();
}
}
}
}
/**
Loads the image with the specified ID from a user. There is a 50gb limit on loading photos. This can be changed easily, however I am not currently sure how this will affect performance. The success block has a UIImage callback so that you can do something with the loaded image.
@parameters: {
- withID: The id of the photo.
- fromUser: The user who owns the photo.
- success: When the image is successfully loaded.
- failure: When there is an error saving the image.
}
*/
public static func loadImage(withID: String, fromUser: User, success: ((_ img: UIImage)->Void)?, failure: (()->Void)?) {
let imgRef = storageRef.child("\(fromUser.uid)/\(withID).jpg");
imgRef.data(withMaxSize: 50 * 1024 * 1024, completion: { (data: Data?, err2: Error?) in
if err2 == nil {
if let d = data {
// Set the image of the post.
let loadedImage = UIImage(data: d)!;
// Run the success block
if let s = success {
s(loadedImage);
}
}
} else {
// Run the failure block
if let fail = failure {
fail();
}
}
});
}
}
| gpl-3.0 | b900d88303ca440c4d007b6417f582fd | 31.263636 | 283 | 0.458439 | 5.468413 | false | false | false | false |
volodg/iAsync.network | Pods/iAsync.utils/Lib/ObjCBridg/JObjcMutableAssignArray.swift | 2 | 1327 | //
// JObjcMutableAssignArray.swift
// JUtils
//
// Created by Vladimir Gorbenko on 06.10.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public class JObjcMutableAssignArray : NSObject {
private let mutArray = JMutableAssignArray<NSObject>()
public var onRemoveObject: JSimpleBlock? {
get {
return mutArray.onRemoveObject
}
set (newValue) {
mutArray.onRemoveObject = newValue
}
}
public var array: NSArray {
return mutArray.map({$0})
}
public var count: Int {
return mutArray.count
}
public func addObject(object: AnyObject) {
mutArray.append(object as! NSObject)
}
public func removeObjectAtIndex(index: Int) {
mutArray.removeAtIndex(index)
}
public func containsObject(object: AnyObject) -> Bool {
let index = mutArray.indexOfObject(object as! NSObject)
return index != Int.max
}
public func indexOfObject(object: AnyObject) -> Int {
let index = mutArray.indexOfObject(object as! NSObject)
return index
}
public func removeObject(object: AnyObject) {
mutArray.removeObject(object as! NSObject)
}
}
| mit | b39692e158120c01303dba4521af217a | 21.491525 | 63 | 0.602864 | 4.544521 | false | false | false | false |
volodg/iAsync.social | Pods/iAsync.network/Lib/Extensions/NSURL+Cookies.swift | 1 | 995 | //
// NSURL+Cookies.swift
// JNetwork
//
// Created by Vladimir Gorbenko on 24.09.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public extension NSURL {
func logCookies() {
var cookiesLog = "Cookies for url: \(self)\n"
if let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self) as? [NSHTTPCookie] {
for cookie in cookies {
cookiesLog += "Name: '\(cookie.name)'; Value: '\(cookie.value)'\n"
}
}
NSLog(cookiesLog)
}
func removeCookies() {
let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookies = cookieStorage.cookiesForURL(self) as? [NSHTTPCookie]
if let cookies = cookies {
for cookie in cookies {
cookieStorage.deleteCookie(cookie as NSHTTPCookie)
}
}
}
}
| mit | 45a8040a1ac70aaf15b9183633fdc63e | 23.875 | 111 | 0.557789 | 5.050761 | false | false | false | false |
eraydiler/password-locker | PasswordLockerSwift/Classes/Controller/TabBarVC/SelectedTypeTableViewController.swift | 1 | 8402 | //
// SelectedTypeTableViewController.swift
// PasswordLockerSwift
//
// Created by Eray on 03/04/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
protocol SelectedTypeTableViewControllerDelegate {
func allDataDeletedForCategory(_ category: Category)
}
class SelectedTypeTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {
// set by former controller
var category: Category?
// delegate to send info to tabBar Controller when there is no more data
var delegate: SelectedTypeTableViewControllerDelegate?
let TAG = "SelectedType TVC"
func configureView() {
self.title = self.category?.name
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
print("\(TAG) MemoryWarning", terminator: "")
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> {
// return if already initialized
if self._fetchedResultsController != nil {
return self._fetchedResultsController!
}
let managedObjectContext = NSManagedObjectContext.mr_default()
let entity = NSEntityDescription.entity(forEntityName: "SavedObject", in: managedObjectContext)
let sort = NSSortDescriptor(key: "date", ascending: true)
let req = NSFetchRequest<NSFetchRequestResult>()
req.entity = entity
req.sortDescriptors = [sort]
req.predicate = NSPredicate(format: "category == %@", self.category!)
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
self._fetchedResultsController = aFetchedResultsController
// perform initial model fetch
var e: NSError?
do {
try self._fetchedResultsController!.performFetch()
} catch let error as NSError {
e = error
print("\(TAG) fetch error: \(e!.localizedDescription)")
abort();
}
return self._fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
// MARK: - fetched results controller delegate
/* called first
begins update to `UITableView`
ensures all updates are animated simultaneously */
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.beginUpdates()
}
/* called:
- when a new model is created
- when an existing model is updated
- when an existing model is deleted */
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch type {
case .insert:
self.tableView.insertRows(at: [newIndexPath!], with: UITableView.RowAnimation.fade)
print("\(TAG) coredata insert")
case .update:
let cell = self.tableView.cellForRow(at: indexPath!)
self.configureCell(cell!, atIndexPath: indexPath!)
self.tableView.reloadRows(at: [indexPath!], with: UITableView.RowAnimation.fade)
print("\(TAG) coredata update")
case .move:
print("\(TAG) coredata move")
self.tableView.deleteRows(at: [indexPath!], with: UITableView.RowAnimation.fade)
self.tableView.insertRows(at: [newIndexPath!], with: UITableView.RowAnimation.fade)
case .delete:
print("\(TAG) coredata delete")
self.tableView.deleteRows(at: [indexPath!], with: UITableView.RowAnimation.fade)
if self.fetchedResultsController.sections![0].numberOfObjects == 0 {
// TODO: Butun veriler silinmisse view controller i da sil
self.delegate?.allDataDeletedForCategory(self.category!)
}
}
}
/* called last
tells `UITableView` updates are complete */
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.tableView.endUpdates()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return self.fetchedResultsController.sections!.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.fetchedResultsController.sections![section].numberOfObjects
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "selectedCell", for: indexPath)
// Configure the cell...
configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
let context = self.fetchedResultsController.managedObjectContext
let objectToBeDeleted: SavedObject = self.fetchedResultsController.object(at: indexPath) as! SavedObject
let relationships = objectToBeDeleted.mutableSetValue(forKey: "rows")
context.delete(objectToBeDeleted)
for row in relationships {
context.delete(row as! NSManagedObject)
}
let managedObjectContext = NSManagedObjectContext.mr_default()
managedObjectContext.mr_saveToPersistentStoreAndWait()
}
}
func configureCell(_ cell: UITableViewCell, atIndexPath indexPath: IndexPath) {
let savedObject = self.fetchedResultsController.object(at: indexPath) as! SavedObject
// cell.textLabel?.text = savedObject.name
let label = cell.contentView.subviews[0] as! UILabel
label.text = savedObject.name
let imageView = cell.contentView.subviews[1] as! UIImageView
imageView.image = UIImage(named: savedObject.type.imageName)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let indexPath = self.tableView.indexPathForSelectedRow
let savedObject = self.fetchedResultsController.object(at: indexPath!) as! SavedObject
if segue.identifier == "toSelectedValuesTVCSegue" {
let targetVC = segue.destination as! SelectedValuesTableViewController
targetVC.category = self.category
targetVC.savedObjectID = savedObject.objectID
}
}
// MARK: - Helper Methods
func parseDataForTitle(_ data: Array<Dictionary<String, String>>,
atIndexPath indexPath: IndexPath) -> String {
var title: String = String()
let dict: Dictionary<String, String> = data[indexPath.row]
if indexPath.section == 0 {
title = dict["value"]!
}
for (key, value) in dict {
print("\(TAG) key: \(key), value: \(value)")
}
return title
}
}
| mit | a942e47d9a8ec84b769512d92fa9fa6a | 37.898148 | 170 | 0.641871 | 5.794483 | false | false | false | false |
SmallElephant/FELeetcode | 1-TwoSum/1-TwoSum/Solution.swift | 1 | 1006 | //
// Solution.swift
// 1-TwoSum
//
// Created by keso on 2017/6/3.
// Copyright © 2017年 FlyElephant. All rights reserved.
//
import Foundation
//https://leetcode.com/problems/two-sum/#/description
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
let count:Int = nums.count
for i in 0..<count - 1 {
let num:Int = nums[i]
for j in (i + 1)..<count {
if num + nums[j] == target {
return [i, j]
}
}
}
return []
}
func twoSum2(_ nums: [Int], _ target: Int) -> [Int] {
var dict = [Int : Int]()
for (i, num) in nums.enumerated() {
if let lastIndex = dict[target - num] {
return [lastIndex, i]
}
dict[num] = i
}
return []
}
}
| mit | 224195d9cac3854985078ee605bc3510 | 19.469388 | 57 | 0.393819 | 4.214286 | false | false | false | false |
hbang/TermHere | TermHere/ViewController.swift | 1 | 3669 | //
// ViewController.swift
// TermHere
//
// Created by Adam Demasi on 13/05/2016.
// Copyright © 2016 HASHBANG Productions. All rights reserved.
//
import Cocoa
import CoreServices
class ViewController: NSViewController {
@IBOutlet weak var terminalPathControl: NSPathControl!
@IBOutlet weak var terminalContextMenusCheckbox: NSButtonCell!
@IBOutlet weak var openSelectionCheckbox: NSButton!
@IBOutlet weak var terminalOpenInPopUpButton: NSPopUpButton!
@IBOutlet weak var editorPathControl: NSPathControl!
@IBOutlet weak var editorContextMenusCheckbox: NSButton!
let preferences = Preferences.sharedInstance
// MARK: - NSViewController
override func viewDidLoad() {
super.viewDidLoad()
// set the values of the controls
terminalPathControl.url = preferences.terminalAppURL
editorPathControl.url = preferences.editorAppURL
openSelectionCheckbox.state = preferences.openSelection ? .on : .off
}
override func viewDidAppear() {
super.viewDidAppear()
requestExtensionEnable()
}
// MARK: - First Run
func requestExtensionEnable() {
// if this is the first run
if preferences.hadFirstRun == false {
// set hadFirstRun so this won’t activate again, then show the setup window
preferences.hadFirstRun = true
showSetupWindow()
}
}
func showSetupWindow() {
let newWindow = storyboard!.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("setupWindowController")) as! NSWindowController
newWindow.showWindow(self)
}
// MARK: - Callbacks
typealias BrowseForAppCompletion = (_ path: URL) -> Void
func browseForApp(pathControl: NSPathControl, completion: @escaping BrowseForAppCompletion) {
// set up the open panel
let panel = NSOpenPanel()
panel.title = NSLocalizedString("CHOOSE_APPLICATION", comment: "Title of the “Choose Application” window.")
// only allow selecting app bundles
panel.allowedFileTypes = [ kUTTypeApplicationBundle as String ]
// configure the selected item. set the path to open to, then the filename to highlight
panel.directoryURL = pathControl.url!.deletingLastPathComponent()
panel.nameFieldStringValue = pathControl.url!.lastPathComponent
panel.prompt = NSLocalizedString("CHOOSE", comment: "Button that chooses the selected app in the open panel.")
// show the panel and define our callback
panel.beginSheetModal(for: view.window!) { (result: NSApplication.ModalResponse) in
// hopefully they clicked ok
if result == .OK {
// get the url that was selected and set it on the path control
let url = panel.urls[0]
pathControl.url = url
// call the callback
completion(url)
}
}
}
@IBAction func terminalBrowseClicked(_ sender: AnyObject) {
browseForApp(pathControl: terminalPathControl) { (url: URL) in
self.preferences.terminalAppURL = url
}
}
@IBAction func editorBrowseClicked(_ sender: AnyObject) {
browseForApp(pathControl: editorPathControl) { (url: URL) in
self.preferences.editorAppURL = url
}
}
@IBAction func terminalContextMenusChanged(_ sender: AnyObject) {
preferences.terminalShowInContextMenu = terminalContextMenusCheckbox.state == .on
}
@IBAction func editorContextMenusChanged(_ sender: AnyObject) {
preferences.editorShowInContextMenu = editorContextMenusCheckbox.state == .on
}
@IBAction func openSelectionChanged(_ sender: AnyObject) {
preferences.openSelection = openSelectionCheckbox.state == .on
}
@IBAction func openInChanged(_ sender: AnyObject) {
// set the preference according to the selected item’s tag
preferences.terminalActivationType = ActivationType(rawValue: UInt(terminalOpenInPopUpButton.selectedItem!.tag))!
}
}
| apache-2.0 | 4cd27098cbcb4194f288e0b0afd7dd84 | 30.016949 | 145 | 0.757377 | 4.089385 | false | false | false | false |
marksands/SwiftLensLuncheon | UserListValueTypes/User.swift | 1 | 448 | //
// Created by Christopher Trott on 1/14/16.
// Copyright © 2016 twocentstudios. All rights reserved.
//
import Foundation
struct User {
let name: String
let avatarURL: NSURL
}
/// User must conform to equatable in order for our Identifiable protocol in the ViewModel layer to function.
extension User: Equatable {}
func ==(lhs: User, rhs: User) -> Bool {
return lhs.name == rhs.name &&
lhs.avatarURL == rhs.avatarURL
}
| mit | 80c568cabd2c61edebd346b1b5cbfda8 | 23.833333 | 109 | 0.689038 | 3.853448 | false | false | false | false |
sempliva/Emotly-iOS | Emotly/EmotlyService.swift | 1 | 13785 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 Emotly Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
import Alamofire
import SwiftyJSON
import Pantry
/// An Emotly.
struct Emotly {
let created_at: NSDate?
let mood: String? // We store the mood as plain String because we
// don't need its id here.
let nickname: String?
}
/// A Mood.
struct Mood {
private let rawJSON: JSON
var value: String? { return rawJSON["value"].stringValue }
var id: UInt { return rawJSON["id"].uIntValue }
init(_ rawJSON: JSON) {
self.rawJSON = rawJSON
}
}
/// A list of Emotly.
typealias Emotlies = [Emotly] // TODO: Order on the fly?
/// A list of Mood.
typealias Moods = [Mood] // TODO: This should be ordered on the fly too.
/// A utility type.
struct EmotlyUtils {
static let EMOTLY_JWT = "EmotlyJWT"
static let EMOTLY_JWT_KEY = "EmotlyJWT_JSON_AsString"
static func convertDateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return dateFormatter.dateFromString(dateString)
}
}
/// The Emotly JWT.
struct EmotlyJWT: Storable {
private let rawJSON: JSON
init(_ rawJson: JSON) {
self.rawJSON = rawJson
}
init(warehouse: JSONWarehouse) {
let wareString = warehouse.get(EmotlyUtils.EMOTLY_JWT_KEY) ?? ""
self.rawJSON = JSON.parse(wareString)
}
func toDictionary() -> [String : AnyObject] {
return [EmotlyUtils.EMOTLY_JWT_KEY : rawJSON.rawString()!]
}
var signature: String {
return rawJSON["signature"].stringValue
}
var payload: [String: JSON] {
return rawJSON["payload"].dictionaryValue
}
var header: [String: JSON] {
return rawJSON["header"].dictionaryValue
}
var nickname: String {
guard let nickname = payload["nickname"] else { return "" }
return nickname.stringValue
}
var expirationDate: NSDate? {
guard let expire = payload["expire"] else { return nil }
return EmotlyUtils.convertDateFromString(expire.stringValue)
}
/// Raw, un-pretty, String representation of the JWT.
var uglyString: String {
return rawJSON.rawString(NSUTF8StringEncoding,
options: NSJSONWritingOptions(rawValue: 0)) ?? ""
}
func isOfType(type: Type) -> Bool {
guard let hdr = header["type"] else {
return false
}
let strType = hdr.stringValue
switch type {
case .JWT:
return strType == "jwt"
default:
return false
}
}
func isUsingAlgo(algo: AlgoType) -> Bool {
guard let hdr = header["algo"] else {
return false
}
let strAlgoType = hdr.stringValue
switch algo {
case .SHA256:
return strAlgoType == "sha256"
default:
return false
}
}
/// Returns whether this JWT is locally valid.
var isValid: Bool {
if !isUsingAlgo(.SHA256) { return false }
if !isOfType(.JWT) { return false }
if nickname.isEmpty { return false }
guard let expDate = expirationDate else { return false }
if NSDate().compare(expDate) != .OrderedAscending { return false }
return true
}
enum Type {
case JWT
case UNKNOWN
}
enum AlgoType {
case SHA256
case UNKNOWN
}
}
/**
A representation of the Emotly service; exposes all the methods available on
the backend.
*DO NOT INSTANTIATE THIS CLASS DIRECTLY*, use the `sharedService` property
instead.
*/
class EmotlyService {
private static let emotlyURL = "https://emotly.herokuapp.com/api/1.0"
private(set) var emotlies: Emotlies = []
private(set) var moods: Moods = []
static let sharedService = EmotlyService()
// The internal JWT. Consumers should use getJWT().
private var jwt: EmotlyJWT? {
didSet {
if let jwt = self.jwt {
// Persistence of JWT object into Pantry with expiration date.
let jwtExpDate = StorageExpiry.Date((jwt.expirationDate)!)
Pantry.pack(jwt, key: EmotlyUtils.EMOTLY_JWT, expires: jwtExpDate)
}
// Remove JWT from Pantry (execute logout).
else { Pantry.expire(EmotlyUtils.EMOTLY_JWT) }
}
}
private init() {} // EmotlyService is a singleton object: enforcing.
/**
Check if JWT is valid.
- Parameters:
- doneCallback: the handler to be called when the operation ends.
If the jwt is valid, the `Bool` parameter would be true, false otherwise.
*/
func is_jwt_valid(doneCallback: (Bool, NSError?) -> Void) {
let endpoint = EmotlyService.emotlyURL + "/is_jwt_valid"
let req = Alamofire.request(.POST, endpoint, encoding: .JSON,
headers: reqHeaders())
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(false, error)
return
}
doneCallback(true, nil)
}
// TODO: Deal with the non-valid requests here.
}
/**
Attempt to login with the given credentials.
- Parameters:
- username: user's username or email
- password: user's password
- doneCallback: the handler to be called when the operation ends.
If the user has succesfully authenticated, the `Bool` parameter would
be true, false otherwise.
*/
func login(username: String, password: String, doneCallback: (Bool, NSError?) -> Void) {
let credentials = [ "user_id" : username, "password" : password]
let endpoint = EmotlyService.emotlyURL + "/login"
let req = Alamofire.request(.POST, endpoint, parameters: credentials, encoding: .JSON)
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(false, error)
return
}
guard let dat = data else {
// TODO: Customize the error here.
doneCallback(false, error)
return
}
let json_response = JSON(data: dat)
let tempJWT = EmotlyJWT(json_response)
let isValid = tempJWT.isValid
if isValid { self.jwt = tempJWT }
doneCallback(isValid, nil)
}
// TODO: Deal with the non-valid requests here.
}
/**
Issues a request to post a new Emotly with the specified mood.
- Parameters:
- id: the id of the mood
- doneCallback: The handler to be called when the operation ends.
*/
func postEmotlyWithMood(id: UInt, doneCallback: (Emotly?, NSError?) -> Void) {
guard jwt != nil else {
doneCallback(nil, nil) // TODO: We need a custom error here.
return
}
let endpoint = EmotlyService.emotlyURL + "/emotlies/new"
let newEmotly = ["mood" : id]
let req = Alamofire.request(.POST, endpoint, encoding: .JSON,
headers: reqHeaders(),
parameters: newEmotly)
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(nil, error)
return
}
guard let dat = data else {
// TODO: Customize the error here.
doneCallback(nil, error)
return
}
// If everything has worked out, we create a new Emotly and we
// append it to our internal list.
let subjson = JSON(data: dat)
guard let newEmotly = self.createEmotlyFromJSON(subjson["emotly"]) else {
// TODO: We need to return an appropriate (proprietary) error
// because the request hasn't failed but the parsing of the
// Emotly has. Tip: subclass NSError and create EmotlyError.
doneCallback(nil, nil)
return
}
self.emotlies.append(newEmotly)
doneCallback(newEmotly, nil)
}
// TODO: Deal with the non-valid requests here.
}
/**
Issue a request to update (refresh) the emotlies.
- Parameters:
- doneCallback: The handler to be called when the operation ends.
*/
func updateEmotlies(doneCallback: (Emotlies?, NSError?) -> Void) {
let endpoint = EmotlyService.emotlyURL + "/emotlies"
let req = Alamofire.request(.GET, endpoint)
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(nil, error)
return
}
guard let dat = data else {
// TODO: Customize the error here.
doneCallback(nil, error)
return
}
let json_dat = JSON(data: dat)
for (_, subjson): (String, JSON) in json_dat["emotlies"] {
if let newEmotly = self.createEmotlyFromJSON(subjson) {
self.emotlies.append(newEmotly)
}
}
// TODO: Order the self.emotlies before calling doneCallback.
doneCallback(self.emotlies, nil)
}
}
/**
Refresh the internal list of moods; this operation is required before
being able to post a new Emotly.
- Parameters:
- doneCallback: The handler to be called when the operation ends.
*/
func updateMoods(doneCallback: (NSError?) -> Void) {
let endpoint = EmotlyService.emotlyURL + "/moods"
let req = Alamofire.request(.GET, endpoint)
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(error)
return
}
guard let dat = data else {
// TODO: Customize the error here.
return
}
let json_dat = JSON(data: dat)
for (_, subjson): (String, JSON) in json_dat["moods"] {
self.moods.append(Mood(subjson))
}
doneCallback(nil)
}
}
/**
Register a new user with the given credentials.
- Parameters:
- nickname: The nickname associated to the new account.
- email: The email address associated to the new account.
- password: The password associated to the new account (hear head!).
*/
func signupWith(nickname: String, email: String, password: String,
doneCallback: (Bool, NSError?) -> Void) {
let endpoint = EmotlyService.emotlyURL + "/signup"
// TODO: Validate and clean-up UI values here!
let newEmotly = ["inputNickname" : nickname, "inputEmail" : email,
"inputPassword" : password]
let req = Alamofire.request(.POST, endpoint, encoding: .JSON,
parameters: newEmotly)
req.validate().response { request, response, data, error in
guard error == nil else {
doneCallback(false, error)
return
}
// /signup API returns HTTP 200 if the account is OK. So we don't
// really need to do any other work here.
doneCallback(true, nil)
return
}
// TODO: /signup API returns errors as HTTP status codes, so we're
// gonna need to customize those and return them to the user.
doneCallback(false, nil)
}
/// Returns the current JWT, if available.
func getJWT() -> EmotlyJWT? {
if let jwt = self.jwt { return jwt }
if let jwt: EmotlyJWT = Pantry.unpack(EmotlyUtils.EMOTLY_JWT) {
self.jwt = jwt
}
return self.jwt
}
/// Used to get prepopulated HTTP headers (incl. the auth info).
private func reqHeaders() -> [String : String] {
return ["X-Emotly-Auth-Token" : getJWT()!.uglyString]
}
private func createEmotlyFromJSON(emotlyJson: JSON) -> Emotly? {
let mood = emotlyJson["mood"].stringValue
let nickname = emotlyJson["nickname"].stringValue
let str_created_at = emotlyJson["created_at"].stringValue
let created_at = EmotlyUtils.convertDateFromString(str_created_at)
return Emotly(created_at: created_at, mood: mood, nickname: nickname)
}
}
| mit | 04641741493fd1c105e9609ea488fc00 | 31.132867 | 94 | 0.589119 | 4.3281 | false | false | false | false |
zhangzhongfu/SwiftProject | TodayNewsSwift/TodayNewsSwift/Class/Home/View/BaseNewsTableViewCell.swift | 1 | 1666 | //
// BaseNewsTableViewCell.swift
// TodayNewsSwift
//
// Created by zzf on 2017/6/8.
// Copyright © 2017年 zzf. All rights reserved.
//
import UIKit
class BaseNewsTableViewCell: DFBaseTableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func createSubView() {
super.createSubView()
self.contentView.addSubview(self.nameLabel)
self.contentView.addSubview(self.iconImageView)
}
lazy var nameLabel: UILabel = {
let nameLabel = UILabel(frame: CGRect.zero)
nameLabel.font = UIFont.systemFont(ofSize: 14)
nameLabel.textColor = UIColor.red
nameLabel.text = "我是测试人员"
return nameLabel
}()
lazy var iconImageView: UIImageView = {
let iconImageView = UIImageView.init()
iconImageView.backgroundColor = UIColor.blue
iconImageView.layer.cornerRadius = 15.0
iconImageView.layer.masksToBounds = true
return iconImageView
}()
public func setModel(_ object: TestModel) {
// self.iconImageView.image = UIImage(named: "")
self.nameLabel.text = object.name
}
override func layoutSubviews() {
super.layoutSubviews()
self.iconImageView.frame = CGRect(x:10.0, y: 10.0, width: 30.0, height: 30.0)
self.nameLabel.frame = CGRect(x:45.0, y: 10.0, width: 80.0, height: 20.0)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 383a04dc4242ebae18c02fd1a1165541 | 26.516667 | 85 | 0.629316 | 4.414439 | false | false | false | false |
wpuricz/vapor-database-sample | Sources/App/Models/User.swift | 1 | 1483 | import Vapor
import Fluent
import Foundation
final class User: Model {
static let tableName = "users"
var id: Node?
var username: String
var email: String
init(node: Node, in context: Context) throws {
id = try node.extract("id")
username = try node.extract("username")
email = try node.extract("email")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"username": username,
"email": email,
])
}
// USING MAKE JSON TO OMIT A FIELD
public func makeJSON() throws -> JSON {
return JSON([
"id": self.id!.makeNode(),
"email": self.email.makeNode()
])
}
// public func makeJSON() throws -> JSON {
// return JSON([
// "id": self.id!.makeNode(),
// "name": self.name.makeNode(),
// "size": "mysize"
// ])
// }
}
extension User: Preparation {
static func prepare(_ database: Database) throws {
try database.create(User.tableName) { user in
user.id()
user.string("username")
user.string("email")
}
}
static func revert(_ database: Database) throws {
try database.delete(User.tableName)
}
}
extension User {
func roles() throws -> [Role] {
let roles : Siblings<Role> = try siblings()
return try roles.all()
}
}
| mit | 59568ee8808725aff298eb8bec65bc76 | 22.539683 | 54 | 0.526635 | 4.130919 | false | false | false | false |
mikelikespie/swiftled | src/main/swift/OPC/Net.swift | 1 | 7464 | //
// Net.swift
// SwiftledMobile
//
// Created by Michael Lewis on 12/29/15.
// Copyright © 2015 Lolrus Industries. All rights reserved.
//
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import RxSwift
import Dispatch
import Foundation
private var hints: addrinfo = {
var hints = addrinfo()
hints.ai_family = PF_UNSPEC
#if os(Linux)
hints.ai_socktype = Int32(SOCK_STREAM.rawValue)
#else
hints.ai_socktype = SOCK_STREAM
#endif
return hints
}()
// Wrapped addrinfo
public struct AddrInfo {
let family: Int32
#if os(Linux)
let socktype: __socket_type
#else
let socktype: Int32
#endif
let proto: Int32
let addr: SockAddr
}
extension AddrInfo {
public func connect(_ workQueue: DispatchQueue=DispatchQueue.global()) -> Observable<Int32> {
return Observable.create { observer in
do {
let socket = try self.socket()
precondition(socket >= 0)
let writeSource = DispatchSource.makeWriteSource(fileDescriptor: socket, queue: workQueue);
let closeItem = DispatchWorkItem {
#if os(Linux)
Glibc.close(socket)
#else
NSLog("CLOSING")
Darwin.close(socket)
#endif
}
func completeConnection() {
// If we got this far, we are successful!
// Clear out the close handler, thsi means somebody else will own the socket after this
NSLog("COMPLETING CONNECTION")
writeSource.suspend()
closeItem.cancel()
writeSource.resume()
observer.onNext(socket)
observer.onCompleted()
}
writeSource.setCancelHandler(handler: closeItem)
writeSource.setEventHandler {
do {
NSLog("Event trying to connect")
try self.tryConnectContinue(socket)
completeConnection()
} catch POSIXErrorCode.EINPROGRESS {
NSLog("EINPROGRESS")
// If we're in progress, we'll be trying again
} catch let e {
observer.onError(e)
}
}
writeSource.resume();
NSLog("STARTING")
do {
NSLog("First trying to connect")
try self.tryConnect(socket)
completeConnection()
} catch POSIXErrorCode.EINPROGRESS {
NSLog("IN PROGRESS!!!")
// If we're in progress, we'll be trying again
}
return Disposables.create {
NSLog("Disposing!!!")
writeSource.cancel()
}
} catch let e {
NSLog("erroring :/")
observer.onError(e)
return Disposables.create()
}
}
}
/// If this doesn't throw, we've connected
private func tryConnect(_ socket: Int32) throws {
NSLog("trying to connect")
let result = self.addr.withUnsafeSockaddrPtr { ptr -> Int32 in
#if os(Linux)
return Glibc.connect(socket, ptr, socklen_t(type(of: self.addr).size))
#else
return Darwin.connect(socket, ptr, socklen_t(type(of: self.addr).size))
#endif
}
if result != 0 {
throw POSIXErrorCode(rawValue: errno)!
}
}
/// If this doesn't throw, we've connected
private func tryConnectContinue(_ socket: Int32) throws {
NSLog("trying to connect")
var result: Int = 0
var len = socklen_t(MemoryLayout.size(ofValue: result))
let status = getsockopt(socket, SOL_SOCKET, SO_ERROR, &result, &len)
precondition(status == 0, "getsockopt should return zero")
if result != 0 {
throw POSIXErrorCode(rawValue: errno)!
}
}
/// Calls socket on this and returns a socket
public func socket() throws -> Int32 {
#if os(Linux)
let fd = Glibc.socket(self.family, Int32(self.socktype.rawValue), self.proto)
#else
let fd = Darwin.socket(self.family, self.socktype, self.proto)
#endif
let result = fcntl(fd, F_SETFL, O_NONBLOCK);
if result < 0 {
throw Error.errorFromStatusCode(fd)!
}
var flag: Int = 1
setsockopt(fd, Int32(IPPROTO_TCP), TCP_NODELAY, &flag, socklen_t(MemoryLayout.size(ofValue: flag)))
return fd
}
}
public func getaddrinfoSockAddrsAsync(_ hostname: String, servname: String, workQueue: DispatchQueue=DispatchQueue.global()) -> Observable<AddrInfo> {
return Observable.create { observer in
var ai: UnsafeMutablePointer<addrinfo>? = nil
workQueue.async {
do {
defer {
if ai != nil {
freeaddrinfo(ai)
}
}
try Error.throwIfNotSuccess(getaddrinfo(hostname, servname, &hints, &ai))
var curAi = ai
while curAi != nil {
if curAi?.pointee.ai_addr == nil {
curAi = curAi?.pointee.ai_next
continue
}
guard let aiMem = curAi?.pointee else {
continue
}
#if os(Linux)
let socktype = __socket_type(UInt32(aiMem.ai_socktype))
#else
let socktype = aiMem.ai_socktype
#endif
switch aiMem.ai_addr.pointee.sa_family {
case sa_family_t(AF_INET):
let addr = unsafeBitCast(curAi?.pointee.ai_addr, to: UnsafePointer<sockaddr_in>.self).pointee
observer.onNext(AddrInfo(family: aiMem.ai_family, socktype: socktype, proto: aiMem.ai_protocol, addr: addr))
case sa_family_t(AF_INET6):
let addr = unsafeBitCast(curAi?.pointee.ai_addr, to: UnsafePointer<sockaddr_in6>.self).pointee
observer.onNext(AddrInfo(family: aiMem.ai_family, socktype: socktype, proto: aiMem.ai_protocol, addr: addr))
default:
NSLog("skiping")
continue
}
curAi = curAi?.pointee.ai_next
}
NSLog("completing")
observer.onCompleted()
} catch let e {
NSLog("erroring")
observer.onError(e)
}
}
return Disposables.create()
}
}
| mit | a00e5f7880446999fe61288d695665a0 | 31.030043 | 151 | 0.474474 | 5.143349 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/TXTReader/Reader/ZSSpeakerViewController.swift | 1 | 3165 | //
// ZSSpeakerViewController.swift
// zhuishushenqi
//
// Created by caony on 2018/10/11.
// Copyright © 2018 QS. All rights reserved.
//
import UIKit
import Zip
import Kingfisher
class ZSSpeakerViewController: UIViewController {
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .singleLine
tableView.qs_registerCellClass(QSMoreSettingCell.self)
tableView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.qs_registerCellClass(ZSSpeakerCell.self)
self.view.addSubview(self.tableView)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.frame = self.view.bounds
}
}
extension ZSSpeakerViewController:UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TTSConfig.share.allSpeakers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.qs_dequeueReusableCell(ZSSpeakerCell.self)
cell?.accessoryType = .disclosureIndicator
let speaker = TTSConfig.share.allSpeakers[indexPath.row]
let url = URL(string: speaker.largeIcon) ?? URL(string:"https://www.baidu.com")!
let resource:QSResource = QSResource(url: url)
cell?.imageView?.kf.setImage(with: resource)
cell?.textLabel?.text = speaker.nickname
cell?.detailTextLabel?.text = speaker.accent
let fileName = "\(speaker.name).jet"
let jet = "\(filePath)\(fileName)"
let exist = FileManager.default.fileExists(atPath: jet)
cell?.download.isSelected = exist
cell?.downloadHandler = { _ in
downloadFile(urlString: speaker.downloadUrl, handler: { (response) in
if let url = response as? URL {
self.unzip(fileURL: url)
self.tableView.reloadData()
}
})
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 70
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
func unzip(fileURL:URL) {
do {
let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0].appendingPathComponent("/speakerres/3589709422/", isDirectory: true)
try Zip.unzipFile(fileURL, destination: documentsDirectory, overwrite: true, password: nil, progress: { (progress) -> () in
print(progress)
}) // Unzip
}
catch {
print("Something went wrong")
}
}
}
| mit | 177137053adf18ce5b35b23b88683008 | 34.954545 | 178 | 0.639381 | 4.612245 | false | false | false | false |
ello/ello-ios | Sources/Utilities/FreeMethods.swift | 1 | 9055 | ////
/// FreeMethods.swift
//
var messages: [(String, String)] = []
func log(comment: String, object: Any?) {
if let object = object {
messages.append((comment, "\(object)"))
}
else {
messages.append((comment, "nil"))
}
}
func getlog() -> [(String, String)] {
let m = messages
messages.removeAll()
return m
}
typealias Block = () -> Void
typealias ErrorBlock = (Error) -> Void
typealias BoolBlock = (Bool) -> Void
typealias AfterBlock = () -> Block
typealias ThrottledBlock = (@escaping Block) -> Void
typealias TakesIndexBlock = (Int) -> Void
typealias OnHeightMismatch = (CGFloat) -> Void
// MARK: Animations
struct AnimationOptions {
let duration: TimeInterval
let delay: TimeInterval
let options: UIView.AnimationOptions
}
class AnimationPromise {
var completionBlock: BoolBlock?
var alwaysBlock: Block?
var resolved: Bool?
func completion(_ block: @escaping BoolBlock) {
if let resolved = resolved {
block(resolved)
return
}
completionBlock = block
}
func done(_ block: @escaping Block) {
if resolved != nil {
block()
return
}
alwaysBlock = block
}
func resolve(completed: Bool) {
resolved = completed
completionBlock?(completed)
alwaysBlock?()
}
}
let DefaultAnimationDuration: TimeInterval = 0.2
let DefaultAppleAnimationDuration: TimeInterval = 0.3
@discardableResult
func animate(
duration: TimeInterval = DefaultAnimationDuration,
delay: TimeInterval = 0,
options: UIView.AnimationOptions = UIView.AnimationOptions(),
animated: Bool? = nil,
animations: @escaping Block
) -> AnimationPromise {
return elloAnimate(
duration: duration,
delay: delay,
options: options,
animated: animated,
animations: animations
)
}
@discardableResult
func animateWithKeyboard(
animated: Bool? = nil,
animations: @escaping Block
) -> AnimationPromise {
return elloAnimate(
duration: Keyboard.shared.duration,
options: Keyboard.shared.options,
animated: animated,
animations: animations
)
}
@discardableResult
func elloAnimate(
duration: TimeInterval = DefaultAnimationDuration,
delay: TimeInterval = 0,
options: UIView.AnimationOptions = UIView.AnimationOptions(),
animated: Bool? = nil,
animations: @escaping Block
) -> AnimationPromise {
let shouldAnimate: Bool = animated ?? !Globals.isTesting
let options = AnimationOptions(duration: duration, delay: delay, options: options)
return performAnimation(options: options, animated: shouldAnimate, animations: animations)
}
@discardableResult
private func performAnimation(
options: AnimationOptions,
animated: Bool = true,
animations: @escaping Block
) -> AnimationPromise {
let promise = AnimationPromise()
if animated {
UIView.animate(
withDuration: options.duration,
delay: options.delay,
options: options.options,
animations: animations,
completion: promise.resolve
)
}
else {
animations()
promise.resolve(completed: true)
}
return promise
}
class Proc {
private var block: Block
init(_ block: @escaping Block) {
self.block = block
}
@objc
func run() {
block()
}
}
func times(_ times: Int, block: Block) {
times_(times) { (_: Int) in block() }
}
func profiler(_ message: String = "") -> Block {
let start = Globals.now
print("--------- PROFILING \(message)...")
return {
print("--------- PROFILING \(message): \(Globals.now.timeIntervalSince(start))")
}
}
func profiler(_ message: String = "", block: Block) {
let p = profiler(message)
block()
p()
}
func times(_ times: Int, block: TakesIndexBlock) {
times_(times, block: block)
}
private func times_(_ times: Int, block: TakesIndexBlock) {
if times <= 0 {
return
}
for i in 0..<times {
block(i)
}
}
// this is similar to after(x), but instead of passing in an int, two closures
// are returned. The first (often called 'afterAll') should be *called*
// everywhere a callback is expected. The second (often called 'done') should
// be called once, after all the callbacks have been registered. e.g.
//
// func networkCalls(completion: Block) {
// let (afterAll, done) = afterN { completion() }
// backgroundProcess1(completion: afterAll())
// backgroundProcess2(completion: afterAll())
// done() // this doesn't execute the callback, just says "i'm done registering callbacks"
// }
//
// without this 'done' trick, there is a bug where if the first process is synchronous, the 'count'
// is incremented (by calling 'afterAll') and then immediately decremented.
func afterN(on queue: DispatchQueue? = nil, execute block: @escaping Block) -> (AfterBlock, Block) {
var count = 0
var called = false
let decrementCount: Block = {
count -= 1
if count == 0 && !called {
if Globals.isTesting, queue == DispatchQueue.main {
block()
}
else if queue == DispatchQueue.main, Thread.isMainThread {
block()
}
else if let queue = queue {
queue.async(execute: block)
}
else {
block()
}
called = true
}
}
let incrementCount: () -> Block = {
count += 1
return decrementCount
}
return (incrementCount, incrementCount())
}
func after(_ times: Int, block: @escaping Block) -> Block {
if times == 0 {
block()
return {}
}
var remaining = times
return {
remaining -= 1
if remaining == 0 {
block()
}
}
}
func until(_ times: Int, block: @escaping Block) -> Block {
if times == 0 {
return {}
}
var remaining = times
return {
remaining -= 1
if remaining >= 0 {
block()
}
}
}
func once(_ block: @escaping Block) -> Block {
return until(1, block: block)
}
func inBackground(_ block: @escaping Block) {
if Globals.isTesting {
block()
}
else {
DispatchQueue.global(qos: .default).async(execute: block)
}
}
func inForeground(_ block: @escaping Block) {
nextTick(block)
}
func nextTick(_ block: @escaping Block) {
if Globals.isTesting {
if Thread.isMainThread {
block()
}
else {
DispatchQueue.main.sync(execute: block)
}
}
else {
nextTick(DispatchQueue.main, block: block)
}
}
func nextTick(_ on: DispatchQueue, block: @escaping Block) {
on.async(execute: block)
}
func timeout(_ duration: TimeInterval, block: @escaping Block) -> Block {
let handler = once(block)
_ = delay(duration) {
handler()
}
return handler
}
func delay(_ duration: TimeInterval, background: Bool = false, block: @escaping Block) {
let killTimeOffset = Int64(CDouble(duration) * CDouble(NSEC_PER_SEC))
let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC)
let queue: DispatchQueue = background ? .global(qos: .background) : .main
queue.asyncAfter(deadline: killTime, execute: block)
}
func cancelableDelay(_ duration: TimeInterval, block: @escaping Block) -> Block {
let killTimeOffset = Int64(CDouble(duration) * CDouble(NSEC_PER_SEC))
let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC)
var cancelled = false
DispatchQueue.main.asyncAfter(deadline: killTime) {
if !cancelled { block() }
}
return { cancelled = true }
}
func debounce(_ timeout: TimeInterval, block: @escaping Block) -> Block {
var timer: Timer?
let proc = Proc(block)
return {
if let prevTimer = timer {
prevTimer.invalidate()
}
timer = Timer.scheduledTimer(
timeInterval: timeout,
target: proc,
selector: #selector(Proc.run),
userInfo: nil,
repeats: false
)
}
}
func debounce(_ timeout: TimeInterval) -> ThrottledBlock {
var timer: Timer?
return { block in
if let prevTimer = timer {
prevTimer.invalidate()
}
let proc = Proc(block)
timer = Timer.scheduledTimer(
timeInterval: timeout,
target: proc,
selector: #selector(Proc.run),
userInfo: nil,
repeats: false
)
}
}
@discardableResult
func every(_ timeout: TimeInterval, _ block: @escaping Block) -> Block {
let proc = Proc(block)
let timer = Timer.scheduledTimer(
timeInterval: timeout,
target: proc,
selector: #selector(Proc.run),
userInfo: nil,
repeats: true
)
return {
timer.invalidate()
}
}
| mit | eb531bf0cf3b4beb6a18dc70a9bc8947 | 24.083102 | 100 | 0.602761 | 4.279301 | false | false | false | false |
ftiff/CasperSplash | SplashBuddy/Tools/Preferences.swift | 1 | 14592 | //
// Copyright © 2018 Amaris Technologies GmbH. All rights reserved.
//
import Cocoa
/**
Preferences() keeps the relevant preferences
*/
class Preferences {
static let sharedInstance = Preferences()
internal var logFileHandle: FileHandle?
public var doneParsingPlist: Bool = false
internal let userDefaults: UserDefaults
//-----------------------------------------------------------------------------------
// MARK: - INIT
//-----------------------------------------------------------------------------------
private init(nsUserDefaults: UserDefaults = UserDefaults.standard) {
self.userDefaults = nsUserDefaults
// Do not change asset path (see comment on var assetPath: URL below)
// TSTAssetPath is meant for unit testing only.
if let assetPath = self.userDefaults.string(forKey: "TSTAssetPath") {
self.assetPath = URL(fileURLWithPath: assetPath, isDirectory: true)
} else {
self.assetPath = URL(fileURLWithPath: "/Library/Application Support/SplashBuddy", isDirectory: true)
}
// TSTJamfLog is meant for unit testing only.
if let jamfLogPath: String = self.userDefaults.string(forKey: "TSTJamfLog") {
self.logFileHandle = self.getFileHandle(from: jamfLogPath)
} else {
self.logFileHandle = self.getFileHandle()
}
// Start parsing the log file
guard let logFileHandle = self.logFileHandle else {
Log.write(string: "Cannot check logFileHandle", cat: "Preferences", level: .error)
return
}
logFileHandle.readabilityHandler = { fileHandle in
let data = fileHandle.readDataToEndOfFile()
guard let string = String(data: data, encoding: .utf8) else {
return
}
for line in string.split(separator: "\n") {
if let software = Software(from: String(line)) {
DispatchQueue.main.async {
SoftwareArray.sharedInstance.array.modify(with: software)
}
}
}
}
}
internal func getFileHandle(from file: String = "/var/log/jamf.log") -> FileHandle? {
do {
return try FileHandle(forReadingFrom: URL(fileURLWithPath: file, isDirectory: false))
} catch {
Log.write(string: "Cannot read \(file)",
cat: "Preferences",
level: .error)
return nil
}
}
//-----------------------------------------------------------------------------------
// MARK: - Asset Path
//-----------------------------------------------------------------------------------
/**
* Returns the path to all the assets used by SplashBuddy
*
* - important: If you decide to change the asset path, make sure you update the entitlements,
* or the WKWebView will display white.
*/
var assetPath: URL
//-----------------------------------------------------------------------------------
// MARK: - Continue Button
//-----------------------------------------------------------------------------------
/**
* Action when the user clicks on the continue button
*
* It can either be:
* - Restart
* - Logout
* - Shutdown
* - Quit
* - Hidden
* - a path to an application (eg. `/Applications/Safari.app`)
*/
public var continueAction: ContinueButton.Action {
let action: String = self.userDefaults.string(forKey: "continueAction") ?? "quit"
return ContinueButton.Action.from(string: action)
}
//-----------------------------------------------------------------------------------
// MARK: - Options
//-----------------------------------------------------------------------------------
/// set to `true` to hide sidebar
public var sidebar: Bool {
return self.userDefaults.bool(forKey: "hideSidebar")
}
/// set to `true` to hide background behind main window (for debugging)
public var background: Bool {
return !self.userDefaults.bool(forKey: "hideBackground")
}
/// set to `true` to enable Big Notification
public var labMode: Bool {
return self.userDefaults.bool(forKey: "labMode")
}
//-----------------------------------------------------------------------------------
// MARK: - HTML Path
//-----------------------------------------------------------------------------------
/**
* Returns the path to the HTML bundle
*
* - important: If you decide to change the asset path, make sure you update the entitlements,
* or the WKWebView will display white.
*/
public var assetBundle: Bundle? {
return Bundle.init(url: self.assetPath.appendingPathComponent("presentation.bundle"))
}
/// Returns `index.html` with the right localization
public var html: URL? {
return self.assetBundle?.url(forResource: "index", withExtension: "html")
}
/// Returns `complete.html` with the right localization
public var labComplete: URL? {
return self.assetBundle?.url(forResource: "complete", withExtension: "html")
}
public var form: URL? {
guard let bundle = assetBundle else {
return nil
}
return bundle.url(forResource: "form", withExtension: "html")
}
//-----------------------------------------------------------------------------------
// MARK: - Tag files
//-----------------------------------------------------------------------------------
/// All softwares are installed
var setupDone: Bool {
get {
return FileManager.default.fileExists(atPath: "Library/.SplashBuddyDone")
}
set(myValue) {
if myValue == true {
FileManager.default.createFile(atPath: "Library/.SplashBuddyDone", contents: nil, attributes: nil)
} else {
do {
try FileManager.default.removeItem(atPath: "Library/.SplashBuddyDone")
} catch {
Log.write(string: "Couldn't remove .SplashBuddyDone",
cat: "Preferences",
level: .info)
}
}
}
}
var formDone: Bool {
get {
return FileManager.default.fileExists(atPath: "Library/.SplashBuddyFormDone")
}
set(myValue) {
if myValue == true {
FileManager.default.createFile(atPath: "Library/.SplashBuddyFormDone", contents: nil, attributes: nil)
} else {
do {
try FileManager.default.removeItem(atPath: "Library/.SplashBuddyFormDone")
} catch {
Log.write(string: "Couldn't remove .SplashBuddyFormDone", cat: "Preferences", level: .info)
}
}
}
}
private enum TagFile: String {
case criticalDone = "CriticalDone"
case errorWhileInstalling = "ErrorWhileInstalling"
case allInstalled = "AllInstalled"
case allSuccessfullyInstalled = "AllSuccessfullyInstalled"
}
private func createSplashBuddyTmpIfNeeded() {
var YES: ObjCBool = true
if !FileManager.default.fileExists(atPath: "/private/tmp/SplashBuddy/", isDirectory: &YES) {
do {
try FileManager.default.createDirectory(atPath: "/private/tmp/SplashBuddy",
withIntermediateDirectories: false,
attributes: [
.groupOwnerAccountID: 20,
.posixPermissions: 0o777
])
} catch {
Log.write(string: "Cannot create /private/tmp/SplashBuddy/",
cat: "Preferences",
level: .error)
fatalError("Cannot create /private/tmp/SplashBuddy/")
}
}
}
private func checkTagFile(named: TagFile) -> Bool {
return FileManager.default.fileExists(atPath: "/private/tmp/SplashBuddy/.".appending(named.rawValue))
}
private func createOrDeleteTagFile(named: TagFile, create: Bool) {
createSplashBuddyTmpIfNeeded()
if create == true {
if FileManager.default.createFile(atPath: "/private/tmp/SplashBuddy/.".appending(named.rawValue),
contents: nil,
attributes: [
.groupOwnerAccountID: 20,
.posixPermissions: 0o777
]) {
Log.write(string: "Created .".appending(named.rawValue),
cat: "Preferences",
level: .info)
} else {
Log.write(string: "Couldn't create .".appending(named.rawValue), cat: "Preferences", level: .error)
do {
try FileManager.default.removeItem(atPath: "Library/.SplashBuddyFormDone")
} catch {
}
}
} else {
do {
try FileManager.default.removeItem(atPath: "/private/tmp/SplashBuddy/.".appending(named.rawValue))
} catch {
Log.write(string: "Couldn't remove .".appending(named.rawValue), cat: "Preferences", level: .info)
}
}
}
/// All critical softwares are installed
var criticalDone: Bool {
get {
return checkTagFile(named: .criticalDone)
}
set(myValue) {
createOrDeleteTagFile(named: .criticalDone, create: myValue)
}
}
/// Errors while installing
var errorWhileInstalling: Bool {
get {
return checkTagFile(named: .errorWhileInstalling)
}
set(myValue) {
createOrDeleteTagFile(named: .errorWhileInstalling, create: myValue)
}
}
/// all software is installed (failed or success)
var allInstalled: Bool {
get {
return checkTagFile(named: .allInstalled)
}
set(myValue) {
createOrDeleteTagFile(named: .allInstalled, create: myValue)
}
}
/// all software is sucessfully installed
var allSuccessfullyInstalled: Bool {
get {
return checkTagFile(named: .allSuccessfullyInstalled)
}
set(myValue) {
createOrDeleteTagFile(named: .allSuccessfullyInstalled, create: myValue)
}
}
//-----------------------------------------------------------------------------------
// MARK: - Software
//-----------------------------------------------------------------------------------
func extractSoftware(from dict: NSDictionary) -> Software? {
guard let name = dict["packageName"] as? String else {
Log.write(string: "Error reading name from an application in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let displayName: String = dict["displayName"] as? String else {
Log.write(string: "Error reading displayName from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let description: String = dict["description"] as? String else {
Log.write(string: "Error reading description from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let iconRelativePath: String = dict["iconRelativePath"] as? String else {
Log.write(string: "Error reading iconRelativePath from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
guard let canContinueBool: Bool = getBool(from: dict["canContinue"]) else {
Log.write(string: "Error reading canContinueBool from application \(name) in io.fti.SplashBuddy",
cat: "Preferences",
level: .error)
return nil
}
let iconPath = self.assetPath.appendingPathComponent(iconRelativePath).path
return Software(packageName: name,
version: nil,
status: .pending,
iconPath: iconPath,
displayName: displayName,
description: description,
canContinue: canContinueBool,
displayToUser: true)
}
/**
Try to get a Bool from an Any (String, Int or Bool)
- returns:
- True if 1, "1" or True
- False if any other value
- nil if cannot cast to String, Int or Bool.
- parameter object: Any? (String, Int or Bool)
*/
func getBool(from object: Any?) -> Bool? {
// In practice, canContinue is sometimes seen as int, sometimes as String
// This workaround helps to be more flexible
if let canContinue = object as? Int {
return (canContinue == 1)
} else if let canContinue = object as? String {
return (canContinue == "1")
} else if let canContinue = object as? Bool {
return canContinue
}
return nil
}
enum Errors: Error {
case noApplicationArray
case malformedApplication
}
/// Generates Software objects from Preferences
func getPreferencesApplications() throws {
guard let applicationsArray = self.userDefaults.array(forKey: "applicationsArray") else {
throw Preferences.Errors.noApplicationArray
}
for application in applicationsArray {
guard let application = application as? NSDictionary else {
throw Preferences.Errors.malformedApplication
}
if let software = extractSoftware(from: application) {
SoftwareArray.sharedInstance.array.append(software)
}
}
self.doneParsingPlist = true
Log.write(string: "DONE Parsing applicationsArray", cat: "Preferences", level: .debug)
}
}
| gpl-3.0 | e81fa99e05a64195c5f48e5d8d5564c2 | 34.938424 | 118 | 0.511891 | 5.388109 | false | false | false | false |
erdemtu/Tablecloth | Pod/Classes/TableViewSectionModel.swift | 1 | 739 | //
// TableViewSectionModel.swift
// TableCloth
//
// Created by Erdem Turanciftci on 23/10/15.
// Copyright © 2015 Erdem Turanciftci. All rights reserved.
//
import Foundation
final public class TableViewSectionModel {
var cellModels: Array<TableViewCellModel>
public var headerModel: TableViewAccessoryModel?
public var footerModel: TableViewAccessoryModel?
public init() {
cellModels = Array<TableViewCellModel>()
}
public init(cellModels: Array<TableViewCellModel>, headerModel: TableViewAccessoryModel? = nil, footerModel: TableViewAccessoryModel? = nil) {
self.cellModels = cellModels
self.headerModel = headerModel
self.footerModel = footerModel
}
}
| mit | d217bb6eb0163b833942dee7fd2b2400 | 27.384615 | 146 | 0.712737 | 4.445783 | false | false | false | false |
Syject/MyLessPass-iOS | LessPass/Presentation/ViewControllers/LessPass/LessPassViewController.swift | 1 | 8779 | //
// LessPassViewController.swift
// LessPass UI
//
// Created by Daniel Slupskiy on 14.01.17.
// Copyright © 2017 Daniel Slupskiy. All rights reserved.
//
import UIKit
import BEMCheckBox
import SCLAlertView
import Alamofire
import SwiftyJSON
class LessPassViewController: UIViewController, BEMCheckBoxDelegate {
@IBOutlet fileprivate weak var siteTextField: UITextField!
@IBOutlet fileprivate weak var loginTextField: UITextField!
@IBOutlet fileprivate weak var masterPasswordTextField: UITextField!
@IBOutlet fileprivate weak var lowerCheckBox: BEMCheckBox!
@IBOutlet fileprivate weak var upperCheckBox: BEMCheckBox!
@IBOutlet fileprivate weak var numbersCheckBox: BEMCheckBox!
@IBOutlet fileprivate weak var symbolsCheckBox: BEMCheckBox!
@IBOutlet fileprivate weak var lengthTextField: UITextField!
@IBOutlet fileprivate weak var counterTextField: UITextField!
fileprivate var waitAlertResponder:SCLAlertViewResponder?
static fileprivate var isFirstTimeLauched:Bool = true
var choosedSavedOption: SavedOption?
var delegate: LessPassViewControllerDelegate?
internal override func viewDidLoad() {
super.viewDidLoad()
if LessPassViewController.isFirstTimeLauched {
switchToMaster()
LessPassViewController.isFirstTimeLauched = false
delegate?.tryToAutologin()
}
doUIPreparations()
setDefaultValues()
}
fileprivate func setDefaultValues() {
siteTextField.text = choosedSavedOption?.site
?? UserDefaults.standard.string(forKey: "siteTextField")
loginTextField.text = choosedSavedOption?.login
?? UserDefaults.standard.string(forKey: "loginTextField")
lowerCheckBox.on = choosedSavedOption?.hasLowerCaseLetters
?? !UserDefaults.standard.bool(forKey: "lowerCheckBox")
upperCheckBox.on = choosedSavedOption?.hasUpperCaseLetters
?? !UserDefaults.standard.bool(forKey: "upperCheckBox")
numbersCheckBox.on = choosedSavedOption?.hasNumbers
?? !UserDefaults.standard.bool(forKey: "numbersCheckBox")
symbolsCheckBox.on = choosedSavedOption?.hasSymbols
?? !UserDefaults.standard.bool(forKey: "symbolsCheckBox")
if let length = choosedSavedOption?.length {
lengthTextField.text = "\(length)"
} else {
lengthTextField.text = UserDefaults.standard.string(forKey: "lengthTextField")
?? "16"
}
if let counter = choosedSavedOption?.counter {
counterTextField.text = "\(counter)"
} else {
counterTextField.text = UserDefaults.standard.string(forKey: "counterTextField")
?? "1"
}
}
fileprivate func switchToMaster() {
if let splitViewController = splitViewController {
if splitViewController.isCollapsed {
let detailNavigationController = parent as! UINavigationController
let masterNavigationController = detailNavigationController.parent as! UINavigationController
masterNavigationController.popToRootViewController(animated: false)
delegate = masterNavigationController.viewControllers[0] as! SavedSitesViewController
} else {
delegate = (splitViewController.viewControllers[0] as! UINavigationController).viewControllers[0] as! SavedSitesViewController
}
}
}
@IBAction fileprivate func generateDidPressed(_ sender: Any) {
self.view.endEditing(true)
guard !masterPasswordTextField.text!.isEmpty else { showFieldMissedAlert(for: "master password"); return }
if !checkFields() {
return
}
let site = siteTextField.text!
let login = loginTextField.text!
let masterPassword = masterPasswordTextField.text!
let length = Int(lengthTextField.text!)!
let counter = Int(counterTextField.text!)!
let template = Template()
template.hasLowerCaseLetters = lowerCheckBox.on
template.hasUpperCaseLetters = upperCheckBox.on
template.hasNumbers = numbersCheckBox.on
template.hasSymbols = symbolsCheckBox.on
template.length = length
template.counter = counter
let data = LesspassData(withSite: site, login: login, andMasterPassword: masterPassword)
let appearance = SCLAlertView.SCLAppearance(
showCloseButton: false,
showCircularIcon: true
)
waitAlertResponder = SCLAlertView(appearance: appearance).showWait("Please wait...", subTitle: "Some magic is happening...", colorStyle: 0x1477D4)
print("waitAlert showed!")
DispatchQueue.global(qos: .userInteractive).async {
let passwordValue = Password.calculateValue(withLesspassData: data, andTemplate: template)
DispatchQueue.main.async {
self.waitAlertResponder?.close()
let successAlert = SCLAlertView()
successAlert.addButton("Copy", action: {
UIPasteboard.general.string = passwordValue
})
successAlert.showSuccess("Here you are",
subTitle: "Your password is \n\(passwordValue)\nThis alert will be closed after 30 seconds", duration: 30)
}
}
}
@IBAction fileprivate func asDefaultDidPressed(_ sender: Any) {
UserDefaults.standard.set(siteTextField.text, forKey: "siteTextField")
UserDefaults.standard.set(loginTextField.text, forKey: "loginTextField")
UserDefaults.standard.set(!lowerCheckBox.on, forKey: "lowerCheckBox")
UserDefaults.standard.set(!upperCheckBox.on, forKey: "upperCheckBox")
UserDefaults.standard.set(!numbersCheckBox.on, forKey: "numbersCheckBox")
UserDefaults.standard.set(!symbolsCheckBox.on, forKey: "symbolsCheckBox")
UserDefaults.standard.set(lengthTextField.text, forKey: "lengthTextField")
UserDefaults.standard.set(counterTextField.text, forKey: "counterTextField")
}
@IBAction fileprivate func saveDidPressed(_ sender: Any) {
guard API.isUserAuthorized else { SCLAlertView().showError("Error", subTitle: "You need to log in"); return }
guard checkFields() else { return }
let options = SavedOption()
options.site = siteTextField.text!
options.login = loginTextField.text!
options.length = Int(lengthTextField.text!)!
options.counter = Int(counterTextField.text!)!
options.hasLowerCaseLetters = lowerCheckBox.on
options.hasUpperCaseLetters = upperCheckBox.on
options.hasNumbers = numbersCheckBox.on
options.hasSymbols = symbolsCheckBox.on
options.id = choosedSavedOption?.id
API.saveOptions(options, onSuccess: { [unowned self] in
self.delegate?.getSitesList()
}, onFailure: {error in
DispatchQueue.main.async {
SCLAlertView().showError("Error", subTitle: error)
}
})
}
@IBAction fileprivate func lengthValueChanged(_ sender: UIStepper) {
lengthTextField.text = String(Int(sender.value))
}
@IBAction fileprivate func counterValueChanged(_ sender: UIStepper) {
counterTextField.text = String(Int(sender.value))
}
// MARK: BEMCheckBoxDelegate
internal func didTap(_ checkBox: BEMCheckBox) {
if !lowerCheckBox.on &&
!upperCheckBox.on &&
!numbersCheckBox.on &&
!symbolsCheckBox.on {
lowerCheckBox.on = true
upperCheckBox.on = true
numbersCheckBox.on = true
symbolsCheckBox.on = true
}
}
// MARK: UI Setup
fileprivate func doUIPreparations() {
// Checkboxes
lowerCheckBox.delegate = self
UIPreparation.configurateStyleOf(checkBox: lowerCheckBox)
upperCheckBox.delegate = self
UIPreparation.configurateStyleOf(checkBox: upperCheckBox)
numbersCheckBox.delegate = self
UIPreparation.configurateStyleOf(checkBox: numbersCheckBox)
symbolsCheckBox.delegate = self
UIPreparation.configurateStyleOf(checkBox: symbolsCheckBox)
}
fileprivate func checkFields() -> Bool {
guard !siteTextField.text!.isEmpty else { showFieldMissedAlert(for: "site"); return false }
guard !loginTextField.text!.isEmpty else { showFieldMissedAlert(for: "login"); return false }
return true
}
}
| gpl-3.0 | eb2d4ca187aedffd62da00cae104988f | 40.211268 | 154 | 0.6563 | 5.151408 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00093-swift-boundgenerictype-get.swift | 1 | 814 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
| apache-2.0 | 9765b00d74cdf68e9a5ca6cc349564fb | 18.380952 | 79 | 0.576167 | 2.917563 | false | false | false | false |
GitHubCha2016/ZLSwiftFM | ZLSwiftFM/ZLSwiftFM/Classes/Tools/照片/PhotoPicker.swift | 1 | 3638 | //
// PhotoPicker.swift
// TodayNews
//
// Created by ZXL on 2017/2/21.
// Copyright © 2017年 zxl. All rights reserved.
//
import UIKit
class PhotoPicker: NSObject {
static let share = PhotoPicker()
// 闭包
var result:((_ photos:Array<UIImage>) -> ())? = nil
// 图片是否可以编辑
var editEnable:Bool = true
/// 选择照片
func pick(result:@escaping (_ photos:Array<UIImage>) -> ()) {
// 闭包
self.result = result
// 获得控制器
let presentVC = getPresentVC()
// 弹框
let alertController = UIAlertController(title: "", message: "选择照片来源", preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "相机", style: .default) { (action) in
// 相机
self.pickerController.sourceType = .camera
if UIImagePickerController.isSourceTypeAvailable(.camera){
presentVC.present(self.pickerController, animated: true, completion: nil)
}
}
let photoAction = UIAlertAction(title: "相册", style: .default) { (action) in
// 相册
self.pickerController.sourceType = .photoLibrary
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
presentVC.present(self.pickerController, animated: true, completion: nil)
}
}
let cancleAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
}
alertController.addAction(cameraAction)
alertController.addAction(photoAction)
alertController.addAction(cancleAction)
presentVC.present(alertController, animated: true) {
customLog("选择照片中")
}
}
private func getPresentVC() -> UIViewController{
let rootVC = UIApplication.shared.keyWindow?.rootViewController as! UITabBarController
let selectedNav = rootVC.selectedViewController as! UINavigationController
return selectedNav.topViewController!
}
//
lazy var pickerController: UIImagePickerController = {
let pickerController = UIImagePickerController()
pickerController.allowsEditing = self.editEnable
pickerController.delegate = self
return pickerController
}()
}
extension PhotoPicker: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
/// 取回图片
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let type:String = info[UIImagePickerControllerMediaType] as! String
// 选择的类型是图片
var image:UIImage? = nil
if type == "public.image" {
if editEnable {
image = info[UIImagePickerControllerEditedImage] as? UIImage
}
else{
image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
// MARK: 压缩方式
let imageData = UIImageJPEGRepresentation(image!, 0.5)
let img = UIImage(data: imageData!)
if (result != nil) {
result!([img!])
}
}
// 退出
pickerController.dismiss(animated: true) {
}
}
/// 取消
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// 退出
pickerController.dismiss(animated: true) {
}
}
}
| mit | bde88e9b6000c894f709309f124cd987 | 28.686441 | 119 | 0.584642 | 5.499215 | false | false | false | false |
brentdax/swift | test/Parse/raw_string.swift | 2 | 2857 | // RUN: %target-swift-frontend -dump-ast %s 2>&1 | %FileCheck --strict-whitespace %s
import Swift
_ = #"""
###################################################################
## This source file is part of the Swift.org open source project ##
###################################################################
"""#
// CHECK: "###################################################################\n## This source file is part of the Swift.org open source project ##\n###################################################################"
_ = #"""
# H1 #
## H2 ##
### H3 ###
"""#
// CHECK: "# H1 #\n## H2 ##\n### H3 ###"
// ===---------- Multiline RawString --------===
_ = ##"""
One
""Alpha""
"""##
// CHECK: "One\n\"\"Alpha\"\""
_ = ##"""
Two
Beta
"""##
// CHECK: " Two\nBeta"
_ = #"""
Three\r
Gamma\
"""#
// CHECK: " Three\\r\n Gamma\\"
_ = ###"""
Four \(foo)
Delta
"""###
// CHECK: " Four \\(foo)\n Delta"
_ = ##"""
print("""
Five\##n\##n\##nEpsilon
""")
"""##
// CHECK: "print(\"\"\"\n Five\n\n\nEpsilon\n \"\"\")"
// ===---------- Single line --------===
_ = #""Zeta""#
// CHECK: "\"Zeta\""
_ = #""Eta"\#n\#n\#n\#""#
// CHECK: "\"Eta\"\n\n\n\""
_ = #""Iota"\n\n\n\""#
// CHECK: "\"Iota\"\\n\\n\\n\\\""
_ = #"a raw string with \" in it"#
// CHECK: "a raw string with \\\" in it"
_ = ##"""
a raw string with """ in it
"""##
// CHECK: "a raw string with \"\"\" in it"
let foo = "Interpolation"
_ = #"\b\b \#(foo)\#(foo) Kappa"#
// CHECK: "\\b\\b "
// CHECK: " Kappa"
_ = """
interpolating \(##"""
delimited \##("string")\#n\##n
"""##)
"""
// CHECK: "interpolating "
// CHECK: "delimited "
// CHECK: "string"
// CHECK: "\\#n\n"
#"unused literal"#
// CHECK: "unused literal"
// ===---------- From proposal --------===
_ = #"This is a string"#
// CHECK: "This is a string"
_ = #####"This is a string"#####
// CHECK: "This is a string"
_ = #"enum\s+.+\{.*case\s+[:upper:]"#
// CHECK: "enum\\s+.+\\{.*case\\s+[:upper:]"
_ = #"Alice: "How long is forever?" White Rabbit: "Sometimes, just one second.""#
// CHECK: "Alice: \"How long is forever?\" White Rabbit: \"Sometimes, just one second.\""
_ = #"\#\#1"#
// CHECK: "\\#1"
_ = ##"\#1"##
// CHECK: "\\#1"
_ = #"c:\windows\system32"#
// CHECK: "c:\\windows\\system32"
_ = #"\d{3) \d{3} \d{4}"#
// CHECK: "\\d{3) \\d{3} \\d{4}"
_ = #"""
a string with
"""
in it
"""#
// CHECK: "a string with\n\"\"\"\nin it"
_ = #"a raw string containing \r\n"#
// CHECK: "a raw string containing \\r\\n"
_ = #"""
[
{
"id": "12345",
"title": "A title that \"contains\" \\\""
}
]
"""#
// CHECK: "[\n {\n \"id\": \"12345\",\n \"title\": \"A title that \\\"contains\\\" \\\\\\\"\"\n }\n]"
_ = #"# #"#
// CHECK: "# #"
| apache-2.0 | d45dcbe358d7a445a0eaed1ffc307584 | 19.854015 | 217 | 0.388519 | 2.9393 | false | false | false | false |
ja-mes/experiments | iOS/rainyshinycloudy/Pods/Alamofire/Source/SessionDelegate.swift | 2 | 30874 | //
// SessionDelegate.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for handling all delegate callbacks for the underlying session.
open class SessionDelegate: NSObject {
// MARK: URLSessionDelegate Overrides
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
open var sessionDidBecomeInvalidWithError: ((URLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
// MARK: URLSessionTaskDelegate Overrides
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
open var taskDidComplete: ((URLSession, URLSessionTask, NSError?) -> Void)?
// MARK: URLSessionDataDelegate Overrides
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)?
// MARK: NSURLSessionDownloadDelegate Overrides
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: URLSessionStreamDelegate Overrides
#if !os(watchOS)
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:readClosedForStreamTask:`.
open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:writeClosedForStreamTask:`.
open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:betterRouteDiscoveredForStreamTask:`.
open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for NSURLSessionStreamDelegate method `URLSession:streamTask:didBecomeInputStream:outputStream:`.
open var streamTaskDidBecomeInputStream: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)?
#endif
// MARK: Properties
private var requests: [Int: Request] = [:]
private let lock = NSLock()
/// Access the task delegate for the specified task in a thread-safe manner.
open subscript(task: URLSessionTask) -> Request? {
get {
lock.lock() ; defer { lock.unlock() }
return requests[task.taskIdentifier]
}
set {
lock.lock() ; defer { lock.unlock() }
requests[task.taskIdentifier] = newValue
}
}
// MARK: Lifecycle
/// Initializes the `SessionDelegate` instance.
///
/// - returns: The new `SessionDelegate` instance.
public override init() {
super.init()
}
// MARK: NSObject Overrides
/// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
/// to a specified message.
///
/// - parameter selector: A selector that identifies a message.
///
/// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
open override func responds(to selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
switch selector {
case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return type(of: self).instancesRespond(to: selector)
}
}
}
// MARK: - URLSessionDelegate
extension SessionDelegate: URLSessionDelegate {
/// Tells the delegate that the session has been invalidated.
///
/// - parameter session: The session object that was invalidated.
/// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
sessionDidBecomeInvalidWithError?(session, error as? NSError)
}
/// Requests credentials from the delegate in response to a session-level authentication request from the
/// remote server.
///
/// - parameter session: The session containing the task that requested authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void))
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
#if !os(OSX)
/// Tells the delegate that all messages enqueued for a session have been delivered.
///
/// - parameter session: The session that no longer has any outstanding requests.
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
#endif
}
// MARK: - URLSessionTaskDelegate
extension SessionDelegate: URLSessionTaskDelegate {
/// Tells the delegate that the remote server requested an HTTP redirect.
///
/// - parameter session: The session containing the task whose request resulted in a redirect.
/// - parameter task: The task whose request resulted in a redirect.
/// - parameter response: An object containing the server’s response to the original request.
/// - parameter request: A URL request object filled out with the new location.
/// - parameter completionHandler: A closure that your handler should call with either the value of the request
/// parameter, a modified URL request object, or NULL to refuse the redirect and
/// return the body of the redirect response.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/// Requests credentials from the delegate in response to an authentication request from the remote server.
///
/// - parameter session: The session containing the task whose request requires authentication.
/// - parameter task: The task whose request requires authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(
session,
task: task,
didReceive: challenge,
completionHandler: completionHandler
)
} else {
urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
/// Tells the delegate when a task requires a new request body stream to send to the remote server.
///
/// - parameter session: The session containing the task that needs a new body stream.
/// - parameter task: The task that needs a new body stream.
/// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task]?.delegate {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/// Periodically informs the delegate of the progress of sending body content to the server.
///
/// - parameter session: The session containing the data task.
/// - parameter task: The data task.
/// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
/// - parameter totalBytesSent: The total number of bytes sent so far.
/// - parameter totalBytesExpectedToSend: The expected length of the body data.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/// Tells the delegate that the task finished transferring data.
///
/// - parameter session: The session containing the task whose request finished transferring data.
/// - parameter task: The task whose request finished transferring data.
/// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error as? NSError)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(session, task: task, didCompleteWithError: error as? NSError)
}
NotificationCenter.default.post(
name: Notification.Name.Task.DidComplete,
object: self,
userInfo: [Notification.Key.Task: task]
)
self[task] = nil
}
}
// MARK: - URLSessionDataDelegate
extension SessionDelegate: URLSessionDataDelegate {
/// Tells the delegate that the data task received the initial reply (headers) from the server.
///
/// - parameter session: The session containing the data task that received an initial reply.
/// - parameter dataTask: The data task that received an initial reply.
/// - parameter response: A URL response object populated with headers.
/// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
/// constant to indicate whether the transfer should continue as a data task or
/// should become a download task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: URLSession.ResponseDisposition = .allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/// Tells the delegate that the data task was changed to a download task.
///
/// - parameter session: The session containing the task that was replaced by a download task.
/// - parameter dataTask: The data task that was replaced by a download task.
/// - parameter downloadTask: The new download task that replaced the data task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
}
}
/// Tells the delegate that the data task has received some of the expected data.
///
/// - parameter session: The session containing the data task that provided data.
/// - parameter dataTask: The data task that provided data.
/// - parameter data: A data object containing the transferred data.
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
/// Asks the delegate whether the data (or upload) task should store the response in the cache.
///
/// - parameter session: The session containing the data (or upload) task.
/// - parameter dataTask: The data (or upload) task.
/// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
/// caching policy and the values of certain received headers, such as the Pragma
/// and Cache-Control headers.
/// - parameter completionHandler: A block that your handler must call, providing either the original proposed
/// response, a modified version of that response, or NULL to prevent caching the
/// response. If your delegate implements this method, it must call this completion
/// handler; otherwise, your app leaks memory.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
}
// MARK: - URLSessionDownloadDelegate
extension SessionDelegate: URLSessionDownloadDelegate {
/// Tells the delegate that a download task has finished downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that finished.
/// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either
/// open the file for reading or move it to a permanent location in your app’s sandbox
/// container directory before returning from this delegate method.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
/// Periodically informs the delegate about the download’s progress.
///
/// - parameter session: The session containing the download task.
/// - parameter downloadTask: The download task.
/// - parameter bytesWritten: The number of bytes transferred since the last time this delegate
/// method was called.
/// - parameter totalBytesWritten: The total number of bytes transferred so far.
/// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
/// header. If this header was not provided, the value is
/// `NSURLSessionTransferSizeUnknown`.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/// Tells the delegate that the download task has resumed downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that resumed. See explanation in the discussion.
/// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
/// existing content, then this value is zero. Otherwise, this value is an
/// integer representing the number of bytes on disk that do not need to be
/// retrieved again.
/// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
/// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
}
// MARK: - URLSessionStreamDelegate
#if !os(watchOS)
extension SessionDelegate: URLSessionStreamDelegate {
/// Tells the delegate that the read side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/// Tells the delegate that the write side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/// Tells the delegate that the system has determined that a better route to the host is available.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
/// - parameter inputStream: The new input stream.
/// - parameter outputStream: The new output stream.
open func urlSession(
_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: OutputStream)
{
streamTaskDidBecomeInputStream?(session, streamTask, inputStream, outputStream)
}
}
#endif
| mit | 41a4d039993aaaff00a853a1cb77a893 | 50.021488 | 182 | 0.690165 | 6.281644 | false | false | false | false |
jordenhill/Birdbrain | Birdbrain/FeedforwardNeuralNetwork.swift | 1 | 15371 | //
// FeedForwardNeuralNetwork.swift
// Birdbrain
// A standard, simple feedforward neural network. Can use accelerate functions or metal GPU
// functions.
// Created by Jorden Hill on 9/29/15.
// Copyright © 2015 Jorden Hill. All rights reserved.
//
///A Feedforward Neural Network class.
public class FeedfowardNeuralNetwork {
var numLayers: Int
var sizes: [Int]
var biases = [[Float]]()
var weights = [[Float]]()
var useMetal: Bool
var activationFunction: String
var GPU: MetalDevice!
/**Constructor for Feedforward Neural Network.
- Parameter sizes: The number of layers and size of each layer in the network.
- Parameter useMetal: Indicate whether to use Metal functions or not.
- Parameter activationFunction: Activation function to use
(sigmoid, tangent, or relu).
*/
public init (size: [Int], useMetal: Bool, activateFunction: String) {
//Set initialization values.
numLayers = size.count
self.sizes = size
self.useMetal = useMetal
self.activationFunction = activateFunction
// Check if size and activationFunction are correct, if not, handle.
if (sizes.count < 2) {
print("Network must be at least two layers. Adding 100 neiron output layer.")
sizes.append(100)
}
if ((activateFunction != "sigmoid") && (activateFunction != "tangent") &&
(activateFunction != "relu")) {
activationFunction = "sigmoid"
}
//Construct Metal Device if using Metal
if (useMetal) {
GPU = MetalDevice()
}
//Initialize the biases
for y in sizes[1..<sizes.endIndex] {
let bias: [Float] = (1...y).map() { _ in 0.0 }
biases.append(bias)
}
//Initialize the weights
for (x, y) in zip(sizes[0..<sizes.endIndex - 1], sizes[1..<sizes.endIndex]) {
let weight: [Float] = (1...x * y).map() { _ in initRand(x)}
weights.append(weight)
}
}
// MARK: Getters
/**Return the weights of the network.
- Returns: An array of the network's weight values.
*/
public func getWeights() -> [[Float]] {
return weights
}
/**Return the biases of the network.
- Returns: An array of the network's bias values.
*/
public func getBiases() -> [[Float]] {
return biases
}
/**Get the number of layers in the network.
- Returns: The number of layers in the network.
*/
public func getNetworkSize() -> Int {
return numLayers
}
// MARK: Setters
/** Assign weights to the network. Number of weights must be fit shape of weight matrix.
*/
public func setWeights(newWeights: [[Float]]) {
var canAssign = true
// Quick check to make sure the weights are equal in size.
for (weight, size) in zip(weights, sizes) {
if (weight.count != size) {
canAssign = false
}
}
// If it checks out assign the weights
if (canAssign) {
weights = newWeights
}
}
//MARK: Forward pass
/**Perform a forward propagation on the network using the given input.
- Parameter input: The input to the network.
- Returns: An array of the activations at each layer of the network.
*/
public func feedforward(input: [Float]) -> [[Float]] {
if (useMetal) { //Use Metal GPU functions
return GPUFeedforward(input)
}
else { //Use Accelerate CPU functions.
return CPUFeedforward(input)
}
}
/**Use Metal GPU functions to perform a forward pass.
- Parameter input: The input to the network.
- Returns: An array of the activations at each layer of the network.
*/
private func GPUFeedforward(input: [Float]) -> [[Float]] {
var activations = [[Float]]()
var inputLayer = input
var layer = 1
for (b,w) in zip(biases,weights) {
let n = sizes[layer]
let m = sizes[layer - 1]
switch activationFunction {
case "sigmoid":
activations.append(GPU.sigmoid(GPU.add(GPU.mvMul(w, m: m, n: n, vector: inputLayer), y: b)))
case "tangent":
activations.append(GPU.tanh(GPU.add(GPU.mvMul(w, m: m, n: n, vector: inputLayer), y: b)))
case "relu":
activations.append(GPU.relu(GPU.add(GPU.mvMul(w, m: m, n: n, vector: inputLayer), y: b)))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
activations.append(GPU.sigmoid(GPU.add(GPU.mvMul(w, m: m, n: n, vector: inputLayer), y: b)))
}
layer += 1
inputLayer = activations[activations.endIndex - 1]
}
return activations
}
/**Use CPU functions to perform a forward pass.
- Parameter input: The input to the network.
- Returns: An array of the activations at each layer of the network.
*/
private func CPUFeedforward(input: [Float]) -> [[Float]] {
var activations = [[Float]]()
var inputLayer = input
var layer = 1
for (b,w) in zip(biases,weights) {
let n = sizes[layer - 1]
let m = sizes[layer]
switch activationFunction {
case "sigmoid":
activations.append(sigmoid(add(mvMul(w, m: m, n: n, x: inputLayer), y: b)))
case "tangent":
activations.append(tanh(add(mvMul(w, m: m, n: n, x: inputLayer), y: b)))
case "relu":
activations.append(relu(add(mvMul(w, m: m, n: n, x: inputLayer), y: b)))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
activations.append(sigmoid(add(mvMul(w, m: m, n: n, x: inputLayer), y: b)))
}
layer += 1
// Get input from last layer.
inputLayer = activations[activations.endIndex - 1]
}
return activations
}
//MARK: Backward pass
/**Perform a backward propagation on the network.
- Parameter input: The input to the network.
- Parameter target: Target output of the network.
- Parameter learningRate: The learning rate of the network.
*/
public func backpropagate(input: [Float], target: [Float], learningRate: Float) {
var nablaB = [[Float]]()
var nablaW = [[Float]]()
if (useMetal) {
(nablaB, nablaW) = gpuBackprop(input, target: target)
} else {
(nablaB, nablaW) = backprop(input, target: target)
}
for l in 0..<numLayers - 1 {
weights[l] = sub(weights[l], y: mul(nablaW[l], c: learningRate))
biases[l] = sub(biases[l], y: mul(nablaB[l], c: learningRate))
}
}
/**Backpropagation helper function.
- Parameter input: Input to neural network.
- Parameter target: Target output of the network.
- Returns: The changes in the weights and biases of the network.
*/
private func backprop(input: [Float], target: [Float]) -> ([[Float]], [[Float]]){
//Build namblaW and namblaB
var nablaW = [[Float]]()
var nablaB = [[Float]]()
var delta = [Float]()
var layer = 1
var m: Int
var n: Int
var zVals = [[Float]]()
var activations: [[Float]] = [input]
var layerInput = input
for w in weights {
nablaW.append([Float](count: w.count, repeatedValue: 0.0))
}
for b in biases {
nablaB.append([Float](count: b.count, repeatedValue: 0.0))
}
//Compute a forward pass, hold z values and activations
for (b, w) in zip(biases, weights) {
m = sizes[layer]
n = sizes[layer - 1]
let z = add(mvMul(w, m: m, n: n, x: layerInput), y: b)
zVals.append(z)
switch activationFunction {
case "sigmoid":
layerInput = sigmoid(z)
case "tangent":
layerInput = tanh(z)
case "relu":
layerInput = relu(z)
default:
print("Net somehow acquired inccorect function name, using sigmoid by default")
activationFunction = "sigmoid"
layerInput = sigmoid(z)
}
switch activationFunction {
case "sigmoid":
layerInput = sigmoid(z)
case "tangent":
layerInput = tanh(z)
case "relu":
layerInput = relu(z)
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
layerInput = sigmoid(z)
}
layer += 1
activations.append(layerInput)
}
//Create delta for last layer based on output, do a backward pass
switch activationFunction {
case "sigmoid":
delta = mul(sub(activations[activations.endIndex - 1], y: target),
y: sigmoidPrime(zVals[zVals.endIndex - 1]))
case "tangent":
delta = mul(sub(activations[activations.endIndex - 1], y: target),
y: tanhPrime(zVals[zVals.endIndex - 1]))
case "relu":
delta = mul(sub(activations[activations.endIndex - 1], y: target),
y: reluPrime(zVals[zVals.endIndex - 1]))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
delta = mul(sub(activations[activations.endIndex - 1], y: target),
y: sigmoidPrime(zVals[zVals.endIndex - 1]))
}
nablaB[nablaB.endIndex - 1] = delta
nablaW[nablaW.endIndex - 1] = outer(activations[activations.endIndex - 2], y: delta)
for l in 2 ..< numLayers {
let z = zVals[zVals.endIndex - l]
let partialDelta = mvMul(weights[weights.endIndex - l + 1], m: sizes[sizes.endIndex - l],
n: sizes[sizes.endIndex - l + 1], x: delta)
switch activationFunction {
case "sigmoid":
delta = mul(partialDelta, y: sigmoidPrime(z))
case "tangent":
delta = mul(partialDelta, y: tanhPrime(z))
case "relu":
delta = mul(partialDelta, y: reluPrime(z))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
delta = mul(partialDelta, y: sigmoidPrime(z))
}
nablaB[nablaB.endIndex - l] = delta
nablaW[nablaW.endIndex - l] = outer(delta, y: activations[activations.endIndex - l - 1])
}
return (nablaB, nablaW)
}
/**Metal version of backpropagation helper function.
- Parameter input: Input to neural network.
- Parameter target: Target output of the network.
- Returns: The changes in the weights and biases of the network.
*/
private func gpuBackprop(input: [Float], target: [Float]) -> ([[Float]], [[Float]]){
//Build namblaW and namblaB
var nablaW = [[Float]]()
var nablaB = [[Float]]()
var delta = [Float]()
var layer = 1
var m: Int
var n: Int
var zVals = [[Float]]()
var layerInput = input
var activations = [[Float]]()
for w in weights {
nablaW.append([Float](count: w.count, repeatedValue: 0.0))
}
for b in biases {
nablaB.append([Float](count: b.count, repeatedValue: 0.0))
}
for (b, w) in zip(biases, weights) {
m = sizes[layer]
n = sizes[layer - 1]
let z = GPU.add(GPU.mvMul(w, m: m, n: n, vector: layerInput), y: b)
zVals.append(z)
switch activationFunction {
case "sigmoid":
layerInput = GPU.sigmoid(z)
case "tangent":
layerInput = GPU.tanh(z)
case "relu":
layerInput = GPU.relu(z)
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
layerInput = GPU.sigmoid(z)
}
layer += 1
activations.append(layerInput)
}
//Create delta for last layer based on output, do a backward pass
switch activationFunction {
case "sigmoid":
delta = GPU.mul(sub(activations[activations.endIndex - 1], y: target),
y: GPU.sigmoidPrime(zVals[zVals.endIndex - 1]))
case "tangent":
delta = GPU.mul(sub(activations[activations.endIndex - 1], y: target),
y: GPU.tanhPrime(zVals[zVals.endIndex - 1]))
case "relu":
delta = GPU.mul(sub(activations[activations.endIndex - 1], y: target),
y: GPU.reluPrime(zVals[zVals.endIndex - 1]))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
delta = GPU.mul(sub(activations[activations.endIndex - 1], y: target),
y: GPU.sigmoidPrime(zVals[zVals.endIndex - 1]))
}
nablaB[nablaB.endIndex - 1] = delta
nablaW[nablaW.endIndex - 1] = outer(activations[activations.endIndex - 2], y: delta)
nablaB[nablaB.endIndex - 1] = delta
nablaW[nablaW.endIndex - 1] = outer(activations[activations.endIndex - 2], y: delta)
for l in 2 ..< numLayers {
let z = zVals[zVals.endIndex - l]
let partialDelta = GPU.mvMul(weights[weights.endIndex - l + 1], m: sizes[sizes.endIndex - l],
n: sizes[sizes.endIndex - l + 1], vector: delta)
switch activationFunction {
case "sigmoid":
delta = GPU.mul(partialDelta, y: GPU.sigmoidPrime(z))
case "tangent":
delta = GPU.mul(partialDelta, y: GPU.tanhPrime(z))
case "relu":
delta = GPU.mul(partialDelta, y: GPU.reluPrime(z))
default:
print("Net somehow acquired inccorect function name, using sigmoid by default.")
activationFunction = "sigmoid"
delta = GPU.mul(partialDelta, y: GPU.sigmoidPrime(z))
}
nablaB[nablaB.endIndex - l] = delta
nablaW[nablaW.endIndex - l] = outer(delta, y: activations[activations.endIndex - l - 1])
}
return (nablaB, nablaW)
}
/** Calculate the loss of the network using mean-squared error loss function.
- Parameter input: Input to the network.
- Parameter target: Target output from the network.
- Returns: The loss of the network after the given output.
*/
public func getMSELoss(input: [Float], target: [Float]) -> Float {
let activations = feedforward(input)
let output = activations[activations.endIndex - 1]
return sum(square(sub(target, y: output))) / Float(target.count)
}
/** Calculate the loss of the network using cross-entropy loss function.
- Parameter input: Input to the network.
- Parameter target: Target output from the network.
- Returns: The loss of the network after the given output.
*/
public func getCrossEntropyLoss(input: [Float], target: [Float]) -> Float {
let activations = feedforward(input)
let output = activations[activations.endIndex - 1]
let ones = [Float](count: target.count, repeatedValue: 1.0)
let part = add(mul(target, y: log(output)), y: mul(sub(ones, y: target), y: log(sub(ones, y: output))))
return -(sum(part) / Float(target.count))
}
/**Combine and average weights in two neural nets.
- Parameter otherNet: Another feedfowrd neural network.
*/
public func combine(otherNet: FeedfowardNeuralNetwork) {
precondition((numLayers == otherNet.numLayers) && (sizes == otherNet.sizes),
"Nets must have the same size.")
var newWeights = [[Float]]()
for (weight1, weight2) in zip(weights, otherNet.weights) {
newWeights.append(div(add(weight1, y: weight2), c: 2.0))
}
weights = newWeights
}
} | mit | 65bd3ff15c7e21ef6ab938c95995aceb | 32.415217 | 107 | 0.613598 | 3.740569 | false | false | false | false |
migueloruiz/la-gas-app-swift | lasgasmx/GasPriceModel.swift | 1 | 907 | //
// GasPriceModel.swift
// lasgasmx
//
// Created by Desarrollo on 4/26/17.
// Copyright © 2017 migueloruiz. All rights reserved.
//
import Foundation
enum FuelType: String {
case Magna = "Magana"
case Premium = "Premium"
case Diesel = "Diesel"
}
struct GasPrice {
var type : FuelType
var price: Float
static func buildArray(from array: [String: String]) -> [GasPrice]{
var prices: [GasPrice] = []
if let magna = array["magna"] {
prices.append(GasPrice(type: .Magna, price: Float(magna) ?? 0 ) )
}
if let premium = array["premium"] {
prices.append(GasPrice(type: .Premium, price: Float(premium) ?? 0 ) )
}
if let diesel = array["diesel"] {
prices.append(GasPrice(type: .Diesel, price: Float(diesel) ?? 0 ) )
}
return prices
}
}
| mit | 061b7024ccc47821397c7234f07c577b | 22.842105 | 81 | 0.555188 | 3.511628 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Views/Cells/Chat/AutocompleteCell.swift | 2 | 964 | //
// AutocompleteCell.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 04/11/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
final class AutocompleteCell: UITableViewCell {
static let minimumHeight = CGFloat(44)
static let identifier = "AutocompleteCell"
@IBOutlet weak var imageViewIcon: UIImageView!
@IBOutlet weak var avatarViewContainer: AvatarView! {
didSet {
if let avatarView = AvatarView.instantiateFromNib() {
avatarView.frame = avatarViewContainer.bounds
avatarViewContainer.addSubview(avatarView)
self.avatarView = avatarView
}
}
}
weak var avatarView: AvatarView! {
didSet {
avatarView.layer.cornerRadius = 4
avatarView.layer.masksToBounds = true
avatarView.labelInitialsFontSize = 15
}
}
@IBOutlet weak var labelTitle: UILabel!
}
| mit | a42116bc29321f05cc8eff5a919aa0a5 | 24.342105 | 65 | 0.635514 | 4.963918 | false | false | false | false |
lorentey/swift | test/AutoDiff/Parse/differentiable_func_type.swift | 1 | 3496 | // RUN: %target-swift-frontend -dump-parse -verify %s | %FileCheck %s
let a: @differentiable (Float) -> Float // okay
// CHECK: (pattern_named 'a'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let b: @differentiable(linear) (Float) -> Float // okay
// CHECK: (pattern_named 'b'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
let c: @differentiable (Float) throws -> Float // okay
// CHECK: (pattern_named 'c'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let d: @differentiable(linear) (Float) throws -> Float // okay
// CHECK: (pattern_named 'd'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
// Generic type test.
struct A<T> {
func foo() {
let local: @differentiable(linear) (T) -> T // okay
// CHECK: (pattern_named 'local'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
}
}
// expected-error @+1 {{expected ')' in '@differentiable' attribute}}
let c: @differentiable(linear (Float) -> Float
// expected-error @+1 {{expected ')' in '@differentiable' attribute}}
let c: @differentiable(notValidArg (Float) -> Float
// expected-error @+1 {{unexpected argument 'notValidArg' in '@differentiable' attribute}}
let d: @differentiable(notValidArg) (Float) -> Float
// Using 'linear' as a type
struct B {
struct linear {}
let propertyB1: @differentiable (linear) -> Float // okay
// CHECK: (pattern_named 'propertyB1'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyB2: @differentiable(linear) (linear) -> linear // okay
// CHECK: (pattern_named 'propertyB2'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
let propertyB3: @differentiable (linear, linear) -> linear // okay
// CHECK: (pattern_named 'propertyB3'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyB4: @differentiable (linear, Float) -> linear // okay
// CHECK: (pattern_named 'propertyB4'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyB5: @differentiable (Float, linear) -> linear // okay
// CHECK: (pattern_named 'propertyB5'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyB6: @differentiable(linear) (linear, linear, Float, linear)
-> Float // okay
// CHECK: (pattern_named 'propertyB6'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
// expected-error @+1 {{expected ')' in '@differentiable' attribute}}
let propertyB7: @differentiable(linear (linear) -> Float
}
// Using 'linear' as a typealias
struct C {
typealias linear = (C) -> C
let propertyC1: @differentiable (linear) -> Float // okay
// CHECK: (pattern_named 'propertyC1'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyC2: @differentiable(linear) (linear) -> linear // okay
// CHECK: (pattern_named 'propertyC2'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
let propertyC3: @differentiable linear // okay
// CHECK: (pattern_named 'propertyC3'
// CHECK-NEXT: (type_attributed attrs=@differentiable{{[^(]}}
let propertyC4: linear // okay
// CHECK: (pattern_named 'propertyC4'
let propertyC5: @differentiable(linear) linear // okay
// CHECK: (pattern_named 'propertyC5'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
let propertyC6: @differentiable(linear) @convention(c) linear // okay
// CHECK: (pattern_named 'propertyC6'
// CHECK-NEXT: (type_attributed attrs=@differentiable(linear)
}
| apache-2.0 | 396dcb30fd72ab48beee4cff8558ba4f | 36.191489 | 90 | 0.686499 | 3.637877 | false | false | false | false |
hooman/swift | test/Serialization/autolinking.swift | 12 | 5235 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/out.txt
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-concurrency -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/out.txt
// RUN: %FileCheck %s < %t/out.txt
// RUN: %FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/out.txt
// RUN: %empty-directory(%t/someModule.framework/Modules/someModule.swiftmodule)
// RUN: mv %t/someModule.swiftmodule %t/someModule.framework/Modules/someModule.swiftmodule/%target-swiftmodule-name
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -lmagic %s -F %t > %t/framework.txt
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-concurrency -runtime-compatibility-version none -emit-ir -lmagic %s -F %t > %t/framework.txt
// RUN: %FileCheck -check-prefix=FRAMEWORK %s < %t/framework.txt
// RUN: %FileCheck -check-prefix=NO-FORCE-LOAD %s < %t/framework.txt
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/force-load.txt
// RUN: %FileCheck %s < %t/force-load.txt
// RUN: %FileCheck -check-prefix FORCE-LOAD-CLIENT -check-prefix FORCE-LOAD-CLIENT-%target-object-format %s < %t/force-load.txt
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -debugger-support %s -I %t > %t/force-load.txt
// RUN: %FileCheck -check-prefix NO-FORCE-LOAD-CLIENT %s < %t/force-load.txt
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift | %FileCheck --check-prefix=NO-FORCE-LOAD %s
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-concurrency -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift | %FileCheck --check-prefix=NO-FORCE-LOAD %s
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name module %S/../Inputs/empty.swift -autolink-force-load | %FileCheck --check-prefix=FORCE-LOAD %s
// RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib -module-name someModule -module-link-name 0module %S/../Inputs/empty.swift -autolink-force-load | %FileCheck --check-prefix=FORCE-LOAD-HEX %s
// RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name someModule -module-link-name module %S/../Inputs/empty.swift -public-autolink-library anotherLib
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/public-autolink.txt
// RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-concurrency -runtime-compatibility-version none -emit-ir -lmagic %s -I %t > %t/public-autolink.txt
// RUN: %FileCheck %s < %t/public-autolink.txt
// RUN: %FileCheck -check-prefix=PUBLIC-DEP %s < %t/public-autolink.txt
// Linux uses a different autolinking mechanism, based on
// swift-autolink-extract. This file tests the Darwin mechanism.
// UNSUPPORTED: autolink-extract
import someModule
// CHECK: !llvm.linker.options = !{
// CHECK-DAG: !{{[0-9]+}} = !{!{{"-lmagic"|"/DEFAULTLIB:magic.lib"}}}
// CHECK-DAG: !{{[0-9]+}} = !{!{{"-lmodule"|"/DEFAULTLIB:module.lib"}}}
// FRAMEWORK: !llvm.linker.options = !{
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!{{"-lmagic"|"/DEFAULTLIB:magic.lib"}}}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!{{"-lmodule"|"/DEFAULTLIB:module.lib"}}}
// FRAMEWORK-DAG: !{{[0-9]+}} = !{!"-framework", !"someModule"}
// NO-FORCE-LOAD-NOT: FORCE_LOAD
// NO-FORCE-LOAD-NOT -lmodule
// NO-FORCE-LOAD-NOT -lmagic
// FORCE-LOAD: @"_swift_FORCE_LOAD_$_module"
// FORCE-LOAD-HEX: @"_swift_FORCE_LOAD_$306d6f64756c65"
// NO-FORCE-LOAD-CLIENT-NOT: FORCE_LOAD
// FORCE-LOAD-CLIENT: @"_swift_FORCE_LOAD_$_module_$_autolinking" = weak_odr hidden constant void ()* @"_swift_FORCE_LOAD_$_module"
// FORCE-LOAD-CLIENT: @llvm.used = appending global [{{[0-9]+}} x i8*] [
// FORCE-LOAD-CLIENT: i8* bitcast (void ()** @"_swift_FORCE_LOAD_$_module_$_autolinking" to i8*)
// FORCE-LOAD-CLIENT: ], section "llvm.metadata"
// FORCE-LOAD-CLIENT-macho: declare extern_weak {{(dllimport )?}}void @"_swift_FORCE_LOAD_$_module"()
// FORCE-LOAD-CLIENT-COFF: declare extern {{(dllimport )?}}void @"_swift_FORCE_LOAD_$_module"()
// PUBLIC-DEP: !llvm.linker.options = !{
// PUBLIC-DEP-DAG: !{{[0-9]+}} = !{!{{"-lmagic"|"/DEFAULTLIB:magic.lib"}}}
// PUBLIC-DEP-DAG: !{{[0-9]+}} = !{!{{"-lmodule"|"/DEFAULTLIB:module.lib"}}}
// PUBLIC-DEP-DAG: !{{[0-9]+}} = !{!{{"-lanotherLib"|"/DEFAULTLIB:anotherLib.lib"}}}
| apache-2.0 | 54897a939ec58a3620f36e860c2eed97 | 78.318182 | 272 | 0.715186 | 3.263716 | false | false | false | false |
lieonCX/Uber | UberDriver/UberDriver/ViewModel/Driver/DriverViewModel.swift | 1 | 3043 | //
// DriverViewModel.swift
// UberDriver
//
// Created by lieon on 2017/3/24.
// Copyright © 2017年 ChangHongCloudTechService. All rights reserved.
//
import Foundation
import FirebaseDatabase
class DriverViewModel {
static var driverAccount: String = ""
var rider: String = ""
var driverID: String = ""
var riderCancleAction: (() -> Void)?
var driverCancleAction: (() -> Void)?
func observeMessageForDriver(hasRiderAction: ((_ latitude: Double, _ longitude: Double) -> Void)?) {
DBProvider.shared.requestRef.observe(.childAdded) { (snapshot, _) in
if let data = snapshot.value as? [String: Any], let latitude = data[Constants.latitude] as? Double, let longitude = data[Constants.longtitude] as? Double, let name = data[Constants.name] as? String {
hasRiderAction?(latitude, longitude)
self.rider = name
}
}
DBProvider.shared.requestRef.observe(.childRemoved) { (snapshot, _) in
if let data = snapshot.value as? [String: Any], let name = data[Constants.name] as? String {
if self.rider == name {
self.rider = ""
self.riderCancleAction?()
}
}
}
DBProvider.shared.requestAcceptedRef.observe(.childAdded, with: { snapshot in
if let data = snapshot.value as? [String: Any], let name = data[Constants.name] as? String {
if name == DriverViewModel.driverAccount {
self.driverID = snapshot.key
}
}
})
DBProvider.shared.requestAcceptedRef.observe(.childRemoved, with: { snapshot in
if let data = snapshot.value as? [String: Any], let name = data[Constants.name] as? String {
if name == DriverViewModel.driverAccount {
self.driverCancleAction?()
}
}
})
}
func acceptUber(lati: Double, long: Double) {
let data: [String: Any] = [Constants.name: DriverViewModel.driverAccount,
Constants.latitude: lati,
Constants.longtitude: long]
DBProvider.shared.requestAcceptedRef.childByAutoId().setValue(data)
}
func cancleUberForDriver() {
DBProvider.shared.requestAcceptedRef.child(driverID).removeValue()
}
func updateDriverLocation(lati: Double, long: Double) {
DBProvider.shared.requestAcceptedRef.child(driverID).updateChildValues([Constants.latitude: lati, Constants.longtitude: long])
}
func updateRiderLocation(action: @escaping (_ lati: Double, _ long: Double) -> Void) {
DBProvider.shared.requestRef.observe(.childChanged, with: { snapshot in
if let data = snapshot.value as? [String: Any], let lati = data[Constants.latitude] as? Double, let long = data[Constants.longtitude] as? Double {
action(lati, long)
}
})
}
}
| mit | 720659a76d7f3c3e2ed1ed593276535c | 40.081081 | 212 | 0.592763 | 4.418605 | false | false | false | false |
kentaiwami/FiNote | ios/FiNote/FiNote/User/UserViewController.swift | 1 | 3874 | //
// UserViewController.swift
// FiNote
//
// Created by 岩見建汰 on 2018/01/28.
// Copyright © 2018年 Kenta. All rights reserved.
//
import UIKit
import Eureka
import KeychainAccess
import PopupDialog
class UserViewController: FormViewController, UITabBarControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
tableView.isScrollEnabled = false
CreateForm()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.delegate = self
self.tabBarController?.navigationItem.title = "User"
self.tabBarController?.navigationItem.setRightBarButton(nil, animated: false)
}
func CreateForm() {
UIView.setAnimationsEnabled(false)
let keychain = Keychain()
form +++ Section(header: "ユーザ情報", footer: "")
<<< TextRow() {
$0.title = "ユーザ名"
$0.value = (try! keychain.get("username"))!
$0.disabled = true
}
<<< ButtonRow("") {
let vc = UserDetailFormViewController()
vc.SetAPIName(name: "password")
$0.title = "パスワードの変更"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return vc}, onDismiss: {vc in vc.navigationController?.popViewController(animated: true)})
$0.tag = "password"
}
<<< ButtonRow("") {
let vc = UserDetailFormViewController()
vc.SetAPIName(name: "email")
$0.title = "メールアドレスの変更"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return vc}, onDismiss: {vc in vc.navigationController?.popViewController(animated: true)})
$0.tag = "email"
}
<<< ButtonRow("") {
let vc = UserDetailFormViewController()
vc.SetAPIName(name: "birthyear")
$0.title = "誕生年の変更"
$0.presentationMode = .show(controllerProvider: ControllerProvider.callback {return vc}, onDismiss: {vc in vc.navigationController?.popViewController(animated: true)})
$0.tag = "birthyear"
}
form +++ Section()
<<< ButtonRow(){
$0.title = "Sign Out"
$0.baseCell.backgroundColor = UIColor.hex(Color.red.rawValue, alpha: 1.0)
$0.baseCell.tintColor = UIColor.white
$0.tag = "sign_out"
}
.onCellSelection { cell, row in
let cancel = CancelButton(title: "Cancel", action: nil)
let ok = DestructiveButton(title: "OK", action: {
let keychain = Keychain()
try! keychain.removeAll()
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sign = storyboard.instantiateViewController(withIdentifier: "Sign")
sign.modalTransitionStyle = .flipHorizontal
self.present(sign, animated: true, completion: nil)
})
let popup = PopupDialog(title: "Sign Out", message: "サインアウトしますがよろしいですか?")
popup.transitionStyle = .zoomIn
popup.addButtons([ok, cancel])
self.present(popup, animated: true, completion: nil)
}
UIView.setAnimationsEnabled(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | daf40aa28152547f5fd50845eca70a25 | 35.514563 | 183 | 0.537357 | 5.137978 | false | false | false | false |
ankit4oct/CreditCardInfo | Pods/CreditCardForm/CreditCardForm/Classes/CreditCardFormView.swift | 1 | 23185 | //
// CreditCardForumView.swift
// CreditCardForm
//
// Created by Atakishiyev Orazdurdy on 11/28/16.
// Copyright © 2016 Veriloft. All rights reserved.
//
import UIKit
public enum Brands : String {
case NONE, Visa, MasterCard, Amex, JCB, DEFAULT, Discover
}
@IBDesignable
public class CreditCardFormView : UIView {
fileprivate var cardView: UIView = UIView(frame: .zero)
fileprivate var backView: UIView = UIView(frame: .zero)
fileprivate var frontView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
fileprivate var gradientLayer = CAGradientLayer()
fileprivate var showingBack:Bool = false
fileprivate var backImage: UIImageView = UIImageView(frame: .zero)
fileprivate var brandImageView = UIImageView(frame: .zero)
fileprivate var cardNumber:AKMaskField = AKMaskField(frame: .zero)
fileprivate var cardHolderText:UILabel = UILabel(frame: .zero)
fileprivate var cardHolder:UILabel = UILabel(frame: .zero)
fileprivate var expireDate: AKMaskField = AKMaskField(frame: .zero)
fileprivate var expireDateText: UILabel = UILabel(frame: .zero)
fileprivate var backLine: UIView = UIView(frame: .zero)
fileprivate var cvc: AKMaskField = AKMaskField(frame: .zero)
fileprivate var chipImg: UIImageView = UIImageView(frame: .zero)
public var colors = [String : [UIColor]]()
@IBInspectable
public var defaultCardColor: UIColor = UIColor.hexStr(hexStr: "363434", alpha: 1) {
didSet {
gradientLayer.colors = [defaultCardColor.cgColor, defaultCardColor.cgColor]
backView.backgroundColor = defaultCardColor
}
}
@IBInspectable
public var cardHolderExpireDateTextColor: UIColor = UIColor.hexStr(hexStr: "#bdc3c7", alpha: 1) {
didSet {
cardHolderText.textColor = cardHolderExpireDateTextColor
expireDateText.textColor = cardHolderExpireDateTextColor
}
}
@IBInspectable
public var cardHolderExpireDateColor: UIColor = .white {
didSet {
cardHolder.textColor = cardHolderExpireDateColor
expireDate.textColor = cardHolderExpireDateColor
cardNumber.textColor = cardHolderExpireDateColor
}
}
@IBInspectable
public var backLineColor: UIColor = .black {
didSet {
backLine.backgroundColor = backLineColor
}
}
@IBInspectable
public var chipImage = UIImage(named: "chip", in: Bundle.currentBundle(), compatibleWith: nil) {
didSet {
chipImg.image = chipImage
}
}
@IBInspectable
public var cardHolderString = "----" {
didSet {
cardHolder.text = cardHolderString
}
}
@IBInspectable
public var expireDatePlaceholderText = "EXPIRY" {
didSet {
expireDateText.text = expireDatePlaceholderText
}
}
@IBInspectable
public var cardNumberMaskExpression = "{....} {....} {....} {....}" {
didSet {
cardNumber.maskExpression = cardNumberMaskExpression
}
}
@IBInspectable
public var cardNumberMaskTemplate = "**** **** **** ****" {
didSet {
cardNumber.maskTemplate = cardNumberMaskTemplate
}
}
public var cardNumberFontSize: CGFloat = 20 {
didSet {
cardNumber.font = UIFont(name: "Helvetica Neue", size: cardNumberFontSize)
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
createViews()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func layoutSubviews() {
super.layoutSubviews()
createViews()
}
private func createViews() {
frontView.isHidden = false
backView.isHidden = true
cardView.clipsToBounds = true
if colors.count < 7 {
setBrandColors()
}
createCardView()
createFrontView()
createbackImage()
createBrandImageView()
createCardNumber()
createCardHolder()
createCardHolderText()
createExpireDate()
createExpireDateText()
createChipImage()
createBackView()
createBackLine()
createCVC()
}
private func setGradientBackground(v: UIView, top: CGColor, bottom: CGColor) {
let colorTop = top
let colorBottom = bottom
gradientLayer.colors = [ colorTop, colorBottom]
gradientLayer.locations = [ 0.0, 1.0]
gradientLayer.frame = v.bounds
backView.backgroundColor = defaultCardColor
v.layer.addSublayer(gradientLayer)
}
private func createCardView() {
cardView.translatesAutoresizingMaskIntoConstraints = false
cardView.layer.cornerRadius = 6
cardView.backgroundColor = .clear
self.addSubview(cardView)
//CardView
self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: cardView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: 0.0));
}
private func createBackView() {
backView.translatesAutoresizingMaskIntoConstraints = false
backView.layer.cornerRadius = 6
backView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
backView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin]
cardView.addSubview(backView)
self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: 0.0));
}
private func createFrontView() {
frontView.translatesAutoresizingMaskIntoConstraints = false
frontView.layer.cornerRadius = 6
frontView.center = CGPoint(x: self.bounds.midX, y: self.bounds.midY)
frontView.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleBottomMargin]
cardView.addSubview(frontView)
setGradientBackground(v: frontView, top: defaultCardColor.cgColor, bottom: defaultCardColor.cgColor)
self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: frontView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.height, multiplier: 1.0, constant: 0.0));
}
private func createbackImage() {
backImage.translatesAutoresizingMaskIntoConstraints = false
backImage.image = UIImage(named: "back.jpg")
backImage.contentMode = UIViewContentMode.scaleAspectFill
frontView.addSubview(backImage)
self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: backImage, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 0.0));
}
private func createBrandImageView() {
//Card brand image
brandImageView.translatesAutoresizingMaskIntoConstraints = false
brandImageView.contentMode = UIViewContentMode.scaleAspectFit
frontView.addSubview(brandImageView)
self.addConstraint(NSLayoutConstraint(item: brandImageView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 10));
self.addConstraint(NSLayoutConstraint(item: brandImageView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -10));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==60)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": brandImageView]));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==40)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": brandImageView]));
}
private func createCardNumber() {
//Credit card number
cardNumber.translatesAutoresizingMaskIntoConstraints = false
cardNumber.maskExpression = cardNumberMaskExpression
cardNumber.maskTemplate = cardNumberMaskTemplate
cardNumber.textColor = cardHolderExpireDateColor
cardNumber.isUserInteractionEnabled = false
cardNumber.textAlignment = NSTextAlignment.center
cardNumber.font = UIFont(name: "Helvetica Neue", size: cardNumberFontSize)
frontView.addSubview(cardNumber)
self.addConstraint(NSLayoutConstraint(item: cardNumber, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0));
self.addConstraint(NSLayoutConstraint(item: cardNumber, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==200)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": cardNumber]));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==30)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": cardNumber]));
}
private func createCardHolder() {
//Name
cardHolder.translatesAutoresizingMaskIntoConstraints = false
cardHolder.font = UIFont(name: "Helvetica Neue", size: 12)
cardHolder.textColor = cardHolderExpireDateColor
cardHolder.text = cardHolderString
frontView.addSubview(cardHolder)
self.addConstraint(NSLayoutConstraint(item: cardHolder, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -20));
self.addConstraint(NSLayoutConstraint(item: cardHolder, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 15));
}
private func createCardHolderText() {
//Card holder uilabel
cardHolderText.translatesAutoresizingMaskIntoConstraints = false
cardHolderText.font = UIFont(name: "Helvetica Neue", size: 10)
cardHolderText.text = "CARD HOLDER"
cardHolderText.textColor = cardHolderExpireDateTextColor
frontView.addSubview(cardHolderText)
self.addConstraint(NSLayoutConstraint(item: cardHolderText, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cardHolder, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: -3));
self.addConstraint(NSLayoutConstraint(item: cardHolderText, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 15));
}
private func createExpireDate() {
//Expire Date
expireDate = AKMaskField()
expireDate.translatesAutoresizingMaskIntoConstraints = false
expireDate.font = UIFont(name: "Helvetica Neue", size: 12)
expireDate.maskExpression = "{..}/{..}"
expireDate.text = "MM/YY"
expireDate.textColor = cardHolderExpireDateColor
frontView.addSubview(expireDate)
self.addConstraint(NSLayoutConstraint(item: expireDate, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: -20));
self.addConstraint(NSLayoutConstraint(item: expireDate, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -55));
}
private func createExpireDateText() {
//Expire Date Text
expireDateText.translatesAutoresizingMaskIntoConstraints = false
expireDateText.font = UIFont(name: "Helvetica Neue", size: 10)
expireDateText.text = expireDatePlaceholderText
expireDateText.textColor = cardHolderExpireDateTextColor
frontView.addSubview(expireDateText)
self.addConstraint(NSLayoutConstraint(item: expireDateText, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: expireDate, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: -3));
self.addConstraint(NSLayoutConstraint(item: expireDateText, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -58));
}
private func createChipImage() {
//Chip image
chipImg.translatesAutoresizingMaskIntoConstraints = false
chipImg.alpha = 0.5
chipImg.image = chipImage
frontView.addSubview(chipImg)
self.addConstraint(NSLayoutConstraint(item: chipImg, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 15));
self.addConstraint(NSLayoutConstraint(item: chipImg, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: cardView, attribute: NSLayoutAttribute.leading, multiplier: 1.0, constant: 15));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==45)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": chipImg]));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==30)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": chipImg]));
}
private func createBackLine() {
//BackLine
backLine.translatesAutoresizingMaskIntoConstraints = false
backLine.backgroundColor = backLineColor
backView.addSubview(backLine)
self.addConstraint(NSLayoutConstraint(item: backLine, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: backView, attribute: NSLayoutAttribute.top, multiplier: 1.0, constant: 20));
self.addConstraint(NSLayoutConstraint(item: backLine, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: backView, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==300)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": backLine]));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": backLine]));
}
private func createCVC() {
//CVC textfield
cvc.translatesAutoresizingMaskIntoConstraints = false
cvc.maskExpression = "..."
cvc.text = "CVC"
cvc.backgroundColor = .white
cvc.textAlignment = NSTextAlignment.center
cvc.isUserInteractionEnabled = false
backView.addSubview(cvc)
self.addConstraint(NSLayoutConstraint(item: cvc, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: backLine, attribute: NSLayoutAttribute.bottom, multiplier: 1.0, constant: 10));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": cvc]));
self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==25)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": cvc]));
self.addConstraint(NSLayoutConstraint(item: cvc, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: backView, attribute: NSLayoutAttribute.trailing, multiplier: 1.0, constant: -10));
}
private func setType(colors: [UIColor], alpha: CGFloat, back: UIColor) {
UIView.animate(withDuration: 2, animations: { () -> Void in
self.gradientLayer.colors = [colors[0].cgColor, colors[1].cgColor]
})
self.backView.backgroundColor = back
self.chipImg.alpha = alpha
}
private func flip() {
var showingSide = frontView
var hiddenSide = backView
if showingBack {
(showingSide, hiddenSide) = (backView, frontView)
}
UIView.transition(from:showingSide,
to: hiddenSide,
duration: 0.7,
options: [UIViewAnimationOptions.transitionFlipFromRight, UIViewAnimationOptions.showHideTransitionViews],
completion: nil)
}
public func paymentCardTextFieldDidChange(cardNumber: String? = "", expirationYear: UInt, expirationMonth: UInt, cvc: String? = "") {
self.cardNumber.text = cardNumber
self.expireDate.text = NSString(format: "%02ld", expirationMonth) as String + "/" + (NSString(format: "%02ld", expirationYear) as String)
if expirationMonth == 0 {
expireDate.text = "MM/YY"
}
let v = CreditCardValidator()
self.cvc.text = cvc
if (cardNumber?.characters.count)! >= 7 || (cardNumber?.characters.count)! < 4 {
guard let type = v.type(from: "\(cardNumber)") else {
self.brandImageView.image = nil
if let name = colors["NONE"] {
setType(colors: [name[0], name[1]], alpha: 0.5, back: name[0])
}
return
}
// Visa, Mastercard, Amex etc.
if let name = colors[type.name] {
self.brandImageView.image = UIImage(named: type.name, in: Bundle.currentBundle(), compatibleWith: nil)
setType(colors: [name[0], name[1]], alpha: 1, back: name[0])
}else{
setType(colors: [self.colors["DEFAULT"]![0], self.colors["DEFAULT"]![0]], alpha: 1, back: self.colors["DEFAULT"]![0])
}
}
}
public func paymentCardTextFieldDidEndEditingExpiration(expirationYear: UInt) {
if "\(expirationYear)".characters.count <= 1 {
expireDate.text = "MM/YY"
}
}
public func paymentCardTextFieldDidBeginEditingCVC() {
if !showingBack {
flip()
showingBack = true
}
}
public func paymentCardTextFieldDidEndEditingCVC() {
if showingBack {
flip()
showingBack = false
}
}
}
//: CardColors
extension CreditCardFormView {
fileprivate func setBrandColors() {
colors[Brands.NONE.rawValue] = [defaultCardColor, defaultCardColor]
colors[Brands.Visa.rawValue] = [UIColor.hexStr(hexStr: "#5D8BF2", alpha: 1), UIColor.hexStr(hexStr: "#3545AE", alpha: 1)]
colors[Brands.MasterCard.rawValue] = [UIColor.hexStr(hexStr: "#ED495A", alpha: 1), UIColor.hexStr(hexStr: "#8B1A2B", alpha: 1)]
colors[Brands.Amex.rawValue] = [UIColor.hexStr(hexStr: "#005B9D", alpha: 1), UIColor.hexStr(hexStr: "#132972", alpha: 1)]
colors[Brands.JCB.rawValue] = [UIColor.hexStr(hexStr: "#265797", alpha: 1), UIColor.hexStr(hexStr: "#3d6eaa", alpha: 1)]
colors["Diners Club"] = [UIColor.hexStr(hexStr: "#5b99d8", alpha: 1), UIColor.hexStr(hexStr: "#4186CD", alpha: 1)]
colors[Brands.Discover.rawValue] = [UIColor.hexStr(hexStr: "#e8a258", alpha: 1), UIColor.hexStr(hexStr: "#D97B16", alpha: 1)]
colors[Brands.DEFAULT.rawValue] = [UIColor.hexStr(hexStr: "#5D8BF2", alpha: 1), UIColor.hexStr(hexStr: "#3545AE", alpha: 1)]
}
}
| mit | 483fc0a7c8ee3fab6d3b2d57d7e4f74d | 50.52 | 232 | 0.684998 | 5.035621 | false | false | false | false |
colemancda/NetworkObjects | Source/HTTPResponse.swift | 1 | 5995 | //
// HTTPResponse.swift
// NetworkObjects
//
// Created by Alsey Coleman Miller on 9/9/15.
// Copyright © 2015 ColemanCDA. All rights reserved.
//
import SwiftFoundation
import CoreModel
public extension ResponseMessage {
/// Decode from HTTP Response.
init?(HTTPResponse: SwiftFoundation.HTTP.Response, parameters: (type: RequestType, entity: Entity)) {
let requestType = parameters.type
let entity = parameters.entity
self.metadata = HTTPResponse.headers
// check for error code
guard HTTPResponse.statusCode == HTTP.StatusCode.OK.rawValue else {
self.response = Response.Error(HTTPResponse.statusCode)
return
}
// parse response body
let jsonResponse: JSON.Value?
do {
let data = HTTPResponse.body
if data.count > 0 {
var jsonString = ""
for byte in data {
let unicode = UnicodeScalar(byte)
jsonString.append(unicode)
}
guard let jsonValue = JSON.Value(string: jsonString) else { return nil }
jsonResponse = jsonValue
}
else { jsonResponse = nil }
}
// parse request
switch requestType {
case .Get:
guard let jsonObject = jsonResponse?.objectValue,
let values = entity.convert(jsonObject)
else { return nil }
self.response = Response.Get(values)
case .Delete:
guard jsonResponse == nil else { return nil }
self.response = Response.Delete
case .Edit:
guard let jsonObject = jsonResponse?.objectValue,
let values = entity.convert(jsonObject)
else { return nil }
self.response = Response.Edit(values)
case .Create:
// parse response
guard let jsonObject = jsonResponse?.objectValue
where jsonObject.count == 1,
let (resourceID, valuesJSON) = jsonObject.first,
let valuesJSONObect = valuesJSON.objectValue,
let values = entity.convert(valuesJSONObect)
else { return nil }
self.response = Response.Create(resourceID, values)
case .Search:
guard let jsonArray = jsonResponse?.arrayValue else { return nil }
var resourceIDs = [String]()
for jsonValue in jsonArray {
switch jsonValue {
case let .String(stringValue):
resourceIDs.append(stringValue)
default: return nil
}
}
self.response = Response.Search(resourceIDs)
case .Function:
let jsonObject: JSON.Object?
if let jsonValue = jsonResponse {
guard let objectValue = jsonValue.objectValue else { return nil }
jsonObject = objectValue
}
else { jsonObject = nil }
self.response = Response.Function(jsonObject)
}
}
func toHTTPResponse() -> HTTP.Response {
var response = HTTP.Response()
response.headers = self.metadata
switch self.response {
case let .Error(errorCode):
response.statusCode = errorCode
case let .Get(values):
let jsonObject = JSON.fromValues(values)
let jsonString = JSON.Value.Object(jsonObject).toString()!
let bytes = jsonString.utf8.map({ (codeUnit) -> Byte in codeUnit })
response.body = bytes
case .Delete: break
case let .Edit(values):
let jsonObject = JSON.fromValues(values)
let jsonString = JSON.Value.Object(jsonObject).toString()!
let bytes = jsonString.utf8.map({ (codeUnit) -> Byte in codeUnit })
response.body = bytes
case let .Create(resourceID, values):
let jsonObject = [resourceID: JSON.Value.Object(JSON.fromValues(values))]
let jsonString = JSON.Value.Object(jsonObject).toString()!
let bytes = jsonString.utf8.map({ (codeUnit) -> Byte in codeUnit })
response.body = bytes
case let .Search(resourceIDs):
let jsonArray = resourceIDs.map({ (resourceID) -> JSON.Value in JSON.Value.String(resourceID) })
let jsonString = JSON.Value.Array(jsonArray).toString()!
let bytes = jsonString.utf8.map({ (codeUnit) -> Byte in codeUnit })
response.body = bytes
case let .Function(jsonObject):
if let jsonObject = jsonObject {
let jsonString = JSON.Value.Object(jsonObject).toString()!
let bytes = jsonString.utf8.map({ (codeUnit) -> Byte in codeUnit })
response.body = bytes
}
}
return response
}
}
| mit | ac925eede3042d560df1931ebcdf5090 | 28.382353 | 108 | 0.466633 | 6.296218 | false | false | false | false |
google/iosched-ios | Source/IOsched/Application/BottomSheetViewController.swift | 1 | 8628 | //
// Copyright (c) 2019 Google Inc.
//
// 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 MaterialComponents
public protocol BottomSheetViewControllerDelegate: NSObjectProtocol {
func bottomSheetController(_ controller: BottomSheetViewController,
didSelect selectedViewController: UIViewController)
}
public class BottomSheetViewController: MDCCollectionViewController {
private let drawerItems: [UIViewController]
public weak var delegate: BottomSheetViewControllerDelegate?
public init(drawerItems: [UIViewController]) {
self.drawerItems = drawerItems
let layout = MDCCollectionViewFlowLayout()
layout.estimatedItemSize = CGSize(width: 375, height: 48)
super.init(collectionViewLayout: MDCCollectionViewFlowLayout())
}
public override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(
BottomSheetCollectionViewCell.self,
forCellWithReuseIdentifier: BottomSheetCollectionViewCell.reuseIdentifier()
)
collectionView.backgroundColor = .white
collectionView.isScrollEnabled = false
collectionView.layer.cornerRadius = 8
collectionView.clipsToBounds = true
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.reloadData()
registerForDynamicTypeUpdates()
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
// MARK: - UICollectionViewDataSource
public override func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return drawerItems.count
}
public override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: BottomSheetCollectionViewCell.reuseIdentifier(),
for: indexPath
) as! BottomSheetCollectionViewCell
cell.populate(item: drawerItems[indexPath.item])
return cell
}
public override func collectionView(_ collectionView: UICollectionView,
shouldHideItemSeparatorAt indexPath: IndexPath) -> Bool {
return true
}
// MARK: - UICollectionViewDelegate
public override func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
super.collectionView(collectionView, didSelectItemAt: indexPath)
collectionView.deselectItem(at: indexPath, animated: true)
let controller = drawerItems[indexPath.item]
delegate?.bottomSheetController(self, didSelect: controller)
}
// MARK: - Layout
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func registerForDynamicTypeUpdates() {
NotificationCenter.default.addObserver(self,
selector: #selector(dynamicTypeTextSizeDidChange(_:)),
name: UIContentSizeCategory.didChangeNotification,
object: nil)
}
@objc func dynamicTypeTextSizeDidChange(_ sender: Any) {
collectionView?.collectionViewLayout.invalidateLayout()
collectionView?.reloadData()
}
}
public class BottomSheetCollectionViewCell: MDCCollectionViewCell {
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFill
return imageView
}()
private let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = ProductSans.regular.style(.body)
label.textColor = UIColor(r: 60, g: 64, b: 67)
return label
}()
public override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(imageView)
contentView.addSubview(titleLabel)
setupConstraints()
shouldHideSeparator = true
}
public func populate(item: UIViewController) {
imageView.image = item.tabBarItem?.image
titleLabel.text = item.tabBarItem?.title
titleLabel.font = ProductSans.regular.style(.body)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var intrinsicContentSize: CGSize {
let imageViewSize = CGSize(width: 60, height: 48)
let textSize = titleLabel.intrinsicContentSize
let maxHeight = max(imageViewSize.height, textSize.height + 32)
let totalWidth = imageViewSize.width + textSize.width + 16
return CGSize(width: totalWidth, height: maxHeight)
}
public override var isAccessibilityElement: Bool {
get { return true }
set {}
}
public override var accessibilityLabel: String? {
get { return titleLabel.text }
set {}
}
public override var accessibilityHint: String? {
set {}
get {
guard let screenName = titleLabel.text else { return nil }
return NSLocalizedString("Double-tap to open the \(screenName) screen.",
comment: "Localized accessibility hint for buttons in the bottom sheet navigation view.")
}
}
private func setupConstraints() {
let constraints = [
// Image view
NSLayoutConstraint(item: imageView,
attribute: .left,
relatedBy: .equal,
toItem: contentView,
attribute: .left,
multiplier: 1,
constant: 24),
NSLayoutConstraint(item: imageView,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: imageView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 20),
NSLayoutConstraint(item: imageView,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 20),
// Title label
NSLayoutConstraint(item: titleLabel,
attribute: .left,
relatedBy: .equal,
toItem: imageView,
attribute: .right,
multiplier: 1,
constant: 16),
NSLayoutConstraint(item: titleLabel,
attribute: .right,
relatedBy: .equal,
toItem: contentView,
attribute: .right,
multiplier: 1,
constant: -16),
NSLayoutConstraint(item: titleLabel,
attribute: .centerY,
relatedBy: .equal,
toItem: contentView,
attribute: .centerY,
multiplier: 1,
constant: 0)
]
imageView.setContentHuggingPriority(.required, for: .horizontal)
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
contentView.addConstraints(constraints)
}
}
enum ProductSans: String {
case regular = "ProductSans-Regular"
func style(_ textStyle: UIFont.TextStyle, sizeOffset: CGFloat = 0) -> UIFont {
let size = UIFont.preferredFont(forTextStyle: textStyle).pointSize + sizeOffset
return UIFont(name: rawValue, size: size)!
}
}
| apache-2.0 | 93d43a45f8a45f4a274bebea961dccb2 | 33.374502 | 99 | 0.626449 | 5.748168 | false | false | false | false |
jngd/advanced-ios10-training | T19E01/ReadFileViewController.swift | 1 | 1953 | /**
* Copyright (c) 2016 Juan Garcia
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
class ReadFileViewController: UIViewController {
/***** Vars *****/
var fileManager = FileManager.default
var documentsPath = (NSSearchPathForDirectoriesInDomains(
FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first! as NSString)
/***** Outlets *****/
@IBOutlet weak var filecontent: UITextView!
@IBOutlet weak var filename: UITextField!
/***** Actions *****/
@IBAction func openFile(_ sender: AnyObject) {
let path =
documentsPath.appendingPathComponent(filename.text!) as String
if (!fileManager.fileExists(atPath: path)) {
print("file not exists")
return
}
let content = NSString(data: fileManager.contents(atPath: path)!,
encoding: String.Encoding.utf8.rawValue)
filecontent.text = content as! String
}
}
| apache-2.0 | 756d38b1d8978f1afd1c803477a00a50 | 37.294118 | 127 | 0.745008 | 4.54186 | false | false | false | false |
anatoliyv/RevealMenuController | RevealMenuController/Classes/RevealMenuAction.swift | 1 | 3169 | //
// RevealMenuAction.swift
// Pods
//
// Created by Anatoliy Voropay on 8/31/16.
//
//
import Foundation
/// Basic Reveal Menu action. When selecting this item in a menu completion get called
/// with `RevealControllerHandler` block
///
/// - Seealso: `RevealControllerHandler`
open class RevealMenuAction: RevealMenuActionProtocol {
/// Text alignment inside menu items
///
/// - Parameter left: Text will be left aligned, image will be on the left side
/// - Parameter center: Text will be centered, image will be placed on the left side
/// - Parameter right: Text will be right aligned, image will be on the right side toward text
public enum TextAlignment {
case left
case center
case right
}
public typealias RevealControllerHandler = ((RevealMenuController, RevealMenuAction) -> Void)
/// Title for action
open private(set) var title: String?
/// Text alignment. Default is `Center`
open private(set) var alignment: NSTextAlignment
/// Label icon image
open private(set) var image: UIImage?
/// Selection handler
open private(set) var handler: RevealControllerHandler?
// MARK: - Lifecycle
/// Initialize action with all possible properties.
///
/// - Parameter title: Menu title. Required.
/// - Parameter image: Image icon that will be displayed beside a title. Optional.
/// - Parameter alignment: Text alignment inside a menu cell.
/// - Parameter handler: Handler will be called right after menu item is pressed.
public required init(
title: String, image: UIImage? = nil,
alignment: NSTextAlignment = .center, handler: RevealControllerHandler?) {
self.title = title
self.image = image
self.alignment = alignment
self.handler = handler
}
}
/// Use `RevealMenuActionGroup` to group few `RevealMenuAction`s in one menu item.
/// Group shoul have it's own `title`, `image` and `alignment`.
///
/// - Seealso: `RevealMenuAction`
open class RevealMenuActionGroup: RevealMenuActionProtocol {
/// Title for action group
open private(set) var title: String?
/// Label icon image
open private(set) var image: UIImage?
/// Text alignment. Default value is `Center`
open private(set) var alignment: NSTextAlignment
/// Array of actions inside a group
/// - Seealso: `RevealMenuAction`
open private(set) var actions: [RevealMenuAction] = []
/// Initialize action group with title, image, text alignment and array of actions.
///
/// - Parameter title: Title for an action group. Required.
/// - Parameter image: Image that will be displayed with a title.
/// - Parameter alignment: Text alignment inside a menu item cell
/// - Parameter actions: Array of actions that will be displayed once user tap on current action group.
///
public required init(title: String, image: UIImage? = nil, alignment: NSTextAlignment = .center, actions: [RevealMenuAction]) {
self.title = title
self.image = image
self.alignment = alignment
self.actions = actions
}
}
| mit | 42917cda3fef904edb8d2f09b86d4268 | 36.72619 | 131 | 0.672136 | 4.546628 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.