repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pasmall/WeTeam | refs/heads/master | WeTools/WeTools/Config/Extensions.swift | apache-2.0 | 1 | //
// Extensions.swift
// WeTools
//
// Created by lhtb on 16/11/2.
// Copyright © 2016年 lhtb. All rights reserved.
//
import Foundation
import UIKit
/// UI 扩展
extension UIView{
/// X值
var x: CGFloat {
return self.frame.origin.x
}
/// Y值
var y: CGFloat {
return self.frame.origin.y
}
/// 宽度
var width: CGFloat {
return self.frame.size.width
}
///高度
var height: CGFloat {
return self.frame.size.height
}
var size: CGSize {
return self.frame.size
}
var point: CGPoint {
return self.frame.origin
}
var centerX: CGFloat {
return self.center.x
}
var centerY: CGFloat {
return self.center.y
}
func setX(x: CGFloat) {
var frame = self.frame;
frame.origin.x = x;
self.frame = frame;
}
func setY(y: CGFloat) {
var frame = self.frame;
frame.origin.y = y;
self.frame = frame;
}
func setWidth(w: CGFloat) {
var frame = self.frame;
frame.size.width = w;
self.frame = frame;
}
func setHeight(h: CGFloat) {
var frame = self.frame;
frame.size.height = h;
self.frame = frame;
}
func setCenterX(cx: CGFloat) {
var center = self.center;
center.x = cx;
self.center = center;
}
func setCenterY(cy: CGFloat) {
var center = self.center;
center.y = cy;
self.center = center;
}
}
extension UIFont {
class func HiraKakuProNW6(size: CGFloat) -> UIFont{
return UIFont(name: "HiraKakuProN-W6", size: size)!
}
class func HiraKakuProNW3(size: CGFloat) -> UIFont{
return UIFont(name: "HiraKakuProN-W3", size: size)!
}
class func Helvetica(size: CGFloat) -> UIFont{
return UIFont(name: "HelveticaNeue", size: size)!
}
class func HelveticaBold(size: CGFloat) -> UIFont{
return UIFont(name: "HelveticaNeue-Bold", size: size)!
}
class func HelveticaMedium(size: CGFloat) -> UIFont{
return UIFont(name: "HelveticaNeue-Medium", size: size)!
}
class func HelventicaNeue(size: CGFloat) -> UIFont{
return UIFont(name: "HelveticaNeue", size: size)!
}
}
extension UIColor {
class func getColor(r:CGFloat,g:CGFloat,b:CGFloat,l:CGFloat = 1) ->UIColor{
let color = UIColor(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1)
return color
}
}
/// Foundation 扩展
public extension Int {
private func newEmptyDateComponents() -> NSDateComponents! {
let dateComponents = NSDateComponents()
dateComponents.year = 0
dateComponents.month = 0
dateComponents.day = 0
dateComponents.hour = 0
dateComponents.minute = 0
dateComponents.second = 0
return dateComponents
}
var year: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.year = self
return components!
}
var month: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.month = self
return components!
}
var day: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.day = self
return components!
}
var hour: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.hour = self
return components!
}
var minute: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.minute = self
return components!
}
var second: NSDateComponents {
let components = self.newEmptyDateComponents()
components?.second = self
return components!
}
}
public extension NSDate {
private convenience init(date otherDate: NSDate) {
let timeInterval = otherDate.timeIntervalSince1970
self.init(timeIntervalSince1970: timeInterval)
}
convenience init(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0, second: Int = 0) {
let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hour
components.minute = minute
components.second = second
let date = calendar!.date(from: components as DateComponents)
self.init(date: date! as NSDate)
}
}
func + (left: NSDate, right: NSDateComponents) -> NSDate {
let calendar = NSCalendar.current
var components = calendar.dateComponents([.year , .month ,.day , .hour , .minute , .second] , from: left as Date)
components.year = components.year! + right.year
components.month = components.month! + right.month
components.day = components.day! + right.day
components.hour = components.hour! + right.hour
components.minute = components.minute! + right.minute
components.second = components.second! + right.second
return calendar.date(from: components)! as NSDate
}
func - (left: NSDate, right: NSDateComponents) -> NSDate {
let calendar = NSCalendar.current
var components = calendar.dateComponents([.year , .month ,.day , .hour , .minute , .second] , from: left as Date)
components.year = components.year! - right.year
components.month = components.month! - right.month
components.day = components.day! - right.day
components.hour = components.hour! - right.hour
components.minute = components.minute! - right.minute
components.second = components.second! - right.second
return calendar.date(from: components)! as NSDate
}
func > (left: NSDate, right: NSDate) -> Bool {
let timeInterval = left.timeIntervalSince(right as Date)
return timeInterval > 0
}
func < (left: NSDate, right: NSDate) -> Bool {
let timeInterval = left.timeIntervalSince(right as Date)
return timeInterval < 0
}
func >= (left: NSDate, right: NSDate) -> Bool {
return (left > right) || (left == right)
}
func <= (left: NSDate, right: NSDate) -> Bool {
return (left < right) || (left == right)
}
| e6f76481c2bbbc19495ca622cbc04dd4 | 22.891791 | 117 | 0.606747 | false | false | false | false |
Den-Ree/InstagramAPI | refs/heads/master | src/InstagramAPI/InstagramAPI/Example/Extensions/Date+Extension.swift | mit | 2 | //
// NSDate+Extension.swift
// ConceptOffice
//
// Created by Denis on 02.03.16.
// Copyright © 2016 Den Ree. All rights reserved.
//
import Foundation
typealias Day = Int
typealias Week = Int
typealias Month = Int
typealias Year = Int
typealias TimeComponent = (hour: Int, minute: Int, second: Int)
typealias TimeRange = (startTime: Date, endTime: Date)
typealias DayRange = (startDay: Date, endDay: Date)
typealias MonthPeriod = (month: Month, year: Year)
extension Month {
static var todayMonth: MonthPeriod {
let date = Date()
return MonthPeriod(date.month, date.year)
}
}
enum Weekdays: Int {
case all = 0
case sunday
case monday
case tuesday
case wednesday
case thursday
case friday
case saturday
}
enum TimeIntervalValue: Int {
case sec = 1
case min = 60
case hour = 3600
case day = 86400
case week = 604800
static func interval(from timeComponent: TimeComponent) -> TimeInterval {
var result = 0
result += timeComponent.hour * TimeIntervalValue.hour.rawValue
result += timeComponent.minute * TimeIntervalValue.min.rawValue
result += timeComponent.second * TimeIntervalValue.sec.rawValue
return TimeInterval(result)
}
}
struct WeeksRange {
var weeks: (start: Week, end: Week) = (0, 0)
var years: (start: Year, end: Year) = (0, 0)
}
extension Month {
var nextMonth: Month {
return self == 12 ? 1 : self + 1
}
var previous: Month {
return self == 1 ? 12 : self - 1
}
var defaultString: String {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale.current
//options: monthSymbols, shortMonthSymbols, veryShortSymbols
let months = dateFormatter.shortMonthSymbols
return months![self - 1]
}
}
extension TimeInterval {
var days: Int {
return Int(self) / TimeIntervalValue.day.rawValue
}
var hours: Int {
return Int(self) / TimeIntervalValue.hour.rawValue
}
var minutes: Int {
return (Int(self)%TimeIntervalValue.hour.rawValue)/TimeIntervalValue.min.rawValue
}
var seconds: Int {
return (Int(self) % TimeIntervalValue.hour.rawValue)%TimeIntervalValue.min.rawValue
}
var formattedTimeString: String {
var result = ""
if hours == 0 {
result = "\(minutes) m"
} else if minutes == 0 {
result = "\(hours) h"
} else {
result = "\(hours) h \(minutes) m"
}
return result
}
}
extension Weekdays {
static var firstWeekday: Weekdays {
return Weekdays(rawValue: Date().calendar.firstWeekday)!
}
static var allWeekdays: [Weekdays] {
let firstWeekday = Date().calendar.firstWeekday
var weekdays = [Weekdays]()
for i in firstWeekday...Weekdays.saturday.rawValue {
weekdays.append(Weekdays(rawValue: i)!)
}
for i in 1..<firstWeekday {
weekdays.append(Weekdays(rawValue: i)!)
}
return weekdays
}
var shortTitle: String {
return Date().calendar.veryShortWeekdaySymbols[rawValue - 1]
}
var defaultTitle: String {
return Date().calendar.shortWeekdaySymbols[rawValue - 1]
}
var longTitle: String {
return Date().calendar.weekdaySymbols[rawValue - 1]
}
var nextWeekday: Weekdays {
if self == Weekdays.saturday {
return Weekdays.sunday
} else {
return Weekdays(rawValue: self.rawValue + 1)!
}
}
var previousWeekday: Weekdays {
if self == Weekdays.sunday {
return Weekdays.saturday
} else {
return Weekdays(rawValue: self.rawValue - 1)!
}
}
}
extension Date {
fileprivate var calendar: Calendar {
return Calendar.current
}
var startOfDay: Date {
return calendar.startOfDay(for: self)
}
var endOfDay: Date {
var components = DateComponents()
components.day = 1
let date = (calendar as NSCalendar).date(byAdding: components, to: startOfDay, options: [])!
return date.addingTimeInterval(-1)
}
var weekday: Weekdays {
let weekdayComponent = (calendar as NSCalendar).component(.weekday, from: self)
return Weekdays(rawValue: weekdayComponent)!
}
var day: Day {
return (calendar as NSCalendar).component(.day, from: self)
}
var month: Month {
return (calendar as NSCalendar).component(.month, from: self)
}
var year: Year {
return (calendar as NSCalendar).component(.year, from: self)
}
var weekOfYear: Int {
return (calendar as NSCalendar).component(.weekOfYear, from: self)
}
var isInToday: Bool {
return calendar.isDateInToday(self)
}
var isInYesterday: Bool {
return calendar.isDateInYesterday(self)
}
var isInTomorrow: Bool {
return calendar.isDateInTomorrow(self)
}
var numberOfDaysInMonth: Int {
return (calendar as NSCalendar).range(of: .day, in: .month, for: self).length
}
var time: Date {
//Date formatter
let timeDateFormatter: DateFormatter = {
let result = DateFormatter()
result.dateFormat = "HH:mm:ss"
result.timeZone = calendar.timeZone
result.locale = Locale(identifier: "en_US_POSIX")
return result
}()
let timeString = timeDateFormatter.string(from: self)
if let time = timeDateFormatter.date(from: timeString) {
return time
} else {
let components = self.timeComponent
return timeDateFormatter.date(from: "\(components.hour):\(components.minute):\(components.second)")!
}
}
var beginingOfDay: Date {
return calendar.startOfDay(for: self).addingTimeInterval(TimeInterval(calendar.timeZone.secondsFromGMT()))
}
var timeComponent: TimeComponent {
let components = calendar.dateComponents([.hour, .minute, .second], from: self)
return TimeComponent(hour: components.hour!, minute: components.minute!, second: components.second!)
}
var calendarTitle: String {
return "\(day) \(month.defaultString) \(weekday.longTitle.uppercased())"
}
// MARK: Methods
static func firstDay(_ year: Year) -> Date {
return firstDay(1, year: year)
}
static func lastDay(_ year: Year) -> Date {
let firstDayInNextYear = Date.firstDay(year + 1)
return firstDayInNextYear.addingTimeInterval(-TimeInterval(TimeIntervalValue.day.rawValue)).endOfDay
}
static func firstDay(_ month: Month, year: Year) -> Date {
var firstDayComponents = DateComponents()
firstDayComponents.year = year
(firstDayComponents as NSDateComponents).timeZone = Date().calendar.timeZone
firstDayComponents.weekOfYear = 1
firstDayComponents.day = 1
firstDayComponents.month = month
return Date().calendar.date(from: firstDayComponents)!.startOfDay
}
static func lastDay(_ month: Month, year: Year) -> Date {
var resultYear = year
if month == 12 {
resultYear += 1
}
let firstDayInNextMonth = Date.firstDay(month.nextMonth, year: resultYear)
return firstDayInNextMonth.addingTimeInterval(-TimeInterval(TimeIntervalValue.hour.rawValue)).endOfDay
}
//Strings
var defaultString: String {
return DateFormatter.appDefaultFormatter.string(from: self)
}
func years(from date: Date) -> Int {
return (calendar as NSCalendar).components(.year, from: date, to: self, options: []).year!
}
func months(from date: Date) -> Int {
return (calendar as NSCalendar).components(.month, from: date, to: self, options: []).month!
}
func weeks(from date: Date) -> Int {
return (calendar as NSCalendar).components(.weekOfYear, from: date, to: self, options: []).weekOfYear!
}
func days(from date: Date) -> Int {
return (calendar as NSCalendar).components(.day, from: date, to: self, options: []).day!
}
func hours(from date: Date) -> Int {
return (calendar as NSCalendar).components(.hour, from: date, to: self, options: []).hour!
}
func minutes(from date: Date) -> Int {
return (calendar as NSCalendar).components(.minute, from: date, to: self, options: []).minute!
}
func seconds(from date: Date) -> Int {
return (calendar as NSCalendar).components(.second, from: date, to: self, options: []).second!
}
func date(_ time: TimeComponent) -> Date {
return self.startOfDay.addingTimeInterval(TimeIntervalValue.interval(from: time))
}
func isOneDay(_ anotherDate: Date) -> Bool {
return day == anotherDate.day && month == anotherDate.month && year == anotherDate.year
}
}
private extension Int {
var timeValue: String {
if self >= 10 {
return "\(self)"
} else {
return "0\(self)"
}
}
}
enum DayPeriods: Int {
case night = -1
case morning = 0
case midday = 1
case evening = 2
static var count = 3
static func timeRange(for period: DayPeriods) -> TimeRange {
var startTimeComponent: TimeComponent
var endTimeComponent: TimeComponent
switch period {
case .morning:
startTimeComponent = TimeComponent(hour: 4, minute: 0, second: 0)
endTimeComponent = TimeComponent(hour: 11, minute: 59, second: 59)
case .midday:
startTimeComponent = TimeComponent(hour: 12, minute: 0, second: 0)
endTimeComponent = TimeComponent(hour: 17, minute: 59, second: 59)
case .evening:
startTimeComponent = TimeComponent(hour: 18, minute: 0, second: 0)
endTimeComponent = TimeComponent(hour: 23, minute: 59, second: 59)
case .night:
startTimeComponent = TimeComponent(hour: 0, minute: 0, second: 0)
endTimeComponent = TimeComponent(hour: 3, minute: 59, second: 59)
}
let startTime = Date().date(startTimeComponent).time
let endTime = Date().date(endTimeComponent).time
return TimeRange(startTime: startTime, endTime: endTime)
}
var next: DayPeriods {
let result = (rawValue + 1)%DayPeriods.count
return DayPeriods(rawValue: result)!
}
var previous: DayPeriods {
var result = rawValue - 1
if result < -1 {
result = 2
}
return DayPeriods(rawValue: result)!
}
}
extension Date {
var dayPeriod: DayPeriods {
let morningRange = DayPeriods.timeRange(for: .morning)
let middayRange = DayPeriods.timeRange(for: .midday)
let eveningRange = DayPeriods.timeRange(for: .evening)
if morningRange.startTime <= time && time <= morningRange.endTime {
return .morning
} else if middayRange.startTime <= time && time <= middayRange.endTime {
return .midday
} else if eveningRange.startTime <= time && time <= eveningRange.endTime {
return .evening
} else {
return .night
}
}
}
extension Calendar {
var is12hour: Bool {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .none
formatter.timeStyle = .short
let dateString = formatter.string(from: Date())
var hasAMSymbol = false
var hasPMSymbol = false
if let amRange = dateString.range(of: formatter.amSymbol), !amRange.isEmpty {
hasAMSymbol = true
}
if let pmRange = dateString.range(of: formatter.pmSymbol), !pmRange.isEmpty {
hasPMSymbol = true
}
return hasPMSymbol || hasAMSymbol
}
}
| ede914ba75ad8fc8012de4e19f1de5e8 | 28.469136 | 114 | 0.619103 | false | false | false | false |
wupingzj/YangRepoApple | refs/heads/master | QiuTuiJian/QiuTuiJian/ShareTableVC.swift | gpl-2.0 | 1 | //
// ShareTableVC.swift
// QiuTuiJian
//
// Created by Ping on 19/07/2014.
// Copyright (c) 2014 Yang Ltd. All rights reserved.
//
import UIKit
import CoreData
public class ShareTableVC: UITableViewController, NSFetchedResultsControllerDelegate {
var dataService:DataService = DataService.sharedInstance
var managedObjectContext: NSManagedObjectContext? = nil
// init(style: UITableViewStyle) {
// super.init(style: style)
// // Custom initialization
// }
override public 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
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table View
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//return self.fetchedResultsController.sections.count
return 0
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// let sectionInfo = self.fetchedResultsController.sections[section] as NSFetchedResultsSectionInfo
// return sectionInfo.numberOfObjects
return 0
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override public func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override public func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = self.fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
println("Unresolved error \(error), \(error!.description)")
abort()
}
}
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
cell.textLabel!.text = "TODO"
}
// #pragma mark - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
println("************* Event entity class name=\(entity!.managedObjectClassName)")
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "timeStamp", ascending: false)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
println("Unresolved error \(error), \(error!.description)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
public func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
public func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case NSFetchedResultsChangeType.Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case NSFetchedResultsChangeType.Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
// Move
// Update
return
}
}
public func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
switch type {
case NSFetchedResultsChangeType.Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case NSFetchedResultsChangeType.Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case NSFetchedResultsChangeType.Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath)!, atIndexPath: indexPath)
case NSFetchedResultsChangeType.Move:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
default:
return
}
}
public func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
/*
Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool {
Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// #pragma 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.
}
*/
}
| a8000f8006a84fb80ff8f20a75968592 | 42.430168 | 216 | 0.692565 | false | false | false | false |
alblue/swift | refs/heads/master | test/SILGen/optional-cast.swift | apache-2.0 | 1 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
class A {}
class B : A {}
// CHECK-LABEL: sil hidden @$s4main3fooyyAA1ACSgF : $@convention(thin) (@guaranteed Optional<A>) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<A>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// Check whether the temporary holds a value.
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]] : $Optional<A>, case #Optional.some!enumelt.1: [[IS_PRESENT:bb[0-9]+]], case #Optional.none!enumelt: [[NOT_PRESENT:bb[0-9]+]]
//
// If so, pull the value out and check whether it's a B.
// CHECK: [[IS_PRESENT]]([[VAL:%.*]] :
// CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
//
// If so, materialize that and inject it into x.
// CHECK: [[IS_B]]([[T0:%.*]] : @owned $B):
// CHECK-NEXT: store [[T0]] to [init] [[X_VALUE]] : $*B
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: br [[CONT:bb[0-9]+]]
//
// If not, destroy_value the A and inject nothing into x.
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A):
// CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<B>, #Optional.none
// CHECK-NEXT: br [[CONT]]
//
// Finish the present path.
// CHECK: [[CONT]]:
// CHECK-NEXT: br [[RETURN_BB:bb[0-9]+]]
//
// Finish.
// CHECK: [[RETURN_BB]]:
// CHECK-NEXT: destroy_value [[X]]
// CHECK-NOT: destroy_value [[ARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
//
// Finish the not-present path.
// CHECK: [[NOT_PRESENT]]:
// CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none
// CHECK-NEXT: br [[RETURN_BB]]
func foo(_ y : A?) {
var x = (y as? B)
}
// CHECK-LABEL: sil hidden @$s4main3baryyAA1ACSgSgSgSgF : $@convention(thin) (@guaranteed Optional<Optional<Optional<Optional<A>>>>) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<Optional<Optional<Optional<A>>>>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<Optional<Optional<B>>> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// -- Check for some(...)
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK-NEXT: switch_enum [[ARG_COPY]] : ${{.*}}, case #Optional.some!enumelt.1: [[P:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_1:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_1]]:
// CHECK: br [[FINISH_NIL_0:bb[0-9]+]]
//
// If so, drill down another level and check for some(some(...)).
// CHECK: [[P]]([[VALUE_OOOA:%.*]] :
// CHECK-NEXT: switch_enum [[VALUE_OOOA]] : ${{.*}}, case #Optional.some!enumelt.1: [[PP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_2:bb[0-9]+]]
//
// CHECK: [[NIL_DEPTH_2]]:
// CHECK: br [[FINISH_NIL_0]]
//
// If so, drill down another level and check for some(some(some(...))).
// CHECK: [[PP]]([[VALUE_OOA:%.*]] :
// CHECK-NEXT: switch_enum [[VALUE_OOA]] : ${{.*}}, case #Optional.some!enumelt.1: [[PPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_3:bb[0-9]+]]
//
// If so, drill down another level and check for some(some(some(some(...)))).
// CHECK: [[PPP]]([[VALUE_OA:%.*]] :
// CHECK-NEXT: switch_enum [[VALUE_OA]] : ${{.*}}, case #Optional.some!enumelt.1: [[PPPP:bb[0-9]+]], case #Optional.none!enumelt: [[NIL_DEPTH_4:bb[0-9]+]]
//
// If so, pull out the A and check whether it's a B.
// CHECK: [[PPPP]]([[VAL:%.*]] :
// CHECK-NEXT: checked_cast_br [[VAL]] : $A to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
//
// If so, inject it back into an optional.
// TODO: We're going to switch back out of this; we really should peephole it.
// CHECK: [[IS_B]]([[T0:%.*]] : @owned $B):
// CHECK-NEXT: enum $Optional<B>, #Optional.some!enumelt.1, [[T0]]
// CHECK-NEXT: br [[SWITCH_OB2:bb[0-9]+]](
//
// If not, inject nothing into an optional.
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $A):
// CHECK-NEXT: destroy_value [[ORIGINAL_VALUE]]
// CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt
// CHECK-NEXT: br [[SWITCH_OB2]](
//
// Switch out on the value in [[OB2]].
// CHECK: [[SWITCH_OB2]]([[VAL:%[0-9]+]] : @owned $Optional<B>):
// CHECK-NEXT: switch_enum [[VAL]] : ${{.*}}, case #Optional.some!enumelt.1: [[HAVE_B:bb[0-9]+]], case #Optional.none!enumelt: [[FINISH_NIL_4:bb[0-9]+]]
//
// CHECK: [[FINISH_NIL_4]]:
// CHECK: br [[FINISH_NIL_0]]
//
// CHECK: [[HAVE_B]]([[UNWRAPPED_VAL:%.*]] :
// CHECK: [[REWRAPPED_VAL:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[UNWRAPPED_VAL]]
// CHECK: br [[DONE_DEPTH0:bb[0-9]+]]
//
// CHECK: [[DONE_DEPTH0]](
// CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.some!enumelt.1,
// CHECK-NEXT: br [[DONE_DEPTH1:bb[0-9]+]]
//
// Set X := some(OOB).
// CHECK: [[DONE_DEPTH1]]
// CHECK-NEXT: enum $Optional<Optional<Optional<B>>>, #Optional.some!enumelt.1,
// CHECK: br [[DONE_DEPTH2:bb[0-9]+]]
// CHECK: [[DONE_DEPTH2]]
// CHECK-NEXT: destroy_value [[X]]
// CHECK-NOT: destroy_value %0
// CHECK: return
//
// On various failure paths, set OOB := nil.
// CHECK: [[NIL_DEPTH_4]]:
// CHECK-NEXT: enum $Optional<B>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE_DEPTH0]]
//
// CHECK: [[NIL_DEPTH_3]]:
// CHECK-NEXT: enum $Optional<Optional<B>>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE_DEPTH1]]
//
// On various failure paths, set X := nil.
// CHECK: [[FINISH_NIL_0]]:
// CHECK-NEXT: inject_enum_addr [[PB]] {{.*}}none
// CHECK-NEXT: br [[DONE_DEPTH2]]
// Done.
func bar(_ y : A????) {
var x = (y as? B??)
}
// CHECK-LABEL: sil hidden @$s4main3bazyyyXlSgF : $@convention(thin) (@guaranteed Optional<AnyObject>) -> () {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<AnyObject>):
// CHECK: [[X:%.*]] = alloc_box ${ var Optional<B> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: switch_enum [[ARG_COPY]]
// CHECK: bb1([[VAL:%.*]] : @owned $AnyObject):
// CHECK-NEXT: [[X_VALUE:%.*]] = init_enum_data_addr [[PB]] : $*Optional<B>, #Optional.some
// CHECK-NEXT: checked_cast_br [[VAL]] : $AnyObject to $B, [[IS_B:bb.*]], [[NOT_B:bb[0-9]+]]
// CHECK: [[IS_B]]([[CASTED_VALUE:%.*]] : @owned $B):
// CHECK: store [[CASTED_VALUE]] to [init] [[X_VALUE]]
// CHECK: [[NOT_B]]([[ORIGINAL_VALUE:%.*]] : @owned $AnyObject):
// CHECK: destroy_value [[ORIGINAL_VALUE]]
// CHECK: } // end sil function '$s4main3bazyyyXlSgF'
func baz(_ y : AnyObject?) {
var x = (y as? B)
}
// <rdar://problem/17013042> T! <-> T? conversions should not produce a diamond
// CHECK-LABEL: sil hidden @$s4main07opt_to_B8_trivialySiSgACF
// CHECK: bb0(%0 : @trivial $Optional<Int>):
// CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "x"
// CHECK-NEXT: return %0 : $Optional<Int>
// CHECK-NEXT:}
func opt_to_opt_trivial(_ x: Int?) -> Int! {
return x
}
// CHECK-LABEL: sil hidden @$s4main07opt_to_B10_referenceyAA1CCSgAEF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Optional<C>):
// CHECK: debug_value [[ARG]] : $Optional<C>, let, name "x"
// CHECK: [[RESULT:%.*]] = copy_value [[ARG]]
// CHECK-NOT: destroy_value [[ARG]]
// CHECK: return [[RESULT]] : $Optional<C>
// CHECK: } // end sil function '$s4main07opt_to_B10_referenceyAA1CCSgAEF'
func opt_to_opt_reference(_ x : C!) -> C? { return x }
// CHECK-LABEL: sil hidden @$s4main07opt_to_B12_addressOnly{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*Optional<T>, %1 : @trivial $*Optional<T>):
// CHECK-NEXT: debug_value_addr %1 : $*Optional<T>, let, name "x"
// CHECK-NEXT: copy_addr %1 to [initialization] %0
// CHECK-NOT: destroy_addr %1
func opt_to_opt_addressOnly<T>(_ x : T!) -> T? { return x }
class C {}
public struct TestAddressOnlyStruct<T> {
func f(_ a : T?) {}
// CHECK-LABEL: sil hidden @$s4main21TestAddressOnlyStructV8testCall{{[_0-9a-zA-Z]*}}F
// CHECK: bb0(%0 : @trivial $*Optional<T>, %1 : @trivial $TestAddressOnlyStruct<T>):
// CHECK: apply {{.*}}<T>(%0, %1)
func testCall(_ a : T!) {
f(a)
}
}
// CHECK-LABEL: sil hidden @$s4main35testContextualInitOfNonAddrOnlyTypeyySiSgF
// CHECK: bb0(%0 : @trivial $Optional<Int>):
// CHECK-NEXT: debug_value %0 : $Optional<Int>, let, name "a"
// CHECK-NEXT: [[X:%.*]] = alloc_box ${ var Optional<Int> }, var, name "x"
// CHECK-NEXT: [[PB:%.*]] = project_box [[X]]
// CHECK-NEXT: store %0 to [trivial] [[PB]] : $*Optional<Int>
// CHECK-NEXT: destroy_value [[X]] : ${ var Optional<Int> }
func testContextualInitOfNonAddrOnlyType(_ a : Int?) {
var x: Int! = a
}
| 29d392a618680945a3ff9d9cf893c8b7 | 41.691176 | 165 | 0.581123 | false | false | false | false |
icylydia/PlayWithLeetCode | refs/heads/master | 198. House Robber/solution.swift | mit | 1 | class Solution {
func rob(nums: [Int]) -> Int {
if nums.count == 0 {
return 0
}
var maxRob = [nums[0]]
var maxNon = [0]
if nums.count > 1 {
for i in 1..<nums.count {
let rob = maxNon.last! + nums[i]
let non = max(maxRob.last!, maxNon.last!)
maxRob.append(rob)
maxNon.append(non)
}
}
return max(maxRob.last!, maxNon.last!)
}
} | 1700f7949b16c3e24f9d95d725c9c0f4 | 24.555556 | 51 | 0.457516 | false | false | false | false |
Pursuit92/antlr4 | refs/heads/master | runtime/Swift/Antlr4/org/antlr/v4/runtime/misc/extension/CharacterExtension.swift | bsd-3-clause | 3 | /* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
//
// CharacterEextension.swift
// Antlr.swift
//
// Created by janyou on 15/9/4.
//
import Foundation
extension Character {
//"1" -> 1 "2" -> 2
var integerValue: Int {
return Int(String(self)) ?? 0
}
public init(integerLiteral value: IntegerLiteralType) {
self = Character(UnicodeScalar(value)!)
}
var utf8Value: UInt8 {
for s in String(self).utf8 {
return s
}
return 0
}
var utf16Value: UInt16 {
for s in String(self).utf16 {
return s
}
return 0
}
//char -> int
var unicodeValue: Int {
return Int(String(self).unicodeScalars.first?.value ?? 0)
}
public static var MAX_VALUE: Int {
let c: Character = "\u{FFFF}"
return c.unicodeValue
}
public static var MIN_VALUE: Int {
let c: Character = "\u{0000}"
return c.unicodeValue
}
public static func isJavaIdentifierStart(_ char: Int) -> Bool {
let ch = Character(integerLiteral: char)
return ch == "_" || ch == "$" || ("a" <= ch && ch <= "z")
|| ("A" <= ch && ch <= "Z")
}
public static func isJavaIdentifierPart(_ char: Int) -> Bool {
let ch = Character(integerLiteral: char)
return isJavaIdentifierStart(char) || ("0" <= ch && ch <= "9")
}
public static func toCodePoint(_ high: Int, _ low: Int) -> Int {
let MIN_SUPPLEMENTARY_CODE_POINT = 65536 // 0x010000
let MIN_HIGH_SURROGATE = 0xd800 //"\u{dbff}" //"\u{DBFF}" //"\u{DBFF}"
let MIN_LOW_SURROGATE = 0xdc00 //"\u{dc00}" //"\u{DC00}"
return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT
- (MIN_HIGH_SURROGATE << 10)
- MIN_LOW_SURROGATE)
}
}
| d4e2c8f4df861f0194927aeba4ae82f6 | 25.932432 | 80 | 0.552935 | false | false | false | false |
icepy/AFImageHelper | refs/heads/master | AF+Image+Helper/AF+ImageVIew+Extension.swift | mit | 1 | //
// AF+ImageView+Extension.swift
//
// Version 1.04
//
// Created by Melvin Rivera on 7/23/14.
// Copyright (c) 2014 All Forces. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
extension UIImageView {
func imageFromURL(url: String, placeholder: UIImage, fadeIn: Bool = true, closure: ((image: UIImage?) -> ())? = nil)
{
self.image = UIImage.imageFromURL(url, placeholder: placeholder, shouldCacheImage: true) {
(image: UIImage?) in
if image == nil {
return
}
if fadeIn {
let crossFade = CABasicAnimation(keyPath: "contents")
crossFade.duration = 0.5
crossFade.fromValue = self.image?.CIImage
crossFade.toValue = image!.CGImage
self.layer.addAnimation(crossFade, forKey: "")
}
if let foundClosure = closure {
foundClosure(image: image)
}
self.image = image
}
}
}
| df59b6a1802fb4ae6ff8a53971c293fd | 25.974359 | 120 | 0.548049 | false | false | false | false |
L3-DANT/findme-app | refs/heads/master | Examples/CoreData/Pods/CryptoSwift/Sources/CryptoSwift/CSArrayType+Extensions.swift | mit | 2 | //
// _ArrayType+Extensions.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 08/10/15.
// Copyright © 2015 Marcin Krzyzanowski. All rights reserved.
//
public protocol CSArrayType: _ArrayType {
func cs_arrayValue() -> [Generator.Element]
}
extension Array: CSArrayType {
public func cs_arrayValue() -> [Generator.Element] {
return self
}
}
public extension CSArrayType where Generator.Element == UInt8 {
public func toHexString() -> String {
return self.lazy.reduce("") { $0 + String(format:"%02x", $1) }
}
public func toBase64() -> String? {
guard let bytesArray = self as? [UInt8] else {
return nil
}
return NSData(bytes: bytesArray).base64EncodedStringWithOptions([])
}
public init(base64: String) {
self.init()
guard let decodedData = NSData(base64EncodedString: base64, options: []) else {
return
}
self.appendContentsOf(decodedData.arrayOfBytes())
}
}
public extension CSArrayType where Generator.Element == UInt8 {
public func md5() -> [Generator.Element] {
return Hash.md5(cs_arrayValue()).calculate()
}
public func sha1() -> [Generator.Element] {
return Hash.sha1(cs_arrayValue()).calculate()
}
public func sha224() -> [Generator.Element] {
return Hash.sha224(cs_arrayValue()).calculate()
}
public func sha256() -> [Generator.Element] {
return Hash.sha256(cs_arrayValue()).calculate()
}
public func sha384() -> [Generator.Element] {
return Hash.sha384(cs_arrayValue()).calculate()
}
public func sha512() -> [Generator.Element] {
return Hash.sha512(cs_arrayValue()).calculate()
}
public func crc32(seed: UInt32? = nil) -> [Generator.Element] {
return Hash.crc32(cs_arrayValue(), seed: seed).calculate()
}
public func crc16(seed: UInt16? = nil) -> [Generator.Element] {
return Hash.crc16(cs_arrayValue(), seed: seed).calculate()
}
public func encrypt(cipher: Cipher) throws -> [Generator.Element] {
return try cipher.cipherEncrypt(cs_arrayValue())
}
public func decrypt(cipher: Cipher) throws -> [Generator.Element] {
return try cipher.cipherDecrypt(cs_arrayValue())
}
public func authenticate(authenticator: Authenticator) throws -> [Generator.Element] {
return try authenticator.authenticate(cs_arrayValue())
}
} | dee65714c292f09790092b0914c39b34 | 27.747126 | 90 | 0.6264 | false | false | false | false |
lkzhao/Hero | refs/heads/master | Sources/Transition/HeroTransition+Complete.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// 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.
#if canImport(UIKit)
import UIKit
extension HeroTransition {
open func complete(finished: Bool) {
if state == .notified {
forceFinishing = finished
}
guard state == .animating || state == .starting else { return }
defer {
transitionContext = nil
fromViewController = nil
toViewController = nil
inNavigationController = false
inTabBarController = false
forceNotInteractive = false
animatingToViews.removeAll()
animatingFromViews.removeAll()
progressUpdateObservers = nil
transitionContainer = nil
completionCallback = nil
forceFinishing = nil
container = nil
startingProgress = nil
processors.removeAll()
animators.removeAll()
plugins.removeAll()
context = nil
progress = 0
totalDuration = 0
state = .possible
}
state = .completing
progressRunner.stop()
context.clean()
if let toView = toView, let fromView = fromView {
if finished && isPresenting && toOverFullScreen {
// finished presenting a overFullScreen VC
context.unhide(rootView: toView)
context.removeSnapshots(rootView: toView)
context.storeViewAlpha(rootView: fromView)
fromViewController?.hero.storedSnapshot = container
container.superview?.addSubview(fromView)
fromView.addSubview(container)
} else if !finished && !isPresenting && fromOverFullScreen {
// cancelled dismissing a overFullScreen VC
context.unhide(rootView: fromView)
context.removeSnapshots(rootView: fromView)
context.storeViewAlpha(rootView: toView)
toViewController?.hero.storedSnapshot = container
container.superview?.addSubview(toView)
toView.addSubview(container)
} else {
context.unhideAll()
context.removeAllSnapshots()
}
// move fromView & toView back from our container back to the one supplied by UIKit
if (toOverFullScreen && finished) || (fromOverFullScreen && !finished) {
transitionContainer?.addSubview(finished ? fromView : toView)
}
transitionContainer?.addSubview(finished ? toView : fromView)
if isPresenting != finished, !inContainerController, transitionContext != nil {
// only happens when present a .overFullScreen VC
// bug: http://openradar.appspot.com/radar?id=5320103646199808
container.window?.addSubview(isPresenting ? fromView : toView)
}
}
if container.superview == transitionContainer {
container.removeFromSuperview()
}
for animator in animators {
animator.clean()
}
transitionContainer?.isUserInteractionEnabled = true
completionCallback?(finished)
// https://github.com/lkzhao/Hero/issues/354
// tabbar not responding after pushing a view controller with hideBottomBarWhenPushed
// this is due to iOS adding a few extra animation to the tabbar but they are not removed when
// the transition completes. Possibly another iOS bug. let me know if you have better work around.
if finished {
toViewController?.tabBarController?.tabBar.layer.removeAllAnimations()
} else {
fromViewController?.tabBarController?.tabBar.layer.removeAllAnimations()
}
if finished {
if let fvc = fromViewController, let tvc = toViewController {
closureProcessForHeroDelegate(vc: fvc) {
$0.heroDidEndAnimatingTo?(viewController: tvc)
$0.heroDidEndTransition?()
}
closureProcessForHeroDelegate(vc: tvc) {
$0.heroDidEndAnimatingFrom?(viewController: fvc)
$0.heroDidEndTransition?()
}
}
transitionContext?.finishInteractiveTransition()
} else {
if let fvc = fromViewController, let tvc = toViewController {
closureProcessForHeroDelegate(vc: fvc) {
$0.heroDidCancelAnimatingTo?(viewController: tvc)
$0.heroDidCancelTransition?()
}
closureProcessForHeroDelegate(vc: tvc) {
$0.heroDidCancelAnimatingFrom?(viewController: fvc)
$0.heroDidCancelTransition?()
}
}
transitionContext?.cancelInteractiveTransition()
}
transitionContext?.completeTransition(finished)
}
}
#endif
| 2865aab38d370982fc96c61ecc137819 | 35.489933 | 102 | 0.691558 | false | false | false | false |
BluechipSystems/viper-module-generator | refs/heads/master | VIPERGenDemo/VIPERGenDemo/Shared/Controllers/TwitterLogin/View/TwitterLoginView.swift | mit | 4 | //
// TwitterLoginView.swift
// TwitterLoginGenDemo
//
// Created by AUTHOR on 24/10/14.
// Copyright (c) 2014 AUTHOR. All rights reserved.
//
import Foundation
import UIKit
import MediaPlayer
class TwitterLoginView: TWViewController, TwitterLoginViewProtocol
{
// MARK: - Styles
private struct Styles {
static private let LOGIN_BUTTON_HEITHT: CGFloat = 50
static private let LOGIN_BUTTON_COLOR: UIColor = Stylesheet.COLOR_BLUE_LIGHT
static private let FLOATING_CORNER_RADIUS: CGFloat = 10
static private let FLOATING_HEIGHT_PERCENTAGE: CGFloat = 0.3
static private let FLOATING_WIDTH_PERCENTAGE: CGFloat = 0.8
static private let LOGO_SIZE: CGFloat = 80
static private let MARGIN_20: CGFloat = 20
}
// MARK: - Attributes
var presenter: TwitterLoginPresenterProtocol?
lazy var backgroundVideoPlayer: MPMoviePlayerController = {
var moviePlayer = MPMoviePlayerController(contentURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("video", ofType: "mp4")!))
moviePlayer.controlStyle = MPMovieControlStyle.None
moviePlayer.repeatMode = MPMovieRepeatMode.One
moviePlayer.scalingMode = MPMovieScalingMode.AspectFill
return moviePlayer
}()
lazy var logoImageView: UIImageView = UIImageView()
lazy var loginButton: UIButton = {
var button = UIButton()
button.backgroundColor = Styles.LOGIN_BUTTON_COLOR
return button
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
self.setupSubviews()
self.setupConstraints()
self.setNeedsStatusBarAppearanceUpdate()
self.presenter?.viewDidLoad()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.backgroundVideoPlayer.stop()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.backgroundVideoPlayer.play()
}
// MARK: - Subviews
/**
Setup subviews and add them to the main View
*/
private func setupSubviews()
{
self.backgroundVideoPlayer.play()
self.view.addSubview(self.backgroundVideoPlayer.view)
self.view.addSubview(self.loginButton)
self.loginButton.addTarget(self, action: Selector("userDidSelectLogin:"), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(self.logoImageView)
}
/**
Add Autolayouts constraints to subviews
*/
private func setupConstraints()
{
self.backgroundVideoPlayer.view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.backgroundVideoPlayer.view.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsZero)
self.loginButton.setTranslatesAutoresizingMaskIntoConstraints(false)
self.loginButton.autoMatchDimension(ALDimension.Width, toDimension: ALDimension.Width, ofView: self.view, withMultiplier: 0.8)
self.loginButton.autoSetDimension(ALDimension.Height, toSize: Styles.LOGIN_BUTTON_HEITHT)
self.loginButton.autoCenterInSuperview()
self.logoImageView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.logoImageView.autoSetDimension(ALDimension.Height, toSize: Styles.LOGO_SIZE)
self.logoImageView.autoSetDimension(ALDimension.Width, toSize: Styles.LOGO_SIZE)
self.logoImageView.autoAlignAxis(ALAxis.Vertical, toSameAxisOfView: self.loginButton)
self.logoImageView.autoPinEdge(ALEdge.Bottom, toEdge: ALEdge.Top, ofView: self.loginButton, withOffset: -Styles.MARGIN_20)
}
// MARK: - TwitterLoginViewProtocol
func setLoginTitle(let title: String)
{
self.loginButton.setTitle(title, forState: UIControlState.Normal)
}
func setLogo(let image: UIImage)
{
self.logoImageView.image = image
self.logoImageView.tintColor = UIColor.whiteColor()
}
func showError(let errorMessage: String)
{
ProgressHUD.showError(errorMessage)
}
func showLoading()
{
ProgressHUD.show("")
}
func hideLoading()
{
ProgressHUD.dismiss()
}
// MARK: Actions
/**
Notifies the selector about the user's action
*/
func userDidSelectLogin(sender: AnyObject)
{
self.presenter?.userDidSelectLogin()
}
// MARK: - Status Bar
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
} | d83221b7c4db1572e73d12e35eb8e7ca | 31.34507 | 149 | 0.685976 | false | false | false | false |
buckstephenh/Morsey | refs/heads/master | Morsey/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// Morsey
//
// Created by Stephen Buck on 7/22/16.
// Copyright © 2016 Stephen Buck. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.buckstephenh.Morsey" in the application's documents Application Support directory.
let urls = FileManager.default.urlsForDirectory(.documentDirectory, inDomains: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.urlForResource("Morsey", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = try! self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bc98b69bf975ec34645d01da6d8da26d | 53.774775 | 291 | 0.716941 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift | mit | 12 | //
// SerialDispatchQueueScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure
that even if concurrent dispatch queue is passed, it's transformed into a serial one.
It is extremely important that this scheduler is serial, because
certain operator perform optimizations that rely on that property.
Because there is no way of detecting is passed dispatch queue serial or
concurrent, for every queue that is being passed, worst case (concurrent)
will be assumed, and internal serial proxy dispatch queue will be created.
This scheduler can also be used with internal serial queue alone.
In case some customization need to be made on it before usage,
internal serial queue can be customized using `serialQueueConfiguration`
callback.
*/
public class SerialDispatchQueueScheduler : SchedulerType {
public typealias TimeInterval = Foundation.TimeInterval
public typealias Time = Date
/**
- returns: Current time.
*/
public var now : Date {
return Date()
}
let configuration: DispatchQueueConfiguration
init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`.
Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`.
- parameter internalSerialQueueName: Name of internal serial dispatch queue.
- parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue.
*/
public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
let queue = DispatchQueue(label: internalSerialQueueName, attributes: [])
serialQueueConfiguration?(queue)
self.init(serialQueue: queue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`.
- parameter queue: Possibly concurrent dispatch queue used to perform work.
- parameter internalSerialQueueName: Name of internal serial dispatch queue proxy.
*/
public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
// Swift 3.0 IUO
let serialQueue = DispatchQueue(label: internalSerialQueueName,
attributes: [],
target: queue)
self.init(serialQueue: serialQueue, leeway: leeway)
}
/**
Constructs new `SerialDispatchQueueScheduler` that wraps on of the global concurrent dispatch queues.
- parameter globalConcurrentQueueQOS: Identifier for global dispatch queue with specified quality of service class.
- parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy.
*/
@available(iOS 8, OSX 10.10, *)
public convenience init(globalConcurrentQueueQOS: DispatchQueueSchedulerQOS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) {
let priority = globalConcurrentQueueQOS.qos
self.init(queue: DispatchQueue.global(qos: priority.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway)
}
/**
Schedules an action to be executed immediatelly.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.scheduleInternal(state, action: action)
}
func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.configuration.schedule(state, action: action)
}
/**
Schedules an action to be executed.
- parameter state: State passed to the action to be executed.
- parameter dueTime: Relative time after which to execute the action.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public final func scheduleRelative<StateType>(_ state: StateType, dueTime: Foundation.TimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable {
return self.configuration.scheduleRelative(state, dueTime: dueTime, action: action)
}
/**
Schedules a periodic piece of work.
- parameter state: State passed to the action to be executed.
- parameter startAfter: Period after which initial work should be run.
- parameter period: Period for running the work periodically.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedulePeriodic<StateType>(_ state: StateType, startAfter: TimeInterval, period: TimeInterval, action: @escaping (StateType) -> StateType) -> Disposable {
return self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action)
}
}
| 9e3dba81518256f986df27c509fe66e5 | 45.290323 | 219 | 0.728223 | false | true | false | false |
petrmanek/revolver | refs/heads/master | Sources/MersenneTwister.swift | mit | 1 | /*
Not original code! (thankfully - who would bother reimplementing this?)
- attribution goes to: Kai Wells, http://kaiwells.me
- see Squall: https://github.com/quells/Squall/blob/master/Sources/Mersenne.swift
--
*/
/// Multiply two `UInt32`'s and discard the overflow.
///
fileprivate func discardMultiply(_ a: UInt32, _ b: UInt32) -> UInt32 {
let ah = UInt64(a & 0xFFFF0000) >> 16
let al = UInt64(a & 0x0000FFFF)
let bh = UInt64(b & 0xFFFF0000) >> 16
let bl = UInt64(b & 0x0000FFFF)
// Most significant bits overflow anyways, so don't bother
// let F = ah * bh
let OI = ah * bl + al * bh
let L = al * bl
let result = (((OI << 16) & 0xFFFFFFFF) + L) & 0xFFFFFFFF
return UInt32(result)
}
/// Generates pseudo-random `UInt32`'s.
///
/// Uses the Mersenne Twister PRNG algorithm described [here](https://en.wikipedia.org/wiki/Mersenne_Twister).
///
open class MersenneTwister: EntropyGenerator {
internal typealias Element = Double
// Magic numbers
private let (w, n, m, r): (UInt32, Int, Int, UInt32) = (32, 624, 397, 31)
private let a: UInt32 = 0x9908B0DF
private let (u, d): (UInt32, UInt32) = (11, 0xFFFFFFFF)
private let (s, b): (UInt32, UInt32) = ( 7, 0x9D2C5680)
private let (t, c): (UInt32, UInt32) = (15, 0xEFC60000)
private let l: UInt32 = 18
private let f: UInt32 = 1812433253
/// The maximum value an `UInt32` may take.
///
internal let maxValue: UInt32 = 4294967295
private var state: [UInt32]
private var index = 0
/// Initialize the internal state of the generator.
///
/// - parameter seed: The value used to generate the intial state. Should be chosen at random.
init(seed: UInt32 = 5489) {
var x = [seed]
for i in 1..<n {
let prev = x[i-1]
let c = discardMultiply(f, prev ^ (prev >> (w-2))) + UInt32(i)
x.append(c)
}
self.state = x
}
/// Puts the twist in Mersenne Twister.
///
private func twist() {
for i in 0..<n {
let x = (state[i] & 0xFFFF0000) + ((state[(i+1) % n] % UInt32(n)) & 0x0000FFFF)
var xA = x >> 1
if (x % 2 != 0) {
xA = xA ^ a
}
state[i] = state[(i + m) % n] ^ xA
index = 0
}
}
/// Provides the next `Double` in the sequence.
///
/// Also modifies the internal state state array, twisting if necessary.
///
open func next() -> Double {
if self.index > n { fatalError("Generator never seeded") }
if self.index == n { self.twist() }
var y = state[index]
y = y ^ ((y >> u) & d)
y = y ^ ((y << s) & b)
y = y ^ ((y << t) & c)
y = y ^ (y >> 1)
index += 1
return Double(y) / Double(UInt32.max)
}
}
| d724e54cbff7bfc54e6b3c22a4b49fac | 30.391304 | 110 | 0.54536 | false | false | false | false |
russbishop/swift | refs/heads/master | benchmark/single-source/DictionarySwap.swift | apache-2.0 | 1 | //===--- DictionarySwap.swift ---------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Dictionary element swapping benchmark
// rdar://problem/19804127
import TestsUtils
@inline(never)
public func run_DictionarySwap(_ N: Int) {
let size = 100
var dict = [Int: Int](minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[i] = i
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var swapped = false
for _ in 1...10000*N {
swap(&dict[25]!, &dict[75]!)
swapped = !swapped
if !swappedCorrectly(swapped, dict[25]!, dict[75]!) {
break
}
}
CheckResults(swappedCorrectly(swapped, dict[25]!, dict[75]!),
"Dictionary value swap failed")
}
// Return true if correctly swapped, false otherwise
func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
return swapped && (p25 == 75 && p75 == 25) ||
!swapped && (p25 == 25 && p75 == 75)
}
class Box<T : Hashable where T : Equatable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
}
extension Box : Equatable {
}
func ==<T: Equatable>(lhs: Box<T>, rhs: Box<T>) -> Bool {
return lhs.value == rhs.value
}
@inline(never)
public func run_DictionarySwapOfObjects(_ N: Int) {
let size = 100
var dict = Dictionary<Box<Int>, Box<Int>>(minimumCapacity: size)
// Fill dictionary
for i in 1...size {
dict[Box(i)] = Box(i)
}
CheckResults(dict.count == size,
"Incorrect dict count: \(dict.count) != \(size).")
var swapped = false
for _ in 1...10000*N {
swap(&dict[Box(25)]!, &dict[Box(75)]!)
swapped = !swapped
if !swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value) {
break
}
}
CheckResults(swappedCorrectly(swapped, dict[Box(25)]!.value, dict[Box(75)]!.value),
"Dictionary value swap failed")
}
| f0e58e9a5ac9daa299a16eb3ba9643bf | 26.611111 | 87 | 0.565392 | false | false | false | false |
ustwo/baseviewcontroller-swift | refs/heads/master | Example/ProfileView.swift | mit | 1 | //
// View.swift
// BaseViewControllerSwift
//
// Created by Aaron McTavish on 06/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import UIKit
final class ProfileView: UIView {
// MARK: - Properties
let titleLabel = UILabel()
let profileImage = UIImageView()
let finishedButton = UIButton(type: .system)
fileprivate let stackView = UIStackView()
// MARK: - Initializers
convenience init() {
self.init(frame: CGRect.zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.white
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1)
stackView.addArrangedSubview(titleLabel)
profileImage.contentMode = .scaleAspectFit
stackView.addArrangedSubview(profileImage)
finishedButton.setTitle(NSLocalizedString("Finished", comment: ""), for: UIControl.State())
stackView.addArrangedSubview(finishedButton)
stackView.axis = .vertical
stackView.distribution = .fill
stackView.alignment = .center
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([
stackView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
stackView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor)
])
} else {
addConstraint(NSLayoutConstraint(item: stackView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: stackView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0.0))
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| a06ee3298c7bdb2f101debdeddb910e5 | 36.072464 | 171 | 0.661063 | false | false | false | false |
yoonhg84/CPAdManager-iOS | refs/heads/master | Source/Native/CPFacebookNativeAd.swift | mit | 1 | //
// Created by Chope on 2017. 6. 1..
// Copyright (c) 2017 ChopeIndustry. All rights reserved.
//
import UIKit
import FBAudienceNetwork
open class CPFacebookNativeAd: CPNativeAd {
public override var identifier: String {
return "Facebook"
}
fileprivate weak var delegate: CPNativeAdDelegate?
fileprivate weak var viewController: UIViewController?
fileprivate var adView: FBNativeAdView?
fileprivate var adViewType: FBNativeAdViewType
private let placementId: String
public init(placementId: String, adViewType: FBNativeAdViewType = .genericHeight100) {
self.placementId = placementId
self.adViewType = adViewType
}
override func request(in viewController: UIViewController) {
self.viewController = viewController
let nativeAd = FBNativeAd(placementID: placementId)
nativeAd.delegate = self
nativeAd.load()
}
override func set(delegate: CPNativeAdDelegate) {
self.delegate = delegate
}
public override func nativeView() -> UIView? {
return adView
}
}
extension CPFacebookNativeAd: FBNativeAdDelegate {
public func nativeAdDidLoad(_ nativeAd: FBNativeAd) {
guard let viewController = viewController else { return }
let adView = FBNativeAdView(nativeAd: nativeAd, with: adViewType)
nativeAd.registerView(forInteraction: adView, with: viewController)
adView.frame.size.height = {
switch adViewType {
case .genericHeight100:
return 100
case .genericHeight120:
return 120
case .genericHeight300:
return 300
case .genericHeight400:
return 400
}
}()
self.adView = adView
delegate?.onLoaded(nativeAd: self)
}
public func nativeAd(_ nativeAd: FBNativeAd, didFailWithError error: Error) {
delegate?.onFailedToLoad(nativeAd: self, error: error)
}
}
| 4936cd4654739149a4068395bc0b4839 | 27.253521 | 90 | 0.654536 | false | false | false | false |
nheagy/WordPress-iOS | refs/heads/develop | WordPress/Classes/Extensions/Notifications/NotificationBlock+Interface.swift | gpl-2.0 | 1 | import Foundation
import WordPressShared.WPStyleGuide
/**
* @extension NotificationBlock
*
* @brief This class extension implements helper methods to aid formatting a NotificationBlock's
* payload, for usage in several different spots of the app.
*
* @details The main goal of this helper Extension is to encapsulate presentation details into a
single piece of code, while preserving a clear sepparation with the Model itself.
We rely on a cache mechanism, implemented for performance purposes, that will get nuked
whenever the related Notification object gets updated.
*/
extension NotificationBlock
{
// MARK: - Public Methods
//
/**
* @brief Formats a NotificationBlock for usage in NoteTableViewCell, in the subject field
*
* @returns A Subject Attributed String
*/
public func attributedSubjectText() -> NSAttributedString {
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.subjectRegularStyle,
quoteStyles: Styles.subjectItalicsStyle,
rangeStylesMap: Constants.subjectRangeStylesMap,
linksColor: nil)
}
return attributedText(Constants.richSubjectCacheKey)
}
/**
* @brief Formats a NotificationBlock for usage in NoteTableViewCell, in the snippet field
*
* @returns A Snippet Attributed String
*/
public func attributedSnippetText() -> NSAttributedString {
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.snippetRegularStyle,
quoteStyles: nil,
rangeStylesMap: nil,
linksColor: nil)
}
return attributedText(Constants.richSnippetCacheKey)
}
/**
* @brief Formats a NotificationBlock for usage in NoteBlockHeaderTableViewCell
*
* @returns A Header Attributed String
*/
public func attributedHeaderTitleText() -> NSAttributedString {
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.headerTitleRegularStyle,
quoteStyles: nil,
rangeStylesMap: Constants.headerTitleRangeStylesMap,
linksColor: nil)
}
return attributedText(Constants.richHeaderTitleCacheKey)
}
/**
* @brief Formats a NotificationBlock for usage in NoteBlockFooterTableViewCell
*
* @returns A Header Attributed String
*/
public func attributedFooterText() -> NSAttributedString {
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.footerRegularStyle,
quoteStyles: nil,
rangeStylesMap: Constants.footerStylesMap,
linksColor: nil)
}
return attributedText(Constants.richHeaderTitleCacheKey)
}
/**
* @brief Formats a NotificationBlock for usage into both, NoteBlockTextTableViewCell
* and NoteBlockCommentTableViewCell.
*
* @returns An Attributed String for usage in both, comments and cell cells
*/
public func attributedRichText() -> NSAttributedString {
// Operations such as editing a comment cause a lag between the REST and Simperium update.
// TextOverride is a transient property meant to store, temporarily, the edited text
if textOverride != nil {
return NSAttributedString(string: textOverride, attributes: Styles.contentBlockRegularStyle)
}
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.contentBlockRegularStyle,
quoteStyles: Styles.contentBlockBoldStyle,
rangeStylesMap: Constants.richRangeStylesMap,
linksColor: Styles.blockLinkColor)
}
return attributedText(Constants.richTextCacheKey)
}
/**
* @brief Formats a NotificationBlock for usage into Badge-Type notifications. This contains
* custom formatting that differs from regular notifications, such as centered texts.
*
* @returns An Attributed String for usage in Badge Notifications
*/
public func attributedBadgeText() -> NSAttributedString {
let attributedText = memoize { () -> NSAttributedString in
return self.textWithStyles(Styles.badgeRegularStyle,
quoteStyles: Styles.badgeBoldStyle,
rangeStylesMap: Constants.badgeRangeStylesMap,
linksColor: Styles.badgeLinkColor)
}
return attributedText(Constants.richBadgeCacheKey)
}
/**
* @brief Given a set of URL's and the Images they reference to, this method will return a Dictionary
* with the NSRange's in which the given UIImage's should be injected
* @details This is used to build an Attributed String containing inline images.
*
* @param mediaMap A Dictionary mapping asset URL's to the already-downloaded assets
*
* @returns A Dictionary mapping Text-Ranges in which the UIImage's should be applied
*/
public func buildRangesToImagesMap(mediaMap: [NSURL: UIImage]?) -> [NSValue: UIImage]? {
// If we've got a text override: Ranges may not match, and the new text may not even contain ranges!
if mediaMap == nil || textOverride != nil {
return nil
}
var ranges = [NSValue: UIImage]()
for theMedia in media as! [NotificationMedia] {
// Failsafe: if the mediaURL couldn't be parsed, don't proceed
if theMedia.mediaURL == nil {
continue
}
if let image = mediaMap![theMedia.mediaURL] {
let rangeValue = NSValue(range: theMedia.range)
ranges[rangeValue] = image
}
}
return ranges
}
// MARK: - Private Helpers
//
/**
* @brief This method is meant to aid cache-implementation into all of the AttriutedString getters
* introduced in this extension.
*
* @param fn A Closure that, on execution, returns an attributed string.
* @returns A new Closure that on execution will either hit the cache, or execute the closure `fn`
* and store its return value in the cache.
*/
private func memoize(fn: () -> NSAttributedString) -> String -> NSAttributedString {
return {
(cacheKey : String) -> NSAttributedString in
// Is it already cached?
if let cachedSubject = self.cacheValueForKey(cacheKey) as? NSAttributedString {
return cachedSubject
}
// Store in Cache
let newValue = fn()
self.setCacheValue(newValue, forKey: cacheKey)
return newValue
}
}
/**
* @brief This method is an all-purpose helper to aid formatting the NotificationBlock's payload text.
*
* @param attributes Represents the attributes to be applied, initially, to the Text.
* @param quoteStyles The Styles to be applied to "any quoted text"
* @param rangeStylesMap A Dictionary object mapping NotificationBlock types to a dictionary of styles
* to be applied.
* @param linksColor The color that should be used on any links contained.
* @returns A NSAttributedString instance, formatted with all of the specified parameters
*/
private func textWithStyles(attributes : [String: AnyObject],
quoteStyles : [String: AnyObject]?,
rangeStylesMap : [String: AnyObject]?,
linksColor : UIColor?) -> NSAttributedString
{
// Is it empty?
if text == nil {
return NSAttributedString()
}
// Format the String
let theString = NSMutableAttributedString(string: text, attributes: attributes)
// Apply Quotes Styles
if let unwrappedQuoteStyles = quoteStyles {
theString.applyAttributesToQuotes(unwrappedQuoteStyles)
}
// Apply the Ranges
var lengthShift = 0
for range in ranges as! [NotificationRange] {
var shiftedRange = range.range
shiftedRange.location += lengthShift
if range.isNoticon {
let noticon = "\(range.value) "
theString.replaceCharactersInRange(shiftedRange, withString: noticon)
lengthShift += noticon.characters.count
shiftedRange.length += noticon.characters.count
}
if let unwrappedRangeStyle = rangeStylesMap?[range.type] as? [String: AnyObject] {
theString.addAttributes(unwrappedRangeStyle, range: shiftedRange)
}
if range.url != nil && linksColor != nil {
theString.addAttribute(NSLinkAttributeName, value: range.url, range: shiftedRange)
theString.addAttribute(NSForegroundColorAttributeName, value: linksColor!, range: shiftedRange)
}
}
return theString
}
// MARK: - Constants
//
private struct Constants {
static let subjectRangeStylesMap = [
NoteRangeTypeUser : Styles.subjectBoldStyle,
NoteRangeTypePost : Styles.subjectItalicsStyle,
NoteRangeTypeComment : Styles.subjectItalicsStyle,
NoteRangeTypeBlockquote : Styles.subjectQuotedStyle,
NoteRangeTypeNoticon : Styles.subjectNoticonStyle
]
static let headerTitleRangeStylesMap = [
NoteRangeTypeUser : Styles.headerTitleBoldStyle,
NoteRangeTypePost : Styles.headerTitleContextStyle,
NoteRangeTypeComment : Styles.headerTitleContextStyle
]
static let footerStylesMap = [
NoteRangeTypeNoticon : Styles.blockNoticonStyle
]
static let richRangeStylesMap = [
NoteRangeTypeBlockquote : Styles.contentBlockQuotedStyle,
NoteRangeTypeNoticon : Styles.blockNoticonStyle,
NoteRangeTypeMatch : Styles.contentBlockMatchStyle
]
static let badgeRangeStylesMap = [
NoteRangeTypeUser : Styles.badgeBoldStyle,
NoteRangeTypePost : Styles.badgeItalicsStyle,
NoteRangeTypeComment : Styles.badgeItalicsStyle,
NoteRangeTypeBlockquote : Styles.badgeQuotedStyle
]
static let richSubjectCacheKey = "richSubjectCacheKey"
static let richSnippetCacheKey = "richSnippetCacheKey"
static let richHeaderTitleCacheKey = "richHeaderTitleCacheKey"
static let richTextCacheKey = "richTextCacheKey"
static let richBadgeCacheKey = "richBadgeCacheKey"
}
private typealias Styles = WPStyleGuide.Notifications
}
| d0c067d1a4a720bd0dc26692e7e9e40e | 40.045936 | 113 | 0.605802 | false | false | false | false |
PseudoSudoLP/Bane | refs/heads/master | Carthage/Checkouts/Moya/Demo/Demo/ViewController.swift | mit | 1 | //
// ViewController.swift
// Demo
//
// Created by Ash Furrow on 2014-11-16.
// Copyright (c) 2014 Ash Furrow. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var repos = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
downloadRepositories("ashfurrow")
}
// MARK: - API Stuff
func downloadRepositories(username: String) {
GitHubProvider.request(.UserRepositories(username), completion: { (data, status, resonse, error) -> () in
var success = error == nil
if let data = data {
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
if let json = json as? NSArray {
// Presumably, you'd parse the JSON into a model object. This is just a demo, so we'll keep it as-is.
self.repos = json
} else {
success = false
}
self.tableView.reloadData()
} else {
success = false
}
if !success {
let alertController = UIAlertController(title: "GitHub Fetch", message: error?.description, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(ok)
self.presentViewController(alertController, animated: true, completion: nil)
}
})
}
func downloadZen() {
GitHubProvider.request(.Zen, completion: { (data, status, response, error) -> () in
var message = "Couldn't access API"
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String ?? message
}
let alertController = UIAlertController(title: "Zen", message: message, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(ok)
self.presentViewController(alertController, animated: true, completion: nil)
})
}
// MARK: - User Interaction
@IBAction func searchWasPressed(sender: UIBarButtonItem) {
var usernameTextField: UITextField?
let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
if let usernameTextField = usernameTextField {
self.downloadRepositories(usernameTextField.text)
}
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
}
promptController.addAction(ok)
promptController.addTextFieldWithConfigurationHandler { (textField) -> Void in
usernameTextField = textField
}
presentViewController(promptController, animated: true, completion: nil)
}
@IBAction func zenWasPressed(sender: UIBarButtonItem) {
downloadZen()
}
// MARK: - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return repos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let object = repos[indexPath.row] as! NSDictionary
(cell.textLabel as UILabel!).text = object["name"] as? String
return cell
}
}
| 9decc2eec9370c34d506f0c8e148d186 | 36.625 | 131 | 0.611807 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripePayments/StripePayments/API Bindings/Models/Sources/STPSourceParams.swift | mit | 1 | //
// STPSourceParams.swift
// StripePayments
//
// Created by Ben Guo on 1/23/17.
// Copyright © 2017 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCore
/// An object representing parameters used to create a Source object.
/// - seealso: https://stripe.com/docs/api#create_source
public class STPSourceParams: NSObject, STPFormEncodable, NSCopying {
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
var redirectMerchantName: String?
/// The type of the source to create. Required.
@objc public var type: STPSourceType {
get {
return STPSource.type(from: rawTypeString ?? "")
}
set(type) {
// If setting unknown and we're already unknown, don't want to override raw value
if type != self.type {
rawTypeString = STPSource.string(from: type)
}
}
}
/// The raw underlying type string sent to the server.
/// Generally you should use `type` instead unless you have a reason not to.
/// You can use this if you want to create a param of a type not yet supported
/// by the current version of the SDK's `STPSourceType` enum.
/// Setting this to a value not known by the SDK causes `type` to
/// return `STPSourceTypeUnknown`
@objc public var rawTypeString: String?
/// A positive integer in the smallest currency unit representing the
/// amount to charge the customer (e.g., @1099 for a €10.99 payment).
/// Required for `single_use` sources.
@objc public var amount: NSNumber?
/// The currency associated with the source. This is the currency for which the source
/// will be chargeable once ready.
@objc public var currency: String?
/// The authentication flow of the source to create. `flow` may be "redirect",
/// "receiver", "verification", or "none". It is generally inferred unless a type
/// supports multiple flows.
@objc public var flow: STPSourceFlow
/// A set of key/value pairs that you can attach to a source object.
@objc public var metadata: [AnyHashable: Any]?
/// Information about the owner of the payment instrument. May be used or required
/// by particular source types.
@objc public var owner: [AnyHashable: Any]?
/// Parameters required for the redirect flow. Required if the source is
/// authenticated by a redirect (`flow` is "redirect").
@objc public var redirect: [AnyHashable: Any]?
/// An optional token used to create the source. When passed, token properties will
/// override source parameters.
@objc public var token: String?
/// Whether this source should be reusable or not. `usage` may be "reusable" or
/// "single_use". Some source types may or may not be reusable by construction,
/// while other may leave the option at creation.
@objc public var usage: STPSourceUsage
/// Initializes an empty STPSourceParams.
override public required init() {
rawTypeString = ""
flow = .unknown
usage = .unknown
additionalAPIParameters = [:]
super.init()
}
}
// MARK: - Constructors
extension STPSourceParams {
/// Creates params for a Bancontact source.
/// - seealso: https://stripe.com/docs/payments/bancontact#create-source
/// - Parameters:
/// - amount: The amount to charge the customer in EUR.
/// - name: The full name of the account holder.
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - statementDescriptor: (Optional) A custom statement descriptor for
/// the payment.
/// @note The currency for Bancontact must be "eur". This will be set automatically
/// for you.
/// - Returns: an STPSourceParams object populated with the provided values.
@objc
public class func bancontactParams(
withAmount amount: Int,
name: String,
returnURL: String,
statementDescriptor: String?
) -> STPSourceParams {
let params = self.init()
params.type = .bancontact
params.amount = NSNumber(value: amount)
params.currency = "eur" // Bancontact must always use eur
params.owner = [
"name": name
]
params.redirect = [
"return_url": returnURL
]
if let statementDescriptor = statementDescriptor {
params.additionalAPIParameters = [
"bancontact": [
"statement_descriptor": statementDescriptor
]
]
}
return params
}
/// Creates params for a Card source.
/// - seealso: https://stripe.com/docs/sources/cards#create-source
/// - Parameter card: An object containing the user's card details
/// - Returns: an STPSourceParams object populated with the provided card details.
@objc
public class func cardParams(withCard card: STPCardParams) -> STPSourceParams {
let params = self.init()
params.type = .card
let keyPairs = STPFormEncoder.dictionary(forObject: card)["card"] as? [AnyHashable: Any]
var cardDict: [AnyHashable: Any] = [:]
let cardKeys = ["number", "cvc", "exp_month", "exp_year"]
for key in cardKeys {
if let keyPair = keyPairs?[key] {
cardDict[key] = keyPair
}
}
params.additionalAPIParameters = [
"card": cardDict
]
var addressDict: [AnyHashable: Any] = [:]
let addressKeyMapping = [
"address_line1": "line1",
"address_line2": "line2",
"address_city": "city",
"address_state": "state",
"address_zip": "postal_code",
"address_country": "country",
]
for key in addressKeyMapping.keys {
if let newKey = addressKeyMapping[key],
let keyPair = keyPairs?[key]
{
addressDict[newKey] = keyPair
}
}
var ownerDict: [AnyHashable: Any] = [:]
ownerDict["address"] = addressDict
ownerDict["name"] = card.name
params.owner = ownerDict
return params
}
/// Creates params for a Giropay source.
/// - seealso: https://stripe.com/docs/sources/giropay#create-source
/// - Parameters:
/// - amount: The amount to charge the customer in EUR.
/// - name: The full name of the account holder.
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - statementDescriptor: (Optional) A custom statement descriptor for
/// the payment.
/// @note The currency for Giropay must be "eur". This will be set automatically
/// for you.
/// - Returns: an STPSourceParams object populated with the provided values.
@objc
public class func giropayParams(
withAmount amount: Int,
name: String,
returnURL: String,
statementDescriptor: String?
) -> STPSourceParams {
let params = self.init()
params.type = .giropay
params.amount = NSNumber(value: amount)
params.currency = "eur" // Giropay must always use eur
params.owner = [
"name": name
]
params.redirect = [
"return_url": returnURL
]
if let statementDescriptor = statementDescriptor {
params.additionalAPIParameters = [
"giropay": [
"statement_descriptor": statementDescriptor
]
]
}
return params
}
/// Creates params for an iDEAL source.
/// - seealso: https://stripe.com/docs/sources/ideal#create-source
/// - Parameters:
/// - amount: The amount to charge the customer in EUR.
/// - name: (Optional) The full name of the account holder.
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - statementDescriptor: (Optional) A custom statement descriptor for t
/// he payment.
/// - bank: (Optional) The customer's bank.
/// @note The currency for iDEAL must be "eur". This will be set automatically
/// for you.
/// - Returns: an STPSourceParams object populated with the provided values.
@objc
public class func idealParams(
withAmount amount: Int,
name: String?,
returnURL: String,
statementDescriptor: String?,
bank: String?
) -> STPSourceParams {
let params = self.init()
params.type = .iDEAL
params.amount = NSNumber(value: amount)
params.currency = "eur" // iDEAL must always use eur
if (name?.count ?? 0) > 0 {
params.owner = [
"name": name ?? ""
]
}
params.redirect = [
"return_url": returnURL
]
if (statementDescriptor?.count ?? 0) > 0 || (bank?.count ?? 0) > 0 {
var idealDict: [AnyHashable: Any] = [:]
if let statementDescriptor = statementDescriptor, statementDescriptor.count > 0 {
idealDict["statement_descriptor"] =
statementDescriptor
}
if let bank = bank, bank.count > 0 {
idealDict["bank"] = bank
}
params.additionalAPIParameters = [
"ideal": idealDict
]
}
return params
}
/// Creates params for a SEPA Debit source.
/// - seealso: https://stripe.com/docs/sources/sepa-debit#create-source
/// - Parameters:
/// - name: The full name of the account holder.
/// - iban: The IBAN number for the bank account you wish to debit.
/// - addressLine1: (Optional) The bank account holder's first address line.
/// - city: (Optional) The bank account holder's city.
/// - postalCode: (Optional) The bank account holder's postal code.
/// - country: (Optional) The bank account holder's two-letter
/// country code.
/// @note The currency for SEPA Debit must be "eur". This will be set automatically
/// for you.
/// - Returns: an STPSourceParams object populated with the provided values.
@objc
public class func sepaDebitParams(
withName name: String,
iban: String,
addressLine1: String?,
city: String?,
postalCode: String?,
country: String?
) -> STPSourceParams {
let params = self.init()
params.type = .SEPADebit
params.currency = "eur" // SEPA Debit must always use eur
var owner: [AnyHashable: Any] = [:]
owner["name"] = name
var address: [String: String]? = [:]
address?["city"] = city
address?["postal_code"] = postalCode
address?["country"] = country
address?["line1"] = addressLine1
if (address?.count ?? 0) > 0 {
if let address = address {
owner["address"] = address
}
}
params.owner = owner
params.additionalAPIParameters = [
"sepa_debit": [
"iban": iban
]
]
return params
}
/// Creates params for a Sofort source.
/// - seealso: https://stripe.com/docs/sources/sofort#create-source
/// - Parameters:
/// - amount: The amount to charge the customer in EUR.
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - country: The country code of the customer's bank.
/// - statementDescriptor: (Optional) A custom statement descriptor for
/// the payment.
/// @note The currency for Sofort must be "eur". This will be set automatically
/// for you.
/// - Returns: an STPSourceParams object populated with the provided values.
@objc
public class func sofortParams(
withAmount amount: Int,
returnURL: String,
country: String,
statementDescriptor: String?
) -> STPSourceParams {
let params = self.init()
params.type = .sofort
params.amount = NSNumber(value: amount)
params.currency = "eur" // sofort must always use eur
params.redirect = [
"return_url": returnURL
]
var sofortDict: [AnyHashable: Any] = [:]
sofortDict["country"] = country
if let statementDescriptor = statementDescriptor {
sofortDict["statement_descriptor"] = statementDescriptor
}
params.additionalAPIParameters = [
"sofort": sofortDict
]
return params
}
/// Creates params for a Klarna source.
/// - seealso: https://stripe.com/docs/sources/klarna#create-source
/// - Parameters:
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - currency: The currency the payment is being created in.
/// - purchaseCountry: The ISO-3166 2-letter country code of the customer's location.
/// - items: An array of STPKlarnaLineItems. Klarna will present these on the confirmation
/// page. The total amount charged will be a sum of the `totalAmount` of each of these items.
/// - customPaymentMethods: Required for customers located in the US. This determines whether Pay Later and/or Slice It
/// is offered to a US customer.
/// - address: An STPAddress for the customer. At a minimum, an `email`, `line1`, `postalCode`, `city`, and `country` must be provided.
/// The address' `name` will be ignored in favor of the `firstName and `lastName` parameters.
/// - firstName: The customer's first name.
/// - lastName: The customer's last name.
/// If the provided information is missing a line1, postal code, city, email, or first/last name, or if the country code is
/// outside the specified country, no address information will be sent to Klarna, and Klarna will prompt the customer to provide their address.
/// - dateOfBirth: The customer's date of birth. This will be used by Klarna for a credit check in some EU countries.
/// The optional fields (address, firstName, lastName, and dateOfBirth) can be provided to skip Klarna's customer information form.
/// If this information is missing, Klarna will prompt the customer for these values during checkout.
/// Be careful with this option: If the provided information is invalid,
/// Klarna may reject the transaction without giving the customer a chance to correct it.
/// - Returns: an STPSourceParams object populated with the provided values.
@available(swift, obsoleted: 1.0)
@objc(
klarnaParamsWithReturnURL:
currency:
purchaseCountry:
items:
customPaymentMethods:
billingAddress:
billingFirstName:
billingLastName:
billingDOB:
)
public class func objc_klarnaParams(
withReturnURL returnURL: String,
currency: String,
purchaseCountry: String,
items: [STPKlarnaLineItem],
customPaymentMethods: [NSNumber],
billingAddress address: STPAddress?,
billingFirstName firstName: String?,
billingLastName lastName: String?,
billingDOB dateOfBirth: STPDateOfBirth?
) -> STPSourceParams {
let customPaymentMethods: [STPKlarnaPaymentMethods] = customPaymentMethods.map {
STPKlarnaPaymentMethods(rawValue: $0.intValue) ?? STPKlarnaPaymentMethods.none
}
return klarnaParams(
withReturnURL: returnURL,
currency: currency,
purchaseCountry: purchaseCountry,
items: items,
customPaymentMethods: customPaymentMethods,
billingAddress: address,
billingFirstName: firstName,
billingLastName: lastName,
billingDOB: dateOfBirth
)
}
/// Creates params for a Klarna source.
/// - seealso: https://stripe.com/docs/sources/klarna#create-source
/// - Parameters:
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - currency: The currency the payment is being created in.
/// - purchaseCountry: The ISO-3166 2-letter country code of the customer's location.
/// - items: An array of STPKlarnaLineItems. Klarna will present these on the confirmation
/// page. The total amount charged will be a sum of the `totalAmount` of each of these items.
/// - customPaymentMethods: Required for customers located in the US. This determines whether Pay Later and/or Slice It
/// is offered to a US customer.
/// - address: An STPAddress for the customer. At a minimum, an `email`, `line1`, `postalCode`, `city`, and `country` must be provided.
/// The address' `name` will be ignored in favor of the `firstName and `lastName` parameters.
/// - firstName: The customer's first name.
/// - lastName: The customer's last name.
/// If the provided information is missing a line1, postal code, city, email, or first/last name, or if the country code is
/// outside the specified country, no address information will be sent to Klarna, and Klarna will prompt the customer to provide their address.
/// - dateOfBirth: The customer's date of birth. This will be used by Klarna for a credit check in some EU countries.
/// The optional fields (address, firstName, lastName, and dateOfBirth) can be provided to skip Klarna's customer information form.
/// If this information is missing, Klarna will prompt the customer for these values during checkout.
/// Be careful with this option: If the provided information is invalid,
/// Klarna may reject the transaction without giving the customer a chance to correct it.
/// - Returns: an STPSourceParams object populated with the provided values.
public class func klarnaParams(
withReturnURL returnURL: String,
currency: String,
purchaseCountry: String,
items: [STPKlarnaLineItem],
customPaymentMethods: [STPKlarnaPaymentMethods],
billingAddress address: STPAddress? = nil,
billingFirstName firstName: String? = nil,
billingLastName lastName: String? = nil,
billingDOB dateOfBirth: STPDateOfBirth? = nil
) -> STPSourceParams {
let params = self.init()
params.type = .klarna
params.currency = currency
params.redirect = [
"return_url": returnURL
]
var additionalAPIParameters: [AnyHashable: Any] = [:]
var klarnaDict: [AnyHashable: Any] = [:]
klarnaDict["product"] = "payment"
klarnaDict["purchase_country"] = purchaseCountry
if let address = address, address.country == purchaseCountry, let line1 = address.line1,
let postalCode = address.postalCode,
let city = address.city, let email = address.email, let firstName = firstName,
let lastName = lastName
{
klarnaDict["first_name"] = firstName
klarnaDict["last_name"] = lastName
var ownerDict: [AnyHashable: Any] = [:]
var addressDict: [AnyHashable: Any] = [:]
addressDict["line1"] = line1
addressDict["line2"] = address.line2
addressDict["city"] = city
addressDict["state"] = address.state
addressDict["postal_code"] = postalCode
addressDict["country"] = address.country
ownerDict["address"] = addressDict
ownerDict["phone"] = address.phone
ownerDict["email"] = email
additionalAPIParameters["owner"] = ownerDict
}
if let dateOfBirth = dateOfBirth {
klarnaDict["owner_dob_day"] = String(format: "%02ld", dateOfBirth.day)
klarnaDict["owner_dob_month"] = String(format: "%02ld", dateOfBirth.month)
klarnaDict["owner_dob_year"] = String(format: "%li", dateOfBirth.year)
}
var amount = 0
let sourceOrderItems = NSMutableArray()
for item in items {
let itemType: String = {
switch item.itemType {
case .SKU:
return "sku"
case .tax:
return "tax"
case .shipping:
return "shipping"
}
}()
sourceOrderItems.add([
"type": itemType,
"description": item.itemDescription,
"quantity": item.quantity,
"amount": item.totalAmount,
"currency": currency,
])
amount = Int(item.totalAmount.uint32Value) + amount
}
params.amount = NSNumber(value: amount)
if !customPaymentMethods.isEmpty {
let customPaymentMethodsArray = NSMutableArray()
if customPaymentMethods.contains(.payIn4)
|| customPaymentMethods.contains(.payIn4OrInstallments)
{
customPaymentMethodsArray.add("payin4")
}
if customPaymentMethods.contains(.installments)
|| customPaymentMethods.contains(.payIn4OrInstallments)
{
customPaymentMethodsArray.add("installments")
}
klarnaDict["custom_payment_methods"] = customPaymentMethodsArray.componentsJoined(
by: ","
)
}
additionalAPIParameters["source_order"] = [
"items": sourceOrderItems
]
additionalAPIParameters["klarna"] = klarnaDict
additionalAPIParameters["flow"] = "redirect"
params.additionalAPIParameters = additionalAPIParameters
return params
}
/// Creates params for a Klarna source.
/// - seealso: https://stripe.com/docs/sources/klarna#create-source
/// - Parameters:
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - currency: The currency the payment is being created in.
/// - purchaseCountry: The ISO-3166 2-letter country code of the customer's location.
/// - items: An array of STPKlarnaLineItems. Klarna will present these in the confirmation
/// dialog. The total amount charged will be a sum of the `totalAmount` of each of these items.
/// - customPaymentMethods: Required for customers located in the US. This determines whether Pay Later and/or Slice It
/// is offered to a US customer.
/// - Returns: an STPSourceParams object populated with the provided values.
@available(swift, obsoleted: 1.0)
@objc(klarnaParamsWithReturnURL:currency:purchaseCountry:items:customPaymentMethods:)
public class func objc_klarnaParams(
withReturnURL returnURL: String,
currency: String,
purchaseCountry: String,
items: [STPKlarnaLineItem],
customPaymentMethods: [NSNumber]
) -> STPSourceParams {
return self.klarnaParams(
withReturnURL: returnURL,
currency: currency,
purchaseCountry: purchaseCountry,
items: items,
customPaymentMethods: customPaymentMethods.map({
STPKlarnaPaymentMethods(rawValue: $0.intValue) ?? .none
}),
billingAddress: nil,
billingFirstName: "",
billingLastName: "",
billingDOB: nil
)
}
/// Creates params for a Klarna source.
/// - seealso: https://stripe.com/docs/sources/klarna#create-source
/// - Parameters:
/// - returnURL: The URL the customer should be redirected to after
/// they have successfully verified the payment.
/// - currency: The currency the payment is being created in.
/// - purchaseCountry: The ISO-3166 2-letter country code of the customer's location.
/// - items: An array of STPKlarnaLineItems. Klarna will present these in the confirmation
/// dialog. The total amount charged will be a sum of the `totalAmount` of each of these items.
/// - customPaymentMethods: Required for customers located in the US. This determines whether Pay Later and/or Slice It
/// is offered to a US customer.
/// - Returns: an STPSourceParams object populated with the provided values.
public class func klarnaParams(
withReturnURL returnURL: String,
currency: String,
purchaseCountry: String,
items: [STPKlarnaLineItem],
customPaymentMethods: [STPKlarnaPaymentMethods]
) -> STPSourceParams {
return self.klarnaParams(
withReturnURL: returnURL,
currency: currency,
purchaseCountry: purchaseCountry,
items: items,
customPaymentMethods: customPaymentMethods,
billingAddress: nil,
billingFirstName: "",
billingLastName: "",
billingDOB: nil
)
}
/// Creates params for a 3DS source.
/// - seealso: https://stripe.com/docs/sources/three-d-secure#create-3ds-source
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - currency: The currency the payment is being created in.
/// - returnURL: The URL the customer should be redirected to after they have
/// successfully verified the payment.
/// - card: The ID of the card source.
/// - Returns: an STPSourceParams object populated with the provided card details.
@objc
public class func threeDSecureParams(
withAmount amount: Int,
currency: String,
returnURL: String,
card: String
) -> STPSourceParams {
let params = self.init()
params.type = .threeDSecure
params.amount = NSNumber(value: amount)
params.currency = currency
params.additionalAPIParameters = [
"three_d_secure": [
"card": card
]
]
params.redirect = [
"return_url": returnURL
]
return params
}
/// Creates params for a single-use Alipay source
/// - seealso: https://stripe.com/docs/sources/alipay#create-source
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - currency: The currency the payment is being created in.
/// - returnURL: The URL the customer should be redirected to after they have
/// successfully verified the payment.
/// - Returns: An STPSourceParams object populated with the provided values
@objc
public class func alipayParams(
withAmount amount: Int,
currency: String,
returnURL: String
) -> STPSourceParams {
let params = self.init()
params.type = .alipay
params.amount = NSNumber(value: amount)
params.currency = currency
params.redirect = [
"return_url": returnURL
]
let bundleID = Bundle.main.bundleIdentifier
let versionKey = Bundle.stp_applicationVersion()
if bundleID != nil && versionKey != nil {
params.additionalAPIParameters = [
"alipay": [
"app_bundle_id": bundleID ?? "",
"app_version_key": versionKey ?? "",
]
]
}
return params
}
/// Creates params for a reusable Alipay source
/// - seealso: https://stripe.com/docs/sources/alipay#create-source
/// - Parameters:
/// - currency: The currency the payment is being created in.
/// - returnURL: The URL the customer should be redirected to after they have
/// successfully verified the payment.
/// - Returns: An STPSourceParams object populated with the provided values
@objc
public class func alipayReusableParams(
withCurrency currency: String,
returnURL: String
) -> STPSourceParams {
let params = self.init()
params.type = .alipay
params.currency = currency
params.redirect = [
"return_url": returnURL
]
params.usage = .reusable
return params
}
/// Creates params for a P24 source
/// - seealso: https://stripe.com/docs/sources/p24#create-source
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - currency: The currency the payment is being created in (this must be
/// EUR or PLN)
/// - email: The email address of the account holder.
/// - name: The full name of the account holder (optional).
/// - returnURL: The URL the customer should be redirected to after they have
/// - Returns: An STPSourceParams object populated with the provided values.
@objc
public class func p24Params(
withAmount amount: Int,
currency: String,
email: String,
name: String?,
returnURL: String
) -> STPSourceParams {
let params = self.init()
params.type = .P24
params.amount = NSNumber(value: amount)
params.currency = currency
var ownerDict = [
"email": email
]
if let name = name {
ownerDict["name"] = name
}
params.owner = ownerDict
params.redirect = [
"return_url": returnURL
]
return params
}
/// Creates params for a card source created from Visa Checkout.
/// - seealso: https://stripe.com/docs/visa-checkout
/// @note Creating an STPSource with these params will give you a
/// source with type == STPSourceTypeCard
/// - Parameter callId: The callId property from a `VisaCheckoutResult` object.
/// - Returns: An STPSourceParams object populated with the provided values.
@objc
public class func visaCheckoutParams(withCallId callId: String) -> STPSourceParams {
let params = self.init()
params.type = .card
params.additionalAPIParameters = [
"card": [
"visa_checkout": [
"callid": callId
]
]
]
return params
}
/// Creates params for a card source created from Masterpass.
/// - seealso: https://stripe.com/docs/masterpass
/// @note Creating an STPSource with these params will give you a
/// source with type == STPSourceTypeCard
/// - Parameters:
/// - cartId: The cartId from a `MCCCheckoutResponse` object.
/// - transactionId: The transactionid from a `MCCCheckoutResponse` object.
/// - Returns: An STPSourceParams object populated with the provided values.
@objc
public class func masterpassParams(
withCartId cartId: String,
transactionId: String
) -> STPSourceParams {
let params = self.init()
params.type = .card
params.additionalAPIParameters = [
"card": [
"masterpass": [
"cart_id": cartId,
"transaction_id": transactionId,
]
]
]
return params
}
/// Create params for an EPS source
/// - seealso: https://stripe.com/docs/sources/eps
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - name: The full name of the account holder.
/// - returnURL: The URL the customer should be redirected to
/// after the authorization process.
/// - statementDescriptor: A custom statement descriptor for the
/// payment (optional).
/// - Returns: An STPSourceParams object populated with the provided values.
@objc
public class func epsParams(
withAmount amount: Int,
name: String,
returnURL: String,
statementDescriptor: String?
) -> STPSourceParams {
let params = self.init()
params.type = .EPS
params.amount = NSNumber(value: amount)
params.currency = "eur" // EPS must always use eur
params.owner = [
"name": name
]
params.redirect = [
"return_url": returnURL
]
if (statementDescriptor?.count ?? 0) > 0 {
params.additionalAPIParameters = [
"statement_descriptor": statementDescriptor ?? ""
]
}
return params
}
/// Create params for a Multibanco source
/// - seealso: https://stripe.com/docs/sources/multibanco
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - returnURL: The URL the customer should be redirected to after the
/// authorization process.
/// - email: The full email address of the customer.
/// - Returns: An STPSourceParams object populated with the provided values.
@objc
public class func multibancoParams(
withAmount amount: Int,
returnURL: String,
email: String
) -> STPSourceParams {
let params = self.init()
params.type = .multibanco
params.currency = "eur" // Multibanco must always use eur
params.amount = NSNumber(value: amount)
params.redirect = [
"return_url": returnURL
]
params.owner = [
"email": email
]
return params
}
/// Create params for a WeChat Pay native app redirect source
/// @note This feature is in private beta.
/// - Parameters:
/// - amount: The amount to charge the customer.
/// - currency: The currency of the payment
/// - appId: Your WeChat-provided application id. WeChat Pay uses
/// this as the redirect URL scheme
/// - statementDescriptor: A custom statement descriptor for the payment (optional).
/// - Returns: An STPSourceParams object populated with the provided values.
@objc(wechatPayParamsWithAmount:currency:appId:statementDescriptor:)
public class func wechatPay(
withAmount amount: Int,
currency: String,
appId: String,
statementDescriptor: String?
) -> STPSourceParams {
let params = self.init()
params.type = .weChatPay
params.amount = NSNumber(value: amount)
params.currency = currency
var wechat: [AnyHashable: Any] = [:]
wechat["appid"] = appId
if (statementDescriptor?.count ?? 0) > 0 {
wechat["statement_descriptor"] = statementDescriptor ?? ""
}
params.additionalAPIParameters = [
"wechat": wechat
]
return params
}
@objc func flowString() -> String? {
return STPSource.string(from: flow)
}
@objc func usageString() -> String? {
return STPSource.string(from: usage)
}
// MARK: - Description
/// :nodoc:
@objc public override var description: String {
let props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPSourceParams.self), self),
// Basic source details
"type = \((STPSource.string(from: type)) ?? "unknown")",
"rawTypeString = \(rawTypeString ?? "")",
// Additional source details (alphabetical)
"amount = \(amount ?? 0)",
"currency = \(currency ?? "")",
"flow = \((STPSource.string(from: flow)) ?? "unknown")",
"metadata = \(((metadata) != nil ? "<redacted>" : nil) ?? "")",
"owner = \(((owner) != nil ? "<redacted>" : nil) ?? "")",
"redirect = \(redirect ?? [:])",
"token = \(token ?? "")",
"usage = \((STPSource.string(from: usage)) ?? "unknown")",
]
return "<\(props.joined(separator: "; "))>"
}
// MARK: - Redirect Dictionary
/// Private setter allows for setting the name of the app in the returnURL so
/// that it can be displayed on hooks.stripe.com if the automatic redirect back
/// to the app fails.
/// We intercept the reading of redirect dictionary from STPFormEncoder and replace
/// the value of return_url if necessary
@objc
public func redirectDictionaryWithMerchantNameIfNecessary() -> [AnyHashable: Any] {
if (redirectMerchantName != nil) && redirect?["return_url"] != nil {
let url = URL(string: redirect?["return_url"] as? String ?? "")
if let url = url {
let urlComponents = NSURLComponents(
url: url,
resolvingAgainstBaseURL: false
)
if let urlComponents = urlComponents {
for item in urlComponents.queryItems ?? [] {
if item.name == "redirect_merchant_name" {
// Just return, don't replace their value
return redirect ?? [:]
}
}
// If we get here, there was no existing redirect name
var queryItems: [URLQueryItem] = urlComponents.queryItems ?? [URLQueryItem]()
queryItems.append(
URLQueryItem(
name: "redirect_merchant_name",
value: redirectMerchantName
)
)
urlComponents.queryItems = queryItems as [URLQueryItem]?
var redirectCopy = redirect
redirectCopy?["return_url"] = urlComponents.url?.absoluteString
return redirectCopy ?? [:]
}
}
}
return redirect ?? [:]
}
// MARK: - STPFormEncodable
public class func rootObjectName() -> String? {
return nil
}
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:rawTypeString)): "type",
NSStringFromSelector(#selector(getter:amount)): "amount",
NSStringFromSelector(#selector(getter:currency)): "currency",
NSStringFromSelector(#selector(flowString)): "flow",
NSStringFromSelector(#selector(getter:metadata)): "metadata",
NSStringFromSelector(#selector(getter:owner)): "owner",
NSStringFromSelector(#selector(redirectDictionaryWithMerchantNameIfNecessary)):
"redirect",
NSStringFromSelector(#selector(getter:token)): "token",
NSStringFromSelector(#selector(usageString)): "usage",
]
}
// MARK: - NSCopying
/// :nodoc:
public func copy(with zone: NSZone? = nil) -> Any {
let copy = Swift.type(of: self).init()
copy.type = type
copy.amount = amount
copy.currency = currency
copy.flow = flow
copy.metadata = metadata
copy.owner = owner
copy.redirect = redirect
copy.token = token
copy.usage = usage
return copy
}
}
| 960af8757634c9d884fd33f1b89b31eb | 39.748718 | 154 | 0.593028 | false | false | false | false |
dmzza/Timepiece | refs/heads/master | Sources/NSDateComponents+Timepiece.swift | mit | 4 | //
// NSDateComponents+Timepiece.swift
// Timepiece
//
// Created by Mattijs on 25/04/15.
// Copyright (c) 2015 Naoto Kaneko. All rights reserved.
//
import Foundation
public extension NSDateComponents {
convenience init(_ duration: Duration) {
self.init()
switch duration.unit{
case NSCalendarUnit.CalendarUnitDay:
day = duration.value
case NSCalendarUnit.CalendarUnitWeekday:
weekday = duration.value
case NSCalendarUnit.CalendarUnitWeekOfMonth:
weekOfMonth = duration.value
case NSCalendarUnit.CalendarUnitWeekOfYear:
weekOfYear = duration.value
case NSCalendarUnit.CalendarUnitHour:
hour = duration.value
case NSCalendarUnit.CalendarUnitMinute:
minute = duration.value
case NSCalendarUnit.CalendarUnitMonth:
month = duration.value
case NSCalendarUnit.CalendarUnitSecond:
second = duration.value
case NSCalendarUnit.CalendarUnitYear:
year = duration.value
default:
() // unsupported / ignore
}
}
}
| e7cef9fa0bd8d995b25d17c7ac03cad0 | 29.783784 | 57 | 0.642669 | false | false | false | false |
gregomni/swift | refs/heads/main | test/Parse/self_rebinding.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
class Writer {
private var articleWritten = 47
func stop() {
let rest: () -> Void = { [weak self] in
let articleWritten = self?.articleWritten ?? 0
guard let `self` = self else {
return
}
self.articleWritten = articleWritten
}
fatalError("I'm running out of time")
rest()
}
func nonStop() {
let write: () -> Void = { [weak self] in
self?.articleWritten += 1
if let self = self {
self.articleWritten += 1
}
if let `self` = self {
self.articleWritten += 1
}
guard let self = self else {
return
}
self.articleWritten += 1
}
write()
}
}
struct T {
var mutable: Int = 0
func f() {
// expected-error @+2 {{keyword 'self' cannot be used as an identifier here}}
// expected-note @+1 {{if this name is unavoidable, use backticks to escape it}}
let self = self
}
}
class MyCls {
func something() {}
func test() {
// expected-warning @+1 {{initialization of immutable value 'self' was never used}}
let `self` = Writer() // Even if `self` is shadowed,
something() // this should still refer `MyCls.something`.
}
}
// MARK: fix method called 'self' can be confused with regular 'self' https://bugs.swift.org/browse/SR-4559
func funcThatReturnsSomething(_ any: Any) -> Any {
any
}
struct TypeWithSelfMethod {
let property = self // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{20-20=TypeWithSelfMethod.}}
// Existing warning expected, not confusable
let property2 = self() // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
let propertyFromClosure: () = {
print(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{15-15=TypeWithSelfMethod.}}
}()
let propertyFromFunc = funcThatReturnsSomething(self) // expected-warning {{'self' refers to the method 'TypeWithSelfMethod.self', which may be unexpected}} expected-note{{use 'TypeWithSelfMethod.self' to silence this warning}} {{53-53=TypeWithSelfMethod.}}
let propertyFromFunc2 = funcThatReturnsSomething(TypeWithSelfMethod.self) // OK
func `self`() {
}
}
/// Test fix_unqualified_access_member_named_self doesn't appear for computed var called `self`
/// it can't currently be referenced as a static member -- unlike a method with the same name
struct TypeWithSelfComputedVar {
let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
let propertyFromClosure: () = {
print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
}()
let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
var `self`: () {
()
}
}
/// Test fix_unqualified_access_member_named_self doesn't appear appear for property called `self`
/// it can't currently be referenced as a static member -- unlike a method with the same name
struct TypeWithSelfProperty {
let property = self // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
let propertyFromClosure: () = {
print(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
}()
let propertyFromFunc = funcThatReturnsSomething(self) // expected-error {{cannot use instance member 'self' within property initializer; property initializers run before 'self' is available}}
let `self`: () = ()
}
enum EnumCaseNamedSelf {
case `self`
init() {
self = .self // OK
self = .`self` // OK
self = EnumCaseNamedSelf.`self` // OK
}
}
// rdar://90624344 - warning about `self` which cannot be fixed because it's located in implicitly generated code.
struct TestImplicitSelfUse : Codable {
let `self`: Int // Ok
}
| 209bc110efb9e4c6e3b96fb2c19643b5 | 34.744361 | 261 | 0.64472 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Room/VoiceMessages/VoiceMessageToolbarView.swift | apache-2.0 | 1 | //
// Copyright 2021 New Vector Ltd
//
// 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 Reusable
protocol VoiceMessageToolbarViewDelegate: AnyObject {
func voiceMessageToolbarViewDidRequestRecordingStart(_ toolbarView: VoiceMessageToolbarView)
func voiceMessageToolbarViewDidRequestRecordingCancel(_ toolbarView: VoiceMessageToolbarView)
func voiceMessageToolbarViewDidRequestRecordingFinish(_ toolbarView: VoiceMessageToolbarView)
func voiceMessageToolbarViewDidRequestLockedModeRecording(_ toolbarView: VoiceMessageToolbarView)
func voiceMessageToolbarViewDidRequestPlaybackToggle(_ toolbarView: VoiceMessageToolbarView)
func voiceMessageToolbarViewDidRequestSeek(to progress: CGFloat)
func voiceMessageToolbarViewDidRequestSend(_ toolbarView: VoiceMessageToolbarView)
}
enum VoiceMessageToolbarViewUIState {
case idle
case record
case lockedModeRecord
case lockedModePlayback
}
struct VoiceMessageToolbarViewDetails {
var state: VoiceMessageToolbarViewUIState = .idle
var elapsedTime: String = ""
var audioSamples: [Float] = []
var isPlaying: Bool = false
var progress: Double = 0.0
var toastMessage: String?
}
class VoiceMessageToolbarView: PassthroughView, NibLoadable, Themable, UIGestureRecognizerDelegate, VoiceMessagePlaybackViewDelegate {
private enum Constants {
static let longPressMinimumDuration: TimeInterval = 0.0
static let animationDuration: TimeInterval = 0.25
static let lockModeTransitionAnimationDuration: TimeInterval = 0.5
static let panDirectionChangeThreshold: CGFloat = 20.0
static let toastContainerCornerRadii: CGFloat = 8.0
static let toastDisplayTimeout: TimeInterval = 5.0
}
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var recordingContainerView: UIView!
@IBOutlet private var recordButtonsContainerView: UIView!
@IBOutlet private var primaryRecordButton: UIButton!
@IBOutlet private var secondaryRecordButton: UIButton!
@IBOutlet private var recordingChromeContainerView: UIView!
@IBOutlet private var recordingIndicatorView: UIView!
@IBOutlet private var elapsedTimeLabel: UILabel!
@IBOutlet private var slideToCancelContainerView: UIView!
@IBOutlet private var slideToCancelLabel: UILabel!
@IBOutlet private var slideToCancelChevron: UIImageView!
@IBOutlet private var slideToCancelGradient: UIImageView!
@IBOutlet private var lockContainerView: UIView!
@IBOutlet private var lockContainerBackgroundView: UIView!
@IBOutlet private var lockButtonsContainerView: UIView!
@IBOutlet private var primaryLockButton: UIButton!
@IBOutlet private var secondaryLockButton: UIButton!
@IBOutlet private var lockChevron: UIView!
@IBOutlet private var lockedModeContainerView: UIView!
@IBOutlet private var deleteButton: UIButton!
@IBOutlet private var playbackViewContainerView: UIView!
@IBOutlet private var sendButton: UIButton!
@IBOutlet private var toastNotificationContainerView: UIView!
@IBOutlet private var toastNotificationLabel: UILabel!
private var playbackView: VoiceMessagePlaybackView!
private var cancelLabelToRecordButtonDistance: CGFloat = 0.0
private var lockChevronToRecordButtonDistance: CGFloat = 0.0
private var lockChevronToLockButtonDistance: CGFloat = 0.0
private var panDirection: UISwipeGestureRecognizer.Direction?
private var tapGesture: UITapGestureRecognizer!
private var details: VoiceMessageToolbarViewDetails?
private var currentTheme: Theme? {
didSet {
updateUIWithDetails(details, animated: true)
}
}
weak var delegate: VoiceMessageToolbarViewDelegate?
override func awakeFromNib() {
super.awakeFromNib()
lockContainerBackgroundView.layer.cornerRadius = lockContainerBackgroundView.bounds.width / 2.0
lockButtonsContainerView.layer.cornerRadius = lockButtonsContainerView.bounds.width / 2.0
toastNotificationContainerView.layer.cornerRadius = Constants.toastContainerCornerRadii
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.delegate = self
longPressGesture.minimumPressDuration = Constants.longPressMinimumDuration
recordButtonsContainerView.addGestureRecognizer(longPressGesture)
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
longPressGesture.delegate = self
recordButtonsContainerView.addGestureRecognizer(panGesture)
playbackView = VoiceMessagePlaybackView.loadFromNib()
playbackView.delegate = self
playbackViewContainerView.vc_addSubViewMatchingParent(playbackView)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleWaveformTap))
playbackView.waveformView.addGestureRecognizer(tapGesture)
tapGesture.delegate = self
self.tapGesture = tapGesture
updateUIWithDetails(VoiceMessageToolbarViewDetails(), animated: false)
}
func configureWithDetails(_ details: VoiceMessageToolbarViewDetails) {
elapsedTimeLabel.text = details.elapsedTime
self.updateToastNotificationsWithDetails(details)
self.updatePlaybackViewWithDetails(details)
if self.details?.state != details.state {
switch details.state {
case .record:
var convertedFrame = self.convert(slideToCancelLabel.frame, from: slideToCancelContainerView)
cancelLabelToRecordButtonDistance = recordButtonsContainerView.frame.minX - convertedFrame.maxX
convertedFrame = self.convert(lockChevron.frame, from: lockContainerView)
lockChevronToRecordButtonDistance = recordButtonsContainerView.frame.midY + convertedFrame.maxY
lockChevronToLockButtonDistance = (lockChevron.frame.minY - lockButtonsContainerView.frame.midY) / 2
startAnimatingRecordingIndicator()
default:
cancelDrag()
}
if details.state == .lockedModeRecord && self.details?.state == .record {
UIView.animate(withDuration: Constants.animationDuration) {
self.lockButtonsContainerView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
} completion: { _ in
self.updateUIWithDetails(details, animated: true)
}
} else {
updateUIWithDetails(details, animated: true)
}
}
self.details = details
}
func getRequiredNumberOfSamples() -> Int {
return playbackView.getRequiredNumberOfSamples()
}
// MARK: - Themable
func update(theme: Theme) {
currentTheme = theme
playbackView.update(theme: theme)
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.tapGesture, self.lastUIState != .lockedModeRecord {
return false
}
return true
}
// MARK: - VoiceMessagePlaybackViewDelegate
func voiceMessagePlaybackViewDidRequestPlaybackToggle() {
delegate?.voiceMessageToolbarViewDidRequestPlaybackToggle(self)
}
func voiceMessagePlaybackViewDidRequestSeek(to progress: CGFloat) {
delegate?.voiceMessageToolbarViewDidRequestSeek(to: progress)
}
func voiceMessagePlaybackViewDidChangeWidth() {
}
// MARK: - Private
@objc private func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
switch gestureRecognizer.state {
case UIGestureRecognizer.State.began:
delegate?.voiceMessageToolbarViewDidRequestRecordingStart(self)
case UIGestureRecognizer.State.ended:
delegate?.voiceMessageToolbarViewDidRequestRecordingFinish(self)
default:
break
}
}
@objc private func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
guard details?.state == .record && gestureRecognizer.state == .changed else {
return
}
let translation = gestureRecognizer.translation(in: self)
if abs(translation.x) <= Constants.panDirectionChangeThreshold && abs(translation.y) <= Constants.panDirectionChangeThreshold {
panDirection = nil
} else if panDirection == nil {
if abs(translation.x) >= abs(translation.y) {
panDirection = .left
} else {
panDirection = .up
}
}
if panDirection == .left {
secondaryRecordButton.transform = CGAffineTransform(translationX: min(translation.x, 0.0), y: 0.0)
slideToCancelContainerView.transform = CGAffineTransform(translationX: min(translation.x + cancelLabelToRecordButtonDistance, 0.0), y: 0.0)
if abs(translation.x - recordButtonsContainerView.frame.width / 2.0) > self.bounds.width / 2.0 {
delegate?.voiceMessageToolbarViewDidRequestRecordingCancel(self)
}
} else if panDirection == .up {
secondaryRecordButton.transform = CGAffineTransform(translationX: 0.0, y: min(0.0, translation.y))
let yTranslation = min(max(translation.y + lockChevronToRecordButtonDistance, -lockChevronToLockButtonDistance), 0.0)
lockChevron.transform = CGAffineTransform(translationX: 0.0, y: yTranslation)
let transitionPercentage = abs(yTranslation) / lockChevronToLockButtonDistance
lockChevron.alpha = 1.0 - transitionPercentage
secondaryRecordButton.alpha = 1.0 - transitionPercentage
primaryLockButton.alpha = 1.0 - transitionPercentage
lockContainerBackgroundView.alpha = 1.0 - transitionPercentage
secondaryLockButton.alpha = transitionPercentage
if transitionPercentage >= 1.0 {
self.delegate?.voiceMessageToolbarViewDidRequestLockedModeRecording(self)
}
} else {
secondaryRecordButton.transform = CGAffineTransform(translationX: min(0.0, translation.x), y: min(0.0, translation.y))
}
}
private func cancelDrag() {
recordButtonsContainerView.gestureRecognizers?.forEach { gestureRecognizer in
gestureRecognizer.isEnabled = false
gestureRecognizer.isEnabled = true
}
}
private func updateUIWithDetails(_ details: VoiceMessageToolbarViewDetails?, animated: Bool) {
guard let details = details else {
return
}
UIView.animate(withDuration: (animated ? Constants.animationDuration : 0.0), delay: 0.0, options: .beginFromCurrentState) {
switch details.state {
case .record:
self.lockContainerBackgroundView.alpha = 1.0
case .idle:
self.lockContainerBackgroundView.alpha = 1.0
self.primaryLockButton.alpha = 1.0
self.secondaryLockButton.alpha = 0.0
self.lockChevron.alpha = 1.0
default:
break
}
self.backgroundView.alpha = (details.state == .idle ? 0.0 : 1.0)
self.primaryRecordButton.alpha = (details.state == .idle ? 1.0 : 0.0)
self.secondaryRecordButton.alpha = (details.state == .record ? 1.0 : 0.0)
self.recordingChromeContainerView.alpha = (details.state == .record ? 1.0 : 0.0)
self.lockContainerView.alpha = (details.state == .record ? 1.0 : 0.0)
self.lockedModeContainerView.alpha = (details.state == .lockedModePlayback || details.state == .lockedModeRecord ? 1.0 : 0.0)
self.recordingContainerView.alpha = (details.state == .idle || details.state == .record ? 1.0 : 0.0)
guard let theme = self.currentTheme else {
return
}
self.backgroundView.backgroundColor = theme.colors.background
self.slideToCancelGradient.tintColor = theme.colors.background
self.primaryRecordButton.tintColor = theme.colors.tertiaryContent
self.slideToCancelLabel.textColor = theme.colors.secondaryContent
self.slideToCancelChevron.tintColor = theme.colors.secondaryContent
self.elapsedTimeLabel.textColor = theme.colors.secondaryContent
self.lockContainerBackgroundView.backgroundColor = theme.colors.navigation
self.lockButtonsContainerView.backgroundColor = theme.colors.navigation
} completion: { _ in
switch details.state {
case .idle:
self.secondaryRecordButton.transform = .identity
self.slideToCancelContainerView.transform = .identity
self.lockChevron.transform = .identity
self.lockButtonsContainerView.transform = .identity
default:
break
}
}
}
private var toastIdleTimer: Timer?
private var lastUIState: VoiceMessageToolbarViewUIState = .idle
private func updateToastNotificationsWithDetails(_ details: VoiceMessageToolbarViewDetails, animated: Bool = true) {
guard self.toastNotificationLabel.text != details.toastMessage || lastUIState != details.state else {
return
}
lastUIState = details.state
let shouldShowNotification = details.state != .idle && details.toastMessage != nil
let requiredAlpha: CGFloat = shouldShowNotification ? 1.0 : 0.0
toastIdleTimer?.invalidate()
toastIdleTimer = nil
if shouldShowNotification {
self.toastNotificationLabel.text = details.toastMessage
}
UIView.animate(withDuration: (animated ? Constants.animationDuration : 0.0)) {
self.toastNotificationContainerView.alpha = requiredAlpha
}
if shouldShowNotification {
toastIdleTimer = Timer.scheduledTimer(withTimeInterval: Constants.toastDisplayTimeout, repeats: false) { [weak self] timer in
guard let self = self else {
return
}
self.toastIdleTimer?.invalidate()
self.toastIdleTimer = nil
UIView.animate(withDuration: Constants.animationDuration) {
self.toastNotificationContainerView.alpha = 0
}
}
}
}
private func updatePlaybackViewWithDetails(_ details: VoiceMessageToolbarViewDetails, animated: Bool = true) {
UIView.animate(withDuration: (animated ? Constants.animationDuration : 0.0)) {
var playbackViewDetails = VoiceMessagePlaybackViewDetails()
playbackViewDetails.recording = (details.state == .record || details.state == .lockedModeRecord)
playbackViewDetails.playing = details.isPlaying
playbackViewDetails.progress = details.progress
playbackViewDetails.currentTime = details.elapsedTime
playbackViewDetails.samples = details.audioSamples
playbackViewDetails.playbackEnabled = true
self.playbackView.configureWithDetails(playbackViewDetails)
}
}
private func startAnimatingRecordingIndicator() {
if self.details?.state != .record {
return
}
UIView.animate(withDuration: Constants.lockModeTransitionAnimationDuration) {
if self.recordingIndicatorView.alpha > 0.0 {
self.recordingIndicatorView.alpha = 0.0
} else {
self.recordingIndicatorView.alpha = 1.0
}
} completion: { [weak self] _ in
self?.startAnimatingRecordingIndicator()
}
}
@IBAction private func onTrashButtonTap(_ sender: UIBarItem) {
delegate?.voiceMessageToolbarViewDidRequestRecordingCancel(self)
}
@IBAction private func onSendButtonTap(_ sender: UIBarItem) {
delegate?.voiceMessageToolbarViewDidRequestSend(self)
}
@objc private func handleWaveformTap(_ gestureRecognizer: UITapGestureRecognizer) {
guard self.lastUIState == .lockedModeRecord else {
return
}
delegate?.voiceMessageToolbarViewDidRequestRecordingFinish(self)
}
}
| 7fc24f5ff53f39dcea1f03369e9a4dad | 41.405276 | 157 | 0.667308 | false | false | false | false |
shinjukunian/core-plot | refs/heads/master | examples/DatePlot/Source/DateController.swift | bsd-3-clause | 1 | import Foundation
import Cocoa
class DateController : NSObject, CPTPlotDataSource {
private let oneDay : Double = 24 * 60 * 60;
@IBOutlet var hostView : CPTGraphHostingView? = nil
private var graph : CPTXYGraph? = nil
private var plotData = [Double]()
// MARK: - Initialization
override func awakeFromNib()
{
self.plotData = newPlotData()
// If you make sure your dates are calculated at noon, you shouldn't have to
// worry about daylight savings. If you use midnight, you will have to adjust
// for daylight savings time.
let refDate = DateFormatter().date(from: "12:00 Oct 29, 2009")
// Create graph
let newGraph = CPTXYGraph(frame: .zero)
let theme = CPTTheme(named: .darkGradientTheme)
newGraph.apply(theme)
if let host = self.hostView {
host.hostedGraph = newGraph;
}
// Setup scatter plot space
let plotSpace = newGraph.defaultPlotSpace as! CPTXYPlotSpace
plotSpace.xRange = CPTPlotRange(location: 0.0, length: (oneDay * 5.0) as NSNumber)
plotSpace.yRange = CPTPlotRange(location: 1.0, length: 3.0)
// Axes
let axisSet = newGraph.axisSet as! CPTXYAxisSet
if let x = axisSet.xAxis {
x.majorIntervalLength = oneDay as NSNumber
x.orthogonalPosition = 2.0
x.minorTicksPerInterval = 0;
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let timeFormatter = CPTTimeFormatter(dateFormatter:dateFormatter)
timeFormatter.referenceDate = refDate;
x.labelFormatter = timeFormatter;
}
if let y = axisSet.yAxis {
y.majorIntervalLength = 0.5
y.minorTicksPerInterval = 5
y.orthogonalPosition = oneDay as NSNumber
y.labelingPolicy = .none
}
// Create a plot that uses the data source method
let dataSourceLinePlot = CPTScatterPlot(frame: .zero)
dataSourceLinePlot.identifier = "Date Plot" as NSString
if let lineStyle = dataSourceLinePlot.dataLineStyle?.mutableCopy() as? CPTMutableLineStyle {
lineStyle.lineWidth = 3.0
lineStyle.lineColor = .green()
dataSourceLinePlot.dataLineStyle = lineStyle
}
dataSourceLinePlot.dataSource = self
newGraph.add(dataSourceLinePlot)
self.graph = newGraph
}
func newPlotData() -> [Double]
{
var newData = [Double]()
for _ in 0 ..< 5 {
newData.append(1.2 * Double(arc4random()) / Double(UInt32.max) + 1.2)
}
return newData
}
// MARK: - Plot Data Source Methods
func numberOfRecords(for plot: CPTPlot) -> UInt {
return UInt(self.plotData.count)
}
func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any?
{
switch CPTScatterPlotField(rawValue: Int(field))! {
case .X:
return (oneDay * Double(record)) as NSNumber
case .Y:
return self.plotData[Int(record)] as NSNumber
}
}
}
| 1e9041339d04c39da93cb33e57e0c926 | 29.875 | 100 | 0.598567 | false | false | false | false |
AlbertXYZ/HDCP | refs/heads/dev | BarsAroundMe/Pods/RxSwift/RxSwift/Observables/Implementations/ConnectableObservable.swift | apache-2.0 | 32 | //
// ConnectableObservable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/1/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/**
Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence.
*/
public class ConnectableObservable<Element>
: Observable<Element>
, ConnectableObservableType {
/**
Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established.
- returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence.
*/
public func connect() -> Disposable {
rxAbstractMethod()
}
}
final class Connection<S: SubjectType> : ObserverType, Disposable {
typealias E = S.SubjectObserverType.E
private var _lock: RecursiveLock
// state
private var _parent: ConnectableObservableAdapter<S>?
private var _subscription : Disposable?
private var _subjectObserver: S.SubjectObserverType
private var _disposed: Bool = false
init(parent: ConnectableObservableAdapter<S>, subjectObserver: S.SubjectObserverType, lock: RecursiveLock, subscription: Disposable) {
_parent = parent
_subscription = subscription
_lock = lock
_subjectObserver = subjectObserver
}
func on(_ event: Event<S.SubjectObserverType.E>) {
if _disposed {
return
}
_subjectObserver.on(event)
if event.isStopEvent {
self.dispose()
}
}
func dispose() {
_lock.lock(); defer { _lock.unlock() } // {
_disposed = true
guard let parent = _parent else {
return
}
if parent._connection === self {
parent._connection = nil
}
_parent = nil
_subscription?.dispose()
_subscription = nil
// }
}
}
final class ConnectableObservableAdapter<S: SubjectType>
: ConnectableObservable<S.E> {
typealias ConnectionType = Connection<S>
fileprivate let _subject: S
fileprivate let _source: Observable<S.SubjectObserverType.E>
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _connection: ConnectionType?
init(source: Observable<S.SubjectObserverType.E>, subject: S) {
_source = source
_subject = subject
_connection = nil
}
override func connect() -> Disposable {
return _lock.calculateLocked {
if let connection = _connection {
return connection
}
let singleAssignmentDisposable = SingleAssignmentDisposable()
let connection = Connection(parent: self, subjectObserver: _subject.asObserver(), lock: _lock, subscription: singleAssignmentDisposable)
_connection = connection
let subscription = _source.subscribe(connection)
singleAssignmentDisposable.setDisposable(subscription)
return connection
}
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == S.E {
return _subject.subscribe(observer)
}
}
| fab63d924a9dd83063437f7871706075 | 30.342593 | 179 | 0.638109 | false | false | false | false |
FuckBoilerplate/RxCache | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/DataStructures/Bag.swift | mit | 12 | //
// Bag.swift
// Rx
//
// Created by Krunoslav Zaher on 2/28/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Swift
let arrayDictionaryMaxSize = 30
/**
Class that enables using memory allocations as a means to uniquely identify objects.
*/
class Identity {
// weird things have known to happen with Swift
var _forceAllocation: Int32 = 0
}
func hash(_ _x: Int) -> Int {
var x = _x
x = ((x >> 16) ^ x) &* 0x45d9f3b
x = ((x >> 16) ^ x) &* 0x45d9f3b
x = ((x >> 16) ^ x)
return x;
}
/**
Unique identifier for object added to `Bag`.
*/
public struct BagKey : Hashable {
let uniqueIdentity: Identity?
let key: Int
public var hashValue: Int {
if let uniqueIdentity = uniqueIdentity {
return hash(key) ^ (ObjectIdentifier(uniqueIdentity).hashValue)
}
else {
return hash(key)
}
}
}
/**
Compares two `BagKey`s.
*/
public func == (lhs: BagKey, rhs: BagKey) -> Bool {
return lhs.key == rhs.key && lhs.uniqueIdentity === rhs.uniqueIdentity
}
/**
Data structure that represents a bag of elements typed `T`.
Single element can be stored multiple times.
Time and space complexity of insertion an deletion is O(n).
It is suitable for storing small number of elements.
*/
public struct Bag<T> : CustomDebugStringConvertible {
/**
Type of identifier for inserted elements.
*/
public typealias KeyType = BagKey
fileprivate typealias ScopeUniqueTokenType = Int
typealias Entry = (key: BagKey, value: T)
fileprivate var _uniqueIdentity: Identity?
fileprivate var _nextKey: ScopeUniqueTokenType = 0
// data
// first fill inline variables
fileprivate var _key0: BagKey? = nil
fileprivate var _value0: T? = nil
fileprivate var _key1: BagKey? = nil
fileprivate var _value1: T? = nil
// then fill "array dictionary"
fileprivate var _pairs = ContiguousArray<Entry>()
// last is sparse dictionary
fileprivate var _dictionary: [BagKey : T]? = nil
fileprivate var _onlyFastPath = true
/**
Creates new empty `Bag`.
*/
public init() {
}
/**
Inserts `value` into bag.
- parameter element: Element to insert.
- returns: Key that can be used to remove element from bag.
*/
public mutating func insert(_ element: T) -> BagKey {
_nextKey = _nextKey &+ 1
#if DEBUG
_nextKey = _nextKey % 20
#endif
if _nextKey == 0 {
_uniqueIdentity = Identity()
}
let key = BagKey(uniqueIdentity: _uniqueIdentity, key: _nextKey)
if _key0 == nil {
_key0 = key
_value0 = element
return key
}
_onlyFastPath = false
if _key1 == nil {
_key1 = key
_value1 = element
return key
}
if _dictionary != nil {
_dictionary![key] = element
return key
}
if _pairs.count < arrayDictionaryMaxSize {
_pairs.append(key: key, value: element)
return key
}
if _dictionary == nil {
_dictionary = [:]
}
_dictionary![key] = element
return key
}
/**
- returns: Number of elements in bag.
*/
public var count: Int {
let dictionaryCount: Int = _dictionary?.count ?? 0
return _pairs.count + (_value0 != nil ? 1 : 0) + (_value1 != nil ? 1 : 0) + dictionaryCount
}
/**
Removes all elements from bag and clears capacity.
*/
public mutating func removeAll() {
_key0 = nil
_value0 = nil
_key1 = nil
_value1 = nil
_pairs.removeAll(keepingCapacity: false)
_dictionary?.removeAll(keepingCapacity: false)
}
/**
Removes element with a specific `key` from bag.
- parameter key: Key that identifies element to remove from bag.
- returns: Element that bag contained, or nil in case element was already removed.
*/
public mutating func removeKey(_ key: BagKey) -> T? {
if _key0 == key {
_key0 = nil
let value = _value0!
_value0 = nil
return value
}
if _key1 == key {
_key1 = nil
let value = _value1!
_value1 = nil
return value
}
if let existingObject = _dictionary?.removeValue(forKey: key) {
return existingObject
}
for i in 0 ..< _pairs.count {
if _pairs[i].key == key {
let value = _pairs[i].value
_pairs.remove(at: i)
return value
}
}
return nil
}
}
extension Bag {
/**
A textual representation of `self`, suitable for debugging.
*/
public var debugDescription : String {
return "\(self.count) elements in Bag"
}
}
// MARK: forEach
extension Bag {
/**
Enumerates elements inside the bag.
- parameter action: Enumeration closure.
*/
public func forEach(_ action: (T) -> Void) {
if _onlyFastPath {
if let value0 = _value0 {
action(value0)
}
return
}
let pairs = _pairs
let value0 = _value0
let value1 = _value1
let dictionary = _dictionary
if let value0 = value0 {
action(value0)
}
if let value1 = value1 {
action(value1)
}
for i in 0 ..< pairs.count {
action(pairs[i].value)
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
action(element)
}
}
}
}
extension Bag where T: ObserverType {
/**
Dispatches `event` to app observers contained inside bag.
- parameter action: Enumeration closure.
*/
public func on(_ event: Event<T.E>) {
if _onlyFastPath {
_value0?.on(event)
return
}
let pairs = _pairs
let value0 = _value0
let value1 = _value1
let dictionary = _dictionary
if let value0 = value0 {
value0.on(event)
}
if let value1 = value1 {
value1.on(event)
}
for i in 0 ..< pairs.count {
pairs[i].value.on(event)
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
element.on(event)
}
}
}
}
/**
Dispatches `dispose` to all disposables contained inside bag.
*/
@available(*, deprecated, renamed: "disposeAll(in:)")
public func disposeAllIn(_ bag: Bag<Disposable>) {
disposeAll(in: bag)
}
/**
Dispatches `dispose` to all disposables contained inside bag.
*/
public func disposeAll(in bag: Bag<Disposable>) {
if bag._onlyFastPath {
bag._value0?.dispose()
return
}
let pairs = bag._pairs
let value0 = bag._value0
let value1 = bag._value1
let dictionary = bag._dictionary
if let value0 = value0 {
value0.dispose()
}
if let value1 = value1 {
value1.dispose()
}
for i in 0 ..< pairs.count {
pairs[i].value.dispose()
}
if dictionary?.count ?? 0 > 0 {
for element in dictionary!.values {
element.dispose()
}
}
}
| e97e8b50c9bc581f43e4f2839c508cdd | 21.229167 | 99 | 0.544383 | false | false | false | false |
0416354917/FeedMeIOS | refs/heads/master | SSRadioButton.swift | bsd-3-clause | 3 | //
// SSRadioButton.swift
// SampleProject
//
// Created by Shamas on 18/05/2015.
// Copyright (c) 2015 Al Shamas Tufail. All rights reserved.
//
// Modified by Jun Chen on 30/03/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
@IBDesignable
class SSRadioButton: UIButton {
private var circleLayer = CAShapeLayer()
private var fillCircleLayer = CAShapeLayer()
override var selected: Bool {
didSet {
toggleButon()
}
}
/**
Color of the radio button circle. Default value is UIColor green.
*/
@IBInspectable var circleColor: UIColor = UIColor.blueColor() {
didSet {
circleLayer.strokeColor = circleColor.CGColor
self.toggleButon()
}
}
/**
Radius of RadioButton circle.
*/
@IBInspectable var circleRadius: CGFloat = 15.0
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
private func circleFrame() -> CGRect {
var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
circleFrame.origin.x = 0 + circleLayer.lineWidth
circleFrame.origin.y = bounds.height/2 - circleFrame.height/2
return circleFrame
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
private func initialize() {
circleLayer.frame = bounds
circleLayer.lineWidth = 2
circleLayer.fillColor = UIColor.clearColor().CGColor
circleLayer.strokeColor = circleColor.CGColor
layer.addSublayer(circleLayer)
fillCircleLayer.frame = bounds
fillCircleLayer.lineWidth = 2
fillCircleLayer.fillColor = UIColor.clearColor().CGColor
fillCircleLayer.strokeColor = UIColor.clearColor().CGColor
layer.addSublayer(fillCircleLayer)
self.titleEdgeInsets = UIEdgeInsetsMake(0, (4*circleRadius + 4*circleLayer.lineWidth), 0, 0)
self.toggleButon()
}
/**
Toggles selected state of the button.
*/
func toggleButon() {
if self.selected {
fillCircleLayer.fillColor = circleColor.CGColor
} else {
fillCircleLayer.fillColor = UIColor.clearColor().CGColor
}
}
private func circlePath() -> UIBezierPath {
return UIBezierPath(ovalInRect: circleFrame())
}
private func fillCirclePath() -> UIBezierPath {
return UIBezierPath(ovalInRect: CGRectInset(circleFrame(), 2, 2))
}
override func layoutSubviews() {
super.layoutSubviews()
circleLayer.frame = bounds
circleLayer.path = circlePath().CGPath
fillCircleLayer.frame = bounds
fillCircleLayer.path = fillCirclePath().CGPath
self.titleEdgeInsets = UIEdgeInsetsMake(0, (2*circleRadius + 4*circleLayer.lineWidth), 0, 0)
}
override func prepareForInterfaceBuilder() {
initialize()
}
}
| 1395a68e6a7bd8078140c48a25b8fc54 | 27.767857 | 100 | 0.625698 | false | false | false | false |
ibm-bluemix-push-notifications/bms-samples-swift-login | refs/heads/master | userIdBasedSwift/PopupController.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// userIdBasedSwift
//
// Created by Anantha Krishnan K G on 20/07/16.
// Copyright © 2016 Ananth. All rights reserved.
//
import UIKit
public enum PopupCustomOption {
case Layout(PopupController.PopupLayout)
case Animation(PopupController.PopupAnimation)
case BackgroundStyle(PopupController.PopupBackgroundStyle)
case Scrollable(Bool)
case DismissWhenTaps(Bool)
case MovesAlongWithKeyboard(Bool)
}
typealias PopupAnimateCompletion = () -> ()
// MARK: - Protocols
/** PopupContentViewController:
Every ViewController which is added on the PopupController must need to be conformed this protocol.
*/
public protocol PopupContentViewController {
/** sizeForPopup(popupController: size: showingKeyboard:):
return view's size
*/
func sizeForPopup(popupController: PopupController, size: CGSize, showingKeyboard: Bool) -> CGSize
}
public class PopupController: UIViewController {
public enum PopupLayout {
case Top, Center, Bottom
func origin(view: UIView, size: CGSize = UIScreen.mainScreen().bounds.size) -> CGPoint {
switch self {
case .Top: return CGPointMake((size.width - view.frame.width) / 2, 0)
case .Center: return CGPointMake((size.width - view.frame.width) / 2, (size.height - view.frame.height) / 2)
case .Bottom: return CGPointMake((size.width - view.frame.width) / 2, size.height - view.frame.height)
}
}
}
public enum PopupAnimation {
case FadeIn, SlideUp
}
public enum PopupBackgroundStyle {
case BlackFilter(alpha: CGFloat)
}
// MARK: - Public variables
public var popupView: UIView!
// MARK: - Private variables
private var movesAlongWithKeyboard: Bool = true
private var scrollable: Bool = true {
didSet {
updateScrollable()
}
}
private var dismissWhenTaps: Bool = true {
didSet {
if dismissWhenTaps {
registerTapGesture()
} else {
unregisterTapGesture()
}
}
}
private var backgroundStyle: PopupBackgroundStyle = .BlackFilter(alpha: 0.4) {
didSet {
updateBackgroundStyle(backgroundStyle)
}
}
private var layout: PopupLayout = .Center
private var animation: PopupAnimation = .FadeIn
private let margin: CGFloat = 16
private let baseScrollView = UIScrollView()
private var isShowingKeyboard: Bool = false
private var defaultContentOffset = CGPoint.zero
private var closedHandler: ((PopupController) -> Void)?
private var showedHandler: ((PopupController) -> Void)?
private var maximumSize: CGSize {
get {
return CGSizeMake(
UIScreen.mainScreen().bounds.size.width - margin * 2,
UIScreen.mainScreen().bounds.size.height - margin * 2
)
}
}
deinit {
self.removeFromParentViewController()
}
// MARK: Overrides
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
registerNotification()
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
unregisterNotification()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateLayouts()
}
}
// MARK: - Publics
public extension PopupController {
// MARK: Classes
public class func create(parentViewController: UIViewController) -> PopupController {
let controller = PopupController()
controller.defaultConfigure()
parentViewController.addChildViewController(controller)
parentViewController.view.addSubview(controller.view)
controller.didMoveToParentViewController(parentViewController)
return controller
}
public func customize(options: [PopupCustomOption]) -> PopupController {
customOptions(options)
return self
}
public func show(childViewController: UIViewController) -> PopupController {
self.addChildViewController(childViewController)
popupView = childViewController.view
configure()
childViewController.didMoveToParentViewController(self)
show(layout, animation: animation) { _ in
self.defaultContentOffset = self.baseScrollView.contentOffset
self.showedHandler?(self)
}
return self
}
public func didShowHandler(handler: (PopupController) -> Void) -> PopupController {
self.showedHandler = handler
return self
}
public func didCloseHandler(handler: (PopupController) -> Void) -> PopupController {
self.closedHandler = handler
return self
}
public func dismiss(completion: (() -> Void)? = nil) {
if isShowingKeyboard {
popupView.endEditing(true)
}
self.closePopup(completion)
}
}
// MARK: Privates
private extension PopupController {
func defaultConfigure() {
scrollable = true
dismissWhenTaps = true
backgroundStyle = .BlackFilter(alpha: 0.4)
}
func configure() {
view.hidden = true
view.frame = UIScreen.mainScreen().bounds
baseScrollView.frame = view.frame
view.addSubview(baseScrollView)
popupView.layer.cornerRadius = 2
popupView.layer.masksToBounds = true
popupView.frame.origin.y = 0
baseScrollView.addSubview(popupView)
}
func registerNotification() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PopupController.popupControllerWillShowKeyboard(_:)), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PopupController.popupControllerWillHideKeyboard(_:)), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PopupController.popupControllerDidHideKeyboard(_:)), name: UIKeyboardDidHideNotification, object: nil)
}
func unregisterNotification() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func customOptions(options: [PopupCustomOption]) {
for option in options {
switch option {
case .Layout(let layout):
self.layout = layout
case .Animation(let animation):
self.animation = animation
case .BackgroundStyle(let style):
self.backgroundStyle = style
case .Scrollable(let scrollable):
self.scrollable = scrollable
case .DismissWhenTaps(let dismiss):
self.dismissWhenTaps = dismiss
case .MovesAlongWithKeyboard(let moves):
self.movesAlongWithKeyboard = moves
}
}
}
func registerTapGesture() {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PopupController.didTapGesture(_:)))
gestureRecognizer.delegate = self
baseScrollView.addGestureRecognizer(gestureRecognizer)
}
func unregisterTapGesture() {
for recognizer in baseScrollView.gestureRecognizers ?? [] {
baseScrollView.removeGestureRecognizer(recognizer)
}
}
func updateLayouts() {
guard let child = self.childViewControllers.last as? PopupContentViewController else { return }
popupView.frame.size = child.sizeForPopup(self, size: maximumSize, showingKeyboard: isShowingKeyboard)
popupView.frame.origin.x = layout.origin(popupView).x
baseScrollView.frame = view.frame
baseScrollView.contentInset.top = layout.origin(popupView).y
defaultContentOffset.y = -baseScrollView.contentInset.top
}
func updateBackgroundStyle(style: PopupBackgroundStyle) {
switch style {
case .BlackFilter(let alpha):
baseScrollView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(alpha)
}
}
func updateScrollable() {
baseScrollView.scrollEnabled = scrollable
baseScrollView.alwaysBounceVertical = scrollable
if scrollable {
baseScrollView.delegate = self
}
}
@objc func popupControllerWillShowKeyboard(notification: NSNotification) {
isShowingKeyboard = true
let obj = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue
if needsToMoveFrom(obj.CGRectValue().origin) {
move(obj.CGRectValue().origin)
}
}
@objc func popupControllerWillHideKeyboard(notification: NSNotification) {
back()
}
@objc func popupControllerDidHideKeyboard(notification: NSNotification) {
self.isShowingKeyboard = false
}
// Tap Gesture
@objc func didTapGesture(sender: UITapGestureRecognizer) {
self.closePopup { _ in }
}
func closePopup(completion: (() -> Void)?) {
hide(animation) { _ in
completion?()
self.didClosePopup()
}
}
func didClosePopup() {
popupView.endEditing(true)
popupView.removeFromSuperview()
childViewControllers.forEach { $0.removeFromParentViewController() }
view.hidden = true
self.closedHandler?(self)
self.removeFromParentViewController()
}
func show(layout: PopupLayout, animation: PopupAnimation, completion: PopupAnimateCompletion) {
guard let childViewController = childViewControllers.last as? PopupContentViewController else {
return
}
popupView.frame.size = childViewController.sizeForPopup(self, size: maximumSize, showingKeyboard: isShowingKeyboard)
popupView.frame.origin.x = layout.origin(popupView!).x
switch animation {
case .FadeIn:
fadeIn(layout, completion: { () -> Void in
completion()
})
case .SlideUp:
slideUp(layout, completion: { () -> Void in
completion()
})
}
}
func hide(animation: PopupAnimation, completion: PopupAnimateCompletion) {
guard let child = childViewControllers.last as? PopupContentViewController else {
return
}
popupView.frame.size = child.sizeForPopup(self, size: maximumSize, showingKeyboard: isShowingKeyboard)
popupView.frame.origin.x = layout.origin(popupView).x
switch animation {
case .FadeIn:
self.fadeOut({ () -> Void in
self.clean()
completion()
})
case .SlideUp:
self.slideOut({ () -> Void in
self.clean()
completion()
})
}
}
func needsToMoveFrom(origin: CGPoint) -> Bool {
guard movesAlongWithKeyboard else {
return false
}
return (CGRectGetMaxY(popupView.frame) + layout.origin(popupView).y) > origin.y
}
func move(origin: CGPoint) {
guard let child = childViewControllers.last as? PopupContentViewController else {
return
}
popupView.frame.size = child.sizeForPopup(self, size: maximumSize, showingKeyboard: isShowingKeyboard)
baseScrollView.contentInset.top = origin.y - popupView.frame.height
baseScrollView.contentOffset.y = -baseScrollView.contentInset.top
defaultContentOffset = baseScrollView.contentOffset
}
func back() {
guard let child = childViewControllers.last as? PopupContentViewController else {
return
}
popupView.frame.size = child.sizeForPopup(self, size: maximumSize, showingKeyboard: isShowingKeyboard)
baseScrollView.contentInset.top = layout.origin(popupView).y
defaultContentOffset.y = -baseScrollView.contentInset.top
}
func clean() {
popupView.endEditing(true)
popupView.removeFromSuperview()
baseScrollView.removeFromSuperview()
}
}
// MARK: Animations
private extension PopupController {
func fadeIn(layout: PopupLayout, completion: () -> Void) {
baseScrollView.contentInset.top = layout.origin(popupView).y
view.hidden = false
popupView.alpha = 0.0
popupView.transform = CGAffineTransformMakeScale(0.9, 0.9)
baseScrollView.alpha = 0.0
UIView.animateWithDuration(0.3, delay: 0.1, options: .CurveEaseInOut, animations: { () -> Void in
self.popupView.alpha = 1.0
self.baseScrollView.alpha = 1.0
self.popupView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}) { (finished) -> Void in
completion()
}
}
func slideUp(layout: PopupLayout, completion: () -> Void) {
view.hidden = false
baseScrollView.backgroundColor = UIColor.clearColor()
baseScrollView.contentInset.top = layout.origin(popupView).y
baseScrollView.contentOffset.y = -UIScreen.mainScreen().bounds.height
UIView.animateWithDuration(
0.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .CurveLinear, animations: { () -> Void in
self.updateBackgroundStyle(self.backgroundStyle)
self.baseScrollView.contentOffset.y = -layout.origin(self.popupView).y
self.defaultContentOffset = self.baseScrollView.contentOffset
}, completion: { (isFinished) -> Void in
completion()
})
}
func fadeOut(completion: () -> Void) {
UIView.animateWithDuration(
0.3, delay: 0.0, options: .CurveEaseInOut, animations: { () -> Void in
self.popupView.alpha = 0.0
self.baseScrollView.alpha = 0.0
self.popupView.transform = CGAffineTransformMakeScale(0.9, 0.9)
}) { (finished) -> Void in
completion()
}
}
func slideOut(completion: () -> Void) {
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: .CurveLinear, animations: { () -> Void in
self.popupView.frame.origin.y = UIScreen.mainScreen().bounds.height
self.baseScrollView.alpha = 0.0
}, completion: { (isFinished) -> Void in
completion()
})
}
}
// MARK: UIScrollViewDelegate methods
extension PopupController: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
let delta: CGFloat = defaultContentOffset.y - scrollView.contentOffset.y
if delta > 20 && isShowingKeyboard {
popupView.endEditing(true)
return
}
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let delta: CGFloat = defaultContentOffset.y - scrollView.contentOffset.y
if delta > 50 {
baseScrollView.contentInset.top = -scrollView.contentOffset.y
animation = .SlideUp
self.closePopup { _ in }
}
}
}
extension PopupController: UIGestureRecognizerDelegate {
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return gestureRecognizer.view == touch.view
}
}
extension UIViewController {
func popupController() -> PopupController? {
var parent = parentViewController
while !(parent is PopupController || parent == nil) {
parent = parent!.parentViewController
}
return parent as? PopupController
}
} | 20f3ead964dddb1749ed64316807143c | 32.749478 | 187 | 0.629261 | false | false | false | false |
ps2/rileylink_ios | refs/heads/dev | MinimedKit/Messages/Models/HistoryPage.swift | mit | 1 | //
// HistoryPage.swift
// RileyLink
//
// Created by Pete Schwamb on 3/3/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public enum HistoryPageError: Error {
case invalidCRC
case unknownEventType(eventType: UInt8)
}
extension HistoryPageError: LocalizedError {
public var errorDescription: String? {
switch self {
case .invalidCRC:
return LocalizedString("History page failed crc check", comment: "Error description for history page failing crc check")
case .unknownEventType(let eventType):
return String(format: LocalizedString("Unknown history record type: %$1@", comment: "Format string for error description for an unknown record type in a history page. (1: event type number)"), eventType)
}
}
}
public struct HistoryPage {
public let events: [PumpEvent]
// Useful interface for testing
init(events: [PumpEvent]) {
self.events = events
}
public init(pageData: Data, pumpModel: PumpModel) throws {
guard checkCRC16(pageData) else {
events = [PumpEvent]()
throw HistoryPageError.invalidCRC
}
let pageData = pageData.subdata(in: 0..<1022)
func matchEvent(_ offset: Int) -> PumpEvent? {
if let eventType = PumpEventType(rawValue: pageData[offset]) {
let remainingData = pageData.subdata(in: offset..<pageData.count)
if let event = eventType.eventType.init(availableData: remainingData, pumpModel: pumpModel) {
return event
}
}
return nil
}
var offset = 0
let length = pageData.count
var unabsorbedInsulinRecord: UnabsorbedInsulinPumpEvent?
var tempEvents = [PumpEvent]()
while offset < length {
// Slurp up 0's
if pageData[offset] == 0 {
offset += 1
continue
}
guard var event = matchEvent(offset) else {
events = [PumpEvent]()
throw HistoryPageError.unknownEventType(eventType: pageData[offset])
}
if unabsorbedInsulinRecord != nil, var bolus = event as? BolusNormalPumpEvent {
bolus.unabsorbedInsulinRecord = unabsorbedInsulinRecord
unabsorbedInsulinRecord = nil
event = bolus
}
if let event = event as? UnabsorbedInsulinPumpEvent {
unabsorbedInsulinRecord = event
} else {
tempEvents.append(event)
}
offset += event.length
}
events = tempEvents
}
}
| da44c4eb71c6463c653e9dcf3ff3865f | 31.023256 | 215 | 0.583515 | false | false | false | false |
uber/RIBs | refs/heads/main | ios/tutorials/tutorial4-completed/TicTacToe/LoggedIn/LoggedInBuilder.swift | apache-2.0 | 1 | //
// Copyright (c) 2017. Uber Technologies
//
// 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 RIBs
protocol LoggedInDependency: Dependency {
var loggedInViewController: LoggedInViewControllable { get }
}
final class LoggedInComponent: Component<LoggedInDependency> {
fileprivate var loggedInViewController: LoggedInViewControllable {
return dependency.loggedInViewController
}
fileprivate var games: [Game] {
return shared {
return [RandomWinAdapter(dependency: self), TicTacToeAdapter(dependency: self)]
}
}
var mutableScoreStream: MutableScoreStream {
return shared { ScoreStreamImpl() }
}
var scoreStream: ScoreStream {
return mutableScoreStream
}
let player1Name: String
let player2Name: String
init(dependency: LoggedInDependency, player1Name: String, player2Name: String) {
self.player1Name = player1Name
self.player2Name = player2Name
super.init(dependency: dependency)
}
}
// MARK: - Builder
protocol LoggedInBuildable: Buildable {
func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> (router: LoggedInRouting, actionableItem: LoggedInActionableItem)
}
final class LoggedInBuilder: Builder<LoggedInDependency>, LoggedInBuildable {
override init(dependency: LoggedInDependency) {
super.init(dependency: dependency)
}
func build(withListener listener: LoggedInListener, player1Name: String, player2Name: String) -> (router: LoggedInRouting, actionableItem: LoggedInActionableItem) {
let component = LoggedInComponent(dependency: dependency,
player1Name: player1Name,
player2Name: player2Name)
let interactor = LoggedInInteractor(games: component.games)
interactor.listener = listener
let offGameBuilder = OffGameBuilder(dependency: component)
let router = LoggedInRouter(interactor: interactor,
viewController: component.loggedInViewController,
offGameBuilder: offGameBuilder)
return (router, interactor)
}
}
| b3f94dda0e0a0480dae926312742845d | 34.358974 | 168 | 0.692168 | false | false | false | false |
brunogodbout/AnimalBrowser | refs/heads/master | AnimalBrowser/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// AnimalBrowser
//
// Created by Oliver Foggin on 12/06/2015.
// Copyright © 2015 Oliver Foggin. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
guard let theWindow = self.window,
let splitViewController: UISplitViewController = theWindow.rootViewController as? UISplitViewController,
let masterNavigationController = splitViewController.viewControllers[0] as? UINavigationController,
let masterViewController = masterNavigationController.topViewController as? AnimalListViewController,
let detailNavController = splitViewController.viewControllers[1] as? UINavigationController,
let detailViewController = detailNavController.topViewController as? AnimalViewController
else {fatalError("View hierarchy not correct!")}
splitViewController.delegate = masterViewController
detailViewController.animal = masterViewController.animalData.animals[0]
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:.
}
}
| ebab7ac9ea14a323f68936e2c7d56ca8 | 53.740741 | 285 | 0.756428 | false | false | false | false |
grokify/ringcentral-swift | refs/heads/master | src/Subscription/Subscription.swift | mit | 1 | //
// Subscription.swift
// src
//
// Created by Anil Kumar BP on 11/20/15.
// Copyright (c) 2015 Anil Kumar BP. All rights reserved.
//
import Foundation
import PubNub
public class Subscription: NSObject, PNObjectEventListener {
public static var EVENT_NOTIFICATION: String = "notification"
public static var EVENT_REMOVE_SUCCESS: String = "removeSuccess"
public static var EVENT_RENEW_SUCCESS: String = "removeError"
public static var EVENT_RENEW_ERROR: String = "renewError"
public static var EVENT_SUBSCRIBE_SUCCESS: String = "subscribeSuccess"
public static var EVENT_SUBSCRIBE_ERROR: String = "subscribeError"
/// Fields of subscription
let platform: Platform!
var pubnub: PubNub?
var eventFilters: [String] = []
var _keepPolling: Bool = false
var subscription: ISubscription?
var function: ((arg: String) -> Void) = {(arg) in }
/// Initializes a subscription with Platform
///
/// :param: platform Authorized platform
public init(platform: Platform) {
self.platform = platform
}
/// Structure holding information about how PubNub is delivered
struct IDeliveryMode {
var transportType: String = "PubNub"
var encryption: Bool = false
var address: String = ""
var subscriberKey: String = ""
var secretKey: String?
var encryptionKey: String = ""
}
/// Structure holding information about the details of PubNub
struct ISubscription {
var eventFilters: [String] = []
var expirationTime: String = ""
var expiresIn: NSNumber = 0
var deliveryMode: IDeliveryMode = IDeliveryMode()
var id: String = ""
var creationTime: String = ""
var status: String = ""
var uri: String = ""
}
/// Returns PubNub object
///
/// :returns: PubNub object
public func getPubNub() -> PubNub? {
return pubnub
}
/// Returns the platform
///
/// :returns: Platform
public func getPlatform() -> Platform {
return platform
}
/// Adds event for PubNub
///
/// :param: events List of events to add
/// :returns: Subscription
public func addEvents(events: [String]) -> Subscription {
for event in events {
self.eventFilters.append(event)
}
return self
}
/// Sets events for PubNub (deletes all previous ones)
///
/// :param: events List of events to set
/// :returns: Subscription
public func setevents(events: [String]) -> Subscription {
self.eventFilters = events
return self
}
/// Returns all the event filters
///
/// :returns: [String] of all the event filters
private func getFullEventFilters() -> [String] {
return self.eventFilters
}
/// Registers for a new subscription or renews an old one
///
/// :param: options List of options for PubNub
public func register(options: [String: AnyObject] = [String: AnyObject](), completion: (transaction: ApiResponse) -> Void) {
if (isSubscribed()) {
return renew(options) {
(t) in
completion(transaction: t)
}
} else {
return subscribe(options) {
(t) in
completion(transaction: t)
}
}
}
/// Renews the subscription
///
/// :param: options List of options for PubNub
public func renew(options: [String: AnyObject], completion: (transaction: ApiResponse) -> Void) {
// include PUT instead of the apiCall
platform.put("/subscription/" + subscription!.id,
body: [
"eventFilters": getFullEventFilters()
]) {
(transaction) in
let dictionary = transaction.getDict()
if let error = dictionary["errorCode"] {
self.subscribe(options){
(t) in
completion(transaction: t)
}
} else {
self.subscription!.expiresIn = dictionary["expiresIn"] as! NSNumber
self.subscription!.expirationTime = dictionary["expirationTime"] as! String
}
}
}
/// Subscribes to a channel with given events
///
/// :param: options Options for PubNub
public func subscribe(options: [String: AnyObject], completion: (transaction: ApiResponse) -> Void) {
// Create Subscription
platform.post("/subscription",
body: [
"eventFilters": getFullEventFilters(),
"deliveryMode": [
"transportType": "PubNub",
"encryption": "false"
]
]) {
(transaction) in
let dictionary = transaction.getDict()
var sub = ISubscription()
sub.eventFilters = dictionary["eventFilters"] as! [String]
self.eventFilters = dictionary["eventFilters"] as! [String]
sub.expirationTime = dictionary["expirationTime"] as! String
sub.expiresIn = dictionary["expiresIn"] as! NSNumber
sub.id = dictionary["id"] as! String
sub.creationTime = dictionary["creationTime"] as! String
sub.status = dictionary["status"] as! String
sub.uri = dictionary["uri"] as! String
self.subscription = sub
var del = IDeliveryMode()
var dictDelivery = dictionary["deliveryMode"] as! NSDictionary
del.transportType = dictDelivery["transportType"] as! String
del.encryption = dictDelivery["encryption"] as! Bool
del.address = dictDelivery["address"] as! String
del.subscriberKey = dictDelivery["subscriberKey"] as! String
del.secretKey = dictDelivery["secretKey"] as? String
del.encryptionKey = dictDelivery["encryptionKey"] as! String
self.subscription!.deliveryMode = del
self.subscribeAtPubnub()
}
}
/// Sets a method that will run after every PubNub callback
///
/// :param: functionHolder Function to be ran after every PubNub callback
public func setMethod(functionHolder: ((arg: String) -> Void)) {
self.function = functionHolder
}
/// Checks if currently subscribed
///
/// :returns: Bool of if currently subscribed
public func isSubscribed() -> Bool {
if let sub = self.subscription {
let dil = sub.deliveryMode
return dil.subscriberKey != "" && dil.address != ""
}
return false
}
/// Emits events
public func emit(event: String) -> AnyObject {
return ""
}
/// Updates the subscription with the one passed in
///
/// :param: subscription New subscription passed in
private func updateSubscription(subscription: ISubscription) {
self.subscription = subscription
}
/// Unsubscribes from subscription
private func unsubscribe() {
if let channel = subscription?.deliveryMode.address {
pubnub?.unsubscribeFromChannelGroups([channel], withPresence: true)
}
if let sub = subscription {
// delete the subscription
platform.delete("/subscription/" + sub.id) {
(transaction) in
self.subscription = nil
self.eventFilters = []
self.pubnub = nil
}
}
}
/// Subscribes to a channel given the settings
private func subscribeAtPubnub() {
let config = PNConfiguration( publishKey: "", subscribeKey: subscription!.deliveryMode.subscriberKey)
self.pubnub = PubNub.clientWithConfiguration(config)
self.pubnub?.addListener(self)
self.pubnub?.subscribeToChannels([subscription!.deliveryMode.address], withPresence: true)
}
/// Notifies
private func notify() {
}
/// Method that PubNub calls when receiving a message back from Subscription
///
/// :param: client The client of the receiver
/// :param: message Message being received back
public func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
var base64Message = message.data.message as! String
var base64Key = self.subscription!.deliveryMode.encryptionKey
let key = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] as [UInt8]
let iv = Cipher.randomIV(AES.blockSize)
let decrypted = AES(key: base64ToByteArray(base64Key), iv: [0x00], blockMode: .ECB)?.decrypt(base64ToByteArray(base64Message), padding: PKCS7())
var endMarker = NSData(bytes: (decrypted as [UInt8]!), length: decrypted!.count)
if let str: String = NSString(data: endMarker, encoding: NSUTF8StringEncoding) as? String {
self.function(arg: str)
} else {
NSException(name: "Error", reason: "Error", userInfo: nil).raise()
}
}
/// Converts base64 to byte array
///
/// :param: base64String base64 String to be converted
/// :returns: [UInt8] byte array
private func base64ToByteArray(base64String: String) -> [UInt8] {
let nsdata: NSData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0))!
var bytes = [UInt8](count: nsdata.length, repeatedValue: 0)
nsdata.getBytes(&bytes, length: nsdata.length)
return bytes
}
/// Converts byte array to base64
///
/// :param: bytes byte array to be converted
/// :returns: String of the base64
private func byteArrayToBase64(bytes: [UInt8]) -> String {
let nsdata = NSData(bytes: bytes, length: bytes.count)
let base64Encoded = nsdata.base64EncodedStringWithOptions(nil);
return base64Encoded;
}
/// Converts a dictionary represented as a String into a NSDictionary
///
/// :param: string Dictionary represented as a String
/// :returns: NSDictionary of the String representation of a Dictionary
private func stringToDict(string: String) -> NSDictionary {
var data: NSData = string.dataUsingEncoding(NSUTF8StringEncoding)!
return NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
}
} | 4a02d82922a636e3871f8c1b6a1d2fc4 | 35.717172 | 152 | 0.581163 | false | false | false | false |
Authman2/Pix | refs/heads/master | Pix/LandingPage.swift | gpl-3.0 | 1 | //
// LandingPage.swift
// Pix
//
// Created by Adeola Uthman on 12/21/16.
// Copyright © 2016 Adeola Uthman. All rights reserved.
//
import UIKit
import SnapKit
import Firebase
import Spring
class LandingPage: UIViewController {
/********************************
*
* VARIABLES
*
********************************/
/* The title of the app, Pix. */
let titleLabel: UILabel = {
let t = UILabel();
t.translatesAutoresizingMaskIntoConstraints = false;
t.text = "Pix";
t.textColor = UIColor.white;
t.font = UIFont(name: t.font.fontName, size: 35);
t.isUserInteractionEnabled = false;
return t;
}();
/* The email text field. */
let emailField: UITextField = {
let e = UITextField();
e.translatesAutoresizingMaskIntoConstraints = false;
e.placeholder = "Email";
e.backgroundColor = UIColor.white;
e.textAlignment = .center;
e.autocorrectionType = .no;
e.autocapitalizationType = .none;
e.keyboardType = .emailAddress;
return e;
}();
/* The password text field. */
let passwordField: UITextField = {
let p = UITextField();
p.translatesAutoresizingMaskIntoConstraints = false;
p.placeholder = "Password";
p.backgroundColor = UIColor.white;
p.textAlignment = .center;
p.isSecureTextEntry = true;
p.autocorrectionType = .no;
p.autocapitalizationType = .none;
return p;
}();
/* The sign up button. */
let signupButton: UIButton = {
let s = UIButton();
s.setTitle("Sign Up", for: .normal);
s.backgroundColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1);
s.layer.cornerRadius = 25;
s.titleLabel?.font = UIFont(name: (s.titleLabel?.font.fontName)!, size: 15);
return s;
}();
/* The login button. */
let loginButton: SpringButton = {
let s = SpringButton();
s.setTitle("Login", for: .normal);
s.backgroundColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1);
s.layer.cornerRadius = 25;
s.titleLabel?.font = UIFont(name: (s.titleLabel?.font.fontName)!, size: 15);
return s;
}();
/* Displays the status of loggin in. */
let statusLabel: UILabel = {
let s = UILabel();
s.translatesAutoresizingMaskIntoConstraints = false;
s.textColor = UIColor.red;
s.isHidden = true;
s.isUserInteractionEnabled = false;
s.textAlignment = .center;
return s;
}();
/* The firebase database reference. */
let fireRef: FIRDatabaseReference! = FIRDatabase.database().reference();
/********************************
*
* METHODS
*
********************************/
override func viewDidLoad() {
super.viewDidLoad();
view.backgroundColor = UIColor(red: 41/255, green: 200/255, blue: 153/255, alpha: 1);
navigationController?.navigationBar.isHidden = true;
/* Set up the view. */
view.addSubview(titleLabel);
view.addSubview(emailField);
view.addSubview(passwordField);
let btnView = UIView();
btnView.addSubview(signupButton);
btnView.addSubview(loginButton);
view.addSubview(btnView);
view.addSubview(statusLabel);
titleLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(view.snp.top).offset(70);
maker.centerX.equalTo(view.snp.centerX);
}
emailField.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(titleLabel.snp.bottom).offset(25);
maker.width.equalTo(view.width);
maker.height.equalTo(30);
}
passwordField.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(emailField.snp.bottom).offset(25);
maker.width.equalTo(view.width);
maker.height.equalTo(30);
}
statusLabel.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(passwordField.snp.bottom);
maker.width.equalTo(view.width);
maker.height.equalTo(30);
maker.centerX.equalTo(view.snp.centerX);
}
btnView.snp.makeConstraints { (maker: ConstraintMaker) in
maker.top.equalTo(statusLabel.snp.bottom).offset(25);
maker.width.equalTo(view.width);
maker.height.equalTo(100);
}
signupButton.snp.makeConstraints { (maker: ConstraintMaker) in
maker.right.equalTo(btnView.snp.centerX).offset(10);
maker.top.equalTo(btnView.snp.top);
maker.width.equalTo(70);
maker.height.equalTo(45);
}
loginButton.snp.makeConstraints { (maker: ConstraintMaker) in
maker.left.equalTo(btnView.snp.centerX).offset(10);
maker.top.equalTo(btnView.snp.top);
maker.width.equalTo(70);
maker.height.equalTo(45);
}
signupButton.addTarget(self, action: #selector(signUp), for: .touchUpInside);
loginButton.addTarget(self, action: #selector(login), for: .touchUpInside);
/* Automatic login. */
self.checkAutoLogin();
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated);
util.loadUsedIDs();
navigationController?.navigationBar.isHidden = true;
statusLabel.isHidden = true;
}
// Checks if a user is already logged in and automatically signs them in.
func checkAutoLogin() {
if let cUser = FIRAuth.auth()?.currentUser {
fireRef.child("Users").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
let dictionary = snapshot.value as? [String: AnyObject] ?? [:];
for user in dictionary {
let em = user.value["email"] as? String ?? "";
if em == cUser.email! {
let pass = user.value["password"] as? String ?? "";
self.emailField.text = em;
self.passwordField.text = pass;
break;
}
}
self.login();
})
}
}
/* Goes to the sign up page. */
@objc func signUp() {
let signupPage = SignUpPage();
show(signupPage, sender: self);
}
/* Logs the user in and sends them to the home feed page. */
@objc func login() {
loginButton.animateButtonClick();
// Sign in.
if((self.emailField.text?.length())! > 0 && (self.passwordField.text?.length())! > 0) {
Networking.loginUser(withEmail: self.emailField.text!, andPassword: self.passwordField.text!, success: {
// Logging in message.
self.statusLabel.textColor = UIColor.green;
self.statusLabel.isHidden = false;
self.statusLabel.text = "Logging In!";
if let cUser = Networking.currentUser {
// Load up the current user's photos while moving to the main app.
util.loadUsersPhotos(user: cUser, continous: true, completion: nil);
util.loadActivity();
feedPage.postFeed.removeAll();
feedPage.adapter.reloadData(completion: nil);
self.goToApp();
}
}, failure: {
self.statusLabel.textColor = UIColor.red;
self.statusLabel.isHidden = false;
self.statusLabel.text = "Email or password is incorrect.";
})
}
}
/* Tells the program to take the user to the actually application. */
private func goToApp() {
if navigationController?.topViewController !== feedPage {
navigationController?.pushViewController(feedPage, animated: false);
}
}
// Close the keyboard
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event);
emailField.endEditing(true);
passwordField.endEditing(true);
}
}
| 6e9d2ca30001e3013f110035a95d4727 | 30.508961 | 116 | 0.538164 | false | false | false | false |
apple/swift-experimental-string-processing | refs/heads/main | Tests/RegexBuilderTests/AnyRegexOutputTests.swift | apache-2.0 | 1 |
import XCTest
import _StringProcessing
import RegexBuilder
private let enablePrinting = false
extension RegexDSLTests {
func testContrivedAROExample() {
// Find and extract potential IDs. IDs are 8 bytes encoded as
// 16 hexadecimal numbers, with an optional `-` between every
// double-byte (i.e. 4 hex digits).
//
// AAAA-BBBB-CCCC-DDDD
// AAAABBBBCCCCDDDD
// AAAABBBBCCCC-DDDD
//
// IDs are converted to uppercase and hyphen separated
//
// The regex can have special capture names which affect replacement
// behavior
// - "salient": presented uppercase in square brackets after
// - "note": presented lowercase in parens
// - none: nothing
// - no captures: "<error>"
//
let input = """
Machine 1234-5678-90ab-CDEF connected
Session FEDCAB0987654321 ended
Artiface 0011deff-2231-abcd contrived
"""
let noCapOutput = """
Machine <error> connected
Session <error> ended
Artiface <error> contrived
"""
let unnamedOutput = """
Machine 1234-5678-90AB-CDEF connected
Session FEDC-AB09-8765-4321 ended
Artiface 0011-DEFF-2231-ABCD contrived
"""
let salientOutput = """
Machine 1234-5678-90AB-CDEF [5678] connected
Session FEDC-AB09-8765-4321 [AB09] ended
Artiface 0011-DEFF-2231-ABCD [DEFF] contrived
"""
let noteOutput = """
Machine 1234-5678-90AB-CDEF (5678) connected
Session FEDC-AB09-8765-4321 (ab09) ended
Artiface 0011-DEFF-2231-ABCD (deff) contrived
"""
enum Kind {
case none
case unnamed
case salient
case note
func contains(captureNamed s: String) -> Bool {
switch self {
case .none: return false
case .unnamed: return false
case .salient: return s == "salient"
case .note: return s == "note"
}
}
var expected: String {
switch self {
case .none: return """
Machine <error> connected
Session <error> ended
Artiface <error> contrived
"""
case .unnamed: return """
Machine 1234-5678-90AB-CDEF connected
Session FEDC-AB09-8765-4321 ended
Artiface 0011-DEFF-2231-ABCD contrived
"""
case .salient: return """
Machine 1234-5678-90AB-CDEF [5678] connected
Session FEDC-AB09-8765-4321 [AB09] ended
Artiface 0011-DEFF-2231-ABCD [DEFF] contrived
"""
case .note: return """
Machine 1234-5678-90AB-CDEF (5678) connected
Session FEDC-AB09-8765-4321 (ab09) ended
Artiface 0011-DEFF-2231-ABCD (deff) contrived
"""
}
}
}
func checkContains<Output>(
_ re: Regex<Output>, _ kind: Kind
) {
for name in ["", "salient", "note", "other"] {
XCTAssertEqual(
kind.contains(captureNamed: name), re.contains(captureNamed: name))
}
}
func checkAROReplacing<Output>(
_ re: Regex<Output>, _ kind: Kind
) {
let aro = Regex<AnyRegexOutput>(re)
let output = input.replacing(aro) {
(match: Regex<AnyRegexOutput>.Match) -> String in
if match.count < 5 { return "<error>" }
let suffix: String
if re.contains(captureNamed: "salient") {
let body = match["salient"]!.substring?.uppercased() ?? "<no capture>"
suffix = " [\(body)]"
} else if re.contains(captureNamed: "note") {
let body = match["note"]!.substring?.lowercased() ?? "<no capture>"
suffix = " (\(body))"
} else {
suffix = ""
}
return match.output.dropFirst().lazy.map {
$0.substring!.uppercased()
}.joined(separator: "-") + suffix
}
XCTAssertEqual(output, kind.expected)
if enablePrinting {
print("---")
print(output)
print(kind)
}
}
func check<Output>(
_ re: Regex<Output>, _ kind: Kind, _ expected: String
) {
let aro = Regex<AnyRegexOutput>(re)
let casted = try! XCTUnwrap(Regex(aro, as: Output.self))
// contains(captureNamed:)
checkContains(re, kind)
checkContains(aro, kind)
checkContains(casted, kind)
// replacing
checkAROReplacing(re, kind)
checkAROReplacing(aro, kind)
checkAROReplacing(casted, kind)
}
// Literals (mocked up via explicit `as` types)
check(try! Regex(#"""
(?x)
\p{hexdigit}{4} -? \p{hexdigit}{4} -?
\p{hexdigit}{4} -? \p{hexdigit}{4}
"""#, as: Substring.self),
.none,
noCapOutput
)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#, as: (Substring, Substring, Substring, Substring, Substring).self),
.unnamed,
unnamedOutput
)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (?<salient>\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#, as: (Substring, Substring, salient: Substring, Substring, Substring).self),
.salient,
salientOutput
)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (?<note>\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#, as: (Substring, Substring, note: Substring, Substring, Substring).self),
.note,
noteOutput
)
// Run-time strings (ARO)
check(try! Regex(#"""
(?x)
\p{hexdigit}{4} -? \p{hexdigit}{4} -?
\p{hexdigit}{4} -? \p{hexdigit}{4}
"""#),
.none,
noCapOutput)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#),
.unnamed,
unnamedOutput
)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (?<salient>\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#),
.salient,
salientOutput
)
check(try! Regex(#"""
(?x)
(\p{hexdigit}{4}) -? (?<note>\p{hexdigit}{4}) -?
(\p{hexdigit}{4}) -? (\p{hexdigit}{4})
"""#),
.note,
noteOutput
)
// Run-time strings (errors)
XCTAssertThrowsError(try Regex("abc", as: (Substring, Substring).self))
XCTAssertThrowsError(try Regex("(abc)", as: Substring.self))
XCTAssertThrowsError(try Regex("(?<test>abc)", as: (Substring, Substring).self))
XCTAssertThrowsError(try Regex("(?<test>abc)?", as: (Substring, test: Substring).self))
XCTAssertNoThrow(try Regex("abc", as: Substring.self))
XCTAssertNoThrow(try Regex("(abc)", as: (Substring, Substring).self))
XCTAssertNoThrow(try Regex("(?<test>abc)", as: (Substring, test: Substring).self))
XCTAssertNoThrow(try Regex("(?<test>abc)?", as: (Substring, test: Substring?).self))
// Builders
check(
Regex {
let doublet = Repeat(.hexDigit, count: 4)
doublet
Optionally { "-" }
doublet
Optionally { "-" }
doublet
Optionally { "-" }
doublet
},
.none,
noCapOutput
)
check(
Regex {
let doublet = Repeat(.hexDigit, count: 4)
Capture { doublet }
Optionally { "-" }
Capture { doublet }
Optionally { "-" }
Capture { doublet }
Optionally { "-" }
Capture { doublet }
},
.unnamed,
unnamedOutput
)
// FIXME: `salient` and `note` builders using a semantically rich
// `mapOutput`
}
}
| 46c325a832f7e60984381e05fb896396 | 27.616541 | 91 | 0.549527 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/powx-n.swift | mit | 2 | /**
* https://leetcode.com/problems/powx-n/
*
*
*/
class Solution {
/// Divide and Conquer
func myPow(_ x: Double, _ n: Int) -> Double {
if n == 0 { return 1 }
if n < 0 { return myPow(1.0 / x, -n) }
if n == 1 { return x }
if n % 2 == 0 {
let pow = myPow(x, n / 2)
return pow * pow
} else {
let pow = myPow(x, n / 2)
return x * pow * pow
}
}
}
/**
* https://leetcode.com/problems/powx-n/
*
*
*/
// Date: Thu Jul 16 09:08:28 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(log n)
/// - Space: O(log n), it's the height of stack calls.
///
func myPow(_ x: Double, _ n: Int) -> Double {
if n < 0 { return myPow(1.0 / x, -n) }
if n == 0 { return 1 }
if n == 1 { return x }
let p = myPow(x, n / 2)
if n % 2 == 0 {
return p * p
} else {
return x * p * p
}
}
}
/**
* https://leetcode.com/problems/powx-n/
*
*
*/
// Date: Thu Jul 16 09:25:19 PDT 2020
class Solution {
/// iterative solution.
func myPow(_ x: Double, _ n: Int) -> Double {
var x = x
var n = n
if n < 0 {
x = 1.0 / x
n = -n
}
var pow = 1.0
while n > 0 {
if n % 2 == 1 {
pow *= x
}
x *= x
n /= 2
}
return pow
}
}
| 7e9ed0f014b46e5cadaa8ac19ee56e2d | 20.492754 | 62 | 0.390425 | false | false | false | false |
JGiola/swift-corelibs-foundation | refs/heads/master | Foundation/NSTimer.swift | apache-2.0 | 13 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal func __NSFireTimer(_ timer: CFRunLoopTimer?, info: UnsafeMutableRawPointer?) -> Void {
let t: Timer = NSObject.unretainedReference(info!)
t._fire(t)
}
open class Timer : NSObject {
typealias CFType = CFRunLoopTimer
internal var _cfObject: CFType {
get {
return _timer!
}
set {
_timer = newValue
}
}
internal var _timer: CFRunLoopTimer? // has to be optional because this is a chicken/egg problem with initialization in swift
internal var _fire: (Timer) -> Void = { (_: Timer) in }
/// Alternative API for timer creation with a block.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
/// - Warning: Capturing the timer or the owner of the timer inside of the block may cause retain cycles. Use with caution
public init(fire date: Date, interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Swift.Void) {
super.init()
_fire = block
var context = CFRunLoopTimerContext()
withRetainedReference {
(refPtr: UnsafeMutablePointer<UInt8>) in
context.info = UnsafeMutableRawPointer(refPtr)
}
let timer = withUnsafeMutablePointer(to: &context) { (ctx: UnsafeMutablePointer<CFRunLoopTimerContext>) -> CFRunLoopTimer in
var t = interval
if !repeats {
t = 0.0
}
return CFRunLoopTimerCreate(kCFAllocatorSystemDefault, date.timeIntervalSinceReferenceDate, t, 0, 0, __NSFireTimer, ctx)
}
_timer = timer
}
// !!! The interface as exposed by Darwin marks init(fire date: Date, interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Swift.Void) with "convenience", but this constructor without.
// !!! That doesn't make sense as init(fire date: Date, ...) is more general than this constructor, which can be implemented in terms of init(fire date: Date, ...).
// !!! The convenience here has been switched around and deliberately does not match what is exposed by Darwin Foundation.
/// Creates and returns a new Timer object initialized with the specified block object.
/// - parameter timeInterval: The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
/// - parameter repeats: If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
/// - parameter block: The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
public convenience init(timeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Swift.Void) {
self.init(fire: Date(), interval: interval, repeats: repeats, block: block)
}
/// Alternative API for timer creation with a block.
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
/// - Warning: Capturing the timer or the owner of the timer inside of the block may cause retain cycles. Use with caution
open class func scheduledTimer(withTimeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) -> Timer {
let timer = Timer(fire: Date(timeIntervalSinceNow: interval), interval: interval, repeats: repeats, block: block)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer._timer!, kCFRunLoopDefaultMode)
return timer
}
open func fire() {
if !isValid {
return
}
_fire(self)
if timeInterval == 0.0 {
invalidate()
}
}
open var fireDate: Date {
get {
return Date(timeIntervalSinceReferenceDate: CFRunLoopTimerGetNextFireDate(_timer!))
}
set {
CFRunLoopTimerSetNextFireDate(_timer!, newValue.timeIntervalSinceReferenceDate)
}
}
open var timeInterval: TimeInterval {
return CFRunLoopTimerGetInterval(_timer!)
}
open var tolerance: TimeInterval {
get {
return CFRunLoopTimerGetTolerance(_timer!)
}
set {
CFRunLoopTimerSetTolerance(_timer!, newValue)
}
}
open func invalidate() {
CFRunLoopTimerInvalidate(_timer!)
}
open var isValid: Bool {
return CFRunLoopTimerIsValid(_timer!)
}
// Timer's userInfo is meant to be read-only. The initializers that are exposed on Swift, however, do not take a custom userInfo, so it can never be set.
// The default value should then be nil, and this is left as subclassable for potential consumers.
open var userInfo: Any? {
return nil
}
}
| 3ef515a1394154386fc46c4df48fa8da | 45.07438 | 202 | 0.673363 | false | false | false | false |
lSlProject/master | refs/heads/master | lSl Project/lSl Project/ModelController.swift | gpl-3.0 | 1 | //
// ModelController.swift
// lSl Project
//
// Created by crotel on 8/6/15.
// Copyright (c) 2015 CROTEL©. All rights reserved.
//
import UIKit
/*
A controller object that manages a simple model -- a collection of month names.
The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:.
It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application.
There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand.
*/
class ModelController: NSObject, UIPageViewControllerDataSource {
var pageData = NSArray()
override init() {
super.init()
// Create the data model.
let dateFormatter = NSDateFormatter()
pageData = dateFormatter.monthSymbols
}
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> DataViewController? {
// Return the data view controller for the given index.
if (self.pageData.count == 0) || (index >= self.pageData.count) {
return nil
}
// Create a new view controller and pass suitable data.
let dataViewController = storyboard.instantiateViewControllerWithIdentifier("DataViewController") as! DataViewController
dataViewController.dataObject = self.pageData[index]
return dataViewController
}
func indexOfViewController(viewController: DataViewController) -> Int {
// Return the index of the given data view controller.
// For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index.
if let dataObject: AnyObject = viewController.dataObject {
return self.pageData.indexOfObject(dataObject)
} else {
return NSNotFound
}
}
// MARK: - Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if (index == 0) || (index == NSNotFound) {
return nil
}
index--
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = self.indexOfViewController(viewController as! DataViewController)
if index == NSNotFound {
return nil
}
index++
if index == self.pageData.count {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
}
| 893319c1e7d41ec0f1a254208ac789b1 | 38.925926 | 225 | 0.708101 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | refs/heads/main | arcgis-ios-sdk-samples/Features/Toggle between feature request modes/ToggleFeatureRequestModesViewController.swift | apache-2.0 | 1 | // Copyright 2021 Esri.
//
// 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 ArcGIS
class ToggleFeatureRequestModesViewController: UIViewController {
@IBOutlet var mapView: AGSMapView! {
didSet {
mapView.map = AGSMap(basemapStyle: .arcGISTopographic)
mapView.setViewpoint(AGSViewpoint(latitude: 45.5266, longitude: -122.6219, scale: 6000))
}
}
@IBOutlet var modeBarButtonItem: UIBarButtonItem!
@IBOutlet var populateBarButtonItem: UIBarButtonItem!
@IBOutlet var statusLabel: UILabel!
private static let featureServiceURL = URL(string: "https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/arcgis/rest/services/Trees_of_Portland/FeatureServer/0")!
private let featureTable = AGSServiceFeatureTable(url: featureServiceURL)
private enum FeatureRequestMode: CaseIterable {
case cache, noCache, manualCache
var title: String {
switch self {
case .cache:
return "Cache"
case .noCache:
return "No cache"
case .manualCache:
return "Manual cache"
}
}
var mode: AGSFeatureRequestMode {
switch self {
case .cache:
return .onInteractionCache
case .noCache:
return .onInteractionNoCache
case .manualCache:
return .manualCache
}
}
}
/// Prompt mode selection.
@IBAction private func modeButtonTapped(_ button: UIBarButtonItem) {
// Set up action sheets.
let alertController = UIAlertController(
title: "Choose a feature request mode.",
message: nil,
preferredStyle: .actionSheet
)
// Create an action for each mode.
FeatureRequestMode.allCases.forEach { mode in
let action = UIAlertAction(title: mode.title, style: .default) { [self] _ in
changeFeatureRequestMode(to: mode.mode)
let message = "\(mode.title) enabled."
setStatus(message: message)
}
alertController.addAction(action)
}
// Add a cancel action.
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.barButtonItem = modeBarButtonItem
present(alertController, animated: true)
}
/// Populate for manual cache mode.
@IBAction private func populateManualCache(_ button: UIBarButtonItem) {
// Set query parameters.
let params = AGSQueryParameters()
// Query for all tree conditions except "dead" with coded value '4'.
params.whereClause = "Condition < '4'"
params.geometry = mapView.visibleArea?.extent
// Show the progress HUD.
UIApplication.shared.showProgressHUD(message: "Populating")
// Populate features based on the query.
featureTable.populateFromService(with: params, clearCache: true, outFields: ["*"]) { [weak self] (result: AGSFeatureQueryResult?, error: Error?) in
guard let self = self else { return }
// Hide progress HUD.
UIApplication.shared.hideProgressHUD()
if let error = error {
self.presentAlert(error: error)
} else {
// Display the number of features found.
let message = "Populated \(result?.featureEnumerator().allObjects.count ?? 0) features."
self.setStatus(message: message)
}
}
}
/// Set the appropriate feature request mode.
private func changeFeatureRequestMode(to mode: AGSFeatureRequestMode) {
// Enable or disable the populate bar button item when appropriate.
if mode == .manualCache {
populateBarButtonItem.isEnabled = true
} else {
populateBarButtonItem.isEnabled = false
}
let map = mapView.map!
map.operationalLayers.removeAllObjects()
// Set the request mode.
featureTable.featureRequestMode = mode
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
// Add the feature layer to the map.
map.operationalLayers.add(featureLayer)
}
/// Set the status.
private func setStatus(message: String) {
statusLabel.text = message
}
override func viewDidLoad() {
super.viewDidLoad()
setStatus(message: "Select a feature request mode.")
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ToggleFeatureRequestModesViewController"]
}
}
| 6ba409d8b0b165781dff1ee9ea2523e3 | 38.91791 | 159 | 0.632455 | false | false | false | false |
IntertechInc/uicollectionview-tutorial | refs/heads/master | CollectionViewCustomLayout/TimeEntryCollectionViewController.swift | mit | 1 | //
// ViewController.swift
// CollectionViewCustomLayout
//
// Created by Ryan Harvey on 7/26/15.
// Copyright (c) 2015 Intertech. All rights reserved.
//
import UIKit
class TimeEntryCollectionViewController: UICollectionViewController {
override func viewDidLoad() {
let layout = TimeEntryCollectionLayout()
layout.days = sampleDataByDay
collectionView?.collectionViewLayout = layout
}
override func viewWillAppear(animated: Bool) {
collectionView!.reloadData()
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sampleDataByDay.count
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return sampleDataByDay[section].entries.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("timeEntryCell", forIndexPath: indexPath)
let timeEntry = sampleDataByDay[indexPath.section].entries[indexPath.item]
let label = cell.viewWithTag(1) as! UILabel
label.text = "\(timeEntry.client) (\(timeEntry.hours))"
return cell
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "dayHeaderCell", forIndexPath: indexPath) ;
let day = sampleDataByDay[indexPath.section];
let totalHours = day.entries.reduce(0) {(total, entry) in total + entry.hours}
let dateLabel = cell.viewWithTag(1) as! UILabel
let hoursLabel = cell.viewWithTag(2) as! UILabel
dateLabel.text = day.date.stringByReplacingOccurrencesOfString(" ", withString: "\n").uppercaseString
hoursLabel.text = String(totalHours)
let hours = String(totalHours)
let bold = [NSFontAttributeName: UIFont.boldSystemFontOfSize(16)]
let text = NSMutableAttributedString(string: "\(hours)\nHOURS")
text.setAttributes(bold, range: NSMakeRange(0, hours.characters.count))
hoursLabel.attributedText = text
return cell
}
} | c18d4b7aee15e58eb90feb4d70793ac1 | 43.381818 | 180 | 0.710246 | false | false | false | false |
qq456cvb/DeepLearningKitForiOS | refs/heads/master | iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/BsonUtil.swift | apache-2.0 | 1 | //
// BsonUtil.swift
// iOSDeepLearningKitApp
//
// Created by Neil on 15/11/2016.
// Copyright © 2016 DeepLearningKit. All rights reserved.
//
import Foundation
func readArr(stream: inout InputStream) -> Any {
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(byteBuf, maxLength: 1)
stream.read(intBuf, maxLength: 4)
let byte = byteBuf[0]
let cnt = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
if byte == 0 { // value
let arrBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: cnt * 4)
stream.read(arrBuf, maxLength: cnt * 4)
let floatArrBuf = arrBuf.deinitialize().assumingMemoryBound(to: Float.self)
var arr = Array(repeating: 0.0, count: cnt) as! [Float]
for i in 0...(cnt-1) {
arr[i] = floatArrBuf[i]
}
arrBuf.deinitialize().deallocate(bytes: cnt * 4, alignedTo: 1)
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 1 { // dictionary
var arr = [Any].init()
for _ in 0...(cnt-1) {
arr.append(readDic(stream: &stream))
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else if byte == 3 { // string
var arr = [String].init()
for _ in 0...(cnt-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
let data = Data(bytes: strBuf, count: strLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
arr.append(valStr!)
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return arr
} else { // never get here
assert(false)
}
assert(false)
return [Any].init()
}
func readDic(stream: inout InputStream) -> Dictionary<String, Any> {
var dic = Dictionary<String, Any>.init()
let intBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 4)
let byteBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: 1)
stream.read(intBuf, maxLength: 4)
let num = intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0]
for _ in 0...(num-1) {
stream.read(intBuf, maxLength: 4)
let strLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
let strBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: strLen)
stream.read(strBuf, maxLength: strLen)
var data = Data(bytes: strBuf, count: strLen)
let str = String(data: data, encoding: String.Encoding.ascii)
stream.read(byteBuf, maxLength: 1)
let byte = byteBuf[0]
if byte == 0 { // value
stream.read(intBuf, maxLength: 4)
let f = intBuf.deinitialize().assumingMemoryBound(to: Float.self)[0]
dic[str!] = f
} else if byte == 1 { // dictionary
dic[str!] = readDic(stream: &stream)
} else if byte == 2 { // array
dic[str!] = readArr(stream: &stream)
} else if byte == 3 { // string
// read string length
stream.read(intBuf, maxLength: 4)
let innerStrLen = Int(intBuf.deinitialize().assumingMemoryBound(to: UInt32.self)[0])
// read string
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: innerStrLen)
stream.read(buf, maxLength: innerStrLen)
data = Data(bytes: buf, count: innerStrLen)
let valStr = String(data: data, encoding: String.Encoding.ascii)
dic[str!] = valStr
buf.deallocate(capacity: innerStrLen)
} else {
assert(false) // cannot get in
}
strBuf.deallocate(capacity: strLen)
}
intBuf.deallocate(capacity: 4)
byteBuf.deallocate(capacity: 1)
return dic
}
func readBson(file: String) -> Dictionary<String, Any> {
var stream = InputStream(fileAtPath: file)
stream?.open()
let dic = readDic(stream: &stream!)
stream?.close()
return dic
}
| 288cca0aa8fa70f46b9b33f7c2ceaad7 | 35.826446 | 96 | 0.598743 | false | false | false | false |
deuiore/mpv | refs/heads/master | video/out/mac/title_bar.swift | gpl-2.0 | 2 | /*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* mpv 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
class TitleBar: NSVisualEffectView {
unowned var common: Common
var mpv: MPVHelper? { get { return common.mpv } }
var systemBar: NSView? {
get { return common.window?.standardWindowButton(.closeButton)?.superview }
}
static var height: CGFloat {
get { return NSWindow.frameRect(forContentRect: CGRect.zero, styleMask: .titled).size.height }
}
var buttons: [NSButton] {
get { return ([.closeButton, .miniaturizeButton, .zoomButton] as [NSWindow.ButtonType]).compactMap { common.window?.standardWindowButton($0) } }
}
override var material: NSVisualEffectView.Material {
get { return super.material }
set {
super.material = newValue
// fix for broken deprecated materials
if material == .light || material == .dark {
state = .active
} else if #available(macOS 10.11, *),
material == .mediumLight || material == .ultraDark
{
state = .active
} else {
state = .followsWindowActiveState
}
}
}
init(frame: NSRect, window: NSWindow, common com: Common) {
let f = NSMakeRect(0, frame.size.height - TitleBar.height,
frame.size.width, TitleBar.height)
common = com
super.init(frame: f)
buttons.forEach { $0.isHidden = true }
isHidden = true
alphaValue = 0
blendingMode = .withinWindow
autoresizingMask = [.width, .minYMargin]
systemBar?.alphaValue = 0
state = .followsWindowActiveState
wantsLayer = true
window.contentView?.addSubview(self, positioned: .above, relativeTo: nil)
window.titlebarAppearsTransparent = true
window.styleMask.insert(.fullSizeContentView)
set(appearance: Int(mpv?.macOpts.macos_title_bar_appearance ?? 0))
set(material: Int(mpv?.macOpts.macos_title_bar_material ?? 0))
set(color: mpv?.macOpts.macos_title_bar_color ?? "#00000000")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// catch these events so they are not propagated to the underlying view
override func mouseDown(with event: NSEvent) { }
override func mouseUp(with event: NSEvent) {
if event.clickCount > 1 {
let def = UserDefaults.standard
var action = def.string(forKey: "AppleActionOnDoubleClick")
// macOS 10.10 and earlier
if action == nil {
action = def.bool(forKey: "AppleMiniaturizeOnDoubleClick") == true ?
"Minimize" : "Maximize"
}
if action == "Minimize" {
window?.miniaturize(self)
} else if action == "Maximize" {
window?.zoom(self)
}
}
common.window?.isMoving = false
}
func set(appearance: Any) {
if appearance is Int {
window?.appearance = appearanceFrom(string: String(appearance as? Int ?? 0))
} else {
window?.appearance = appearanceFrom(string: appearance as? String ?? "auto")
}
}
func set(material: Any) {
if material is Int {
self.material = materialFrom(string: String(material as? Int ?? 0))
} else {
self.material = materialFrom(string: material as? String ?? "titlebar")
}
}
func set(color: Any) {
if color is String {
layer?.backgroundColor = NSColor(hex: color as? String ?? "#00000000").cgColor
} else {
let col = color as? m_color ?? m_color(r: 0, g: 0, b: 0, a: 0)
let red = CGFloat(col.r)/255
let green = CGFloat(col.g)/255
let blue = CGFloat(col.b)/255
let alpha = CGFloat(col.a)/255
layer?.backgroundColor = NSColor(calibratedRed: red, green: green,
blue: blue, alpha: alpha).cgColor
}
}
func show() {
guard let window = common.window else { return }
if !window.border && !window.isInFullscreen { return }
let loc = common.view?.convert(window.mouseLocationOutsideOfEventStream, from: nil)
buttons.forEach { $0.isHidden = false }
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 0.20
systemBar?.animator().alphaValue = 1
if !window.isInFullscreen && !window.isAnimating {
animator().alphaValue = 1
isHidden = false
}
}, completionHandler: nil )
if loc?.y ?? 0 > TitleBar.height {
hideDelayed()
} else {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(hide), object: nil)
}
}
@objc func hide() {
guard let window = common.window else { return }
if window.isInFullscreen && !window.isAnimating {
alphaValue = 0
isHidden = true
return
}
NSAnimationContext.runAnimationGroup({ (context) -> Void in
context.duration = 0.20
systemBar?.animator().alphaValue = 0
animator().alphaValue = 0
}, completionHandler: {
self.buttons.forEach { $0.isHidden = true }
self.isHidden = true
})
}
func hideDelayed() {
NSObject.cancelPreviousPerformRequests(withTarget: self,
selector: #selector(hide),
object: nil)
perform(#selector(hide), with: nil, afterDelay: 0.5)
}
func appearanceFrom(string: String) -> NSAppearance? {
switch string {
case "1", "aqua":
return NSAppearance(named: .aqua)
case "3", "vibrantLight":
return NSAppearance(named: .vibrantLight)
case "4", "vibrantDark":
return NSAppearance(named: .vibrantDark)
default: break
}
if #available(macOS 10.14, *) {
switch string {
case "2", "darkAqua":
return NSAppearance(named: .darkAqua)
case "5", "aquaHighContrast":
return NSAppearance(named: .accessibilityHighContrastAqua)
case "6", "darkAquaHighContrast":
return NSAppearance(named: .accessibilityHighContrastDarkAqua)
case "7", "vibrantLightHighContrast":
return NSAppearance(named: .accessibilityHighContrastVibrantLight)
case "8", "vibrantDarkHighContrast":
return NSAppearance(named: .accessibilityHighContrastVibrantDark)
case "0", "auto": fallthrough
default:
#if HAVE_MACOS_10_14_FEATURES
return nil
#else
break
#endif
}
}
let style = UserDefaults.standard.string(forKey: "AppleInterfaceStyle")
return appearanceFrom(string: style == nil ? "aqua" : "vibrantDark")
}
func materialFrom(string: String) -> NSVisualEffectView.Material {
switch string {
case "1", "selection": return .selection
case "0", "titlebar": return .titlebar
case "14", "dark": return .dark
case "15", "light": return .light
default: break
}
#if HAVE_MACOS_10_11_FEATURES
if #available(macOS 10.11, *) {
switch string {
case "2,", "menu": return .menu
case "3", "popover": return .popover
case "4", "sidebar": return .sidebar
case "16", "mediumLight": return .mediumLight
case "17", "ultraDark": return .ultraDark
default: break
}
}
#endif
#if HAVE_MACOS_10_14_FEATURES
if #available(macOS 10.14, *) {
switch string {
case "5,", "headerView": return .headerView
case "6", "sheet": return .sheet
case "7", "windowBackground": return .windowBackground
case "8", "hudWindow": return .hudWindow
case "9", "fullScreen": return .fullScreenUI
case "10", "toolTip": return .toolTip
case "11", "contentBackground": return .contentBackground
case "12", "underWindowBackground": return .underWindowBackground
case "13", "underPageBackground": return .underPageBackground
default: break
}
}
#endif
return .titlebar
}
}
| e0a9bcbe5715438ff27c198f571e3dc3 | 36.066667 | 152 | 0.561997 | false | false | false | false |
narner/AudioKit | refs/heads/master | Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Morphing Oscillator Bank.xcplaygroundpage/Contents.swift | mit | 1 | //: ## Morphing Oscillator Bank
import AudioKitPlaygrounds
import AudioKit
import AudioKitUI
let bank = AKMorphingOscillatorBank()
AudioKit.output = bank
AudioKit.start()
class LiveView: AKLiveViewController, AKKeyboardDelegate {
var keyboard: AKKeyboardView!
override func viewDidLoad() {
addTitle("Morphing Oscillator Bank")
addView(AKSlider(property: "Morph Index", value: bank.index, range: 0 ... 3) { sliderValue in
bank.index = sliderValue
})
let adsrView = AKADSRView { att, dec, sus, rel in
bank.attackDuration = att
bank.decayDuration = dec
bank.sustainLevel = sus
bank.releaseDuration = rel
}
adsrView.attackDuration = bank.attackDuration
adsrView.decayDuration = bank.decayDuration
adsrView.releaseDuration = bank.releaseDuration
adsrView.sustainLevel = bank.sustainLevel
addView(adsrView)
addView(AKSlider(property: "Pitch Bend",
value: bank.pitchBend,
range: -12 ... 12,
format: "%0.2f semitones"
) { sliderValue in
bank.pitchBend = sliderValue
})
addView(AKSlider(property: "Vibrato Depth",
value: bank.vibratoDepth,
range: 0 ... 2,
format: "%0.2f semitones"
) { sliderValue in
bank.vibratoDepth = sliderValue
})
addView(AKSlider(property: "Vibrato Rate",
value: bank.vibratoRate,
range: 0 ... 10,
format: "%0.2f Hz"
) { sliderValue in
bank.vibratoRate = sliderValue
})
keyboard = AKKeyboardView(width: 440, height: 100)
keyboard.polyphonicMode = false
keyboard.delegate = self
addView(keyboard)
addView(AKButton(title: "Go Polyphonic") { button in
self.keyboard.polyphonicMode = !self.keyboard.polyphonicMode
if self.keyboard.polyphonicMode {
button.title = "Go Monophonic"
} else {
button.title = "Go Polyphonic"
}
})
}
func noteOn(note: MIDINoteNumber) {
DispatchQueue.main.async {
bank.play(noteNumber: note, velocity: 80)
}
}
func noteOff(note: MIDINoteNumber) {
DispatchQueue.main.async {
bank.stop(noteNumber: note)
}
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| d987127cdd3052596a7a84f82db390a5 | 29.318182 | 101 | 0.571589 | false | false | false | false |
omnypay/omnypay-sdk-ios | refs/heads/master | ExampleApp/OmnyPayAllSdkDemo/OmnyPayAllSdkDemo/Helpers.swift | apache-2.0 | 1 | /**
Copyright 2017 OmnyPay 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 Foundation
import UIKit
import JavaScriptCore
struct Helpers {
static func getUrl(forType url: String) -> String {
let urlString = Constants.hostScheme + "://" + Constants.hostUrl + ":" + String(Constants.hostPort) + url
return urlString
}
static func serialize(urlResponse:URLResponse?, data:Data?, error:Error?) -> Any? {
guard error == nil else { return nil }
if let urlResponse = urlResponse as? HTTPURLResponse, urlResponse.statusCode == 204 { return NSNull() }
guard let validData = data, validData.count > 0 else {
return nil
}
do {
let JSON = try JSONSerialization.jsonObject(with: validData, options: .allowFragments)
return JSON
} catch {
return nil
}
}
static func extract(qrString:String)->String?{
var qrString = qrString
var index = qrString.range(of: ";", options: .backwards)
guard index != nil else{return nil}
if index!.upperBound == qrString.range(of: qrString)?.upperBound {
qrString = qrString.substring(to: index!.lowerBound)
index = qrString.range(of: ";", options: .backwards)
guard index != nil else{return nil}
}
qrString = qrString.substring(to: index!.lowerBound)
index = qrString.range(of: ";", options: .backwards)
guard index != nil else{return nil}
return qrString.substring(from: index!.upperBound)
}
static func makeButtonEnabled(button: UIButton) {
button.isEnabled = true
button.setTitleColor(UIColor.black, for: .normal)
}
static func makeButtonDisabled(button: UIButton) {
button.isEnabled = false
button.setTitleColor(UIColor.white, for: .normal)
}
static func getSignatureForAPI(timeStamp: String, correlationId: String, requestMethod: String, relativePath: String, payload: String) -> String {
let stringToEncode = Constants.merchantApiKey + timeStamp + correlationId + requestMethod + relativePath + payload
let key = Constants.merchantApiSecret
if let functionGenSign = jsContext?.objectForKeyedSubscript("generateAPISignature") {
if let signed = functionGenSign.call(withArguments: [stringToEncode, key]) {
print("stringToEncode:", stringToEncode, " signature: ", signed.toString())
return signed.toString()
}
}
return ""
}
}
| 67afe4ad3da941e2bfb34cca1279b49c | 32.72093 | 148 | 0.696552 | false | false | false | false |
CodeInventorGroup/CIComponentKit | refs/heads/master | CIComponentKitDemo/View/RootTableViewCell.swift | mit | 1 | //
// RootTableViewCell.swift
// CIComponentKitDemo
//
// Created by ManoBoo on 04/01/2018.
// Copyright © 2018 club.codeinventor. All rights reserved.
//
import UIKit
import CIComponentKit
class RootTableViewCell: UITableViewCell {
var data: (title: String, subtitle: String, info: String) = ("", "", "")
private let containerView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
private let titleLabel = UILabel().font(UIFont.cic.preferred(.headline))
private let subtitleLabel = UILabel().font(UIFont.init(name: "GillSans-SemiBold", size: 16.0)!).line(0)
private let infoLabel = CICLabel().font(UIFont.cic.preferred(.body)).line(0)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
NotificationCenter.default.addObserver(self,
selector: #selector(CICAppearance.didToggleTheme),
name: Notification.Name.cic.themeDidToggle,
object: nil)
initSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initSubviews() {
selectionStyle = .none
contentView.addSubview(containerView)
containerView.contentView.addSubview(titleLabel)
containerView.contentView.addSubview(subtitleLabel)
containerView.contentView.addSubview(infoLabel)
infoLabel.longPressAction(.copy)
infoLabel.copySuccessClousure = { [weak self] in
guard let `self` = self else { return }
let alertView = CICAlertView.init(contentView: nil,
title: "复制文本为:",
content: self.data.info)
alertView.show()
}
}
func render() {
containerView.size(contentView)
didToggleTheme()
let contentWidth = contentView.cic.width - 2 * 10
titleLabel.text(data.title).sizeTo(layout: .maxWidth(contentWidth))
.x(10).y(10)
subtitleLabel.text(data.subtitle).width(contentWidth)
.sizeTo(layout: .maxHeight(.greatestFiniteMagnitude))
.x(10).y(titleLabel.cic.bottom + 10)
infoLabel.text(data.info).width(contentWidth)
.sizeTo(layout: .maxHeight(.greatestFiniteMagnitude))
.x(10).y(subtitleLabel.cic.bottom + 10)
containerView.height(infoLabel.cic.bottom + 10)
}
override func layoutSubviews() {
super.layoutSubviews()
render()
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
self.width(size.width)
return CGSize.init(width: size.width, height: containerView.cic.bottom)
}
}
extension RootTableViewCell: CICAppearance {
func willToggleTheme() {
}
func didToggleTheme() {
let config = CIComponentKitThemeCurrentConfig
// containerView.backgroundColor(config.mainColor)
self.backgroundColor(config.mainColor)
UIView.animate(withDuration: 0.35) {
self.titleLabel.textColor(config.tintColor)
self.subtitleLabel.textColor(config.textColor)
self.infoLabel.textColor(config.textColor)
}
}
}
| 17d10a0b9e7c764288ff680c6da8d5fd | 33.742268 | 107 | 0.624332 | false | true | false | false |
FsThatOne/VOne | refs/heads/master | VOne/Classes/Controller/Main/LoginAndRegist/WelcomeViewController.swift | mit | 1 | //
// WelcomeViewController.swift
// VOne
//
// Created by 王正一 on 16/11/22.
// Copyright © 2016年 FsThatOne. All rights reserved.
//
import UIKit
import MediaPlayer
import AVKit
import SnapKit
public enum ScalingMode {
case resize
case resizeAspect
case resizeAspectFill
}
class WelcomeViewController: FSBaseViewController {
fileprivate var loginButton: UIButton = {
let btn = UIButton(type: .system)
btn.frame = CGRect.zero
btn.setTitleColor(UIColor.white, for: .normal)
btn.titleLabel?.font = UIFont(name: "Avenir Next", size: 22)
btn.setTitle("Login", for: .normal)
btn.setBackgroundImage(UIImage.imageWith(Color: UIColor(red:0.063, green:0.698, blue:0.137, alpha:1)), for: .normal)
btn.layer.cornerRadius = 5
btn.clipsToBounds = true
return btn
}()
fileprivate var registButton: UIButton = {
let btn = UIButton(type: .system)
btn.frame = CGRect.zero
btn.setTitleColor(UIColor(red:0.063, green:0.698, blue:0.137, alpha:1), for: .normal)
btn.setTitle("Sign up", for: .normal)
btn.titleLabel?.font = UIFont(name: "Avenir Next", size: 22)
btn.setBackgroundImage(UIImage.imageWith(Color: UIColor.white), for: .normal)
btn.layer.cornerRadius = 5
btn.clipsToBounds = true
return btn
}()
fileprivate let moviePlayer = AVPlayerViewController()
fileprivate var moviePlayerSoundLevel: Float = 1.0
var contentURL: URL? {
didSet {
setMoviePlayer(contentURL!)
}
}
var videoFrame: CGRect = CGRect()
var startTime: CGFloat = 0.0
var duration: CGFloat = 0.0
var backgroundColor: UIColor = UIColor.black {
didSet {
view.backgroundColor = backgroundColor
}
}
var sound: Bool = true {
didSet {
if sound {
moviePlayerSoundLevel = 1.0
}else{
moviePlayerSoundLevel = 0.0
}
}
}
var alpha: CGFloat = CGFloat() {
didSet {
moviePlayer.view.alpha = alpha
}
}
var alwaysRepeat: Bool = true {
didSet {
if alwaysRepeat {
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd) , name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: moviePlayer.player?.currentItem)
}
}
}
var fillMode: ScalingMode = .resizeAspectFill {
didSet {
switch fillMode {
case .resize:
moviePlayer.videoGravity = AVLayerVideoGravityResize
case .resizeAspect:
moviePlayer.videoGravity = AVLayerVideoGravityResizeAspect
case .resizeAspectFill:
moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill
}
}
}
convenience init(vFrame: CGRect, sTime: CGFloat) {
self.init()
videoFrame = vFrame
startTime = sTime
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
moviePlayer.view.frame = videoFrame
moviePlayer.showsPlaybackControls = false
view.addSubview(moviePlayer.view)
view.sendSubview(toBack: moviePlayer.view)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - 设置界面相关
extension WelcomeViewController {
override internal func setupUI() {
view.addSubview(loginButton)
loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
view.addSubview(registButton)
loginButton.snp.makeConstraints { (make) in
make.bottom.equalTo(view).offset(-40)
make.left.equalTo(view).offset(30)
make.right.equalTo(view).offset(-30)
make.height.equalTo(55)
}
registButton.snp.makeConstraints { (make) in
make.bottom.equalTo(loginButton.snp.top).offset(-40)
make.left.equalTo(view).offset(30)
make.right.equalTo(view).offset(-30)
make.height.equalTo(loginButton)
}
}
}
extension WelcomeViewController {
@objc fileprivate func login() {
let loginVC = LoginViewController()
loginVC.modalTransitionStyle = .crossDissolve
present(loginVC, animated: true, completion: nil)
}
}
// MARK: - 设置media播放相关
extension WelcomeViewController {
fileprivate func setMoviePlayer(_ url: URL){
let videoCutter = VideoCutter()
videoCutter.cropVideoWithUrl(videoUrl: url, startTime: startTime, duration: duration) { (videoPath, error) -> Void in
if let path = videoPath as URL? {
self.moviePlayer.player = AVPlayer(url: path)
self.moviePlayer.player?.play()
self.moviePlayer.player?.volume = self.moviePlayerSoundLevel
}
}
}
func playerItemDidReachEnd() {
moviePlayer.player?.seek(to: kCMTimeZero)
moviePlayer.player?.play()
}
}
// MARK: - VideoCutter模型
class VideoCutter: NSObject {
func cropVideoWithUrl(videoUrl url: URL, startTime: CGFloat, duration: CGFloat, completion: ((_ videoPath: URL?, _ error: NSError?) -> Void)?) {
DispatchQueue.global().async {
let asset = AVURLAsset(url: url, options: nil)
let exportSession = AVAssetExportSession(asset: asset, presetName: "AVAssetExportPresetHighestQuality")
let paths: NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
var outputURL = paths.object(at: 0) as! String
let manager = FileManager.default
do {
try manager.createDirectory(atPath: outputURL, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
outputURL = outputURL.NS.appendingPathComponent("output.mp4")
do {
try manager.removeItem(atPath: outputURL)
} catch _ {
}
if let exportSession = exportSession as AVAssetExportSession? {
exportSession.outputURL = URL(fileURLWithPath: outputURL)
exportSession.shouldOptimizeForNetworkUse = true
exportSession.outputFileType = AVFileTypeMPEG4
let start = CMTimeMakeWithSeconds(Float64(startTime), 600)
let duration = CMTimeMakeWithSeconds(Float64(duration), 600)
let range = CMTimeRangeMake(start, duration)
exportSession.timeRange = range
exportSession.exportAsynchronously { () -> Void in
switch exportSession.status {
case AVAssetExportSessionStatus.completed:
completion?(exportSession.outputURL, nil)
case AVAssetExportSessionStatus.failed:
print("Failed: \(exportSession.error)")
case AVAssetExportSessionStatus.cancelled:
print("Failed: \(exportSession.error)")
default:
print("default case")
}
}
}
}
}
}
extension String {
var NS: NSString { return (self as NSString) }
}
| 7983081026e7f00d68977533f47e60d9 | 32.70614 | 202 | 0.603774 | false | false | false | false |
OliverLetterer/PlaceIt | refs/heads/master | PlaceIt/PlaceIt/SecondExampleViewController.swift | mit | 1 | //
// SecondExampleViewController.swift
// PlaceIt
//
// Created by Oliver Letterer on 02.08.14.
// Copyright (c) 2014 Sparrow-Labs. All rights reserved.
//
import UIKit
class SecondExampleViewController: UIViewController {
var blueView: UIView! = nil, greenView: UIView! = nil
var leftImageView: UIView! = nil, leftLabel: UILabel! = nil
var rightImageView: UIView! = nil, rightLabel: UILabel! = nil
override func loadView() {
super.loadView()
blueView = UIView(frame: CGRectZero)
blueView.backgroundColor = UIColor.blueColor()
view.addSubview(blueView);
greenView = UIView(frame: CGRectZero)
greenView.backgroundColor = UIColor.greenColor()
view.addSubview(greenView)
let imageDimension: CGFloat = 100
leftImageView = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: imageDimension, height: imageDimension)))
leftImageView.backgroundColor = UIColor.whiteColor()
leftImageView.layer.masksToBounds = true
leftImageView.layer.cornerRadius = 14
view.addSubview(leftImageView)
leftLabel = UILabel()
leftLabel.text = "Option 1"
leftLabel.textColor = UIColor.whiteColor()
leftLabel.font = UIFont.boldSystemFontOfSize(17)
leftLabel.numberOfLines = 0
leftLabel.textAlignment = .Center
view.addSubview(leftLabel)
rightImageView = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: imageDimension, height: imageDimension)))
rightImageView.backgroundColor = UIColor.whiteColor()
rightImageView.layer.masksToBounds = true
rightImageView.layer.cornerRadius = 14
view.addSubview(rightImageView)
rightLabel = UILabel()
rightLabel.text = "Option 2"
rightLabel.textColor = UIColor.whiteColor()
rightLabel.font = UIFont.boldSystemFontOfSize(17)
rightLabel.numberOfLines = 0
rightLabel.textAlignment = .Center
view.addSubview(rightLabel)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let buttonHeight: CGFloat = 66.0
let (leftFrame, rightFrame) = view.bounds
.inset(UIEdgeInsets(bottom: buttonHeight))
.divide(CGRectGetWidth(view.bounds) / 2, edge: .MinXEdge)
view
.layoutSubview(blueView,
atPosition: (horizontal: .Left(0.0), vertical: .Bottom(0.0)),
withSize: CGSize(width: CGRectGetWidth(view.bounds) / 2.0, height: buttonHeight))
.layoutSubview(greenView,
atPosition: (horizontal: .Right(0.0), vertical: .Bottom(0.0)),
withSize: CGSize(width: CGRectGetWidth(view.bounds) / 2.0, height: buttonHeight))
.layoutSubviews([ leftImageView, leftLabel ],
atPosition: (horizontal: .Center, vertical: .Center),
direction: .TopToBottom,
inRect: leftFrame,
interItemSpacing: 7)
.layoutSubviews([ rightImageView, rightLabel ],
atPosition: (horizontal: .Center, vertical: .Center),
direction: .TopToBottom,
inRect: rightFrame,
interItemSpacing: 7)
}
}
| ad09869ca0821a7a5e19b0277209a3de | 36.666667 | 128 | 0.643363 | false | false | false | false |
monisun/warble | refs/heads/master | Warble/User.swift | mit | 1 | //
// User.swift
// Warble
//
// Created by Monica Sun on 5/21/15.
// Copyright (c) 2015 Monica Sun. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLogInNotification = "userDidLogInNotification"
let userDidLogOutNotification = "userDidLogOutInNotification"
class User: NSObject {
var name: String?
var username: String?
var profileImageUrl: String?
var tagline: String?
var dict: NSDictionary
init(dict: NSDictionary) {
self.dict = dict
name = dict["name"] as? String
username = dict["screen_name"] as? String
profileImageUrl = dict["profile_image_url"] as? String
tagline = dict["description"] as? String
}
class var currentUser: User? {
get {
if _currentUser == nil {
var data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
if data != nil {
var dict = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary
_currentUser = User(dict: dict)
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
var data = NSJSONSerialization.dataWithJSONObject(user!.dict, options: nil, error: nil)
NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
} else {
NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func logout() {
User.currentUser = nil
TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
NSNotificationCenter.defaultCenter().postNotificationName(userDidLogOutNotification, object: nil)
}
}
| fa26c6844c062dcd74e2e27ffafc16f6 | 29.238806 | 119 | 0.601678 | false | false | false | false |
zeroc-ice/ice-demos | refs/heads/3.7 | swift/Ice/helloUI/views/FormView.swift | gpl-2.0 | 2 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import SwiftUI
let hostnameKey = "hostnameKey"
struct FormView: View {
@StateObject var client = Client()
@State var statusBarHidden = true
@State var statusBarText = ""
var communicator: Ice.Communicator!
var body: some View {
ZStack {
Form {
// Proxy Settings
ProxySettingsView(connection: $client.proxySettings.connection,
delay: $client.proxySettings.delay,
timeout: $client.proxySettings.timeout,
methodIndex: $client.proxySettings.methodIndex).environmentObject(client)
// Buttons
Section("Actions") {
ButtonView(helloEnabled: $client.helloEnabled,
flushEnabled: $client.flushEnabled,
shutdownEnabled: $client.shutdownEnabled)
.environmentObject(client)
}
Section("Status message") {
// Status view
StatusView(isSpinning: $client.isSpinning, text: $client.statusMessage)
}
}
}
// Displaying Alerts
.alert(isPresented: $client.showingError) {
Alert(title: Text("Error"),
message: Text(client.error?.localizedDescription ?? ""),
dismissButton: .default(Text("Got it!")))
}
}
}
extension Binding {
func didSet(_ didSet: @escaping (Value) -> Void) -> Binding<Value> {
Binding(
get: { wrappedValue },
set: { newValue in
self.wrappedValue = newValue
didSet(newValue)
}
)
}
}
| d10fa0629ec83905dbf0a2fc5af8fcfd | 29.65 | 107 | 0.509516 | false | false | false | false |
JohnEstropia/CoreStore | refs/heads/develop | Sources/DiffableDataSource.CollectionViewAdapter-UIKit.swift | mit | 1 | //
// DiffableDataSource.CollectionViewAdapter-UIKit.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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.
//
#if canImport(UIKit) && (os(iOS) || os(tvOS))
import UIKit
import CoreData
// MARK: - DiffableDataSource
extension DiffableDataSource {
// MARK: - CollectionView
/**
The `DiffableDataSource.CollectionViewAdapter` serves as a `UICollectionViewDataSource` that handles `ListPublisher` snapshots for a `UICollectionView`. Subclasses of `DiffableDataSource.CollectionViewAdapter` may override some `UICollectionViewDataSource` methods as needed.
The `DiffableDataSource.CollectionViewAdapter` instance needs to be held on (retained) for as long as the `UICollectionView`'s lifecycle.
```
self.dataSource = DiffableDataSource.CollectionViewAdapter<Person>(
collectionView: self.collectionView,
dataStack: CoreStoreDefaults.dataStack,
cellProvider: { (collectionView, indexPath, person) in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell") as! PersonCell
cell.setPerson(person)
return cell
}
)
```
The dataSource can then apply changes from a `ListPublisher` as shown:
```
listPublisher.addObserver(self) { [weak self] (listPublisher) in
self?.dataSource?.apply(
listPublisher.snapshot,
animatingDifferences: true
)
}
```
`DiffableDataSource.CollectionViewAdapter` fully handles the reload animations.
- SeeAlso: CoreStore's DiffableDataSource implementation is based on https://github.com/ra1028/DiffableDataSources
*/
open class CollectionViewAdapter<O: DynamicObject>: BaseAdapter<O, DefaultCollectionViewTarget<UICollectionView>>, UICollectionViewDataSource {
// MARK: Public
/**
Initializes the `DiffableDataSource.CollectionViewAdapter`. This instance needs to be held on (retained) for as long as the `UICollectionView`'s lifecycle.
```
self.dataSource = DiffableDataSource.CollectionViewAdapter<Person>(
collectionView: self.collectionView,
dataStack: CoreStoreDefaults.dataStack,
cellProvider: { (collectionView, indexPath, person) in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell") as! PersonCell
cell.setPerson(person)
return cell
}
)
```
- parameter collectionView: the `UICollectionView` to set the `dataSource` of. This instance is not retained by the `DiffableDataSource.CollectionViewAdapter`.
- parameter dataStack: the `DataStack` instance that the dataSource will fetch objects from
- parameter cellProvider: a closure that configures and returns the `UICollectionViewCell` for the object
- parameter supplementaryViewProvider: an optional closure for providing `UICollectionReusableView` supplementary views. If not set, defaults to returning `nil`
*/
public init(
collectionView: UICollectionView,
dataStack: DataStack,
cellProvider: @escaping (UICollectionView, IndexPath, O) -> UICollectionViewCell?,
supplementaryViewProvider: @escaping (UICollectionView, String, IndexPath) -> UICollectionReusableView? = { _, _, _ in nil }
) {
self.cellProvider = cellProvider
self.supplementaryViewProvider = supplementaryViewProvider
super.init(target: .init(collectionView), dataStack: dataStack)
collectionView.dataSource = self
}
// MARK: - UICollectionViewDataSource
@objc
@MainActor
public dynamic func numberOfSections(
in collectionView: UICollectionView
) -> Int {
return self.numberOfSections()
}
@objc
@MainActor
public dynamic func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int
) -> Int {
return self.numberOfItems(inSection: section) ?? 0
}
@objc
@MainActor
open dynamic func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath
) -> UICollectionViewCell {
guard let objectID = self.itemID(for: indexPath) else {
Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) already removed from list")
}
guard let object = self.dataStack.fetchExisting(objectID) as O? else {
Internals.abort("Object at \(Internals.typeName(IndexPath.self)) \(indexPath) has been deleted")
}
guard let cell = self.cellProvider(collectionView, indexPath, object) else {
Internals.abort("\(Internals.typeName(UICollectionViewDataSource.self)) returned a `nil` cell for \(Internals.typeName(IndexPath.self)) \(indexPath)")
}
return cell
}
@objc
@MainActor
open dynamic func collectionView(
_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath
) -> UICollectionReusableView {
guard let view = self.supplementaryViewProvider(collectionView, kind, indexPath) else {
return UICollectionReusableView()
}
return view
}
// MARK: Private
private let cellProvider: (UICollectionView, IndexPath, O) -> UICollectionViewCell?
private let supplementaryViewProvider: (UICollectionView, String, IndexPath) -> UICollectionReusableView?
}
// MARK: - DefaultCollectionViewTarget
public struct DefaultCollectionViewTarget<T: UICollectionView>: Target {
// MARK: Public
public typealias Base = T
public private(set) weak var base: Base?
public init(_ base: Base) {
self.base = base
}
// MARK: DiffableDataSource.Target
public var shouldSuspendBatchUpdates: Bool {
return self.base?.window == nil
}
public func deleteSections(at indices: IndexSet, animated: Bool) {
self.base?.deleteSections(indices)
}
public func insertSections(at indices: IndexSet, animated: Bool) {
self.base?.insertSections(indices)
}
public func reloadSections(at indices: IndexSet, animated: Bool) {
self.base?.reloadSections(indices)
}
public func moveSection(at index: IndexSet.Element, to newIndex: IndexSet.Element, animated: Bool) {
self.base?.moveSection(index, toSection: newIndex)
}
public func deleteItems(at indexPaths: [IndexPath], animated: Bool) {
self.base?.deleteItems(at: indexPaths)
}
public func insertItems(at indexPaths: [IndexPath], animated: Bool) {
self.base?.insertItems(at: indexPaths)
}
public func reloadItems(at indexPaths: [IndexPath], animated: Bool) {
self.base?.reloadItems(at: indexPaths)
}
public func moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath, animated: Bool) {
self.base?.moveItem(at: indexPath, to: newIndexPath)
}
public func performBatchUpdates(updates: () -> Void, animated: Bool, completion: @escaping () -> Void) {
self.base?.performBatchUpdates(updates, completion: { _ in completion() })
}
public func reloadData() {
self.base?.reloadData()
}
}
}
// MARK: Deprecated
extension DiffableDataSource {
@available(*, deprecated, renamed: "CollectionViewAdapter")
public typealias CollectionView = CollectionViewAdapter
}
#endif
| fa398f01d0872c8ea2f2acaa052b5a94 | 34.936508 | 280 | 0.658679 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/RightSide/Topic/Controllers/ThemeTopic/QSThemeTopicInteractor.swift | mit | 1 | //
// QSThemeTopicInteractor.swift
// zhuishushenqi
//
// Created Nory Cao on 2017/4/13.
// Copyright © 2017年 QS. All rights reserved.
//
// Template generated by Juanpe Catalán @JuanpeCMiOS
//
import UIKit
import ZSAPI
class QSThemeTopicInteractor: QSThemeTopicInteractorProtocol {
var output: QSThemeTopicInteractorOutputProtocol!
var models:[[ThemeTopicModel]] = [[],[],[]]
var selectedIndex = 0
var tag = ""
var gender = ""
let segTitles = ["本周最热","最新发布","最多收藏"]
func filter(index:Int,title:String,name:String){
//此处index为tag的index
var titleString = title
let genders = ["male","female"]
if name == "性别" {
gender = genders[index]
tag = ""
titleString = "\(titleString)生书单"
}else{
gender = ""
tag = title
}
self.output.showFilter(title: titleString,index: selectedIndex, tag: tag, gender: gender)
}
func initTitle(index:Int){
self.output.showFilter(title: "全部书单", index: index, tag: tag, gender: gender)
}
func setupSeg(index:Int){
self.output.showSegView(titles:segTitles )
}
//
func requestTitle(index:Int,tag:String,gender:String){
selectedIndex = index
models = [[],[],[]]
request(index: index, tag: tag, gender: gender)
}
func requestDetail(index:Int){
if selectedIndex == index {
return
}
selectedIndex = index
if self.models[index].count > 0 {
self.output.fetchModelSuccess(models: self.models[index])
return
}
request(index: index, tag: tag, gender: gender)
}
func request(index:Int,tag:String,gender:String){
//本周最热
// http://api.zhuishushenqi.com/book-list?sort=collectorCount&duration=last-seven-days&start=0
//最新发布
// http://api.zhuishushenqi.com/book-list?sort=created&duration=all&start=0
//最多收藏 (全部书单)
// http://api.zhuishushenqi.com/book-list?sort=collectorCount&duration=all&start=0
var sorts:[String] = ["collectorCount","created","collectorCount"]
var durations:[String] = ["last-seven-days","all","all"]
let api = ZSAPI.themeTopic(sort: sorts[index], duration: durations[index], start: "0", gender: gender, tag: tag)
zs_get(api.path, parameters: api.parameters) { (response) in
QSLog(response)
if let books = response?["bookLists"] {
if let models = [ThemeTopicModel].deserialize(from: books as? [Any]) as? [ThemeTopicModel] {
self.models[index] = models
self.output.fetchModelSuccess(models: models)
} else {
self.output.fetchModelFailed()
}
} else{
self.output.fetchModelFailed()
}
}
}
}
| ffd6b7b2f644aa305edafa14e4c015bb | 31.293478 | 120 | 0.571525 | false | false | false | false |
LordBonny/project-iOSRTCApp | refs/heads/master | platforms/ios/iOSRTCApp/Plugins/cordova-plugin-iosrtc/PluginRTCPeerConnection.swift | agpl-3.0 | 2 | import Foundation
class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate {
var rtcPeerConnectionFactory: RTCPeerConnectionFactory
var rtcPeerConnection: RTCPeerConnection!
var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig
var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints
// PluginRTCDataChannel dictionary.
var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:]
var eventListener: (data: NSDictionary) -> Void
var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void
var eventListenerForRemoveStream: (id: String) -> Void
var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)!
var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)!
var onSetDescriptionSuccessCallback: (() -> Void)!
var onSetDescriptionFailureCallback: ((error: NSError) -> Void)!
init(
rtcPeerConnectionFactory: RTCPeerConnectionFactory,
pcConfig: NSDictionary?,
pcConstraints: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void,
eventListenerForRemoveStream: (id: String) -> Void
) {
NSLog("PluginRTCPeerConnection#init()")
self.rtcPeerConnectionFactory = rtcPeerConnectionFactory
self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig)
self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints)
self.eventListener = eventListener
self.eventListenerForAddStream = eventListenerForAddStream
self.eventListenerForRemoveStream = eventListenerForRemoveStream
}
func run() {
NSLog("PluginRTCPeerConnection#run()")
self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers(
self.pluginRTCPeerConnectionConfig.getIceServers(),
constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(),
delegate: self
)
}
func createOffer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createOffer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createOffer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createOfferWithDelegate(self,
constraints: pluginRTCPeerConnectionConstraints.getConstraints())
}
func createAnswer(
options: NSDictionary?,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#createAnswer()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options)
self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | success callback [type:\(rtcSessionDescription.type)]")
let data = [
"type": rtcSessionDescription.type,
"sdp": rtcSessionDescription.description
]
callback(data: data)
}
self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.createAnswerWithDelegate(self,
constraints: RTCMediaConstraints())
}
func setLocalDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setLocalDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setLocalDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func setRemoteDescription(
desc: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: (error: NSError) -> Void
) {
NSLog("PluginRTCPeerConnection#setRemoteDescription()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let type = desc.objectForKey("type") as? String ?? ""
let sdp = desc.objectForKey("sdp") as? String ?? ""
let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp)
self.onSetDescriptionSuccessCallback = { () -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback")
let data = [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
callback(data: data)
}
self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in
NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: \(error)")
errback(error: error)
}
self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self,
sessionDescription: rtcSessionDescription
)
}
func addIceCandidate(
candidate: NSDictionary,
callback: (data: NSDictionary) -> Void,
errback: () -> Void
) {
NSLog("PluginRTCPeerConnection#addIceCandidate()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let sdpMid = candidate.objectForKey("sdpMid") as? String ?? ""
let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0
let candidate = candidate.objectForKey("candidate") as? String ?? ""
let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate(
mid: sdpMid,
index: sdpMLineIndex,
sdp: candidate
))
var data: NSDictionary
if result == true {
if self.rtcPeerConnection.remoteDescription != nil {
data = [
"remoteDescription": [
"type": self.rtcPeerConnection.remoteDescription.type,
"sdp": self.rtcPeerConnection.remoteDescription.description
]
]
} else {
data = [
"remoteDescription": false
]
}
callback(data: data)
} else {
errback()
}
}
func addStream(pluginMediaStream: PluginMediaStream) -> Bool {
NSLog("PluginRTCPeerConnection#addStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return false
}
return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream)
}
func removeStream(pluginMediaStream: PluginMediaStream) {
NSLog("PluginRTCPeerConnection#removeStream()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream)
}
func createDataChannel(
dcId: Int,
label: String,
options: NSDictionary?,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#createDataChannel()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcPeerConnection: rtcPeerConnection,
label: label,
options: options,
eventListener: eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
}
func RTCDataChannel_setListener(
dcId: Int,
eventListener: (data: NSDictionary) -> Void,
eventListenerForBinaryMessage: (data: NSData) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()")
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
// Set the eventListener.
pluginRTCDataChannel!.setListener(eventListener,
eventListenerForBinaryMessage: eventListenerForBinaryMessage
)
}
func close() {
NSLog("PluginRTCPeerConnection#close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.rtcPeerConnection.close()
}
func RTCDataChannel_sendString(
dcId: Int,
data: String,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendString(data, callback: callback)
}
func RTCDataChannel_sendBinary(
dcId: Int,
data: NSData,
callback: (data: NSDictionary) -> Void
) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.sendBinary(data, callback: callback)
}
func RTCDataChannel_close(dcId: Int) {
NSLog("PluginRTCPeerConnection#RTCDataChannel_close()")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId]
if pluginRTCDataChannel == nil {
return;
}
pluginRTCDataChannel!.close()
// Remove the pluginRTCDataChannel from the dictionary.
self.pluginRTCDataChannels[dcId] = nil
}
/**
* Methods inherited from RTCPeerConnectionDelegate.
*/
func peerConnection(peerConnection: RTCPeerConnection!,
signalingStateChanged newState: RTCSignalingState) {
let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:\(state_str)]")
self.eventListener(data: [
"type": "signalingstatechange",
"signalingState": state_str
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceGatheringChanged newState: RTCICEGatheringState) {
let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:\(state_str)]")
self.eventListener(data: [
"type": "icegatheringstatechange",
"iceGatheringState": state_str
])
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
// Emit an empty candidate if iceGatheringState is "complete".
if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil {
self.eventListener(data: [
"type": "icecandidate",
// NOTE: Cannot set null as value.
"candidate": false,
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
gotICECandidate candidate: RTCICECandidate!) {
NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:\(candidate.sdpMid), sdpMLineIndex:\(candidate.sdpMLineIndex), candidate:\(candidate.sdp)]")
if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue {
return
}
self.eventListener(data: [
"type": "icecandidate",
"candidate": [
"sdpMid": candidate.sdpMid,
"sdpMLineIndex": candidate.sdpMLineIndex,
"candidate": candidate.sdp
],
"localDescription": [
"type": self.rtcPeerConnection.localDescription.type,
"sdp": self.rtcPeerConnection.localDescription.description
]
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
iceConnectionChanged newState: RTCICEConnectionState) {
let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String!
NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:\(state_str)]")
self.eventListener(data: [
"type": "iceconnectionstatechange",
"iceConnectionState": state_str
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
addedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onaddstream")
let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream)
pluginMediaStream.run()
// Let the plugin store it in its dictionary.
self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream)
// Fire the 'addstream' event so the JS will create a new MediaStream.
self.eventListener(data: [
"type": "addstream",
"stream": pluginMediaStream.getJSON()
])
}
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
removedStream rtcMediaStream: RTCMediaStream!) {
NSLog("PluginRTCPeerConnection | onremovestream")
// Let the plugin remove it from its dictionary.
self.eventListenerForRemoveStream(id: rtcMediaStream.label)
self.eventListener(data: [
"type": "removestream",
"streamId": rtcMediaStream.label // NOTE: No "id" property yet.
])
}
func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) {
NSLog("PluginRTCPeerConnection | onnegotiationeeded")
self.eventListener(data: [
"type": "negotiationneeded"
])
}
func peerConnection(peerConnection: RTCPeerConnection!,
didOpenDataChannel rtcDataChannel: RTCDataChannel!) {
NSLog("PluginRTCPeerConnection | ondatachannel")
let dcId = PluginUtils.randomInt(10000, max:99999)
let pluginRTCDataChannel = PluginRTCDataChannel(
rtcDataChannel: rtcDataChannel
)
// Store the pluginRTCDataChannel into the dictionary.
self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel
// Run it.
pluginRTCDataChannel.run()
// Fire the 'datachannel' event so the JS will create a new RTCDataChannel.
self.eventListener(data: [
"type": "datachannel",
"channel": [
"dcId": dcId,
"label": rtcDataChannel.label,
"ordered": rtcDataChannel.isOrdered,
"maxPacketLifeTime": rtcDataChannel.maxRetransmitTime,
"maxRetransmits": rtcDataChannel.maxRetransmits,
"protocol": rtcDataChannel.`protocol`,
"negotiated": rtcDataChannel.isNegotiated,
"id": rtcDataChannel.streamId,
"readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!,
"bufferedAmount": rtcDataChannel.bufferedAmount
]
])
}
/**
* Methods inherited from RTCSessionDescriptionDelegate.
*/
func peerConnection(rtcPeerConnection: RTCPeerConnection!,
didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) {
if error == nil {
self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription)
} else {
self.onCreateDescriptionFailureCallback(error: error)
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
didSetSessionDescriptionWithError error: NSError!) {
if error == nil {
self.onSetDescriptionSuccessCallback()
} else {
self.onSetDescriptionFailureCallback(error: error)
}
}
}
| ecf5d679e75f6783bafd86b6f3f7ce2c | 27.503534 | 150 | 0.755284 | false | false | false | false |
sadawi/PrimarySource | refs/heads/master | Pod/iOS/FieldCell.swift | mit | 1 | //
// FieldCell.swift
// Pods
//
// Created by Sam Williams on 11/30/15.
//
//
import UIKit
enum ControlAlignment {
case right
}
public enum FieldLabelPosition {
case top
case left
}
public enum FieldState {
case normal
case error([String])
case editing
}
open class FieldCell<Value: Equatable>: TitleDetailsCell {
var errorLabel:UILabel?
var errorIcon:UIImageView?
open var value:Value? {
didSet {
if oldValue != self.value {
self.valueChanged(from: oldValue, to: self.value)
}
self.update()
}
}
open var isReadonly:Bool = false
open var placeholderText:String? {
didSet {
self.update()
}
}
open var isBlank:Bool {
get { return self.value == nil }
}
open var state:FieldState = .normal {
didSet {
self.update()
self.stylize()
}
}
open dynamic var errorTextColor:UIColor? = UIColor.red
lazy var accessoryToolbar:UIToolbar = {
let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: 36))
self.configureAccessoryToolbar(toolbar)
return toolbar
}()
func configureAccessoryToolbar(_ toolbar:UIToolbar) {
var items:[UIBarButtonItem] = []
if self.toolbarShowsCancelButton {
items.append(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FieldCell.cancel)))
}
if self.toolbarShowsClearButton {
items.append(UIBarButtonItem(title: "Clear", style: .plain, target: self, action: #selector(FieldCell.clear)))
}
items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
items.append(UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(FieldCell.commit)))
toolbar.items = items
}
var toolbarShowsCancelButton = false
var toolbarShowsClearButton = false
open func commit() {
}
open func cancel() {
}
open func clear() {
self.cancel()
self.update()
}
open var onChange:((Value?, Value?) -> Void)?
override open func buildView() {
super.buildView()
let errorLabel = UILabel(frame: self.detailContent!.bounds)
errorLabel.numberOfLines = 0
errorLabel.translatesAutoresizingMaskIntoConstraints = false
self.detailContent?.addSubview(errorLabel)
self.errorLabel = errorLabel
}
private var detailConstraints:[NSLayoutConstraint] = []
override func setupConstraints() {
super.setupConstraints()
guard let errorLabel = self.errorLabel, let detailContent = self.detailContent else { return }
detailContent.removeConstraints(self.detailConstraints)
self.detailConstraints.removeAll()
let views = ["error":errorLabel]
let metrics = [
"left": self.defaultContentInsets.left,
"right": self.defaultContentInsets.right,
"top": self.defaultContentInsets.top,
"bottom": self.defaultContentInsets.bottom,
"icon": 20
]
self.detailConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[error]-right-|", options: .alignAllTop, metrics: metrics, views: views)
self.detailConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[error]|", options: .alignAllTop, metrics: metrics, views: views)
detailContent.addConstraints(self.detailConstraints)
}
override open func update() {
super.update()
switch self.state {
case .error(let messages):
self.errorIcon?.image = UIImage(named: "error-32", in: Bundle(for: FieldCell.self), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
self.errorLabel?.text = messages.joined(separator: "\n")
default:
self.errorIcon?.image = nil
self.errorLabel?.text = nil
}
}
override open func stylize() {
super.stylize()
self.errorLabel?.textColor = self.errorTextColor
self.errorIcon?.tintColor = self.errorTextColor
self.errorLabel?.font = self.valueFont
}
open func valueChanged(from oldValue: Value?, to newValue: Value?) {
if let onChange = self.onChange {
onChange(oldValue, newValue)
}
}
open override func prepareForReuse() {
super.prepareForReuse()
self.onChange = nil
self.accessoryType = .none
self.placeholderText = nil
}
}
| 2f18b198a349baf0edf286b44c803a91 | 28.187879 | 165 | 0.605689 | false | false | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/game-of-life.swift | mit | 2 | /**
* https://leetcode.com/problems/game-of-life/
*
*
*/
// Date: Wed Dec 30 09:10:03 PST 2020
class Solution {
func gameOfLife(_ board: inout [[Int]]) {
guard board.count > 0 else { return }
guard board[0].count > 0 else { return }
for i in 0..<board.count {
for j in 0..<board[0].count {
// cell is dead
if board[i][j] == 0 {
if getLivesCount(board, i, j) == 3 {
board[i][j] = 3 // dead -> alive
}
}
// cell is alive
if board[i][j] == 1 {
if getLivesCount(board, i, j) < 2 || getLivesCount(board, i, j) > 3 {
board[i][j] = 2 // alive -> dead
}
}
}
}
for i in 0..<board.count {
for j in 0..<board[0].count {
board[i][j] %= 2
}
}
}
private func getLivesCount(_ board: [[Int]], _ i: Int, _ j: Int) -> Int {
let dimensions: [[Int]] = [
[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
var lives = 0
for d in dimensions {
let x = d[0] + i
let y = d[1] + j
guard x >= 0, x < board.count, y >= 0, y < board[0].count else {
continue
}
if board[x][y] == 1 || board[x][y] == 2 {
lives += 1
}
}
return lives
}
} | 6420ef78663dcca609ee25082157b580 | 19.77193 | 74 | 0.477599 | false | false | false | false |
stomp1128/TIY-Assignments | refs/heads/master | 12-InDueTimeRedux/12-InDueTimeRedux/AppDelegate.swift | cc0-1.0 | 1 | //
// AppDelegate.swift
// 12-InDueTimeRedux
//
// Created by Chris Stomp on 12/1/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.tiy._2_InDueTimeRedux" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("_2_InDueTimeRedux", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| aa4b6d9c09b9ecdd65db5ba68fbaf901 | 54.09009 | 291 | 0.719542 | false | false | false | false |
JaSpa/swift | refs/heads/master | stdlib/public/Platform/TiocConstants.swift | apache-2.0 | 21 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Tty ioctl request constants, needed only on Darwin and FreeBSD.
// Constants available on all platforms, also available on Linux.
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) || os(FreeBSD)
/// Set exclusive use of tty.
public var TIOCEXCL: UInt { return 0x2000740d }
/// Reset exclusive use of tty.
public var TIOCNXCL: UInt { return 0x2000740e }
/// Flush buffers.
public var TIOCFLUSH: UInt { return 0x80047410 }
/// Get line discipline.
public var TIOCGETD: UInt { return 0x4004741a }
/// Set line discipline.
public var TIOCSETD: UInt { return 0x8004741b }
/// Set break bit.
public var TIOCSBRK: UInt { return 0x2000747b }
/// Clear break bit.
public var TIOCCBRK: UInt { return 0x2000747a }
/// Set data terminal ready.
public var TIOCSDTR: UInt { return 0x20007479 }
/// Clear data terminal ready.
public var TIOCCDTR: UInt { return 0x20007478 }
/// Get pgrp of tty.
public var TIOCGPGRP: UInt { return 0x40047477 }
/// Set pgrp of tty.
public var TIOCSPGRP: UInt { return 0x80047476 }
/// Output queue size.
public var TIOCOUTQ: UInt { return 0x40047473 }
/// Simulate terminal input.
public var TIOCSTI: UInt { return 0x80017472 }
/// Void tty association.
public var TIOCNOTTY: UInt { return 0x20007471 }
/// Pty: set/clear packet mode.
public var TIOCPKT: UInt { return 0x80047470 }
/// Stop output, like `^S`.
public var TIOCSTOP: UInt { return 0x2000746f }
/// Start output, like `^Q`.
public var TIOCSTART: UInt { return 0x2000746e }
/// Set all modem bits.
public var TIOCMSET: UInt { return 0x8004746d }
/// Bis modem bits.
public var TIOCMBIS: UInt { return 0x8004746c }
/// Bic modem bits.
public var TIOCMBIC: UInt { return 0x8004746b }
/// Get all modem bits.
public var TIOCMGET: UInt { return 0x4004746a }
/// Get window size.
public var TIOCGWINSZ: UInt { return 0x40087468 }
/// Set window size.
public var TIOCSWINSZ: UInt { return 0x80087467 }
/// Pty: set/clr usr cntl mode.
public var TIOCUCNTL: UInt { return 0x80047466 }
/// Simulate `^T` status message.
public var TIOCSTAT: UInt { return 0x20007465 }
/// Become virtual console.
public var TIOCCONS: UInt { return 0x80047462 }
/// Become controlling tty.
public var TIOCSCTTY: UInt { return 0x20007461 }
/// Pty: external processing.
public var TIOCEXT: UInt { return 0x80047460 }
/// Wait till output drained.
public var TIOCDRAIN: UInt { return 0x2000745e }
/// Modem: set wait on close.
public var TIOCMSDTRWAIT: UInt { return 0x8004745b }
/// Modem: get wait on close.
public var TIOCMGDTRWAIT: UInt { return 0x4004745a }
/// Enable/get timestamp of last input event.
public var TIOCTIMESTAMP: UInt { return 0x40107459 }
/// Set ttywait timeout.
public var TIOCSDRAINWAIT: UInt { return 0x80047457 }
/// Get ttywait timeout.
public var TIOCGDRAINWAIT: UInt { return 0x40047456 }
// From ioctl_compat.h.
/// Hang up on last close.
public var TIOCHPCL: UInt { return 0x20007402 }
/// Get parameters -- gtty.
public var TIOCGETP: UInt { return 0x40067408 }
/// Set parameters -- stty.
public var TIOCSETP: UInt { return 0x80067409 }
/// As above, but no flushtty.
public var TIOCSETN: UInt { return 0x8006740a }
/// Set special characters.
public var TIOCSETC: UInt { return 0x80067411 }
/// Get special characters.
public var TIOCGETC: UInt { return 0x40067412 }
/// Bis local mode bits.
public var TIOCLBIS: UInt { return 0x8004747f }
/// Bic local mode bits.
public var TIOCLBIC: UInt { return 0x8004747e }
/// Set entire local mode word.
public var TIOCLSET: UInt { return 0x8004747d }
/// Get local modes.
public var TIOCLGET: UInt { return 0x4004747c }
/// Set local special chars.
public var TIOCSLTC: UInt { return 0x80067475 }
/// Get local special chars.
public var TIOCGLTC: UInt { return 0x40067474 }
#endif
// Darwin only constants, also available on Linux.
#if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
/// Get termios struct.
public var TIOCGETA: UInt { return 0x40487413 }
/// Set termios struct.
public var TIOCSETA: UInt { return 0x80487414 }
/// Drain output, set.
public var TIOCSETAW: UInt { return 0x80487415 }
/// Drn out, fls in, set.
public var TIOCSETAF: UInt { return 0x80487416 }
/// Pty: generate signal.
public var TIOCSIG: UInt { return 0x2000745f }
/// Get modem control state.
public var TIOCMODG: UInt { return 0x40047403 }
/// Set modem control state.
public var TIOCMODS: UInt { return 0x80047404 }
/// Internal input VSTART.
public var TIOCIXON: UInt { return 0x20007481 }
/// Internal input VSTOP.
public var TIOCIXOFF: UInt { return 0x20007480 }
/// Remote input editing.
public var TIOCREMOTE: UInt { return 0x80047469 }
/// 4.2 compatibility.
public var TIOCSCONS: UInt { return 0x20007463 }
/// Enable/get timestamp of last DCd rise.
public var TIOCDCDTIMESTAMP: UInt { return 0x40107458 }
/// Download microcode to DSI Softmodem.
public var TIOCDSIMICROCODE: UInt { return 0x20007455 }
/// Grantpt(3).
public var TIOCPTYGRANT: UInt { return 0x20007454 }
/// Ptsname(3).
public var TIOCPTYGNAME: UInt { return 0x40807453 }
/// Unlockpt(3).
public var TIOCPTYUNLK: UInt { return 0x20007452 }
#endif
// FreeBSD specific values and constants available only on FreeBSD.
#if os(FreeBSD)
/// Get termios struct.
public var TIOCGETA: UInt { return 0x402c7413 }
/// Set termios struct.
public var TIOCSETA: UInt { return 0x802c7414 }
/// Drain output, set.
public var TIOCSETAW: UInt { return 0x802c7415 }
/// Drn out, fls in, set.
public var TIOCSETAF: UInt { return 0x802c7416 }
/// Pty: generate signal.
public var TIOCSIG: UInt { return 0x2004745f }
/// Get pts number.
public var TIOCGPTN: UInt { return 0x4004740f }
/// Pts master validation.
public var TIOCPTMASTER: UInt { return 0x2000741c }
/// Get session id.
public var TIOCGSID: UInt { return 0x40047463 }
#endif
| 8cdced045fe2bf312f1e23423c54768b | 34.254237 | 80 | 0.711218 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/Extensions/Bundle+ScienceJournal.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
extension Bundle {
/// Returns the current bundle, based on the AppDelegate class. For open-source, this will always
/// be equivalent to Bundle.main.
static var currentBundle: Bundle = {
return Bundle(for: AppDelegateOpen.self)
}()
/// Returns the app version string.
static var appVersionString: String {
let dictionary = Bundle.currentBundle.infoDictionary!
// swiftlint:disable force_cast
return dictionary["CFBundleVersion"] as! String
// swiftlint:enable force_cast
}
/// Returns the build number as an integer.
static var buildVersion: Int32 {
#if SCIENCEJOURNAL_DEV_BUILD
// This can be set to arbitrary values in dev as needed.
return 9999
#else
// This assumes the version string is in the format "1.2.3".
let versionParts = appVersionString.components(separatedBy: ".")
let build = versionParts[2]
guard let version = Int32(build) else {
fatalError("Build version string must be three integers separated by periods.")
}
return version
#endif
}
/// Returns the strings sub-bundle or nil if it is not found.
static var stringsBundle: Bundle? = {
// Look for the Strings.bundle sub-bundle.
guard let subBundlePath =
Bundle.currentBundle.path(forResource: "Strings", ofType: "bundle") else {
return nil
}
return Bundle(url: URL(fileURLWithPath: subBundlePath, isDirectory: true))
}()
}
| 4936b5020dfe209e0aa1b07e2beee62d | 32.612903 | 99 | 0.697217 | false | false | false | false |
kevinvanderlugt/Exercism-Solutions | refs/heads/master | swift/phone-number/PhoneNumber.swift | mit | 1 | import Foundation
private let invalidNumberResponse = "0000000000"
struct PhoneNumber {
var startingNumber: String
func number() -> String {
return sanitizedPhoneNumber(startingNumber)
}
func areaCode() -> String {
return sanitizedPhoneNumber(startingNumber)[0..<3]
}
func description() -> String {
let phoneNumber = sanitizedPhoneNumber(startingNumber)
return "(\(areaCode())) \(phoneNumber[3..<6])-\(phoneNumber[6..<10])"
}
private func sanitizedPhoneNumber(phoneNumber: String) -> String {
let allowedCharacterSet = NSCharacterSet.decimalDigitCharacterSet()
let components = phoneNumber.componentsSeparatedByCharactersInSet(allowedCharacterSet.invertedSet)
let sanitizedNumber = join("", components)
switch countElements(sanitizedNumber) {
case 10: return sanitizedNumber
case 11: return sanitizedNumber[0] == "1" ? dropFirst(sanitizedNumber) : invalidNumberResponse
default: return invalidNumberResponse
}
}
}
extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
subscript (r: Range<Int>) -> String {
return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex)))
}
} | fd0b1972f3f08d0f84d6c20dfc56b799 | 32.195122 | 120 | 0.670588 | false | false | false | false |
omarojo/MyC4FW | refs/heads/master | Demos/DemoApp/Pods/C4/C4/UI/RegularPolygon.swift | mit | 2 | // Copyright © 2014 C4
//
// 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 CoreGraphics
///RegularPolygon is a is a concrete subclass of Polygon that defines a shape whose sides are uniform (e.g. pentagon, octagon, etc.).
///
/// This class defines two variables called `sides` and `phase` that represent the number of sides and the initial rotation of the shape (respectively). The default shape is a hexagon.
public class RegularPolygon: Polygon {
/// Returns the number of sides in the polygon.
///
/// Assigning a value to this property will change the number of sides and cause the receiver to automatically update its
/// path.
///
/// ````
/// let f = Rect(100,100,100,100)
/// var p = RegularPolygon(frame: f)
/// p.sides = 3
/// canvas.add(p)
/// ````
@IBInspectable
public var sides: Int = 6 {
didSet {
assert(sides > 0)
updatePath()
}
}
/// Returns the phase (i.e. "rotated" beginning position) of the shape. This is not actual rotation, it simply changes
/// where the beginning of the shape is.
///
/// Assigning a value to this property will change the starting position of the beginning of the shape. The shape will
/// still calculate its points based on the frame.
///
/// ````
/// let f = Rect(100,100,100,100)
/// var p = RegularPolygon(frame: f)
/// p.phase = M_PI_2
/// canvas.add(p)
/// ````
@IBInspectable
public var phase: Double = 0 {
didSet {
updatePath()
}
}
/// Initializes a new RegularPolygon.
///
/// Default values are are sides = 6 (i.e. a hexagon), phase = 0.
convenience public init(center: Point, radius: Double = 50.0, sides: Int = 6, phase: Double = 0.0) {
let dΘ = 2.0*M_PI / Double(sides)
var pointArray = [Point]()
for i in 0..<sides {
let Θ = phase + dΘ * Double(i)
pointArray.append(Point(radius*cos(Θ), radius*sin(Θ)))
}
self.init(pointArray)
self.close()
self.fillColor = C4Blue
self.center = center
}
internal override func updatePath() {
self.path = RegularPolygon(center: center, radius: width/2.0, sides:self.sides, phase:self.phase).path
}
}
| fc313ddc64d06a2dbfa1a06bea3cbae2 | 38.423529 | 184 | 0.65473 | false | false | false | false |
FrancisBaileyH/Garden-Wall | refs/heads/master | Garden Wall/AddItemViewController.swift | mit | 1 | //
// AddItemViewController.swift
// Garden Wall
//
// Created by Francis Bailey on 2015-12-06.
// Copyright © 2015 Francis Bailey. All rights reserved.
//
import UIKit
import SwiftForms
class AddItemViewController: FormViewController {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.form = self.initializeForm()
}
override func viewDidLoad() {
super.viewDidLoad()
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelButtonPressed:")
let saveButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "saveButtonPressed:")
self.navigationItem.leftBarButtonItem = cancelButton
self.navigationItem.rightBarButtonItem = saveButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/*
* Handle cancel button action
*/
func cancelButtonPressed(sender: AnyObject) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
/*
* Save the new rule and close the view, unless an error occurred
*/
func saveButtonPressed(sender: AnyObject) {
self.cancelButtonPressed(sender)
}
func initializeForm() -> FormDescriptor {
return FormDescriptor()
}
func showAlert(message: String) {
let alert = UIAlertController(title: "Validation Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| aea20d250070e988c631d6e354e612ac | 25.457143 | 140 | 0.657127 | false | false | false | false |
jay18001/brickkit-ios | refs/heads/master | Example/Source/Navigation/NavigationDataSource.swift | apache-2.0 | 1 | //
// RootNavigationDataSource.swift
// BrickKit
//
// Created by Ruben Cagnie on 9/14/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
// Mark: - Navigation Item
struct NavigationItem: Equatable {
let title: String
let subTitle: String
var viewControllers: [UIViewController.Type]
}
func ==(lhs: NavigationItem, rhs: NavigationItem) -> Bool {
return lhs.title == rhs.title && lhs.subTitle == rhs.subTitle
}
/// NavigationDataSource: DataSource for the navigation objects
class NavigationDataSource {
#if os(iOS)
var layoutNavigationItem = NavigationItem(title: "Layout", subTitle: "Examples of different layout behaviors", viewControllers: [
OffsetBrickViewController.self,
SizeClassesBrickViewController.self
])
#else
var layoutNavigationItem = NavigationItem(title: "Layout", subTitle: "Examples of different layout behaviors", viewControllers: [
OffsetBrickViewController.self
])
#endif
var selectedItem: NavigationItem?
var selectedIndex: Int? {
guard let selectedItem = self.selectedItem else {
return nil
}
return sections.index(of: selectedItem)
}
lazy var sections: [ NavigationItem ] = [
NavigationItem(title: "Simple", subTitle: "Simple Examples", viewControllers: [
SimpleBrickViewController.self,
SimpleRepeatBrickViewController.self,
HugeRepeatBrickViewController.self,
HugeRepeatCollectionViewController.self,
NibLessViewController.self,
SimpleRepeatFixedWidthViewController.self,
SimpleRepeatFixedHeightViewController.self,
SimpleRepeatHeightRatioViewController.self,
FillBrickViewController.self,
MultiSectionBrickViewController.self,
MultiDimensionBrickViewController.self,
AlignmentBrickViewController.self
]),
self.InteractiveExamples,
NavigationItem(title: "Sticky", subTitle: "Examples of different sticky behaviors", viewControllers: [
BasicStickingViewController.self,
StackedStickingViewController.self,
SectionStickingViewController.self,
StickingSectionsViewController.self,
OnScrollDownStickingViewController.self,
StickingFooterBaseViewController.self,
StickingFooterSectionsViewController.self,
StackingFooterViewController.self
]),
NavigationItem(title: "Scrolling", subTitle: "Examples of different scrolling behaviors", viewControllers: [
SpotlightScrollingViewController.self,
EmbeddedSpotlightSnapScrollingViewController.self,
CardScrollingViewController.self,
CoverFlowScrollingViewController.self,
]),
self.layoutNavigationItem,
NavigationItem(title: "CollectionBrick", subTitle: "Examples of how to use CollectionBrick", viewControllers: [
SimpleCollectionBrickViewController.self,
RepeatCollectionBrickViewController.self,
HorizontalScrollSectionBrickViewController.self
]),
NavigationItem(title: "Horizontal", subTitle: "Examples of how to use horizontal scroll", viewControllers: [
SimpleHorizontalScrollBrickViewController.self,
HorizontalSnapToPointViewController.self,
BlockHorizontalViewController.self,
HorizontalCollectionViewController.self
]),
NavigationItem(title: "Images", subTitle: "Examples of how to use images", viewControllers: [
ImageViewBrickViewController.self,
ImageURLBrickViewController.self,
ImagesInCollectionBrickViewController.self,
ImagesInCollectionBrickHorizontalViewController.self
]),
NavigationItem(title: "Demo", subTitle: "Example Of Using BrickKit in Real Case", viewControllers: [
MockTwitterViewController.self])
]
var numberOfItems: Int {
return sections.count
}
func item(for index: Int) -> NavigationItem {
return sections[index]
}
#if os(iOS)
var InteractiveExamples = NavigationItem(title: "Interactive", subTitle: "Interactive Examples", viewControllers: [
BasicInteractiveViewController.self,
BrickCollectionInteractiveViewController.self,
HideBrickViewController.self,
AdvancedRepeatViewController.self,
InsertBrickViewController.self,
ChangeNibBrickViewController.self,
HideSectionsViewController.self,
IsHiddenBrickViewController.self,
DynamicContentViewController.self,
InvalidateHeightViewController.self,
InteractiveAlignViewController.self,
])
#else
var InteractiveExamples = NavigationItem(title: "Interactive", subTitle: "Interactive Examples", viewControllers: [
BrickCollectionInteractiveViewController.self,
HideBrickViewController.self,
AdvancedRepeatViewController.self,
InsertBrickViewController.self,
ChangeNibBrickViewController.self,
HideSectionsViewController.self,
IsHiddenBrickViewController.self,
DynamicContentViewController.self,
InvalidateHeightViewController.self,
InteractiveAlignViewController.self
])
#endif
}
// Mark: - NavigationIdentifiers
struct NavigationIdentifiers {
static let titleSection = "TitleSection"
static let titleBrick = "TitleBrick"
static let navItemSection = "NavItemSection"
static let navItemBrick = "NavItemBrick"
static let subItemSection = "SubItemSection"
static let subItemBrick = "SubItemBrick"
}
// MARK: - title / subTitle extension
extension UIViewController {
class var brickTitle: String {
return "Title"
}
class var subTitle: String {
return "Sub Title"
}
}
| 9a15bd1e0b6ff68b35623dd9746f776d | 35.888889 | 137 | 0.691934 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Exchange/CustomView/ContactListCell.swift | gpl-3.0 | 1 | //
// ContactListCell.swift
// iOSStar
//
// Created by J-bb on 17/4/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class GetOrderStarsVCCell : OEZTableViewCell{
@IBOutlet var dodetail: UIButton!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var chatButton: UIButton!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var contView: UIView!
@IBOutlet var ownsecond: UILabel!
var cellModel: StarInfoModel = StarInfoModel()
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func haveAChat(_sender: UIButton) {
didSelectRowAction(3, data: cellModel)
}
override func update(_ data: Any!) {
guard data != nil else{return}
let model = data as! StarInfoModel
StartModel.getStartName(startCode: model.starcode) { (response) in
if let star = response as? StartModel {
self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail))
}
}
cellModel = model
nameLabel.text = model.starname
ownsecond.text = "\(model.ownseconds)"
}
@IBAction func dochat(_ sender: Any) {
didSelectRowAction(5, data: cellModel)
}
@IBAction func domeet(_ sender: Any) {
didSelectRowAction(4, data: cellModel)
}
}
//MARK: -普通的cell
class ContactListCell: OEZTableViewCell {
//工作
@IBOutlet var doStarDeatil: UIButton!
@IBOutlet weak var jobLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var unreadLabel: UILabel!
@IBOutlet weak var chatButton: UIButton!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet var orderTime: UILabel!
var cellModel: StarInfoModel = StarInfoModel()
override func awakeFromNib() {
super.awakeFromNib()
chatButton.layer.cornerRadius = 2
chatButton.layer.masksToBounds = true
self.clipsToBounds = true
self.layer.masksToBounds = true
self.layer.cornerRadius = 2
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func haveAChat(_sender: UIButton) {
didSelectRowAction(3, data: cellModel)
}
override func update(_ data: Any!) {
guard data != nil else{return}
if let model = data as? StarInfoModel{
unreadLabel.text = " \(model.unreadCount) "
unreadLabel.isHidden = model.unreadCount == 0
StartModel.getStartName(startCode: model.starcode) { (response) in
if let star = response as? StartModel {
self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + star.pic_url_tail))
}
}
var title = ""
var color = ""
if model.appoint == 0 {
color = AppConst.Color.main
title = "没有约见"
} else if model.appoint == 1{
color = AppConst.Color.main
title = "待确认"
}
else if model.appoint == 2{
color = "CCCCCC"
title = "已拒绝"
}
else if model.appoint == 3{
color = AppConst.Color.main
title = "已完成"
}
else {
color = AppConst.Color.main
title = "已同意"
}
chatButton.setTitle(title, for: .normal)
chatButton.backgroundColor = UIColor.init(hexString: color)
chatButton.backgroundColor = UIColor.init(hexString: AppConst.Color.orange)
cellModel = model
if (nameLabel != nil){
nameLabel.text = model.starname
jobLabel.text = model.work
chatButton.setTitle("聊一聊", for: .normal)
}
}
else{
if let model = data as? OrderStarListInfoModel{
var title = ""
var color = ""
if model.meet_type == 4 {
color = AppConst.Color.orange
title = "已同意"
} else if model.meet_type == 1{
color = AppConst.Color.orange
title = "已预订"
}
else if model.meet_type == 2{
color = "CCCCCC"
title = "已拒绝"
}
else if model.meet_type == 3{
color = "CCCCCC"
title = "已完成"
}
else {
color = "CCCCCC"
title = "已同意"
}
chatButton.setTitle(title, for: .normal)
chatButton.backgroundColor = UIColor.init(hexString: color)
jobLabel.text = model.star_name
orderTime.text = model.meet_time
self.iconImageView.kf.setImage(with: URL(string:ShareDataModel.share().qiniuHeader + model.star_pic_tail))
orderTime.text = model.meet_time
}
}
}
}
| b7ddb1735b548ba0154c046914a98b1a | 31.602339 | 124 | 0.535067 | false | false | false | false |
imex94/KCLTech-iOS-Sessions-2014-2015 | refs/heads/master | session202/session202/SignupViewController.swift | mit | 1 | //
// SignupViewController.swift
// session202
//
// Created by Alex Telek on 10/11/2014.
// Copyright (c) 2014 KCLTech. All rights reserved.
//
import UIKit
class SignupViewController: UIViewController {
@IBOutlet var txtUsername: UITextField!
@IBOutlet var txtPassword: UITextField!
@IBOutlet var txtEmail: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signup(sender: AnyObject) {
if let user = Store.loadData(txtUsername.text) {
println("User already exist")
} else {
performSegueWithIdentifier("signup", sender: self)
}
}
// 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.
let nav = segue.destinationViewController as! UINavigationController
let nextView = nav.topViewController as! NotesTableViewController
let newUser = User(username: txtUsername.text, password: txtPassword.text, email: txtEmail.text)
nextView.currentUser = newUser
Store.saveData(newUser)
}
}
| 0ec99443c06e0e954cb8f9a7baa01546 | 31.729167 | 106 | 0.681095 | false | false | false | false |
drumbart/SwiftyHTML | refs/heads/master | SwiftyHTML/Classes/Models/Attributes/Style.swift | mit | 1 | //
// Style.swift
// Pods
//
// Created by Bartosz Tułodziecki on 28/10/2016.
//
//
open class Style: TagAttribute {
private let TextDecorationKey = "text-decoration:"
private let FontWeightKey = "font-weight:"
private let FontStyleKey = "font-style:"
public var name: String = "style"
open var value: String
public var font: UIFont? {
didSet {
self.value = self.computedValue()
}
}
public var color: UIColor? {
didSet {
self.value = self.computedValue()
}
}
public var backgroundColor: UIColor? {
didSet {
self.value = self.computedValue()
}
}
public var underline: Bool? {
didSet {
self.value = self.computedValue()
}
}
public var strikethrough: Bool? {
didSet {
self.value = self.computedValue()
}
}
public var textAlignment: NSTextAlignment? {
didSet {
self.value = self.computedValue()
}
}
private var fontColorString: String {
if let color = self.color, let rgb = color.rgb() {
return "color:rgb(\(rgb.red),\(rgb.green),\(rgb.blue));"
}
return ""
}
private var bgColorString: String {
if let bgColor = self.backgroundColor, let rgb = bgColor.rgb() {
return "background-color:rgb(\(rgb.red),\(rgb.green),\(rgb.blue));"
}
return ""
}
private var fontString: String {
if let font = self.font {
return self.getFontAttributes(font: font)
}
return ""
}
private var underlineStrikethroughString: String {
var str = ""
if let underline = self.underline, underline == true {
str += "text-decoration:underline;"
}
if let strikethrough = self.strikethrough, strikethrough == true {
if str.contains(TextDecorationKey) {
str.insert(contentsOf: " line-through", at: str.index(str.endIndex, offsetBy: -1))
}
else {
str += "text-decoration:line-through;"
}
}
return str
}
private var alignmentString: String {
if let alignment = self.textAlignment {
switch alignment {
case .left:
return "text-align:left; display:block;"
case .center:
return "text-align:center; display:block;"
case .right:
return "text-align:right; display:block;"
case .justified:
return "text-align:justify; display:block;"
default:
return ""
}
}
return ""
}
public required init?(value: String) {
self.value = value
}
public init() {
self.value = ""
}
private func computedValue() -> String {
var str = ""
str += self.fontColorString
str += self.bgColorString
str += self.fontString
str += self.underlineStrikethroughString
str += self.alignmentString
return str
}
private func getFontAttributes(font: UIFont) -> String {
var str = ""
str += "font-family:\(font.fontName); font-size:\(Int(font.pointSize))px;"
str += FontWeightKey + (font.isBold ? "bold;" : "normal;")
if font.isItalic {
str += FontStyleKey + "italic;"
}
return str
}
}
| 155c2a52236385c4203c0f69488ded34 | 25.481481 | 98 | 0.519441 | false | false | false | false |
footyapps27/Storyboard | refs/heads/master | Swift/Storyboard_Example_Swift/Initial Launch View Controller/SBViewController.swift | mit | 1 | //
// ViewController.swift
// Storyboard_Example_Swift
//
// Created by Samrat on 12/22/14.
// Copyright (c) 2014 footyapps27. All rights reserved.
//
import UIKit
class SBViewController: UITableViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 7;
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
//variable type is inferred
var cell = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
}
//we know that cell is not empty now so we use ! to force unwrapping
cell!.textLabel!.text = "Baking Soda"
return cell!;
}
}
| 08687b3c364363dd722041e4b10cc566 | 25.826087 | 116 | 0.642626 | false | false | false | false |
kevintavog/PeachMetadata | refs/heads/master | source/PeachMetadata/AllKeywordsController.swift | mit | 1 | //
// PeachMetadata
//
import AppKit
import RangicCore
class AllKeywordsTableViewController : NSObject, NSTableViewDelegate, NSTableViewDataSource
{
let tableView: NSTableView
var filesAndKeywords: FilesAndKeywords
init(tableView: NSTableView)
{
self.tableView = tableView
filesAndKeywords = FilesAndKeywords()
}
func keywordToggled(index: Int)
{
let keyword = AllKeywords.sharedInstance.keywords[index]
if filesAndKeywords.uniqueKeywords.contains(keyword) {
filesAndKeywords.removeKeyword(keyword)
} else {
filesAndKeywords.addKeyword(keyword)
}
}
func updateTable()
{
tableView.reloadData()
}
func updateColumns()
{
let columnWidth = self.calculateMaxColumnWidth()
let tableWidth = tableView.bounds.width
let columnCount = max(1, Int(tableWidth) / columnWidth)
Logger.debug("table: \(tableWidth) -- column: \(columnWidth) -- #columns: \(columnCount) -- current: \(tableView.numberOfColumns)")
if (columnCount < tableView.numberOfColumns) {
while (columnCount < tableView.numberOfColumns) {
tableView.removeTableColumn(tableView.tableColumns.last!)
Logger.debug("removed column, now \(tableView.numberOfColumns), \(tableView.tableColumns.count)")
}
} else if (columnCount > tableView.numberOfColumns) {
while (columnCount > tableView.numberOfColumns) {
tableView.addTableColumn(NSTableColumn())
Logger.debug("added column, now \(tableView.numberOfColumns), \(tableView.tableColumns.count)")
}
}
}
func selectionChanged(_ selectedItems: FilesAndKeywords)
{
// updateColumns()
filesAndKeywords = selectedItems
tableView.reloadData()
}
func numberOfRows(in tableView: NSTableView) -> Int
{
let keywordCount = AllKeywords.sharedInstance.keywords.count;
return keywordCount / tableView.numberOfColumns + ((keywordCount % tableView.numberOfColumns) == 0 ? 0 : 1)
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?
{
if AllKeywords.sharedInstance.keywords.count == 0 {
return nil
}
var columnView:NSButton? = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "allKeywordsView"), owner: tableView) as! NSButton?
if (columnView == nil)
{
let control = NSButton(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
control.identifier = NSUserInterfaceItemIdentifier(rawValue: "allKeywordsView")
control.setButtonType(NSButton.ButtonType.onOff)
control.bezelStyle = NSButton.BezelStyle.rounded
control.action = #selector(PeachWindowController.allKeywordClick(_:))
columnView = control
}
let columnIndex = getColumnIndex(tableView, tableColumn: tableColumn!)
let keywordIndex = (row * tableView.numberOfColumns) + columnIndex
columnView?.tag = keywordIndex
if keywordIndex >= AllKeywords.sharedInstance.keywords.count {
columnView?.isTransparent = true
} else {
let keyword = AllKeywords.sharedInstance.keywords[keywordIndex]
columnView?.title = keyword
columnView?.isTransparent = false
columnView?.state = filesAndKeywords.uniqueKeywords.contains(keyword) ? .on : .off
}
return columnView
}
func getColumnIndex(_ tableView: NSTableView, tableColumn: NSTableColumn) -> Int
{
for index in 0 ..< tableView.numberOfColumns {
if tableView.tableColumns[index] == tableColumn {
return index
}
}
return -1
}
func calculateMaxColumnWidth() -> Int
{
var maxWidth = 0
for row in 0 ..< tableView.numberOfRows {
for column in 0 ..< tableView.numberOfColumns {
if let view = tableView.view(atColumn: column, row: row, makeIfNecessary: false) {
let width = view.fittingSize.width
maxWidth = max(Int(width), maxWidth)
}
}
}
return maxWidth
}
}
| 56ef139733f1b06a907ece02d65e4e7b | 33.265625 | 161 | 0.625627 | false | false | false | false |
SomeHero/Twurl-iOS | refs/heads/master | Twurl-iOS/Managers/TwurlApiManager.swift | mit | 1 | //
// TwurlApiManager.swift
// Twurl-iOS
//
// Created by James Rhodes on 6/6/15.
// Copyright (c) 2015 James Rhodes. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class TwurlApiManager: NSObject {
static func getTwurls(category_id: Int?, page_number: Int?, success: (response: JSON!) -> Void, failure: (NSError?) -> Void) {
var category = ""
if let v = category_id {
category = "\(v)"
}
var page = ""
if let v = page_number {
page = "\(v)"
}
let params = ["category_id": category, "page_number": page]
Alamofire.request(.GET, "https://twurl.herokuapp.com/api/v1/twurls", parameters: params)
.responseJSON { (request, response, data, error) in
if let anError = error {
failure(anError)
}
else if let data: AnyObject = data {
let json = JSON(data)
success(response: json)
}
}
}
static func getCategories(success: (response: JSON!) -> Void, failure: (NSError?) -> Void) {
Alamofire.request(.GET, "https://twurl.herokuapp.com/api/v1/categories")
.responseJSON { (request, response, data, error) in
if let anError = error {
failure(anError)
}
else if let data: AnyObject = data {
let json = JSON(data)
success(response: json)
}
}
}
}
| 147af42ee56b7ae7de4e35c49b874027 | 29.943396 | 130 | 0.489634 | false | false | false | false |
khoogheem/GenesisKit | refs/heads/master | Shared/UI/CountryFlag.swift | mit | 1 | //
// CountryFlag.swift
// GenesisKit
//
// Created by Kevin A. Hoogheem on 10/26/14.
// Copyright (c) 2014 Kevin A. Hoogheem. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
/**
A Helper Object for retrieval of a Country Flag
***Does not support Objective-C****
*/
public class CountryFlag {
/**
Defines the Size of the Country Flag
*/
public enum CountyFlagSize:Int {
/** 64px Size Flag */
case ExtraLarge = 64
/** 48px Size flag */
case Large = 48
/** 32px Size flag */
case Normal = 32
/** 24px Size flag */
case Small = 24
/** 16px Size flag */
case ExtraSmall = 16
}
//MARK: - Functions
/**
The Offical GenesisKit Country Flag for the Countries ISO_Alpha2 code.
:param: alpha_2 The ISO_Alpha2 code for the country
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of the Countries Flag
:see: CountyFlagSize
*/
public class func imageFor(alpha_2: String, size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
//TODO: Will use something later to change alpha3 to alpha2 visversa
// Lets for now check if alpha_2 is really a Alpha2
assert(count(alpha_2) == 2, "Two shall be the number thou shalt count, and the number of the counting shall be Two")
return getImage(alpha_2.uppercaseString, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for the Olympics.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of the Olympics
:see: CountyFlagSize
*/
public class func olympicFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagOlympics, size: size, shiny: shiny)
// let filetype = "png"
// var flagDir = kCountryFlagFlatDirectory
// if (shiny) {
// flagDir = kCountryFlagShinyDirectory
// }
// let fileName = "\(flagDir)/\(size.rawValue)/\(kCountryFlagFlagOlympics)"
// let frameworkBundle = NSBundle.frameworkBundle()
// println("fi: \(fileName)")
//
// //No need to check for nil as wek now the Olympic flag is there
// let resoruce = frameworkBundle.pathForResource(fileName, ofType: "png")
// println(resoruce)
// return GKImage(contentsOfFile:resoruce!)!
}
/**
The Offical GenesisKit Country Flag for NATO.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of NATO
:see: CountyFlagSize
*/
public class func natoFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagNATO, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for the UN.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of the UN
:see: CountyFlagSize
*/
public class func unitedNationsFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagUnitedNations, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for England.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of England
:see: CountyFlagSize
*/
public class func englandFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagEngland, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for The Commonwealth.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of the Commonwealth
:see: CountyFlagSize
*/
public class func commonwealthFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagCommonWealth, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for Scotland.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of Scotland
:see: CountyFlagSize
*/
public class func scotlandFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagScotland, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for Wales.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of Wales
:see: CountyFlagSize
*/
public class func walesFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagWales, size: size, shiny: shiny)
}
/**
The Offical GenesisKit Country Flag for Basque.
:param: size (default .Normal) The size of the flag you wish to return
:param: shiny (default false) If true will return a glossy verison of the flag otherwise it returns a flat image
:returns: The GKImage (either a UIImage or NSImage) of Basque
:see: CountyFlagSize
*/
public class func basqueFlag(size: CountyFlagSize = CountyFlagSize.Normal, shiny: Bool = false) -> GKImage {
return getImage(kCountryFlagFlagBasque, size: size, shiny: shiny)
}
//MARK: - Private
private class var kCountryFlagFlatDirectory:String { return "flags-iso/flat" }
private class var kCountryFlagShinyDirectory:String { return "flags-iso/shiny" }
private class var kCountryFlagFlagUnknown:String { return "_unknown" }
private class var kCountryFlagFlagOlympics:String { return "_olympics" }
private class var kCountryFlagFlagNATO:String { return "_nato" }
private class var kCountryFlagFlagUnitedNations:String { return "_united-nations" }
private class var kCountryFlagFlagEngland:String { return "_england" }
private class var kCountryFlagFlagCommonWealth:String { return "_commonwealth" }
private class var kCountryFlagFlagScotland:String { return "_scotland" }
private class var kCountryFlagFlagWales:String { return "_wales" }
private class var kCountryFlagFlagBasque:String { return "_basque-country" }
/**
Internal getImage
*/
private class func getImage(fileName: String, size: CountyFlagSize, shiny: Bool) -> GKImage {
let filetype = "png"
var flagDir = kCountryFlagFlatDirectory
if (shiny) {
flagDir = kCountryFlagShinyDirectory
}
let unkFlag = "\(flagDir)/\(size.rawValue)/\(kCountryFlagFlagUnknown)"
let fileName = "\(flagDir)/\(size.rawValue)/\(fileName)"
let frameworkBundle = NSBundle.frameworkBundle()
//Unwarp and if ISO flag is found return it
if let resoruce = frameworkBundle.pathForResource(fileName, ofType: "png"){
return GKImage(contentsOfFile:resoruce)!
}
//No file for the ISO Code was found above.. Returnt the Unknown flag
let resoruce = frameworkBundle.pathForResource(unkFlag, ofType: "png")
return GKImage(contentsOfFile:resoruce!)!
}
}
| 4204d9d47dfe208403880cdecfa36e6c | 37.169492 | 124 | 0.739343 | false | false | false | false |
nevercry/VideoMarks | refs/heads/master | VideoMarks/PlayerController.swift | mit | 1 | //
// PlayerController.swift
// VideoMarks
//
// Created by nevercry on 7/14/16.
// Copyright © 2016 nevercry. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class PlayerController: NSObject {
let avPlayer = AVPlayerViewController()
var isInPiP = false
weak var viewController: UIViewController?
override init() {
super.init()
// 设置画中画代理
avPlayer.delegate = self
avPlayer.allowsPictureInPicturePlayback = true
avPlayer.modalTransitionStyle = .crossDissolve
//注册视频播放器播放完成通知
NotificationCenter.default.addObserver(self, selector: #selector(rePlay), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(updatePlayer), name: NSNotification.Name.AVAudioSessionInterruption, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
class var sharedInstance: PlayerController {
struct Static {
static let instance : PlayerController = PlayerController()
}
return Static.instance
}
// MARK: - 播放视频
func playVideo(_ player: AVPlayer, inViewController: UIViewController) {
player.allowsExternalPlayback = true
player.actionAtItemEnd = .none
viewController = inViewController
DispatchQueue.main.async { [weak self] in
self?.avPlayer.player = player
self?.viewController?.present(self!.avPlayer, animated: true) {
self?.avPlayer.player?.play()
self?.updateForPiP()
}
}
}
func rePlay(_ note: Notification) {
avPlayer.player?.seek(to: kCMTimeZero)
avPlayer.player?.play()
}
// 修复调用Siri完毕后,音频自动播放的bug
func updatePlayer(_ note: Notification) {
if let userInfo = (note as NSNotification).userInfo {
if let interruptType = userInfo[AVAudioSessionInterruptionTypeKey] as? NSNumber {
if interruptType.uintValue == AVAudioSessionInterruptionType.ended.rawValue {
if viewController?.view.window != nil && isInPiP == false {
avPlayer.player = nil
}
}
}
}
}
func updateForPiP() {
if let _ = viewController?.presentationController {
if isInPiP {
DispatchQueue.main.async { [weak self] in
self?.viewController?.dismiss(animated: true, completion: nil)
}
}
}
}
}
extension PlayerController: AVPlayerViewControllerDelegate {
func playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart(_ playerViewController: AVPlayerViewController) -> Bool {
print("playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart")
return true
}
func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
print("restoreUserInterfaceForPictureInPictureStopWithCompletionHandler")
if let _ = self.viewController?.presentedViewController {
} else {
DispatchQueue.main.async { [weak self] in
self?.viewController?.present(playerViewController, animated: true, completion: nil)
}
}
completionHandler(true)
}
func playerViewControllerWillStartPictureInPicture(_ playerViewController: AVPlayerViewController) {
print("WillStartPictureInPicture(")
}
func playerViewControllerDidStartPictureInPicture(_ playerViewController: AVPlayerViewController) {
print("DidStartPictureInPicture")
isInPiP = true
}
func playerViewControllerWillStopPictureInPicture(_ playerViewController: AVPlayerViewController) {
print("WillStopPictureInP")
isInPiP = false
}
func playerViewControllerDidStopPictureInPicture(_ playerViewController: AVPlayerViewController) {
print("DidStopPictureInP")
}
}
| 7ba16f3a8308605a2accdd7b13c1b8d3 | 33.844262 | 189 | 0.649965 | false | false | false | false |
jairoeli/Instasheep | refs/heads/master | InstagramFirebase/InstagramFirebase/AddPhoto/PhotoSelectController.swift | mit | 1 | //
// PhotoSelectController.swift
// InstagramFirebase
//
// Created by Jairo Eli de Leon on 3/30/17.
// Copyright © 2017 DevMountain. All rights reserved.
//
import UIKit
import Photos
class PhotoSelectorController: UICollectionViewController {
let cellId = "cellId"
let headerId = "headerId"
var images = [UIImage]()
var selectedImage: UIImage?
var assets = [PHAsset]()
var header: PhotoSelectorHeader?
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
setupNavigationButtons()
collectionView?.register(PhotoSelectorCell.self, forCellWithReuseIdentifier: cellId)
collectionView?.register(PhotoSelectorHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerId)
fetchPhotos()
}
override var prefersStatusBarHidden: Bool {
return true
}
fileprivate func setupNavigationButtons() {
navigationController?.navigationBar.tintColor = .black
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(handleNext))
}
// MARK: - Handles
@objc func handleCancel() {
dismiss(animated: true, completion: nil)
}
@objc func handleNext() {
let sharePhotoController = SharePhotoController()
sharePhotoController.selectedImage = header?.photoImageView.image
navigationController?.pushViewController(sharePhotoController, animated: true)
}
// MARK: - Fetch Photos
fileprivate func fetchPhotos() {
let fetchOptions = assetsFetchOptions()
let allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
DispatchQueue.global(qos: .background).async {
allPhotos.enumerateObjects({ (asset, count, _) in
print(count)
let imageManager = PHImageManager.default()
let targetSize = CGSize(width: 200, height: 200)
let options = PHImageRequestOptions()
options.isSynchronous = true
imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, _) in
if let image = image {
self.images.append(image)
self.assets.append(asset)
if self.selectedImage == nil {
self.selectedImage = image
}
}
if count == allPhotos.count - 1 {
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
})
})
}
}
fileprivate func assetsFetchOptions() -> PHFetchOptions {
let fetchOptions = PHFetchOptions()
fetchOptions.fetchLimit = 30
let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
fetchOptions.sortDescriptors = [sortDescriptor]
return fetchOptions
}
}
// MARK: - CollectionView Data Source
extension PhotoSelectorController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedImage = images[indexPath.item]
self.collectionView?.reloadData()
let indexPath = IndexPath(item: 0, section: 0)
collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as? PhotoSelectorHeader else { return UICollectionViewCell() }
self.header = header
header.photoImageView.image = selectedImage
if let selectedImage = selectedImage {
if let index = self.images.index(of: selectedImage) {
let selectedAsset = self.assets[index]
let imageManager = PHImageManager.default()
let targetSize = CGSize(width: 600, height: 600)
imageManager.requestImage(for: selectedAsset, targetSize: targetSize, contentMode: .default, options: nil, resultHandler: { (image, _) in
header.photoImageView.image = image
})
}
}
return header
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as? PhotoSelectorCell else { return UICollectionViewCell() }
cell.photoImageView.image = images[indexPath.item]
return cell
}
}
// MARK: - CollectionView Flow Layout
extension PhotoSelectorController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let width = view.frame.width
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (view.frame.width - 3) / 4
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
| 343c7dc8d136b1ed362408bc7616c178 | 33.577143 | 194 | 0.726657 | false | false | false | false |
gauuni/SwiftyExtension | refs/heads/master | SwiftyExtension/Extension/NSNumberExtension.swift | mit | 1 | //
// NSNumberExtension.swift
// SwiftyExtension
//
// Created by Khoi Nguyen on 7/25/18.
// Copyright © 2018 Nguyen. All rights reserved.
//
import UIKit
struct Number {
static let formatterWithSepator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.decimalSeparator = "."
formatter.numberStyle = .decimal
return formatter
}()
}
extension NSInteger {
var stringFormatedWithSepator: String {
let number = NSNumber(integerLiteral: hashValue)
return Number.formatterWithSepator.string(from: number) ?? ""
}
}
extension Double{
func stringWithSeparator(minimumFractionDigits: Int=0, maximumFractionDigits: Int=8) -> String{
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.decimalSeparator = "."
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = minimumFractionDigits
formatter.maximumFractionDigits = maximumFractionDigits
formatter.minimumIntegerDigits = 1
return formatter.string(from: NSNumber.init(value: self)) ?? ""
}
func toString(maximumFractionDigits: Int=0) -> String {
return String(format: "%.\(maximumFractionDigits)f", self)
}
}
| 6ab6ffc60275c1ea494ee886515be25b | 28.622222 | 99 | 0.667667 | false | false | false | false |
ish2028/MSeriesBle | refs/heads/master | MSeriesBle/Classes/MSBluetooth.swift | mit | 1 | //
// MSBluetooth.swift
// MSeries
//
// Created by Ismael Huerta on 12/9/16.
// Copyright © 2016 Ismael Huerta. All rights reserved.
//
import UIKit
import CoreBluetooth
public class MSBluetooth: NSObject, CBCentralManagerDelegate {
private var bleCentralManager: CBCentralManager!;
private var cleanUpTimer: Timer?
public var focusedBikeId: Int?
public var discoveredBikes = [(machineBroadcast: MSBLEMachineBroadcast, lastReceivedTime: Date)]() {
didSet {
let notification = Notification(name: NSNotification.Name(rawValue: BluetoothConnectionNotifications.BluetoothConnectionUpdateDiscoveredMachines), object: self)
NotificationCenter.default.post(notification)
}
}
public struct BluetoothConnectionNotifications {
static public let BluetoothConnectionDidDiscoverMachine = "DiscoveredMachine"
static public let BluetoothConnectionDidReceiveMachineBroadcast = "ReceivedMachineBroadcast"
static public let BluetoothConnectionUpdateDiscoveredMachines = "UpdatedDiscoveredMachine"
}
static public let sharedInstance: MSBluetooth = {
let instance = MSBluetooth()
return instance
}()
override init() {
super.init()
bleCentralManager = CBCentralManager.init(delegate: self, queue: nil)
}
@objc func cleanUpDiscoveredBikes() {
let machinesAvailable = discoveredBikes.filter({$0.lastReceivedTime.timeIntervalSinceNow >= -60})
if (!machinesAvailable.elementsEqual(discoveredBikes, by: { (available, discovered) -> Bool in
return available == discovered
})) {
discoveredBikes = machinesAvailable
}
}
private func startScanning() {
cycle()
cleanUpTimer = Timer(timeInterval: 60, target: self, selector: #selector(cleanUpDiscoveredBikes), userInfo: nil, repeats: true)
RunLoop.current.add(cleanUpTimer!, forMode: .defaultRunLoopMode)
}
private func cycle() {
if bleCentralManager.isScanning {
bleCentralManager.stopScan()
}
bleCentralManager.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOn: startScanning()
case .unsupported: break // TODO: send notification to controller that bluetooth is not enabled.
case .unauthorized: break // TODO: send notification to controller that bluetooth is not authorized
case .poweredOff: break // TODO: send notification to controller that power is off
default: break
}
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
if peripheral.name != nil {
if (peripheral.name?.compare("M3") != ComparisonResult.orderedSame){
return;
}
let machineBroadcast = MSBLEMachineBroadcast(manufactureData: advertisementData[CBAdvertisementDataManufacturerDataKey] as! Data)
machineBroadcast.name = peripheral.name!
machineBroadcast.address = peripheral.identifier.uuidString
if (machineBroadcast.isValid){
if (focusedBikeId != nil && machineBroadcast.machineID == focusedBikeId!){
let notification = Notification(name: Notification.Name(BluetoothConnectionNotifications.BluetoothConnectionDidReceiveMachineBroadcast), object: self, userInfo: ["broadcast" : machineBroadcast])
NotificationCenter.default.post(notification)
return;
}
var found = false
for i in 0..<discoveredBikes.count {
var discoveredBikeTuple = discoveredBikes[i]
if discoveredBikeTuple.machineBroadcast.machineID == machineBroadcast.machineID {
found = true
discoveredBikeTuple.lastReceivedTime = Date()
discoveredBikes[i] = discoveredBikeTuple
}
}
if !found {
discoveredBikes.append((machineBroadcast, Date()))
let notification = Notification(name: Notification.Name(BluetoothConnectionNotifications.BluetoothConnectionDidDiscoverMachine), object: self, userInfo: ["broadcast" : machineBroadcast])
NotificationCenter.default.post(notification)
}
}
}
}
}
| b427e97089b864ce83b001f920d7c9ed | 43.102804 | 214 | 0.655224 | false | false | false | false |
DigitalCroma/CodPol | refs/heads/master | CodPol/SideMenu/SideMenuViewController.swift | mit | 1 | //
// SideMenuViewController.swift
// CodPol
//
// Created by Juan Carlos Samboní Ramírez on 18/02/17.
// Copyright © 2017 DigitalCroma. All rights reserved.
//
import UIKit
import SideMenu
let kSideMenuCellIdentifier = "Cell"
class SideMenuViewController: UIViewController {
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var menuTableView: UITableView!
let menuOptions = PlistParser.getSideMenuList()
var selectedIndexPath: IndexPath!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationController?.setNavigationBarHidden(true, animated: false)
menuTableView.register(UITableViewCell.self, forCellReuseIdentifier: kSideMenuCellIdentifier)
selectedIndexPath = IndexPath(row: 0, section: 0)
menuTableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .top)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension SideMenuViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuOptions?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: kSideMenuCellIdentifier)
cell?.textLabel?.text = menuOptions?[indexPath.row].text
return cell!
}
}
extension SideMenuViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedIndexPath = indexPath
guard let location = menuOptions?[indexPath.row].location,
let identifier = menuOptions?[indexPath.row].identifier
else {
return
}
let viewController = UIStoryboard.init(name: location, bundle: nil).instantiateViewController(withIdentifier: identifier)
navigationController?.pushViewController(viewController, animated: true)
}
}
| 9a7eae6e11d94d55de2ed257bc92c126 | 33.144928 | 129 | 0.704584 | false | false | false | false |
AgaKhanFoundation/WCF-iOS | refs/heads/develop | Floral/Pods/RxSwift/RxSwift/Observables/Map.swift | apache-2.0 | 14 | //
// Map.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) throws -> Result)
-> Observable<Result> {
return self.asObservable().composeMap(transform)
}
}
final private class MapSink<SourceType, Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Transform = (SourceType) throws -> ResultType
typealias ResultType = Observer.Element
typealias Element = SourceType
private let _transform: Transform
init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) {
self._transform = transform
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let element):
do {
let mappedElement = try self._transform(element)
self.forwardOn(.next(mappedElement))
}
catch let e {
self.forwardOn(.error(e))
self.dispose()
}
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
self.forwardOn(.completed)
self.dispose()
}
}
}
#if TRACE_RESOURCES
fileprivate let _numberOfMapOperators = AtomicInt(0)
extension Resources {
public static var numberOfMapOperators: Int32 {
return load(_numberOfMapOperators)
}
}
#endif
internal func _map<Element, Result>(source: Observable<Element>, transform: @escaping (Element) throws -> Result) -> Observable<Result> {
return Map(source: source, transform: transform)
}
final private class Map<SourceType, ResultType>: Producer<ResultType> {
typealias Transform = (SourceType) throws -> ResultType
private let _source: Observable<SourceType>
private let _transform: Transform
init(source: Observable<SourceType>, transform: @escaping Transform) {
self._source = source
self._transform = transform
#if TRACE_RESOURCES
_ = increment(_numberOfMapOperators)
#endif
}
override func composeMap<Result>(_ selector: @escaping (ResultType) throws -> Result) -> Observable<Result> {
let originalSelector = self._transform
return Map<SourceType, Result>(source: self._source, transform: { (s: SourceType) throws -> Result in
let r: ResultType = try originalSelector(s)
return try selector(r)
})
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType {
let sink = MapSink(transform: self._transform, observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
#if TRACE_RESOURCES
deinit {
_ = decrement(_numberOfMapOperators)
}
#endif
}
| 92e5d34c4700a8f61379a55617573255 | 31.472222 | 174 | 0.651554 | false | false | false | false |
vkochar/tweety | refs/heads/master | Tweety/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Tweety
//
// Created by Varun on 9/26/17.
// Copyright © 2017 Varun. All rights reserved.
//
import UIKit
let logoutNotification = Notification.Name("logout")
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if User.currentUser != nil {
print("There is a current user")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tweetsNavigationController = storyboard.instantiateViewController(withIdentifier: "tweetsNavigationController")
window?.rootViewController = tweetsNavigationController
window?.makeKeyAndVisible()
} else {
print("There is NO current user")
}
NotificationCenter.default.addObserver(forName: logoutNotification, object: nil, queue: OperationQueue.main) { (notification) in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard.instantiateInitialViewController()
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url)
TwitterApi.sharedInstance.handleOpenUrl(url: url)
return true
}
}
| 59f81e5a8883202b0170a5efd9a3cb88 | 46.657143 | 285 | 0.717326 | false | false | false | false |
coppercash/Anna | refs/heads/master | Anna/Analyzer/BaseAnalyzer.swift | mit | 1 | //
// BaseAnalyzer.swift
// Anna_iOS
//
// Created by William on 2018/5/10.
//
import Foundation
struct
Identity : Equatable
{
let
manager :Manager,
nodeID :NodeID
static func
== (
lhs :Identity,
rhs :Identity
) -> Bool {
return lhs.manager === rhs.manager &&
lhs.nodeID == rhs.nodeID
}
}
struct
IdentityContext : Equatable
{
let
manager :Manager,
nodeID :NodeID,
parentID :NodeID?,
name :String,
index :Int?
static func
== (
lhs :IdentityContext,
rhs :IdentityContext
) -> Bool {
return lhs.manager === rhs.manager &&
lhs.nodeID == rhs.nodeID &&
lhs.parentID == rhs.parentID &&
lhs.name == rhs.name &&
lhs.index == rhs.index
}
}
protocol
IdentityResolving : class
{
typealias
Callback = (Identity) -> Void
func
resolveIdentity(
then callback : @escaping Callback
) -> Void
var
identity :Identity? { get }
typealias
ObservationToken = Int
typealias
ObservationCallback = (BaseAnalyzer) -> Void
func
addIdentityObserver(
callback : @escaping ObservationCallback
) -> ObservationToken
func
removeIdentityObserver(
by token :ObservationToken
)
}
public class
BaseAnalyzer :
NSObject,
IdentityResolving
{
var
namespace :String? = nil
deinit {
self.unbindNode()
}
// MARK: - Node Identity
func
resolveIdentity(
then callback: @escaping IdentityResolving.Callback
) {
fatalError("Overidding needed.")
}
func
bindNode(
with context :IdentityContext
) {
guard self.identity == nil
else { return }
self.identity = Identity(
manager: context.manager,
nodeID: context.nodeID
)
let
namespace = self.namespace
context.manager.registerNode(
by: context.nodeID,
under: context.parentID,
name: context.name,
index: context.index,
namespace: namespace,
attributes: nil
)
}
func
unbindNode() {
guard let
identity = self.identity
else { return }
let
manager = identity.manager,
nodeID = identity.nodeID
if nodeID.isOwned(by: self) {
manager.deregisterNodes(by: nodeID)
}
self.identity = nil
}
var
identity :Identity? = nil {
didSet {
for
callback in self.identityObservationByToken.values
{
callback(self)
}
}
}
typealias
ObservationToken = Int
typealias
ObservationCallback = (BaseAnalyzer) -> Void
var
nextIdentityObservationToken :ObservationToken = 0,
identityObservationByToken :[ObservationToken : ObservationCallback] = [:]
func
addIdentityObserver(
callback : @escaping ObservationCallback
) -> ObservationToken {
let
token = self.nextIdentityObservationToken
self.identityObservationByToken[token] = callback
self.nextIdentityObservationToken += 1
return token
}
func
removeIdentityObserver(
by token :ObservationToken
) {
self.identityObservationByToken[token] = nil
}
// MARK: - Event Recording
struct
Event
{
typealias
Properties = NSObject.Propertiez
let
name :String,
properties :Properties?
}
func
recordEventOnPath(
named name :String,
with attributes :Manager.Attributes? = nil
) {
let
identityResolver = self
identityResolver.resolveIdentity {
let
manager = $0.manager,
nodeID = $0.nodeID
manager.recordEvent(
named: name,
with: attributes,
onNodeBy: nodeID
)
}
}
}
extension
BaseAnalyzer : Recording
{
public func
recordEvent(
named name: String,
with attributes: Recording.Attributes?
) {
self.recordEventOnPath(
named: name,
with: attributes
)
}
}
| 01dcdd7a30aa4e07c2a484a4907c7bd9 | 20.736585 | 78 | 0.539946 | false | false | false | false |
kickstarter/ios-ksapi | refs/heads/master | KsApi/models/UpdateDraft.swift | apache-2.0 | 1 | import Argo
import Curry
import Runes
public struct UpdateDraft {
public let update: Update
public let images: [Image]
public let video: Video?
public enum Attachment {
case image(Image)
case video(Video)
}
public struct Image {
public let id: Int
public let thumb: String
public let full: String
}
public struct Video {
public let id: Int
public let status: Status
public let frame: String
public enum Status: String {
case processing
case failed
case successful
}
}
}
extension UpdateDraft: Equatable {}
public func == (lhs: UpdateDraft, rhs: UpdateDraft) -> Bool {
return lhs.update.id == rhs.update.id
}
extension UpdateDraft.Attachment {
public var id: Int {
switch self {
case let .image(image):
return image.id
case let .video(video):
return video.id
}
}
public var thumbUrl: String {
switch self {
case let .image(image):
return image.full
case let .video(video):
return video.frame
}
}
}
extension UpdateDraft.Attachment: Equatable {}
public func == (lhs: UpdateDraft.Attachment, rhs: UpdateDraft.Attachment) -> Bool {
return lhs.id == rhs.id
}
extension UpdateDraft: Decodable {
public static func decode(_ json: JSON) -> Decoded<UpdateDraft> {
return curry(UpdateDraft.init)
<^> Update.decode(json)
<*> json <|| "images"
<*> json <|? "video"
}
}
extension UpdateDraft.Image: Decodable {
public static func decode(_ json: JSON) -> Decoded<UpdateDraft.Image> {
return curry(UpdateDraft.Image.init)
<^> json <| "id"
<*> json <| "thumb"
<*> json <| "full"
}
}
extension UpdateDraft.Video: Decodable {
public static func decode(_ json: JSON) -> Decoded<UpdateDraft.Video> {
return curry(UpdateDraft.Video.init)
<^> json <| "id"
<*> json <| "status"
<*> json <| "frame"
}
}
extension UpdateDraft.Video.Status: Decodable {
}
| 8b1643c6fd3f9d09c45d0c9682d0f8ff | 20.347826 | 83 | 0.639002 | false | false | false | false |
gustavosaume/DotUserDefaults | refs/heads/master | Example/DotUserDefaults/ViewController.swift | mit | 1 | //
// ViewController.swift
// DotUserDefaults
//
// Created by Gustavo Saume on 05/07/2016.
// Copyright (c) 2016 Gustavo Saume. All rights reserved.
//
import UIKit
import DotUserDefaults
enum MyDefaults: String {
case WelcomeText = "welcomeText"
}
enum WelcomeText: String {
case Hai = "👋"
case Cheers = "🍻"
case Cool = "👌"
var next: WelcomeText {
switch self {
case .Hai: return .Cheers
case .Cheers: return .Cool
case .Cool: return .Hai
}
}
}
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel! {
didSet {
let message:WelcomeText = NSUserDefaults.standardUserDefaults().enumForKey(MyDefaults.WelcomeText) ?? WelcomeText.Hai
label.text = message.rawValue
// update defaults
NSUserDefaults.standardUserDefaults().setEnum(message.next, forKey: MyDefaults.WelcomeText)
}
}
}
| 35331e92ecb8e61c56092437d5c6f237 | 20.071429 | 123 | 0.679096 | false | false | false | false |
suzp1984/IOS-ApiDemo | refs/heads/master | ApiDemo-Swift/ApiDemo-Swift/ConstraintSwapViewController.swift | apache-2.0 | 1 | //
// ConstraintSwapViewController.swift
// ApiDemo-Swift
//
// Created by Jacob su on 5/9/16.
// Copyright © 2016 iboxpay. All rights reserved.
//
import UIKit
class ConstraintSwapViewController: UIViewController {
var v1 : UIView!
var v2 : UIView!
var v3 : UIView!
var constraintsWith = [NSLayoutConstraint]()
var constraintsWithout = [NSLayoutConstraint]()
override func viewDidLoad() {
super.viewDidLoad()
// add swap button
let button = UIButton(type: UIButtonType.system) as UIButton
// button.frame = CGRectMake(100, 100, 50, 50)
button.backgroundColor = UIColor.green
button.setTitle("Swap", for: UIControlState())
button.addTarget(self, action: #selector(ConstraintSwapViewController.swapContraint), for: UIControlEvents.touchUpInside)
self.view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let d = ["b" : button]
NSLayoutConstraint.activate([
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[b]", options: [], metrics: nil, views: d),
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(80)-[b]", options: [], metrics: nil, views: d)
].joined().map{$0})
// add custom UIView
let v1 = UIView()
v1.backgroundColor = UIColor.red
v1.translatesAutoresizingMaskIntoConstraints = false
let v2 = UIView()
v2.backgroundColor = UIColor.yellow
v2.translatesAutoresizingMaskIntoConstraints = false
let v3 = UIView()
v3.backgroundColor = UIColor.blue
v3.translatesAutoresizingMaskIntoConstraints = false
self.view.backgroundColor = UIColor.white
self.view.addSubview(v1)
self.view.addSubview(v2)
self.view.addSubview(v3)
self.v1 = v1
self.v2 = v2
self.v3 = v3
let c1 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[v(100)]", options: [], metrics: nil, views: ["v" : v1])
let c2 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[v(100)]", options: [], metrics: nil, views: ["v" : v2])
let c3 = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[v(100)]", options: [], metrics: nil, views: ["v" : v3])
let c4 = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(200)-[v(20)]", options: [], metrics: nil, views: ["v" : v1])
let c5with = NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-(20)-[v2(20)]-(20)-[v3(20)]", options: [], metrics: nil, views: ["v1":v1, "v2":v2, "v3":v3])
let c5without = NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-(20)-[v3(20)]", options: [], metrics: nil, views: ["v1":v1, "v3":v3])
self.constraintsWith.append(contentsOf: c1)
self.constraintsWith.append(contentsOf: c2)
self.constraintsWith.append(contentsOf: c3)
self.constraintsWith.append(contentsOf: c4)
self.constraintsWith.append(contentsOf: c5with)
self.constraintsWithout.append(contentsOf: c1)
self.constraintsWithout.append(contentsOf: c3)
self.constraintsWithout.append(contentsOf: c4)
self.constraintsWithout.append(contentsOf: c5without)
NSLayoutConstraint.activate(self.constraintsWith)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func swapContraint() {
print("Swap Contraint")
let mainView = self.view
if self.v2.superview != nil {
self.v2.removeFromSuperview()
NSLayoutConstraint.deactivate(self.constraintsWith)
NSLayoutConstraint.activate(self.constraintsWithout)
} else {
mainView?.addSubview(v2)
NSLayoutConstraint.deactivate(self.constraintsWithout)
NSLayoutConstraint.activate(self.constraintsWith)
}
}
/*
// 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.
}
*/
}
| c3780b63b51f1dfd92c1755b2da47905 | 40.046296 | 170 | 0.641778 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | refs/heads/master | watchOS2/PrimeNumbers/PrimeNumbers WatchKit Extension/InterfaceController.swift | mit | 1 | //
// InterfaceController.swift
// PrimeNumbers WatchKit Extension
//
// Created by Luis Castillo on 1/6/16.
// Copyright © 2016 Luis Castillo. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
@IBOutlet var numberSlider: WKInterfaceSlider!
@IBOutlet var primeQLabel: WKInterfaceLabel!
@IBOutlet var Updatebutton: WKInterfaceButton!
@IBOutlet var resultLabel: WKInterfaceLabel!
var number:Int = 50
override func awakeWithContext(context: AnyObject?)
{
super.awakeWithContext(context)
numberSlider.setValue( Float(number) )
primeQLabel.setText("is \(number) prime?")
resultLabel.setText("")
}//eom
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}//eom
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}//eom
@IBAction func sliderValueChanged(value: Float)
{
number = Int(value)
//setting up new question
primeQLabel.setText("is \(number) Prime?")
//clearing results since its a new Question
resultLabel.setText("")
}//eo-a
@IBAction func findOut()
{
//checking if prime
var isPrime:Bool = true
if number == 1 || number == 0
{
isPrime = false
}
if number != 2 && number != 1
{
for (var iter = 2; iter < number ;iter++)
{
if number % iter == 0
{
isPrime = false
}
}//eofl
}
//print("is prime? \(isPrime)")//testing
//update result
if isPrime
{
resultLabel.setText("\(number) is Prime")
}
else
{
resultLabel.setText("\(number) is NOT Prime")
}
}//eo-a
}
| eecb1f6525fcb433bef5c00e6dad0ba9 | 20.578431 | 90 | 0.529305 | false | false | false | false |
allevato/SwiftCGI | refs/heads/master | Sources/SwiftCGI/FCGIRecordInputStream.swift | apache-2.0 | 1 | // Copyright 2015 Tony Allevato
//
// 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.
/// An input stream that reads its data from FastCGI records (of type `Stdin` or `Data`) read from
/// its underlying stream.
class FCGIRecordInputStream: InputStream {
/// Denotes whether the records read from the underlying stream are expected to have bodies of
/// type `Stdin` or `Data`.
enum BodyType {
/// Expect `FCGIRecordBody.Stdin` for the records read from the underlying stream.
case Stdin
/// Expect `FCGIRecordBody.Data` for the records read from the underlying stream.
case Data
}
/// The underlying stream from which the FastCGI records will be read.
private let inputStream: InputStream
/// The expected body type of records read from the underlying stream.
private let bodyType: BodyType
/// The buffer that holds data read from the most recent record.
private var inputBuffer: [UInt8]
/// The index into the buffer at which the next data will be read.
private var inputBufferOffset: Int
/// Indicates whether the final empty record denoting the end of the stream has been read.
private var endOfStreamReached = false
/// Creates an input stream that reads FastCGI records from another input stream with the given
/// expected body type.
///
/// - Parameter inputStream: The input stream from which the FastCGI records will be read.
/// - Parameter bodyType: The expected body type of records read from the underlying stream.
init(inputStream: InputStream, bodyType: BodyType) {
self.inputStream = inputStream
self.bodyType = bodyType
inputBuffer = []
inputBufferOffset = 0
}
func read(inout buffer: [UInt8], offset: Int, count: Int) throws -> Int {
if count == 0 {
return 0
}
if endOfStreamReached {
throw IOError.EOF
}
// Repeatedly read from the stream until we've gotten the requested number of bytes or reached
// the end of the stream.
var readSoFar = 0
while readSoFar < count {
let remaining = count - readSoFar
do {
let readThisTime = try readFromUnderlyingStream(
&buffer, offset: offset + readSoFar, count: remaining)
readSoFar += readThisTime
if readThisTime == 0 {
return readSoFar
}
} catch IOError.EOF {
// Only allow EOF to be thrown if it's the first time we're trying to read. If we get an EOF
// from the underlying stream after successfully reading some data, we just return the count
// that was actually read.
if readSoFar > 0 {
return readSoFar
}
throw IOError.EOF
}
}
return readSoFar
}
/// Seeking is not supported on FCGI input streams.
func seek(offset: Int, origin: SeekOrigin) throws -> Int {
throw IOError.Unsupported
}
func close() {
inputStream.close()
}
/// Reads data at most once from the underlying stream.
///
/// - Parameter buffer: The array into which the data should be written.
/// - Parameter offset: The byte offset in `buffer` into which to start writing data.
/// - Parameter count: The maximum number of bytes to read from the stream.
/// - Returns: The number of bytes that were actually read. This can be less than the requested
/// number of bytes if that many bytes are not available, or 0 if the end of the stream is
/// reached.
/// - Throws: `IOError` if an error other than reaching the end of the stream occurs.
private func readFromUnderlyingStream(
inout buffer: [UInt8], offset: Int, count: Int) throws -> Int {
var available = inputBuffer.count - inputBufferOffset
if available == 0 {
// Fill the buffer by reading from the underlying stream.
inputBuffer = try readNextRecord()
inputBufferOffset = 0
available = inputBuffer.count
}
let countToCopy = (available < count) ? available : count
buffer.replaceRange(offset..<offset + countToCopy,
with: inputBuffer[inputBufferOffset..<inputBufferOffset + countToCopy])
inputBufferOffset += countToCopy
return countToCopy
}
/// Reads the next record from the stream, verifies that it is the expected type, and returns its
/// byte array.
///
/// - Returns: The byte array from the body of the next record.
/// - Throws: `FCGIError.UnexpectedRecordType` if an unexpected record (for example, `.Data` when
/// expecting `.Stdin`) is encountered.
private func readNextRecord() throws -> [UInt8] {
let record = try FCGIRecord(inputStream: inputStream)
let buffer: [UInt8]
switch (record.body, bodyType) {
case (.Stdin(let bytes), .Stdin):
buffer = bytes
case (.Data(let bytes), .Data):
buffer = bytes
default:
throw FCGIError.UnexpectedRecordType
}
// The end of the stream is denoted by a final record with no content.
endOfStreamReached = (buffer.count == 0)
if endOfStreamReached {
throw IOError.EOF
}
return buffer
}
}
| 91ccb1624d1ce6464d626427c76a95f6 | 34.358974 | 100 | 0.68673 | false | false | false | false |
kysonyangs/ysbilibili | refs/heads/master | ysbilibili/Classes/Home/Recommend/Controller/YSRecommendViewController.swift | mit | 1 | //
// YSHomeRecommendViewController.swift
// ysbilibili
//
// Created by MOLBASE on 2017/8/7.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
let kCellReuseKey = "kCellReuseKey"
let kCommenAreaCell = "kCommenAreaCell"
let kLiveCellReuseKey = "kLiveCellReuseKey"
let kBanmikuCellReuseKey = "kBanmikuCellReuseKey"
let kActivityCellReuseKey = "kActivityCellReuseKey"
let kHeaderReuseKey = "kHeaderReuseKey"
let kFooterReuseKey = "kFooterReuseKey"
class YSRecommendViewController: YSRabbitFreshBaseViewController {
// MARK: - 私有属性
fileprivate lazy var recommendVM: YSRecommendViewModel = YSRecommendViewModel()
// MARK: - 懒加载控件
fileprivate lazy var maincollectionView: UICollectionView = {[unowned self] in
let flowLayout = UICollectionViewFlowLayout()
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = kPadding
let mainCollectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: flowLayout)
mainCollectionView.delegate = self
mainCollectionView.dataSource = self
mainCollectionView.showsVerticalScrollIndicator = false
// 注册cell foot head
mainCollectionView.register(YSNormalBaseCell.self, forCellWithReuseIdentifier: kCellReuseKey)
mainCollectionView.register(YSRecommendActivityCell.self, forCellWithReuseIdentifier: kActivityCellReuseKey)
mainCollectionView.register(YSCommenAreaCell.self, forCellWithReuseIdentifier: kCommenAreaCell)
mainCollectionView.register(YSLiveShowCell.self, forCellWithReuseIdentifier: kLiveCellReuseKey)
mainCollectionView.register(YSBanmikuShowCell.self, forCellWithReuseIdentifier: kBanmikuCellReuseKey)
mainCollectionView.register(YSRecommendHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderReuseKey)
mainCollectionView.register(YSRecommendFooterView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: kFooterReuseKey)
return mainCollectionView
}()
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
// 加载数据
loadData()
// 设置代理
recommendVM.delegate = self
// 监听
NotificationCenter.default.addObserver(self, selector: #selector(clickCarousel(notification:)), name: kCarouselViewSelectedRecommendNotification, object: nil)
}
// MARK: - 重写父类的方法
// 1. 初始化滑动view
override func setUpScrollView() -> UIScrollView {
return maincollectionView
}
// 2. 刷新状态调用的方法
override func startRefresh() {
loadData()
}
}
//======================================================================
// MARK:- 私有方法
//======================================================================
extension YSRecommendViewController {
fileprivate func loadData() {
recommendVM.requestDatas(finishCallBack: { [weak self] in
guard (self?.recommendVM.statusArray) != nil else {
// 没数据的情况
self?.endRefresh(loadSuccess: false)
return
}
// 有数据的情况
DispatchQueue.main.async {
self?.maincollectionView.reloadData()
self?.endRefresh(loadSuccess: true)
}
// 失败的情况
}, failueCallBack: { [weak self] in
self?.endRefresh(loadSuccess: false)
})
}
}
//======================================================================
// MARK:- collectionView 的数据源
//======================================================================
extension YSRecommendViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return recommendVM.statusArray.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return recommendVM.calculateRowCount(section: section)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return recommendVM.creatCell(collectionView: collectionView, indexPath: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return recommendVM.createFootOrHead(kind: kind, collectionView: collectionView, indexPath: indexPath)
}
}
//======================================================================
// MARK:- collectionView 的代理方法
//======================================================================
extension YSRecommendViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// banner 跳转的时候需要考虑可能是直播 bilibili://live/11
let sectionModel = recommendVM.statusArray[indexPath.section]
if sectionModel.sectionType == HomeStatustype.live {
/// 实在拿不到播放的url
// let liveVC = ZHNbilibiliLivePlayerViewController()
}else if sectionModel.sectionType == HomeStatustype.bangumi {
// let bangumiVC = ZHNbangumiDetailViewController()
// let rowModel = sectionModel.body[indexPath.row]
// let detaimModel = YSHomeBangumiDetailModel()
// detaimModel.season_id = rowModel.param
// bangumiVC.bangumiDetailModel = detaimModel
// _ = navigationController?.pushViewController(bangumiVC, animated: true)
}else {
// let rowModel = sectionModel.body[indexPath.row]
// let playerVC = ZHNnormalPlayerViewController()
// playerVC.itemModel = rowModel
// self.navigationController?.pushViewController(playerVC, animated: true)
}
}
}
//======================================================================
// MARK:- collectionView layout 的代理方法
//======================================================================
extension YSRecommendViewController: UICollectionViewDelegateFlowLayout {
// 1. 每个section的inset (item.size.with < collectionview.frame.size.width - (2 * padding) 如果items的width不满足上面这个的话会报警告)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return recommendVM.calculateSectionInset(section: section)
}
// 2.每个item的大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return recommendVM.calculateItemSize(section: indexPath.section)
}
// 2.header的size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return recommendVM.calulateSectionHeadSize(section: section)
}
// 3.footer的size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
return recommendVM.calulateSectionfootSize(section: section)
}
}
//======================================================================
// MARK:- recommendViewModel 的代理方法
//======================================================================
extension YSRecommendViewController: YSRecommendViewModelDelegate {
func recommendViewModelReloadSetion(section: Int) {
DispatchQueue.main.async {
self.maincollectionView.reloadSections(IndexSet(integer: section))
}
}
}
//======================================================================
// MARK:- 轮播的点击
//======================================================================
extension YSRecommendViewController {
@objc func clickCarousel(notification: Notification) {
let url = notification.userInfo?[kCarouselSelectedUrlKey] as! String
let webVC = YSBilibiliWebViewController()
webVC.urlString = url
_ = navigationController?.pushViewController(webVC, animated: true)
}
}
| 3831c08a6aaf4f45c271233fe9ed61da | 41.474747 | 170 | 0.634483 | false | false | false | false |
CPRTeam/CCIP-iOS | refs/heads/master | Pods/CryptoSwift/Sources/CryptoSwift/UInt32+Extension.swift | gpl-3.0 | 1 | //
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif
protocol _UInt32Type {}
extension UInt32: _UInt32Type {}
/** array of bytes */
extension UInt32 {
@_specialize(where T == ArraySlice<UInt8>)
init<T: Collection>(bytes: T) where T.Element == UInt8, T.Index == Int {
self = UInt32(bytes: bytes, fromIndex: bytes.startIndex)
}
@_specialize(where T == ArraySlice<UInt8>)
init<T: Collection>(bytes: T, fromIndex index: T.Index) where T.Element == UInt8, T.Index == Int {
if bytes.isEmpty {
self = 0
return
}
let count = bytes.count
let val0 = count > 0 ? UInt32(bytes[index.advanced(by: 0)]) << 24 : 0
let val1 = count > 1 ? UInt32(bytes[index.advanced(by: 1)]) << 16 : 0
let val2 = count > 2 ? UInt32(bytes[index.advanced(by: 2)]) << 8 : 0
let val3 = count > 3 ? UInt32(bytes[index.advanced(by: 3)]) : 0
self = val0 | val1 | val2 | val3
}
}
| 5fc1fd1cd85e88096b7e39508152ea6b | 37.1875 | 217 | 0.695581 | false | false | false | false |
dduan/swift | refs/heads/master | stdlib/public/core/Bool.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Bool Datatype and Supporting Operators
//===----------------------------------------------------------------------===//
/// A value type whose instances are either `true` or `false`.
public struct Bool {
internal var _value: Builtin.Int1
/// Default-initialize Boolean value to `false`.
@_transparent
public init() {
let zero: Int8 = 0
self._value = Builtin.trunc_Int8_Int1(zero._value)
}
@_transparent
internal init(_ v: Builtin.Int1) { self._value = v }
}
extension Bool : _BuiltinBooleanLiteralConvertible, BooleanLiteralConvertible {
@_transparent
public init(_builtinBooleanLiteral value: Builtin.Int1) {
self._value = value
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self = value
}
}
extension Bool : Boolean {
@_transparent
@warn_unused_result
public func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}
/// Identical to `self`.
@_transparent public var boolValue: Bool { return self }
/// Construct an instance representing the same logical value as
/// `value`.
public init<T : Boolean>(_ value: T) {
self = value.boolValue
}
}
extension Bool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self ? "true" : "false"
}
}
// This is a magic entry point known to the compiler.
@_transparent
public // COMPILER_INTRINSIC
func _getBool(v: Builtin.Int1) -> Bool { return Bool(v) }
@_transparent
extension Bool : Equatable, Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: the hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
return self ? 1 : 0
}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
// Unary logical complement.
@_transparent
@warn_unused_result
public prefix func !(a: Bool) -> Bool {
return Bool(Builtin.xor_Int1(a._value, true._value))
}
@_transparent
@warn_unused_result
public func ==(lhs: Bool, rhs: Bool) -> Bool {
return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value))
}
| 7802940d0978b981dcf90d09f6bef051 | 27.683168 | 80 | 0.588885 | false | false | false | false |
dobleuber/my-swift-exercises | refs/heads/master | Challenge6/Challenge6/ViewController.swift | mit | 1 | //
// ViewController.swift
// Challenge6
//
// Created by Wbert Castro on 16/07/17.
// Copyright © 2017 Wbert Castro. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var countries = [Country]()
override func viewDidLoad() {
super.viewDidLoad()
let countriesUrl = "https://restcountries.eu/rest/v2/all"
if let url = URL(string: countriesUrl) {
if let data = try? Data(contentsOf: url) {
let json = JSON(data: data)
for countryData in json.array! {
countries.append(Country(countryData: countryData))
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return countries.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailTableViewController {
vc.country = countries[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Country", for: indexPath) as! CountryCell
let country = countries[indexPath.item]
cell.countryName.text = country.name
let imageFlag = UIImage(named: "\(country.code.lowercased()).png") ??
UIImage(named: "image-not-available.png")
cell.imageFlag.image = imageFlag
return cell
}
}
| e3c3c75fb51a5ccaf4591b36f5b27a96 | 30.704918 | 115 | 0.612203 | false | false | false | false |
ThumbWorks/i-meditated | refs/heads/master | Carthage/Checkouts/RxSwift/RxSwift/Schedulers/MainScheduler.swift | mit | 6 | //
// MainScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling.
This scheduler is usually used to perform UI work.
Main scheduler is a specialization of `SerialDispatchQueueScheduler`.
This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn`
operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose.
*/
public final class MainScheduler : SerialDispatchQueueScheduler {
private let _mainQueue: DispatchQueue
var numberEnqueued: AtomicInt = 0
private init() {
_mainQueue = DispatchQueue.main
super.init(serialQueue: _mainQueue)
}
/**
Singleton instance of `MainScheduler`
*/
public static let instance = MainScheduler()
/**
Singleton instance of `MainScheduler` that always schedules work asynchronously
and doesn't perform optimizations for calls scheduled from main thread.
*/
public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main)
/**
In case this method is called on a background thread it will throw an exception.
*/
public class func ensureExecutingOnScheduler(errorMessage: String? = nil) {
if !Thread.current.isMainThread {
rxFatalError(errorMessage ?? "Executing on backgound thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.")
}
}
override func scheduleInternal<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let currentNumberEnqueued = AtomicIncrement(&numberEnqueued)
if Thread.current.isMainThread && currentNumberEnqueued == 1 {
let disposable = action(state)
_ = AtomicDecrement(&numberEnqueued)
return disposable
}
let cancel = SingleAssignmentDisposable()
_mainQueue.async {
if !cancel.isDisposed {
_ = action(state)
}
_ = AtomicDecrement(&self.numberEnqueued)
}
return cancel
}
}
| e75df41712e94f64353d42aa844d67f0 | 31.643836 | 169 | 0.694503 | false | false | false | false |
JGiola/swift | refs/heads/main | test/type/types.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift
var a : Int
func test() {
var y : a // expected-error {{cannot find type 'a' in scope}}
var z : y // expected-error {{cannot find type 'y' in scope}}
var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}}
}
var b : (Int) -> Int = { $0 }
var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}}
var d2 : () -> Int = { 4 }
var d3 : () -> Float = { 4 }
var d4 : () -> Int = { d2 } // expected-error{{function 'd2' was used as a property; add () to call it}} {{26-26=()}}
if #available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) {
var e0 : [Int]
e0[] // expected-error {{missing argument for parameter #1 in call}} {{6-6=<#Int#>}}
}
var f0 : [Float]
var f1 : [(Int,Int)]
var g : Swift // expected-error {{cannot find type 'Swift' in scope}} expected-note {{cannot use module 'Swift' as a type}}
var h0 : Int?
_ = h0 == nil // no-warning
var h1 : Int??
_ = h1! == nil // no-warning
var h2 : [Int?]
var h3 : [Int]?
var h3a : [[Int?]]
var h3b : [Int?]?
var h4 : ([Int])?
var h5 : ([([[Int??]])?])?
var h7 : (Int,Int)?
var h8 : ((Int) -> Int)?
var h9 : (Int?) -> Int?
var h10 : Int?.Type?.Type
var i = Int?(42)
func testInvalidUseOfParameterAttr() {
var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}}
func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}}
var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}}
func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}}
var bad_iow : (Int) -> (__owned Int, Int) // expected-error {{'__owned' may only be used on parameters}}
func bad_iow2(_ a: (__owned Int, Int)) {} // expected-error {{'__owned' may only be used on parameters}}
}
// <rdar://problem/15588967> Array type sugar default construction syntax doesn't work
func test_array_construct<T>(_: T) {
_ = [T]() // 'T' is a local name
_ = [Int]() // 'Int is a global name'
_ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name.
_ = [UnsafeMutablePointer<Int?>]() // Nesting.
_ = [([UnsafeMutablePointer<Int>])]()
_ = [(String, Float)]()
}
extension Optional {
init() {
self = .none
}
}
// <rdar://problem/15295763> default constructing an optional fails to typecheck
func test_optional_construct<T>(_: T) {
_ = T?() // Local name.
_ = Int?() // Global name
_ = (Int?)() // Parenthesized name.
}
// Test disambiguation of generic parameter lists in expression context.
struct Gen<T> {}
var y0 : Gen<Int?>
var y1 : Gen<Int??>
var y2 : Gen<[Int?]>
var y3 : Gen<[Int]?>
var y3a : Gen<[[Int?]]>
var y3b : Gen<[Int?]?>
var y4 : Gen<([Int])?>
var y5 : Gen<([([[Int??]])?])?>
var y7 : Gen<(Int,Int)?>
var y8 : Gen<((Int) -> Int)?>
var y8a : Gen<[([Int]?) -> Int]>
var y9 : Gen<(Int?) -> Int?>
var y10 : Gen<Int?.Type?.Type>
var y11 : Gen<Gen<Int>?>
var y12 : Gen<Gen<Int>?>?
var y13 : Gen<Gen<Int?>?>?
var y14 : Gen<Gen<Int?>>?
var y15 : Gen<Gen<Gen<Int?>>?>
var y16 : Gen<Gen<Gen<Int?>?>>
var y17 : Gen<Gen<Gen<Int?>?>>?
var z0 = Gen<Int?>()
var z1 = Gen<Int??>()
var z2 = Gen<[Int?]>()
var z3 = Gen<[Int]?>()
var z3a = Gen<[[Int?]]>()
var z3b = Gen<[Int?]?>()
var z4 = Gen<([Int])?>()
var z5 = Gen<([([[Int??]])?])?>()
var z7 = Gen<(Int,Int)?>()
var z8 = Gen<((Int) -> Int)?>()
var z8a = Gen<[([Int]?) -> Int]>()
var z9 = Gen<(Int?) -> Int?>()
var z10 = Gen<Int?.Type?.Type>()
var z11 = Gen<Gen<Int>?>()
var z12 = Gen<Gen<Int>?>?()
var z13 = Gen<Gen<Int?>?>?()
var z14 = Gen<Gen<Int?>>?()
var z15 = Gen<Gen<Gen<Int?>>?>()
var z16 = Gen<Gen<Gen<Int?>?>>()
var z17 = Gen<Gen<Gen<Int?>?>>?()
y0 = z0
y1 = z1
y2 = z2
y3 = z3
y3a = z3a
y3b = z3b
y4 = z4
y5 = z5
y7 = z7
y8 = z8
y8a = z8a
y9 = z9
y10 = z10
y11 = z11
y12 = z12
y13 = z13
y14 = z14
y15 = z15
y16 = z16
y17 = z17
// Type repr formation.
// <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr)
let tupleTypeWithNames = (age:Int, count:Int)(4, 5)
let dictWithTuple = [String: (age:Int, count:Int)]()
// <rdar://problem/21684837> typeexpr not being formed for postfix !
let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' is not allowed here; treating this as '?' instead}}{{15-16=?}}
// <rdar://problem/21560309> inout allowed on function return type
func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}}
r21560309 { x in x }
// <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties
class r21949448 {
var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}}
}
// SE-0066 - Standardize function type argument syntax to require parentheses
let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}}
let _ : inout Int -> Float // expected-error {{'inout' may only be used on parameters}}
// expected-error@-1 {{single argument function types require parentheses}} {{15-15=(}} {{18-18=)}}
func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}}
func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{35-35=(}} {{38-38=)}}
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}}
class C {
func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}}
func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}}
func foo3() {
let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}}
let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}}
}
}
let _ : inout @convention(c) (Int) -> Int // expected-error {{'inout' may only be used on parameters}}
func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }}
// expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}}
func sr5505(arg: Int) -> String {
return "hello"
}
var _: sr5505 = sr5505 // expected-error {{cannot find type 'sr5505' in scope}}
typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}}
// expected-error@-1 {{only a single element can be variadic}} {{35-39=}}
// expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
// rdar://94888357 - failed to produce a diagnostic when type is used incorrectly
func rdar94888357() {
struct S<T> { // expected-note {{generic type 'S' declared here}}
init(_ str: String) {}
}
let _ = S<String, String>("") // expected-error {{generic type 'S' specialized with too many type parameters (got 2, but expected 1)}}
}
| 82a62553efc5aa6a59752973e375ecb9 | 37.317073 | 175 | 0.620115 | false | false | false | false |
morgz/SwiftGoal | refs/heads/master | Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift | mit | 2 | //
// GitHubSearchRepositoriesViewController.swift
// RxExample
//
// Created by Yoshinori Sano on 9/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate {
static let startLoadingOffset: CGFloat = 20.0
static func isNearTheBottomEdge(contentOffset: CGPoint, _ tableView: UITableView) -> Bool {
return contentOffset.y + tableView.frame.size.height + startLoadingOffset > tableView.contentSize.height
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>()
override func viewDidLoad() {
super.viewDidLoad()
let tableView = self.tableView
let searchBar = self.searchBar
dataSource.cellFactory = { (tv, ip, repository: Repository) in
let cell = tv.dequeueReusableCellWithIdentifier("Cell")!
cell.textLabel?.text = repository.name
cell.detailTextLabel?.text = repository.url
return cell
}
dataSource.titleForHeaderInSection = { [unowned dataSource] sectionIndex in
let section = dataSource.sectionAtIndex(sectionIndex)
return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found"
}
let loadNextPageTrigger = tableView.rx_contentOffset
.flatMap { offset in
GitHubSearchRepositoriesViewController.isNearTheBottomEdge(offset, tableView)
? Observable.just()
: Observable.empty()
}
let searchResult = searchBar.rx_text.asDriver()
.throttle(0.3)
.distinctUntilChanged()
.flatMapLatest { query -> Driver<RepositoriesState> in
if query.isEmpty {
return Driver.just(RepositoriesState.empty)
} else {
return GitHubSearchRepositoriesAPI.sharedAPI.search(query, loadNextPageTrigger: loadNextPageTrigger)
.asDriver(onErrorJustReturn: RepositoriesState.empty)
}
}
searchResult
.map { $0.serviceState }
.drive(navigationController!.rx_serviceState)
.addDisposableTo(disposeBag)
searchResult
.map { [SectionModel(model: "Repositories", items: $0.repositories)] }
.drive(tableView.rx_itemsWithDataSource(dataSource))
.addDisposableTo(disposeBag)
searchResult
.filter { $0.limitExceeded }
.driveNext { n in
showAlert("Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting")
}
.addDisposableTo(disposeBag)
// dismiss keyboard on scroll
tableView.rx_contentOffset
.subscribe { _ in
if searchBar.isFirstResponder() {
_ = searchBar.resignFirstResponder()
}
}
.addDisposableTo(disposeBag)
// so normal delegate customization can also be used
tableView.rx_setDelegate(self)
.addDisposableTo(disposeBag)
// activity indicator in status bar
// {
GitHubSearchRepositoriesAPI.sharedAPI.activityIndicator
.drive(UIApplication.sharedApplication().rx_networkActivityIndicatorVisible)
.addDisposableTo(disposeBag)
// }
}
// MARK: Table view delegate
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
deinit {
// I know, I know, this isn't a good place of truth, but it's no
self.navigationController?.navigationBar.backgroundColor = nil
}
}
| 5956cdcb02ee975c797bb3c5b525005e | 34.59292 | 177 | 0.631527 | false | false | false | false |
dillonhafer/pipe-board | refs/heads/master | pipe-board/ConfigureViewController.swift | apache-2.0 | 1 | //
// ConfigureViewController.swift
// pipe-board
//
// Created by Dillon Hafer on 2/19/16.
// Copyright © 2016 Dillon Hafer. All rights reserved.
//
import Cocoa
import Server
class ConfigureViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource {
@IBOutlet weak var serverTable: NSTableView!
@IBOutlet weak var removeButton: NSButton!
@IBOutlet weak var errorBox: NSTextField!
var servers: [Server] = []
@IBAction func Add(sender: AnyObject) {
let newServer = Server(title:"", address: "")
let idx = self.servers.count
self.servers.append(newServer)
self.serverTable.insertRowsAtIndexes(NSIndexSet(index: idx), withAnimation: NSTableViewAnimationOptions.SlideDown)
}
@IBAction func Save(sender: AnyObject) {
let text = sender as? NSTextField
let row = self.serverTable.rowForView(text!)
let columnName = text!.identifier! as String
let newValue = text!.stringValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if row >= 0 {
let server = self.servers[row]
switch columnName {
case "title":
server.title = newValue
case "address":
server.address = newValue
default:
return
}
if server.valid() {
Server.saveServers(servers)
errorBox.hidden = true
} else {
errorBox.hidden = false
}
}
}
@IBAction func Delete(sender: AnyObject) {
if let server = selectedServerRow() {
self.serverTable.removeRowsAtIndexes(NSIndexSet(index:self.serverTable.selectedRow),
withAnimation: NSTableViewAnimationOptions.SlideUp)
let idx = findServerIndex(server)
servers.removeAtIndex(idx)
Server.saveServers(servers)
}
}
override func viewDidLoad() {
super.viewDidLoad()
removeButton.enabled = false
fetchServers()
}
func findServerIndex(server: Server) -> Int {
var idx = 0
for s in servers {
if s == server {
return idx
}
idx++
}
return -1
}
func fetchServers() {
servers = Server.allServers()
let max = servers.count == 0 ? 0 : servers.count - 1
let range = NSMakeRange(0, max)
self.serverTable.insertRowsAtIndexes(NSIndexSet(indexesInRange: range), withAnimation: NSTableViewAnimationOptions.EffectGap)
}
func selectedServerRow() -> Server? {
let selectedRow = self.serverTable.selectedRow;
if selectedRow >= 0 && selectedRow < self.servers.count {
return self.servers[selectedRow]
}
return nil
}
func tableViewSelectionDidChange(notification: NSNotification) {
let enableButton = selectedServerRow() != nil
removeButton.enabled = enableButton
errorBox.hidden = true
}
func numberOfRowsInTableView(aTableView: NSTableView) -> Int {
return self.servers.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cellView: NSTableCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
if row < self.servers.count {
let server = self.servers[row]
switch tableColumn!.identifier {
case "title":
cellView.textField!.stringValue = server.title!
return cellView
case "address":
cellView.textField!.stringValue = server.address!
return cellView
default:
return nil
}
} else {
return nil
}
}
} | 0988b4beb795dbe9374e67f80ed034f9 | 26.865079 | 129 | 0.671795 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/SILGen/existential_metatypes.swift | apache-2.0 | 10 | // RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s | FileCheck %s
protocol P {
init()
static func staticMethod() -> Self
}
struct S: P {
init() {}
static func staticMethod() -> S { return S() }
}
// CHECK-LABEL: sil hidden @_TF21existential_metatypes19existentialMetatypeFPS_1P_T_
// CHECK: bb0([[X:%.*]] : $*P):
func existentialMetatype(x: P) {
// CHECK: [[TYPE1:%.*]] = existential_metatype $@thick P.Type, [[X]]
let type1 = x.dynamicType
// CHECK: [[INSTANCE1:%.*]] = alloc_stack $P
// CHECK: [[OPEN_TYPE1:%.*]] = open_existential_metatype [[TYPE1]]
// CHECK: [[INSTANCE1_VALUE:%.*]] = init_existential_addr [[INSTANCE1]]#1 : $*P
// CHECK: [[INIT:%.*]] = witness_method {{.*}} #P.init!allocator
// CHECK: apply [[INIT]]<{{.*}}>([[INSTANCE1_VALUE]], [[OPEN_TYPE1]])
let instance1 = type1.init()
// CHECK: [[S:%.*]] = metatype $@thick S.Type
// CHECK: [[TYPE2:%.*]] = init_existential_metatype [[S]] : $@thick S.Type, $@thick P.Type
let type2: P.Type = S.self
// CHECK: [[INSTANCE2:%.*]] = alloc_stack $P
// CHECK: [[OPEN_TYPE2:%.*]] = open_existential_metatype [[TYPE2]]
// CHECK: [[INSTANCE2_VALUE:%.*]] = init_existential_addr [[INSTANCE2]]#1 : $*P
// CHECK: [[STATIC_METHOD:%.*]] = witness_method {{.*}} #P.staticMethod
// CHECK: apply [[STATIC_METHOD]]<{{.*}}>([[INSTANCE2_VALUE]], [[OPEN_TYPE2]])
let instance2 = type2.staticMethod()
}
protocol PP: P {}
protocol Q {}
// CHECK-LABEL: sil hidden @_TF21existential_metatypes26existentialMetatypeUpcast1FPMPS_2PP_PMPS_1P_
// CHECK: [[OPENED:%.*]] = open_existential_metatype %0
// CHECK: [[NEW:%.*]] = init_existential_metatype [[OPENED]]
// CHECK: return [[NEW]]
func existentialMetatypeUpcast1(x: PP.Type) -> P.Type {
return x
}
// CHECK-LABEL: sil hidden @_TF21existential_metatypes26existentialMetatypeUpcast2FPMPS_1PS_1Q_PMPS0__
// CHECK: [[OPENED:%.*]] = open_existential_metatype %0
// CHECK: [[NEW:%.*]] = init_existential_metatype [[OPENED]]
// CHECK: return [[NEW]]
func existentialMetatypeUpcast2(x: protocol<P,Q>.Type) -> P.Type {
return x
}
| cc222515b9363d28753fe04e4abc16c4 | 38.981132 | 102 | 0.617272 | false | false | false | false |
Laptopmini/SwiftyArtik | refs/heads/master | Source/DeviceStatus.swift | mit | 1 | //
// DeviceStatus.swift
// SwiftyArtik
//
// Created by Paul-Valentin Mini on 6/2/17.
// Copyright © 2017 Paul-Valentin Mini. All rights reserved.
//
import Foundation
import ObjectMapper
import PromiseKit
open class DeviceStatus: Mappable, AccessibleArtikInstance {
public var did: String?
public var lastMessageTs: ArtikTimestamp?
public var lastActionTs: ArtikTimestamp?
public var lastTimeOnline: ArtikTimestamp?
public var availability: DeviceStatusAvailability?
public var snapshot: [String:Any]?
public enum DeviceStatusAvailability: String {
case online = "online"
case offline = "offline"
case unknown = "unknown"
}
public init() {}
required public init?(map: Map) {}
public func mapping(map: Map) {
did <- map["did"]
lastMessageTs <- map["data.lastMessageTs"]
lastActionTs <- map["data.lastActionTs"]
lastTimeOnline <- map["data.lastTimeOnline"]
availability <- map["data.availability"]
snapshot <- map["data.snapshot"]
}
// MARK: - AccessibleArtikInstance
public func updateOnArtik() -> Promise<Void> {
let promise = Promise<Void>.pending()
if let did = did {
if let availability = availability {
DevicesAPI.updateStatus(id: did, to: availability).then { _ -> Void in
promise.fulfill(())
}.catch { error -> Void in
promise.reject(error)
}
} else {
promise.reject(ArtikError.missingValue(reason: .noAvailability))
}
} else {
promise.reject(ArtikError.missingValue(reason: .noID))
}
return promise.promise
}
public func pullFromArtik() -> Promise<Void> {
let promise = Promise<Void>.pending()
if let did = did {
DevicesAPI.getStatus(id: did).then { status -> Void in
self.mapping(map: Map(mappingType: .fromJSON, JSON: status.toJSON(), toObject: true, context: nil, shouldIncludeNilValues: true))
promise.fulfill(())
}.catch { error -> Void in
promise.reject(error)
}
} else {
promise.reject(ArtikError.missingValue(reason: .noID))
}
return promise.promise
}
}
| 8050034b7c9abc966750169276811978 | 30.207792 | 145 | 0.583021 | false | false | false | false |
vi4m/Zewo | refs/heads/master | Modules/Reflection/Sources/Reflection/Properties.swift | mit | 1 | private struct HashedType : Hashable {
let hashValue: Int
init(_ type: Any.Type) {
hashValue = unsafeBitCast(type, to: Int.self)
}
}
private func == (lhs: HashedType, rhs: HashedType) -> Bool {
return lhs.hashValue == rhs.hashValue
}
private var cachedProperties = [HashedType : Array<Property.Description>]()
/// An instance property
public struct Property {
public let key: String
public let value: Any
/// An instance property description
public struct Description {
public let key: String
public let type: Any.Type
let offset: Int
}
}
/// Retrieve properties for `instance`
public func properties(_ instance: Any) throws -> [Property] {
let props = try properties(type(of: instance))
var copy = instance
let storage = storageForInstance(©)
return props.map { nextProperty(description: $0, storage: storage) }
}
private func nextProperty(description: Property.Description, storage: UnsafeRawPointer) -> Property {
return Property(
key: description.key,
value: AnyExistentialContainer(
type: description.type,
pointer: storage.advanced(by: description.offset)
).any
)
}
/// Retrieve property descriptions for `type`
public func properties(_ type: Any.Type) throws -> [Property.Description] {
let hashedType = HashedType(type)
if let properties = cachedProperties[hashedType] {
return properties
} else if let nominalType = Metadata.Struct(type: type) {
return try fetchAndSaveProperties(nominalType: nominalType, hashedType: hashedType)
} else if let nominalType = Metadata.Class(type: type) {
return try fetchAndSaveProperties(nominalType: nominalType, hashedType: hashedType)
} else {
throw ReflectionError.notStruct(type: type)
}
}
private func fetchAndSaveProperties<T : NominalType>(nominalType: T, hashedType: HashedType) throws -> [Property.Description] {
let properties = try propertiesForNominalType(nominalType)
cachedProperties[hashedType] = properties
return properties
}
private func propertiesForNominalType<T : NominalType>(_ type: T) throws -> [Property.Description] {
guard type.nominalTypeDescriptor.numberOfFields != 0 else { return [] }
guard let fieldTypes = type.fieldTypes, let fieldOffsets = type.fieldOffsets else {
throw ReflectionError.unexpected
}
let fieldNames = type.nominalTypeDescriptor.fieldNames
return (0..<type.nominalTypeDescriptor.numberOfFields).map { i in
return Property.Description(key: fieldNames[i], type: fieldTypes[i], offset: fieldOffsets[i])
}
}
| 7468c0b42c5807e425c8989be7c3a4fb | 34.918919 | 127 | 0.702784 | false | false | false | false |
michaello/Aloha | refs/heads/master | AlohaGIF/SwiftyBeaverTokens.swift | mit | 1 | //
// SwiftyBeaverTokens.swift
// AlohaGIF
//
// Created by Michal Pyrka on 30/09/2017.
// Copyright © 2017 Michal Pyrka. All rights reserved.
//
struct SwiftyBeaverTokens {
private enum Constants {
static let appID = "appID"
static let encryptionKey = "encryptionKey"
static let appSecret = "appSecret"
}
let appID: String
let appSecret: String
let encryptionKey: String
init?(dictionary: [String: Any]?) {
guard let dictionary = dictionary else { return nil }
self.appID = dictionary[Constants.appID] as? String ?? ""
self.encryptionKey = dictionary[Constants.encryptionKey] as? String ?? ""
self.appSecret = dictionary[Constants.appSecret] as? String ?? ""
}
}
| 1911d7aacd9a79459f36412efd09fd94 | 27.444444 | 81 | 0.640625 | false | false | false | false |
time-fighters/patachu | refs/heads/master | Time Fighter/AztecEnemy.swift | mit | 1 | //
// AztecEnemy.swift
// Time Fighter
//
// Created by Paulo Henrique Favero Pereira on 7/15/17.
// Copyright © 2017 Fera. All rights reserved.
//
import UIKit
import SpriteKit
class AztecEnemy: SKSpriteNode {
enum texturesAtlasTypes: String {
case EnemyIdleAtlas
case EnemyDieAtlas
}
let atlasNamesArray: [texturesAtlasTypes] = [.EnemyIdleAtlas, .EnemyDieAtlas,]
var AtlasArray = [SKTextureAtlas]()
var idleTextures = [SKTexture]()
var dieTextures = [SKTexture]()
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
func setup()
{
//key:value
var atlasMap = [texturesAtlasTypes:SKTextureAtlas]()
atlasMap[.EnemyIdleAtlas] = SKTextureAtlas(named: "EnemyIdleAtlas")
atlasMap[.EnemyDieAtlas] = SKTextureAtlas(named: "EnemyDieAtlas")
for atlasType in atlasMap.keys
{
let atlas = atlasMap[atlasType]!
switch atlasType {
case .EnemyIdleAtlas:
for i in 1 ... atlas.textureNames.count{
let idleTextureName = "EnemyIdle\(i)"
idleTextures.append(atlas.textureNamed(idleTextureName))
}
case .EnemyDieAtlas:
for j in 1 ... atlas.textureNames.count{
let dieTextureName = "EnemyDeado\(j)"
dieTextures.append(atlas.textureNamed(dieTextureName))
}
}
}
}
func animateIdle(scene: SKScene) {
self.removeAllActions()
self.run(SKAction.repeatForever(SKAction.animate(with: idleTextures, timePerFrame: 0.1)))
}
func animateDie(scene: SKScene) {
self.run(SKAction.animate(with: dieTextures, timePerFrame: 0.2), completion: {
self.removeFromParent()
})
}
}
| 9fecea4b899ab61340e5ab2194dcb74c | 26.209877 | 97 | 0.556261 | false | false | false | false |
AlexeyTyurenkov/NBUStats | refs/heads/develop | NBUStatProject/NBUStat/Modules/PFTSCurrentIndex/PFTSCurrentIndexPresenter.swift | mit | 1 | //
// UXCurrentIndexPresenter.swift
// FinStat Ukraine
//
// Created by Aleksey Tyurenkov on 3/6/18.
// Copyright © 2018 Oleksii Tiurenkov. All rights reserved.
//
import Foundation
import FinstatLib
protocol PFTSCurrentIndexPresenterProtocol: PresenterProtocol
{
func showDataProviderInfo()
}
class PFTSCurrentIndexPresenter: PFTSCurrentIndexPresenterProtocol
{
weak var delegate: PresenterViewDelegate?
var router: PFTSIndexRouter?
var interactor = PFTSIndexInteractor()
var currentModel: PFTSIndexModel?
func updateView() {
}
func viewLoaded() {
interactor.load { (models, error) in
guard error == nil else { self.delegate?.presenter(self, getError: error!); return }
if let model = models.first
{
self.currentModel = model
self.delegate?.presenter(self, updateAsProfessional: false)
}
else
{
self.delegate?.presenter(self, getError: IndexError.general)
}
}
}
var cellTypes: [BaseTableCellProtocol.Type] = []
var dataProviderInfo: DataProviderInfoProtocol {
return self
}
func showDataProviderInfo() {
if let controller = delegate as? PFTSCurrentIndexViewController
{
router?.presentDataProviderInfo(from: controller, dataProviderInfo: dataProviderInfo)
}
}
}
| 0770fcba5e1462f17190ea6a6a232232 | 25.472727 | 97 | 0.633929 | false | false | false | false |
beckasaurus/skin-ios | refs/heads/master | skin/skin/Product.swift | mit | 1 | //
// Product.swift
// skin
//
// Created by Becky on 9/11/17.
// Copyright © 2017 Becky Henderson. All rights reserved.
//
import Foundation
import RealmSwift
final class Product: Object {
dynamic var id: String = UUID().uuidString
dynamic var name = ""
dynamic var brand: String?
let price = RealmOptional<Double>()
dynamic var link: String?
dynamic var expirationDate: Date?
dynamic var category: String = ProductCategory.active.rawValue
dynamic var ingredients: String?
let rating = RealmOptional<Int>()
let numberUsed = RealmOptional<Int>()
let numberInStash = RealmOptional<Int>()
let willRepurchase = RealmOptional<Bool>()
override static func primaryKey() -> String? {
return "id"
}
}
| efa751ee738756f9cf3e5f72fc3c8ae2 | 23.689655 | 63 | 0.726257 | false | false | false | false |
WangYang-iOS/YiDeXuePin_Swift | refs/heads/master | DiYa/DiYa/Class/Tools/Managers/YYGoodsManager.swift | mit | 1 | //
// YYGoodsManager.swift
// DiYa
//
// Created by wangyang on 2017/12/14.
// Copyright © 2017年 wangyang. All rights reserved.
//
import UIKit
var _goodsSelectView : YYGoodsSkuView!
var _shadowView : UIView!
var _complete: ((_ skuValue: String, _ number: Int)->())?
class YYGoodsManager: NSObject {
static let shareManagre = YYGoodsManager()
private override init() {}
}
extension YYGoodsManager {
func showGoodsSelectView(goodsModel : GoodsModel, skuCategoryList:[SkuCategoryModel], goodsSkuList:[GoodsSkuModel], complete:((_ skuValue: String, _ number: Int)->())?) {
_complete = complete
let window = (UIApplication.shared.delegate as! AppDelegate).window
_shadowView = UIView()
_shadowView.frame = RECT(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
_shadowView.backgroundColor = UIColor.hexString(colorString: "000000", alpha: 0.3)
window?.addSubview(_shadowView)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(hiddenSelectView))
_shadowView.addGestureRecognizer(tap)
_goodsSelectView = YYGoodsSkuView.loadXib1() as! YYGoodsSkuView
_goodsSelectView.delegate = self
window?.addSubview(_goodsSelectView)
_goodsSelectView.goodsModel = goodsModel
_goodsSelectView.skuList = skuCategoryList
_goodsSelectView.goodsSkuList = goodsSkuList
_goodsSelectView.changeNumberView.number = 1;
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
UIView.animate(withDuration: 0.25) {
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT - _goodsSelectView.goodsSkuViewHieght, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
}
}
@objc func hiddenSelectView() {
_shadowView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
}) { (finish) in
_goodsSelectView.removeFromSuperview()
}
}
}
extension YYGoodsManager : YYGoodsSkuViewDelegate {
func didSelectedGoodsWith(skuValue: String, number: Int) {
_complete?(skuValue,number)
}
}
| 9152ab9935d449469e16d172f971a455 | 38.949153 | 174 | 0.682647 | false | false | false | false |
marty-suzuki/FluxCapacitor | refs/heads/master | Examples/Flux/FluxCapacitorSample/Sources/Common/Flux/Repository/RepositoryAction.swift | mit | 1 | //
// RepositoryAction.swift
// FluxCapacitorSample
//
// Created by marty-suzuki on 2017/08/02.
// Copyright © 2017年 marty-suzuki. All rights reserved.
//
import Foundation
import FluxCapacitor
import GithubKit
final class RepositoryAction: Actionable {
typealias DispatchStateType = Dispatcher.Repository
private let session: ApiSessionType
init(session: ApiSessionType = ApiSession.shared) {
self.session = session
}
func fetchRepositories(withUserId id: String, after: String?) {
invoke(.isRepositoryFetching(true))
let request = UserNodeRequest(id: id, after: after)
let task = session.send(request) { [weak self] in
switch $0 {
case .success(let value):
self?.invoke(.lastPageInfo(value.pageInfo))
self?.invoke(.addRepositories(value.nodes))
self?.invoke(.repositoryTotalCount(value.totalCount))
case .failure:
break
}
self?.invoke(.isRepositoryFetching(false))
}
invoke(.lastTask(task))
}
}
| 78d0ef2e3ac546340e9b925073674578 | 28.342105 | 69 | 0.626009 | false | false | false | false |
manfengjun/KYMart | refs/heads/master | Section/Mine/View/KYShopAddressTVCell.swift | mit | 1 | //
// KYShopAddressTVCell.swift
// KYMart
//
// Created by Jun on 2017/6/14.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYShopAddressTVCell: UITableViewCell {
@IBOutlet weak var nameL: UILabel!
@IBOutlet weak var addressL: UILabel!
@IBOutlet weak var phoneL: UILabel!
@IBOutlet weak var isDefaultBtn: UIButton!
// 删除回调传值
var SelectResultClosure: ResultClosure? // 闭包
typealias ResultValueClosure = (_ value: AnyObject)->()
var model:KYAddressModel?{
didSet {
if let text = model?.consignee {
nameL.text = text
}
if let text = model?.mobile {
phoneL.text = "电话:\(text)"
}
var addressStr = ""
if let provice = model?.province {
addressStr += getAddressName(id: provice)
if let city = model?.city{
addressStr += getAddressName(id: city)
if let district = model?.district {
addressStr += getAddressName(id: district)
if let twon = model?.twon {
addressStr += getAddressName(id: twon)
if let address = model?.address {
addressStr += "\(address)"
addressL.text = addressStr
}
}
}
}
}
if let isDefault = model?.is_default {
isDefaultBtn.setImage(isDefault == 1 ? UIImage(named:"cart_select_yes.png") : UIImage(named:"cart_select_no.png"), for: .normal)
}
}
}
func getAddressName(id:Int) -> String {
if let array = CitiesDataTool.sharedManager().queryData(with: id) {
if array.count > 0 {
return array[0] as! String + " "
}
}
return " "
}
@IBAction func setDefaultAction(_ sender: UIButton) {
SelectResultClosure?(1)
}
@IBAction func delAction(_ sender: UIButton) {
SelectResultClosure?(2)
}
/**
删除回调
*/
func selectResult(_ finished: @escaping ResultClosure) {
SelectResultClosure = finished
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 045856e59a83e8b3d868d8f792dace1c | 29.928571 | 144 | 0.517706 | false | false | false | false |
arvindhsukumar/ARVIndicatorButton | refs/heads/master | Example/ARVIndicatorButton.swift | mit | 2 | //
// ARVIndicatorButton.swift
// ARVIndicatorButton
//
// Created by Arvindh Sukumar on 14/03/15.
// Copyright (c) 2015 Arvindh Sukumar. All rights reserved.
//
import UIKit
class ARVIndicatorButton: UIButton {
var indicators: [UIBezierPath] = []
var indicatorColor: UIColor = UIColor(white: 0.9, alpha: 1)
override var highlighted: Bool {
didSet {
if highlighted {
self.backgroundColor = UIColor(white: 0.95, alpha: 1)
self.indicatorColor = UIColor(white: 0.7, alpha: 1)
}
else {
self.backgroundColor = UIColor.whiteColor()
self.indicatorColor = UIColor(white: 0.9, alpha: 1)
}
self.setNeedsDisplay()
}
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// Drawing code
//// Color Declarations
let color = self.indicatorColor
let indicatorVerticalMargin: CGFloat = 3
let indicatorHeight: CGFloat = 3
let indicatorCount:CGFloat = 3
var originY: CGFloat = (rect.size.height - ((indicatorCount * indicatorHeight)+((indicatorCount-1) * indicatorVerticalMargin)))/2
let originX = rect.size.width - 10
for i in 0..<Int(indicatorCount) {
let rectanglePath = UIBezierPath(rect: CGRectMake(originX, originY, indicatorHeight, indicatorHeight))
color.setFill()
rectanglePath.fill()
originY += indicatorHeight + indicatorVerticalMargin
self.indicators.append(rectanglePath)
}
}
}
| c8985cb601996f904bc1f258e623f0e9 | 28.032258 | 137 | 0.592222 | false | false | false | false |
ljubinkovicd/Lingo-Chat | refs/heads/master | Lingo Chat/UserNameController.swift | mit | 1 | //
// UserNameController.swift
// Lingo Chat
//
// Created by Dorde Ljubinkovic on 8/30/17.
// Copyright © 2017 Dorde Ljubinkovic. All rights reserved.
//
import UIKit
import SkyFloatingLabelTextField
class UserNameController: UIViewController {
var newUser: TheUser?
lazy var userFirstNameTextField: SkyFloatingLabelTextField = {
let textField = SkyFloatingLabelTextField(frame: CGRect(x: 0, y: 0, width: 132, height: 44))
textField.translatesAutoresizingMaskIntoConstraints = false // use to disable conflicts with auto layout
textField.placeholder = "First Name"
textField.title = "Your First Name"
textField.errorColor = UIColor.red
return textField
}()
lazy var userLastNameTextField: SkyFloatingLabelTextField = {
let textField = SkyFloatingLabelTextField(frame: CGRect(x: 0, y: 0, width: 132, height: 44))
textField.translatesAutoresizingMaskIntoConstraints = false // use to disable conflicts with auto layout
textField.placeholder = "Last Name"
textField.title = "Your Last Name"
textField.errorColor = UIColor.red
return textField
}()
lazy var continueButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("Continue", comment: "Move from the email controller screen to name controller screen."), for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.layer.cornerRadius = 4.0
button.layer.masksToBounds = true
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.cyan.cgColor
button.backgroundColor = UIColor.blue
button.contentEdgeInsets = UIEdgeInsetsMake(15, 0, 15, 0)
button.addTarget(self, action: #selector(continueButtonTapped(sender:)), for: .touchUpInside)
return button
}()
lazy var alreadyHaveAnAccountButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("I already have an account", comment: "The user already has an account and doesn't need to sign up."), for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.layer.cornerRadius = 4.0
button.layer.masksToBounds = true
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.black.cgColor
button.backgroundColor = UIColor.gray
button.contentEdgeInsets = UIEdgeInsetsMake(5, 15, 5, 15)
button.addTarget(self, action: #selector(alreadyHaveAnAccountButtonTapped(sender:)), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: .UIKeyboardWillHide, object: nil)
view.addSubview(userFirstNameTextField)
view.addSubview(userLastNameTextField)
view.addSubview(continueButton)
view.addSubview(alreadyHaveAnAccountButton)
userFirstNameTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
userFirstNameTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
userLastNameTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
userLastNameTextField.topAnchor.constraint(equalTo: userFirstNameTextField.bottomAnchor, constant: 16.0).isActive = true
continueButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
continueButton.topAnchor.constraint(equalTo: userLastNameTextField.bottomAnchor, constant: 16.0).isActive = true
continueButton.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1.0, constant: -32).isActive = true
alreadyHaveAnAccountButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
alreadyHaveAnAccountButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16.0).isActive = true
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Globals.nameToPasswordSegue {
let passwordController = segue.destination as! UserPasswordController
passwordController.newUser = newUser
}
}
}
extension UserNameController: UITextFieldDelegate {
func keyboardWillShow(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
func keyboardWillHide(notification: Notification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardSize.height
}
}
}
}
extension UserNameController: RegistrationFormProtocol {
func continueButtonTapped(sender: UIButton) {
validateForm()
}
// Unwind Segue
func alreadyHaveAnAccountButtonTapped(sender: UIButton) {
newUser = nil
performSegue(withIdentifier: "unwindSegueToLoginController", sender: self)
}
func validateForm() {
let firstName = userFirstNameTextField.text!
let lastName = userLastNameTextField.text!
if (firstName == "" || lastName == "") {
print("Invalid Form!")
return
} else {
// newUser = User()
newUser?.firstName = firstName
newUser?.lastName = lastName
performSegue(withIdentifier: Globals.nameToPasswordSegue, sender: nil)
}
}
}
| 03cd2c7b136f75fb8a88efb32ac0c393 | 38.4125 | 158 | 0.667777 | false | false | false | false |
P0ed/Magikombat | refs/heads/master | Magikombat/GameScenes/Renderer.swift | mit | 1 | import Foundation
import SpriteKit
let tileSize = 32
func createHero() -> SKNode {
let color = SKColor(red: 0.9, green:0.2, blue: 0.3, alpha: 1.0)
let size = CGSize(width: tileSize, height: 2 * tileSize)
return SKSpriteNode(color: color, size: size)
}
final class Renderer {
let world: SKNode
let level: Level
let camera: SKNode
var hero: SKNode
init(level: Level, world: SKNode, camera: SKNode) {
self.level = level
self.world = world
self.camera = camera
hero = createHero()
drawLevel()
drawHero()
}
private func drawHero() {
world.addChild(hero)
}
private func drawLevel() {
level.forEach {
let platform = $0.platform
func tileColor(tile: Tile) -> SKColor {
switch tile {
case .Wall: return SKColor(red: 0.8, green: 0.7, blue: 0.3, alpha: 1.0)
case .Platform: return SKColor(red: 0.4, green: 0.5, blue: 0.5, alpha: 1.0)
}
}
let size = CGSize(width: platform.size.width * tileSize, height: platform.size.height * tileSize)
let node = SKSpriteNode(color: tileColor(platform.type), size: size)
node.position = CGPoint(x: platform.position.x * tileSize, y: platform.position.y * tileSize)
node.anchorPoint = CGPointZero
world.addChild(node)
}
}
func renderState(state: GameState) {
let position = state.hero.position
hero.position = CGPoint(x: Double(position.dx) * Double(tileSize), y: Double(position.dy) * Double(tileSize))
camera.position = hero.position
}
}
extension CGPoint {
init(_ vector: Vector) {
x = CGFloat(vector.dx)
y = CGFloat(vector.dy)
}
}
| a9318731c26aab7e4056abe183a960aa | 22.575758 | 111 | 0.679949 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.