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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
296245482/ILab-iOS | refs/heads/master | Charts-master/Charts/Classes/Utils/ChartFill.swift | apache-2.0 | 13 | //
// ChartFill.swift
// Charts
//
// Created by Daniel Cohen Gindi on 27/01/2016.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
public class ChartFill: NSObject
{
@objc(ChartFillType)
public enum Type: Int
{
case Empty
case Color
case LinearGradient
case RadialGradient
case Image
case TiledImage
case Layer
}
private var _type: Type = Type.Empty
private var _color: CGColorRef?
private var _gradient: CGGradientRef?
private var _gradientAngle: CGFloat = 0.0
private var _gradientStartOffsetPercent: CGPoint = CGPoint()
private var _gradientStartRadiusPercent: CGFloat = 0.0
private var _gradientEndOffsetPercent: CGPoint = CGPoint()
private var _gradientEndRadiusPercent: CGFloat = 0.0
private var _image: CGImageRef?
private var _layer: CGLayerRef?
// MARK: Properties
public var type: Type
{
return _type
}
public var color: CGColorRef?
{
return _color
}
public var gradient: CGGradientRef?
{
return _gradient
}
public var gradientAngle: CGFloat
{
return _gradientAngle
}
public var gradientStartOffsetPercent: CGPoint
{
return _gradientStartOffsetPercent
}
public var gradientStartRadiusPercent: CGFloat
{
return _gradientStartRadiusPercent
}
public var gradientEndOffsetPercent: CGPoint
{
return _gradientEndOffsetPercent
}
public var gradientEndRadiusPercent: CGFloat
{
return _gradientEndRadiusPercent
}
public var image: CGImageRef?
{
return _image
}
public var layer: CGLayerRef?
{
return _layer
}
// MARK: Constructors
public override init()
{
}
public init(CGColor: CGColorRef)
{
_type = .Color
_color = CGColor
}
public convenience init(color: NSUIColor)
{
self.init(CGColor: color.CGColor)
}
public init(linearGradient: CGGradientRef, angle: CGFloat)
{
_type = .LinearGradient
_gradient = linearGradient
_gradientAngle = angle
}
public init(
radialGradient: CGGradientRef,
startOffsetPercent: CGPoint,
startRadiusPercent: CGFloat,
endOffsetPercent: CGPoint,
endRadiusPercent: CGFloat
)
{
_type = .RadialGradient
_gradient = radialGradient
_gradientStartOffsetPercent = startOffsetPercent
_gradientStartRadiusPercent = startRadiusPercent
_gradientEndOffsetPercent = endOffsetPercent
_gradientEndRadiusPercent = endRadiusPercent
}
public convenience init(radialGradient: CGGradientRef)
{
self.init(
radialGradient: radialGradient,
startOffsetPercent: CGPointMake(0.0, 0.0),
startRadiusPercent: 0.0,
endOffsetPercent: CGPointMake(0.0, 0.0),
endRadiusPercent: 1.0
)
}
public init(CGImage: CGImageRef, tiled: Bool)
{
_type = tiled ? .TiledImage : .Image
_image = CGImage
}
public convenience init(image: NSUIImage, tiled: Bool)
{
if image.CGImage == nil
{
self.init()
}
else
{
self.init(CGImage: image.CGImage!, tiled: tiled)
}
}
public convenience init(CGImage: CGImageRef)
{
self.init(CGImage: CGImage, tiled: false)
}
public convenience init(image: NSUIImage)
{
self.init(image: image, tiled: false)
}
public init(CGLayer: CGLayerRef)
{
_type = .Layer
_layer = CGLayer
}
// MARK: Constructors
public class func fillWithCGColor(CGColor: CGColorRef) -> ChartFill
{
return ChartFill(CGColor: CGColor)
}
public class func fillWithColor(color: NSUIColor) -> ChartFill
{
return ChartFill(color: color)
}
public class func fillWithLinearGradient(linearGradient: CGGradientRef, angle: CGFloat) -> ChartFill
{
return ChartFill(linearGradient: linearGradient, angle: angle)
}
public class func fillWithRadialGradient(
radialGradient: CGGradientRef,
startOffsetPercent: CGPoint,
startRadiusPercent: CGFloat,
endOffsetPercent: CGPoint,
endRadiusPercent: CGFloat
) -> ChartFill
{
return ChartFill(
radialGradient: radialGradient,
startOffsetPercent: startOffsetPercent,
startRadiusPercent: startRadiusPercent,
endOffsetPercent: endOffsetPercent,
endRadiusPercent: endRadiusPercent
)
}
public class func fillWithRadialGradient(radialGradient: CGGradientRef) -> ChartFill
{
return ChartFill(radialGradient: radialGradient)
}
public class func fillWithCGImage(CGImage: CGImageRef, tiled: Bool) -> ChartFill
{
return ChartFill(CGImage: CGImage, tiled: tiled)
}
public class func fillWithImage(image: NSUIImage, tiled: Bool) -> ChartFill
{
return ChartFill(image: image, tiled: tiled)
}
public class func fillWithCGImage(CGImage: CGImageRef) -> ChartFill
{
return ChartFill(CGImage: CGImage)
}
public class func fillWithImage(image: NSUIImage) -> ChartFill
{
return ChartFill(image: image)
}
public class func fillWithCGLayer(CGLayer: CGLayerRef) -> ChartFill
{
return ChartFill(CGLayer: CGLayer)
}
// MARK: Drawing code
/// Draws the provided path in filled mode with the provided area
public func fillPath(
context context: CGContext,
rect: CGRect)
{
let fillType = _type
if fillType == .Empty
{
return
}
CGContextSaveGState(context)
switch fillType
{
case .Color:
CGContextSetFillColorWithColor(context, _color)
CGContextFillPath(context)
case .Image:
CGContextClip(context)
CGContextDrawImage(context, rect, _image)
case .TiledImage:
CGContextClip(context)
CGContextDrawTiledImage(context, rect, _image)
case .Layer:
CGContextClip(context)
CGContextDrawLayerInRect(context, rect, _layer)
case .LinearGradient:
let radians = ChartUtils.Math.FDEG2RAD * (360.0 - _gradientAngle)
let centerPoint = CGPointMake(rect.midX, rect.midY)
let xAngleDelta = cos(radians) * rect.width / 2.0
let yAngleDelta = sin(radians) * rect.height / 2.0
let startPoint = CGPointMake(
centerPoint.x - xAngleDelta,
centerPoint.y - yAngleDelta
)
let endPoint = CGPointMake(
centerPoint.x + xAngleDelta,
centerPoint.y + yAngleDelta
)
CGContextClip(context)
CGContextDrawLinearGradient(
context,
_gradient,
startPoint,
endPoint,
[.DrawsAfterEndLocation, .DrawsBeforeStartLocation]
)
case .RadialGradient:
let centerPoint = CGPointMake(rect.midX, rect.midY)
let radius = max(rect.width, rect.height) / 2.0
CGContextClip(context)
CGContextDrawRadialGradient(
context,
_gradient,
CGPointMake(
centerPoint.x + rect.width * _gradientStartOffsetPercent.x,
centerPoint.y + rect.height * _gradientStartOffsetPercent.y
),
radius * _gradientStartRadiusPercent,
CGPointMake(
centerPoint.x + rect.width * _gradientEndOffsetPercent.x,
centerPoint.y + rect.height * _gradientEndOffsetPercent.y
),
radius * _gradientEndRadiusPercent,
[.DrawsAfterEndLocation, .DrawsBeforeStartLocation]
)
case .Empty:
break;
}
CGContextRestoreGState(context)
}
} | 3a4db153b0474eb93d20b76783684f71 | 25.146707 | 104 | 0.576958 | false | false | false | false |
imitationgame/pokemonpassport | refs/heads/master | pokepass/View/Projects/VProjectsDetailHeader.swift | mit | 1 | import UIKit
class VProjectsDetailHeader:UICollectionReusableView
{
weak var label:UILabel!
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.backgroundColor = UIColor.clear
label.font = UIFont.bold(size:15)
label.textColor = UIColor.black
label.textAlignment = NSTextAlignment.center
label.numberOfLines = 0
self.label = label
addSubview(label)
let views:[String:UIView] = [
"label":label]
let metrics:[String:CGFloat] = [:]
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"H:|-10-[label]-10-|",
options:[],
metrics:metrics,
views:views))
addConstraints(NSLayoutConstraint.constraints(
withVisualFormat:"V:[label(20)]-10-|",
options:[],
metrics:metrics,
views:views))
}
required init?(coder:NSCoder)
{
fatalError()
}
}
| 95d9dbfb831c9668d228830f8a53e6f7 | 26.680851 | 63 | 0.583397 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/Blog/Site Settings/DateAndTimeFormatSettingsViewController.swift | gpl-2.0 | 1 | import Foundation
import CocoaLumberjack
import WordPressShared
/// This class will display the Blog's date and time settings, and will allow the user to modify them.
/// Upon selection, WordPress.com backend will get hit, and the new value will be persisted.
///
open class DateAndTimeFormatSettingsViewController: UITableViewController {
// MARK: - Private Properties
fileprivate var blog: Blog!
fileprivate var service: BlogService!
fileprivate lazy var handler: ImmuTableViewHandler = {
return ImmuTableViewHandler(takeOver: self)
}()
// MARK: - Computed Properties
fileprivate var settings: BlogSettings {
return blog.settings!
}
// MARK: - Static Properties
fileprivate static let footerHeight = CGFloat(34.0)
fileprivate static let learnMoreUrl = "https://codex.wordpress.org/Formatting_Date_and_Time"
// MARK: - Typealiases
fileprivate typealias DateFormat = BlogSettings.DateFormat
fileprivate typealias TimeFormat = BlogSettings.TimeFormat
fileprivate typealias DaysOfTheWeek = BlogSettings.DaysOfTheWeek
// MARK: - Initializer
@objc public convenience init(blog: Blog) {
self.init(style: .grouped)
self.blog = blog
self.service = BlogService(managedObjectContext: settings.managedObjectContext!)
}
// MARK: - View Lifecycle
open override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Date and Time Format", comment: "Title for the Date and Time Format Settings Screen")
ImmuTable.registerRows([NavigationItemRow.self], tableView: tableView)
WPStyleGuide.configureColors(view: view, tableView: tableView)
reloadViewModel()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadViewModel()
}
// MARK: - Model
fileprivate func reloadViewModel() {
handler.viewModel = tableViewModel()
}
func tableViewModel() -> ImmuTable {
let dateFormatRow = NavigationItemRow(title: NSLocalizedString("Date Format",
comment: "Blog Writing Settings: Date Format"),
detail: settings.dateFormatDescription,
action: self.pressedDateFormat())
let timeFormatRow = NavigationItemRow(title: NSLocalizedString("Time Format",
comment: "Blog Writing Settings: Time Format"),
detail: settings.timeFormatDescription,
action: self.pressedTimeFormat())
let startOfWeekRow = NavigationItemRow(title: NSLocalizedString("Week starts on",
comment: "Blog Writing Settings: Weeks starts on"),
detail: settings.startOfWeekDescription,
action: self.pressedStartOfWeek())
return ImmuTable(sections: [
ImmuTableSection(
headerText: "",
rows: [dateFormatRow, timeFormatRow, startOfWeekRow],
footerText: nil)
])
}
// MARK: Learn More footer
open override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return DateAndTimeFormatSettingsViewController.footerHeight
}
open override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footer = UITableViewHeaderFooterView(frame: CGRect(x: 0.0,
y: 0.0,
width: tableView.frame.width,
height: DateAndTimeFormatSettingsViewController.footerHeight))
footer.textLabel?.text = NSLocalizedString("Learn more about date and time formatting.",
comment: "Writing, Date and Time Settings: Learn more about date and time settings footer text")
footer.textLabel?.font = UIFont.preferredFont(forTextStyle: .footnote)
footer.textLabel?.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(handleLearnMoreTap(_:)))
footer.addGestureRecognizer(tap)
return footer
}
// MARK: - Row Handlers
func pressedDateFormat() -> ImmuTableAction {
return { [unowned self] row in
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Date Format",
comment: "Writing Date Format Settings Title")
settingsViewController.currentValue = self.settings.dateFormat as NSObject
var allTitles = DateFormat.allTitles
var allValues = DateFormat.allValues
if let _ = DateFormat(rawValue: self.settings.dateFormat) {
allTitles.append(NSLocalizedString("Tap to enter a custom value",
comment: "Message in a row indicating to tap to enter a custom value"))
allValues.append("")
} else {
allTitles.append(self.settings.dateFormat)
allValues.append(self.settings.dateFormat)
}
settingsViewController.titles = allTitles
settingsViewController.values = allValues
settingsViewController.editableIndex = allTitles.count - 1
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
if let newDateFormat = selected as? String {
self?.settings.dateFormat = newDateFormat
self?.saveSettings()
}
}
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
}
func pressedTimeFormat() -> ImmuTableAction {
return { [unowned self] row in
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Time Format",
comment: "Writing Time Format Settings Title")
settingsViewController.currentValue = self.settings.timeFormat as NSObject
var allTitles = TimeFormat.allTitles
var allValues = TimeFormat.allValues
if let _ = TimeFormat(rawValue: self.settings.timeFormat) {
allTitles.append(NSLocalizedString("Tap to enter a custom value",
comment: "Message in a row indicating to tap to enter a custom value"))
allValues.append("")
} else {
allTitles.append(self.settings.timeFormat)
allValues.append(self.settings.timeFormat)
}
settingsViewController.titles = allTitles
settingsViewController.values = allValues
settingsViewController.editableIndex = allTitles.count - 1
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
if let newTimeFormat = selected as? String {
self?.settings.timeFormat = newTimeFormat
self?.saveSettings()
}
}
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
}
func pressedStartOfWeek() -> ImmuTableAction {
return { [unowned self] row in
let settingsViewController = SettingsSelectionViewController(style: .grouped)
settingsViewController.title = NSLocalizedString("Week starts on",
comment: "Blog Writing Settings: Weeks starts on")
settingsViewController.currentValue = self.settings.startOfWeek as NSObject
settingsViewController.titles = DaysOfTheWeek.allTitles
settingsViewController.values = DaysOfTheWeek.allValues
settingsViewController.onItemSelected = { [weak self] (selected: Any?) in
if let newStartOfWeek = selected as? String {
self?.settings.startOfWeek = newStartOfWeek
self?.saveSettings()
}
}
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
}
// MARK: - Footer handler
@objc fileprivate func handleLearnMoreTap(_ sender: UITapGestureRecognizer) {
guard let url = URL(string: DateAndTimeFormatSettingsViewController.learnMoreUrl) else {
return
}
let webViewController = WebViewControllerFactory.controller(url: url)
if presentingViewController != nil {
navigationController?.pushViewController(webViewController, animated: true)
} else {
let navController = UINavigationController(rootViewController: webViewController)
present(navController, animated: true)
}
}
// MARK: - Persistance
fileprivate func saveSettings() {
service.updateSettings(for: blog,
success: { SiteStatsInformation.sharedInstance.updateTimeZone() },
failure: { [weak self] (error: Error) -> Void in
self?.refreshSettings()
DDLogError("Error while persisting settings: \(error)")
})
}
fileprivate func refreshSettings() {
let service = BlogService(managedObjectContext: settings.managedObjectContext!)
service.syncSettings(for: blog,
success: { [weak self] in
self?.reloadViewModel()
DDLogInfo("Reloaded Settings")
},
failure: { (error: Error) in
DDLogError("Error while sync'ing blog settings: \(error)")
})
}
}
| 46a22fbcf6c81a2484b15c529d4703f0 | 43.487288 | 147 | 0.586246 | false | false | false | false |
programersun/HiChongSwift | refs/heads/master | HiChongSwift/PetSubTypeViewController.swift | apache-2.0 | 1 | //
// PetSubTypeViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/24.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class PetSubTypeViewController: UITableViewController {
weak var delegate: PetCateFilterDelegate?
weak var root: UIViewController?
var parentID: String?
private var subTypeInfo: LCYPetSubTypeBase?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
if let uid = parentID{
let parameter = ["f_id": uid]
LCYNetworking.sharedInstance.POST(LCYApi.PetSubType, parameters: parameter, success: { [weak self] (object) -> Void in
var info = LCYPetSubTypeBase.modelObjectWithDictionary(object as [NSObject : AnyObject])
if info.childStyle.count == 3 {
info.childStyle = (info.childStyle as! [LCYPetSubTypeChildStyle]).sorted({
func toSortInt(name: String) -> Int {
if name == "大型犬" {
return 3
} else if name == "中型犬" {
return 2
} else {
return 1
}
}
let first = toSortInt($0.name)
let second = toSortInt($1.name)
return first > second
})
}
self?.subTypeInfo = info
self?.tableView.reloadData()
return
}, failure: { [weak self](error) -> Void in
self?.alert("您的网络状态不给力哟")
return
})
} else {
alert("内部错误,请退回重试")
}
tableView.backgroundColor = UIColor.LCYThemeColor()
navigationItem.title = "分类"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
if subTypeInfo != nil {
return 1
} else {
return 0
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
if let count = subTypeInfo?.childStyle.count {
return count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(PetCateFilterCell.identifier(), forIndexPath: indexPath) as! PetCateFilterCell
if let childInfo = subTypeInfo?.childStyle[indexPath.row] as? LCYPetSubTypeChildStyle {
cell.icyImageView?.setImageWithURL(NSURL(string: childInfo.headImg.toAbsolutePath()), placeholderImage: UIImage(named: "placeholderLogo"))
cell.icyTextLabel?.text = childInfo.name
}
return cell
}
// 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.
if let identifier = segue.identifier {
switch identifier {
case "showLV3":
let destination = segue.destinationViewController as! PetFinalFilterViewController
if let indexPath = tableView.indexPathForSelectedRow()?.row {
let info = subTypeInfo?.childStyle[indexPath] as? LCYPetSubTypeChildStyle
destination.parentID = info?.catId
destination.delegate = delegate
destination.root = root
}
default:
break
}
}
}
}
| 66f3b569281a22f812c9cdf343d04444 | 35.28 | 150 | 0.574201 | false | false | false | false |
johnjohn7188/NetActivity | refs/heads/master | NetActivity/FTDI.swift | mit | 1 | //
// FTDI.swift
// NetActivity
//
// Created by John Aguilar on 2/3/18.
// Copyright © 2018 John. All rights reserved.
//
import Foundation
struct FTDI {
struct Pins: OptionSet, CustomStringConvertible {
let rawValue: UInt8
static let tx = Pins(rawValue: 1 << 0)
static let rx = Pins(rawValue: 1 << 1)
static let rts = Pins(rawValue: 1 << 2)
static let cts = Pins(rawValue: 1 << 3)
static let dtr = Pins(rawValue: 1 << 4)
static let dsr = Pins(rawValue: 1 << 5)
static let dcd = Pins(rawValue: 1 << 6)
static let ri = Pins(rawValue: 1 << 7)
var description: String {
var outputString = ""
if self.contains(.tx) { outputString += "TX " }
if self.contains(.rx) { outputString += "RX " }
if self.contains(.rts) { outputString += "RTS " }
if self.contains(.cts) { outputString += "CTS " }
if self.contains(.dtr) { outputString += "DTR " }
if self.contains(.dsr) { outputString += "DSR " }
if self.contains(.dcd) { outputString += "DCD " }
if self.contains(.ri) { outputString += "RI " }
return outputString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
/// Intialize FTDI to BitBang output mode and set all outputs to low
static func initDevice() -> Bool {
var ftHandle: FT_HANDLE?
// Open Device
if FT_Open(0, &ftHandle) != FT_OK { return false }
// Handle must be valid
guard let handle = ftHandle else { return false }
// Set Output Mode to Bit Bang
let mask: UCHAR = 0xFF
let mode: UCHAR = 0x01
if FT_SetBitMode(handle, mask, mode) != FT_OK { return false }
// Set all outputs to low
var outputByte: UCHAR = 0
let outputByteCount: DWORD = 1
var bytesWritten: DWORD = 0
if FT_Write(handle, &outputByte, outputByteCount, &bytesWritten) != FT_OK { return false }
// Close Device
if FT_Close(handle) != FT_OK { return false }
return true
}
static func setOutput(for pins: Pins, value: Bool) -> Bool {
var ftHandle: FT_HANDLE?
// Open Device
if FT_Open(0, &ftHandle) != FT_OK { return false }
// Handle must be valid
guard let handle = ftHandle else { return false }
var currentPins: UCHAR = 0
var bytesReturned: DWORD = 0
if FT_Read(handle, ¤tPins, 1, &bytesReturned) != FT_OK || bytesReturned != 1 { return false }
if value == true {
// set output
currentPins |= pins.rawValue
} else {
currentPins &= ~pins.rawValue
}
// Write new value
var bytesWritten: DWORD = 0
if FT_Write(handle, ¤tPins, 1, &bytesWritten) != FT_OK { return false }
// Close Device
if FT_Close(handle) != FT_OK { return false }
return true
}
}
| 054d49a43a7b2ed784783928d990448c | 30.643564 | 107 | 0.529412 | false | false | false | false |
mozilla-mobile/focus-ios | refs/heads/main | Blockzilla/Onboarding/OnboardingConstants.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
struct OnboardingConstants {
static let onboardingDidAppear = "OnboardingDidAppear"
static let alwaysShowOnboarding = "AlwaysShowOnboarding"
static let ignoreOnboardingExperiment = "IgnoreOnboardingExperiment"
static let showOldOnboarding = "ShowOldOnboarding"
static let shownTips = "ShownTips"
}
| 051c5cc983aac84c2aebc0c6b079c272 | 40.769231 | 72 | 0.760589 | false | false | false | false |
oscarqpe/machine-learning-algorithms | refs/heads/master | LNN/HashTable.swift | gpl-3.0 | 1 | //
// HastTable.swift
// LSH Test
//
// Created by Andre Valdivia on 18/05/16.
// Copyright © 2016 Andre Valdivia. All rights reserved.
//
import Foundation
class HashTable {
private var hashUnits = Array<HashUnit>()
var keys = Array<Double>()
var key:Double = 0
init(){
for _ in 0..<Param.K{
hashUnits.append(HashUnit())
keys.append(0)
}
}
//Retorna el key de multiplicar
func train(x:Array<Double>) -> Double{
//Get key de todos los hashUnits
for i in 0..<hashUnits.count{
keys[i] = hashUnits[i].getKey(x)
}
//Setear el key = keys * Primos
self.key = 1
for i in 0..<Param.P2.count{
let pos = Param.hpos[i]
self.key += keys[pos] * Double(Param.P2[i])
}
return key
}
//Setear el delta de todos los HashUnits
func setDeltas(delta:Double){
for i in 0..<Param.P2.count{
let pos = Param.hpos[i]
hashUnits[pos].setDelta(delta * Double(Param.P2[i])) // El delta del HT * Primo usado para hallar key
}
}
func actualizarPesos(x:Array<Double>){
for HU in hashUnits{
HU.actualizarPesos(x)
}
}
} | 9a80d35021c3c395c4a0328f2392e138 | 23.692308 | 113 | 0.536243 | false | false | false | false |
tkabit/Aless | refs/heads/master | Aless/Aless/Uncompressor.swift | mit | 1 | //
// Uncompressor.swift
// aless
//
// Created by Sergey Tkachenko on 10/6/15.
// Copyright © 2015 Sergey Tkachenko. All rights reserved.
//
import Foundation
open class Uncompressor {
fileprivate let data : Data
fileprivate let centralDirectory : CentralDirectory
fileprivate var headers : [FileHeader] = [FileHeader]()
fileprivate var offsetFh : Int
/// File names inside the zip
open var files : [String] = [String]()
init?(fromData data : Data) {
self.data = data
self.centralDirectory = CentralDirectory.init(fromData: self.data)!
self.offsetFh = Int(centralDirectory.cdPosition)
for _ in 0...centralDirectory.countOfItems {
if let fh : FileHeader = FileHeader.init(data: data, fhOffset: offsetFh) {
headers.append(fh)
offsetFh = fh.extraDataRange.upperBound + Int(fh.fileComLen) - 1
self.files.append(fh.filename)
}
}
}
/// Test if `file` exists
func containsFile(_ file: String) -> Bool {
return false
}
/// Get data for `file`
func dataForFile(_ file: String) -> Data? {
return nil
}
}
public extension Uncompressor {
/// Create an Uncompressor with an URL, shortcut for `createWithData`
static func createWithURL(_ zipFileURL: URL) -> Uncompressor? {
if let data = try? Data(contentsOf: zipFileURL) {
return createWithData(data)
}
return nil
}
/// Create an Uncompressor with given `NSData`
static func createWithData(_ data: Data) -> Uncompressor? {
return Uncompressor(fromData: data)
}
}
| 2fdc2e0149074eff176c590048a071dd | 26.919355 | 86 | 0.599653 | false | false | false | false |
lipka/JSON | refs/heads/master | Tests/JSONTests/Post.swift | mit | 2 | import Foundation
import JSON
struct Post: Equatable {
enum State: String {
case draft
case published
}
let title: String
let author: User
let state: State
static func == (lhs: Post, rhs: Post) -> Bool {
return lhs.title == rhs.title && lhs.author == rhs.author && lhs.state == rhs.state
}
}
extension Post: JSONDeserializable {
init(json: JSON) throws {
title = try json.decode(key: "title")
author = try json.decode(key: "author")
state = try json.decode(key: "state")
}
}
| c5141f5003e91b37dad5e1e4e9413476 | 19 | 85 | 0.67 | false | false | false | false |
lockersoft/Winter2016-iOS | refs/heads/master | BMICalcLecture/Charts/Classes/Data/Implementations/Standard/LineRadarChartDataSet.swift | unlicense | 1 | //
// LineRadarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class LineRadarChartDataSet: LineScatterCandleRadarChartDataSet, ILineRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// The color that is used for filling the line surface area.
private var _fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
/// The color that is used for filling the line surface area.
public var fillColor: UIColor
{
get { return _fillColor }
set
{
_fillColor = newValue
fill = nil
}
}
/// The object that is used for filling the area below the line.
/// - default: nil
public var fill: ChartFill?
/// The alpha value that is used for filling the line surface,
/// - default: 0.33
public var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
/// line width of the chart (min = 0.2, max = 10)
///
/// **default**: 1
public var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if (newValue < 0.2)
{
_lineWidth = 0.2
}
else if (newValue > 10.0)
{
_lineWidth = 10.0
}
else
{
_lineWidth = newValue
}
}
}
public var drawFilledEnabled = false
public var isDrawFilledEnabled: Bool
{
return drawFilledEnabled
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineRadarChartDataSet
copy.fillColor = fillColor
copy._lineWidth = _lineWidth
copy.drawFilledEnabled = drawFilledEnabled
return copy
}
}
| 0ef31c79f2e3cd283392767b69f8d867 | 23.228261 | 105 | 0.565276 | false | false | false | false |
StachkaConf/ios-app | refs/heads/develop | RectangleDissolve/Classes/TempoCounter.swift | mit | 2 | //
// TempoCounter.swift
// GithubItunesViewer
//
// Created by MIKHAIL RAKHMANOV on 12.02.17.
// Copyright © 2017 m.rakhmanov. All rights reserved.
//
import Foundation
import Foundation
import QuartzCore
enum BeatStep: Int {
case fourth = 4
case eighth = 8
case sixteenth = 16
case thirtyTwo = 32
}
typealias Handler = () -> ()
class TempoCounter {
fileprivate var displayLink: CADisplayLink?
fileprivate let frameRate = 60
fileprivate var internalCounter = 0
var tempo = 60.0
var beatStep = BeatStep.fourth
var handler: Handler?
fileprivate var nextTickLength: Int {
return Int(Double(frameRate) / (tempo / 60.0 * Double(beatStep.rawValue) / 4.0))
}
init() {
displayLink = CADisplayLink(target: self, selector: #selector(fire))
if #available(iOS 10.0, *) {
displayLink?.preferredFramesPerSecond = frameRate
}
displayLink?.add(to: RunLoop.main, forMode: .commonModes)
displayLink?.isPaused = true
}
deinit {
displayLink?.remove(from: RunLoop.main, forMode: .commonModes)
}
func start() {
displayLink?.isPaused = false
}
func stop() {
displayLink?.isPaused = true
}
@objc func fire() {
internalCounter += 1
if internalCounter >= nextTickLength {
internalCounter = 0
handler?()
}
}
}
| 4f3e60adfb23233f3d18d359ead97e78 | 20.861538 | 88 | 0.617875 | false | false | false | false |
cam-hop/APIUtility | refs/heads/master | Carthage/Checkouts/RxSwift/Tests/RxTest.swift | mit | 6 | //
// RxTest.swift
// Tests
//
// Created by Krunoslav Zaher on 2/8/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
import struct Foundation.TimeInterval
import struct Foundation.Date
import class Foundation.RunLoop
#if os(Linux)
import Foundation
#endif
#if TRACE_RESOURCES
#elseif RELEASE
#elseif os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
#elseif os(Linux)
#else
let failure = unhandled_case()
#endif
// because otherwise macOS unit tests won't run
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
#if os(Linux)
// TODO: Implement PerformanceTests.swift for Linux
func getMemoryInfo() -> (bytes: Int64, allocations: Int64) {
return (0, 0)
}
#endif
class RxTest
: XCTestCase {
#if TRACE_RESOURCES
fileprivate var startResourceCount: Int32 = 0
#endif
var accumulateStatistics: Bool {
return true
}
#if TRACE_RESOURCES
static var totalNumberOfAllocations: Int64 = 0
static var totalNumberOfAllocatedBytes: Int64 = 0
var startNumberOfAllocations: Int64 = 0
var startNumberOfAllocatedBytes: Int64 = 0
#endif
override func setUp() {
super.setUp()
setUpActions()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
tearDownActions()
}
}
extension RxTest {
struct Defaults {
static let created = 100
static let subscribed = 200
static let disposed = 1000
}
func sleep(_ time: TimeInterval) {
let _ = RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: time))
}
func setUpActions(){
#if TRACE_RESOURCES
self.startResourceCount = Resources.total
//registerMallocHooks()
(startNumberOfAllocatedBytes, startNumberOfAllocations) = getMemoryInfo()
#endif
}
func tearDownActions() {
#if TRACE_RESOURCES
// give 5 sec to clean up resources
for _ in 0..<30 {
if self.startResourceCount < Resources.total {
// main schedulers need to finish work
print("Waiting for resource cleanup ...")
RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.05) )
}
else {
break
}
}
XCTAssertEqual(self.startResourceCount, Resources.total)
let (endNumberOfAllocatedBytes, endNumberOfAllocations) = getMemoryInfo()
let (newBytes, newAllocations) = (endNumberOfAllocatedBytes - startNumberOfAllocatedBytes, endNumberOfAllocations - startNumberOfAllocations)
if accumulateStatistics {
RxTest.totalNumberOfAllocations += newAllocations
RxTest.totalNumberOfAllocatedBytes += newBytes
}
print("allocatedBytes = \(newBytes), allocations = \(newAllocations) (totalBytes = \(RxTest.totalNumberOfAllocatedBytes), totalAllocations = \(RxTest.totalNumberOfAllocations))")
#endif
}
}
| 9fd8dbfaed313c306705ac60397959b8 | 25.467742 | 190 | 0.641682 | false | true | false | false |
GMSLabs/Hyber-SDK-iOS | refs/heads/swift-3.0 | Hyber/Classes/HyberLogger/HyberLogger.swift | apache-2.0 | 1 | //
// HyberLogger.swift
// Hyber-SDK
//
// Created by Taras on 10/27/16.
// Incuube
//
public let HyberLogger = Hyber.hyberLog
public extension Hyber {
static let hyberLog : Logger = {
let log = Logger()
return log
}()
}
private let benchmarker = Benchmarker()
public enum Level {
case trace, debug, info, warning, error
var description: String {
switch self {
case .trace: return "✅ HyberTrace"
case .debug: return "🐞HyberDEBUG"
case .info: return "❗️HyberInfo"
case .warning: return "⚠️ HyberWarinig"
case .error: return "❌ HyberERROR"
}
}
}
extension Level: Comparable {}
public func ==(x: Level, y: Level) -> Bool {
return x.hashValue == y.hashValue
}
public func <(x: Level, y: Level) -> Bool {
return x.hashValue < y.hashValue
}
open class Logger {
public var enabled: Bool = true
public var formatter: Formatter {
didSet { formatter.logger = self }
}
public var theme: Theme?
public var minLevel: Level
public var format: String {
return formatter.description
}
public var colors: String {
return theme?.description ?? ""
}
private let queue = DispatchQueue(label: "Hyber.log")
public init(formatter: Formatter = .default, theme: Theme? = nil, minLevel: Level = .trace) {
self.formatter = formatter
self.theme = theme
self.minLevel = minLevel
formatter.logger = self
}
open func trace(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.trace, items, separator, terminator, file, line, column, function)
}
open func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.debug, items, separator, terminator, file, line, column, function)
}
open func info(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.info, items, separator, terminator, file, line, column, function)
}
open func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.warning, items, separator, terminator, file, line, column, function)
}
open func error(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.error, items, separator, terminator, file, line, column, function)
}
private func log(_ level: Level, _ items: [Any], _ separator: String, _ terminator: String, _ file: String, _ line: Int, _ column: Int, _ function: String) {
guard enabled && level >= minLevel else { return }
let date = Date()
let result = formatter.format(
level: level,
items: items,
separator: separator,
terminator: terminator,
file: file,
line: line,
column: column,
function: function,
date: date
)
queue.async {
Swift.print(result, separator: "", terminator: "")
}
}
public func measure(_ description: String? = nil, iterations n: Int = 10, file: String = #file, line: Int = #line, column: Int = #column, function: String = #function, block: () -> Void) {
guard enabled && .debug >= minLevel else { return }
let measure = benchmarker.measure(description, iterations: n, block: block)
let date = Date()
let result = formatter.format(
description: measure.description,
average: measure.average,
relativeStandardDeviation: measure.relativeStandardDeviation,
file: file,
line: line,
column: column,
function: function,
date: date
)
queue.async {
Swift.print(result)
}
}
}
| 6ceb08168ff8cc472d8e8057d9c4832e | 29.689655 | 192 | 0.568539 | false | false | false | false |
Hikaruapp/Swift-PlayXcode | refs/heads/master | Swift-TegakiNumberGame/Swift-TegakiNumberGame/MPSCNN/SlimMPSCNN.swift | mit | 1 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
This file describes slimmer routines to create some common MPSCNNFunctions, it is useful especially to fetch network parameters from .dat files
*/
import Foundation
import MetalPerformanceShaders
/**
This depends on MetalPerformanceShaders.framework
The SlimMPSCNNConvolution is a wrapper class around MPSCNNConvolution used to encapsulate:
- making an MPSCNNConvolutionDescriptor,
- adding network parameters (weights and bias binaries by memory mapping the binaries)
- getting our convolution layer
*/
class SlimMPSCNNConvolution: MPSCNNConvolution{
/**
A property to keep info from init time whether we will pad input image or not for use during encode call
*/
private var padding = true
/**
Initializes a fully connected kernel.
- Parameters:
- kernelWidth: Kernel Width
- kernelHeight: Kernel Height
- inputFeatureChannels: Number feature channels in input of this layer
- outputFeatureChannels: Number feature channels from output of this layer
- neuronFilter: A neuronFilter to add at the end as activation, default is nil
- device: The MTLDevice on which this SlimMPSCNNConvolution filter will be used
- kernelParamsBinaryName: name of the layer to fetch kernelParameters by adding a prefix "weights_" or "bias_"
- padding: Bool value whether to use padding or not
- strideXY: Stride of the filter
- destinationFeatureChannelOffset: FeatureChannel no. in the destination MPSImage to start writing from, helps with concat operations
- groupNum: if grouping is used, default value is 1 meaning no groups
- Returns:
A valid SlimMPSCNNConvolution object or nil, if failure.
*/
init(kernelWidth: UInt, kernelHeight: UInt, inputFeatureChannels: UInt, outputFeatureChannels: UInt, neuronFilter: MPSCNNNeuron? = nil, device: MTLDevice, kernelParamsBinaryName: String, padding willPad: Bool = true, strideXY: (UInt, UInt) = (1, 1), destinationFeatureChannelOffset: UInt = 0, groupNum: UInt = 1){
// calculate the size of weights and bias required to be memory mapped into memory
let sizeBias = outputFeatureChannels * UInt(MemoryLayout<Float>.size)
let sizeWeights = inputFeatureChannels * kernelHeight * kernelWidth * outputFeatureChannels * UInt(MemoryLayout<Float>.size)
// get the url to this layer's weights and bias
let wtPath = Bundle.main.path(forResource: "weights_" + kernelParamsBinaryName, ofType: "dat")
let bsPath = Bundle.main.path(forResource: "bias_" + kernelParamsBinaryName, ofType: "dat")
// open file descriptors in read-only mode to parameter files
let fd_w = open( wtPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
let fd_b = open( bsPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(fd_w != -1, "Error: failed to open output file at \""+wtPath!+"\" errno = \(errno)\n")
assert(fd_b != -1, "Error: failed to open output file at \""+bsPath!+"\" errno = \(errno)\n")
// memory map the parameters
let hdrW = mmap(nil, Int(sizeWeights), PROT_READ, MAP_FILE | MAP_SHARED, fd_w, 0)
let hdrB = mmap(nil, Int(sizeBias), PROT_READ, MAP_FILE | MAP_SHARED, fd_b, 0)
// cast Void pointers to Float
let w = UnsafePointer(hdrW!.bindMemory(to: Float.self, capacity: Int(sizeWeights)))
let b = UnsafePointer(hdrB!.bindMemory(to: Float.self, capacity: Int(sizeBias)))
assert(w != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
assert(b != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
// create appropriate convolution descriptor with appropriate stride
let convDesc = MPSCNNConvolutionDescriptor(kernelWidth: Int(kernelWidth),
kernelHeight: Int(kernelHeight),
inputFeatureChannels: Int(inputFeatureChannels),
outputFeatureChannels: Int(outputFeatureChannels),
neuronFilter: neuronFilter)
convDesc.strideInPixelsX = Int(strideXY.0)
convDesc.strideInPixelsY = Int(strideXY.1)
assert(groupNum > 0, "Group size can't be less than 1")
convDesc.groups = Int(groupNum)
// initialize the convolution layer by calling the parent's (MPSCNNConvlution's) initializer
super.init(device: device,
convolutionDescriptor: convDesc,
kernelWeights: w,
biasTerms: b,
flags: MPSCNNConvolutionFlags.none)
self.destinationFeatureChannelOffset = Int(destinationFeatureChannelOffset)
// set padding for calculation of offset during encode call
padding = willPad
// unmap files at initialization of MPSCNNConvolution, the weights are copied and packed internally we no longer require these
assert(munmap(hdrW, Int(sizeWeights)) == 0, "munmap failed with errno = \(errno)")
assert(munmap(hdrB, Int(sizeBias)) == 0, "munmap failed with errno = \(errno)")
// close file descriptors
close(fd_w)
close(fd_b)
}
/**
Encode a MPSCNNKernel into a command Buffer. The operation shall proceed out-of-place.
We calculate the appropriate offset as per how TensorFlow calculates its padding using input image size and stride here.
This [Link](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/nn.py) has an explanation in header comments how tensorFlow pads its convolution input images.
- Parameters:
- commandBuffer: A valid MTLCommandBuffer to receive the encoded filter
- sourceImage: A valid MPSImage object containing the source image.
- destinationImage: A valid MPSImage to be overwritten by result image. destinationImage may not alias sourceImage
*/
override func encode(commandBuffer: MTLCommandBuffer, sourceImage: MPSImage, destinationImage: MPSImage) {
// select offset according to padding being used or not
if padding {
let pad_along_height = ((destinationImage.height - 1) * strideInPixelsY + kernelHeight - sourceImage.height)
let pad_along_width = ((destinationImage.width - 1) * strideInPixelsX + kernelWidth - sourceImage.width)
let pad_top = Int(pad_along_height / 2)
let pad_left = Int(pad_along_width / 2)
self.offset = MPSOffset(x: ((Int(kernelWidth)/2) - pad_left), y: (Int(kernelHeight/2) - pad_top), z: 0)
}
else{
self.offset = MPSOffset(x: Int(kernelWidth)/2, y: Int(kernelHeight)/2, z: 0)
}
super.encode(commandBuffer: commandBuffer, sourceImage: sourceImage, destinationImage: destinationImage)
}
}
/**
This depends on MetalPerformanceShaders.framework
The SlimMPSCNNFullyConnected is a wrapper class around MPSCNNFullyConnected used to encapsulate:
- making an MPSCNNConvolutionDescriptor,
- adding network parameters (weights and bias binaries by memory mapping the binaries)
- getting our fullyConnected layer
*/
class SlimMPSCNNFullyConnected: MPSCNNFullyConnected{
/**
Initializes a fully connected kernel.
- Parameters:
- kernelWidth: Kernel Width
- kernelHeight: Kernel Height
- inputFeatureChannels: Number feature channels in input of this layer
- outputFeatureChannels: Number feature channels from output of this layer
- neuronFilter: A neuronFilter to add at the end as activation, default is nil
- device: The MTLDevice on which this SlimMPSCNNConvolution filter will be used
- kernelParamsBinaryName: name of the layer to fetch kernelParameters by adding a prefix "weights_" or "bias_"
- destinationFeatureChannelOffset: FeatureChannel no. in the destination MPSImage to start writing from, helps with concat operations
- Returns:
A valid SlimMPSCNNFullyConnected object or nil, if failure.
*/
init(kernelWidth: UInt, kernelHeight: UInt, inputFeatureChannels: UInt, outputFeatureChannels: UInt, neuronFilter: MPSCNNNeuron? = nil, device: MTLDevice, kernelParamsBinaryName: String, destinationFeatureChannelOffset: UInt = 0){
// calculate the size of weights and bias required to be memory mapped into memory
let sizeBias = outputFeatureChannels * UInt(MemoryLayout<Float>.size)
let sizeWeights = inputFeatureChannels * kernelHeight * kernelWidth * outputFeatureChannels * UInt(MemoryLayout<Float>.size)
// get the url to this layer's weights and bias
let wtPath = Bundle.main.path(forResource: "weights_" + kernelParamsBinaryName, ofType: "dat")
let bsPath = Bundle.main.path(forResource: "bias_" + kernelParamsBinaryName, ofType: "dat")
// open file descriptors in read-only mode to parameter files
let fd_w = open(wtPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
let fd_b = open(bsPath!, O_RDONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
assert(fd_w != -1, "Error: failed to open output file at \""+wtPath!+"\" errno = \(errno)\n")
assert(fd_b != -1, "Error: failed to open output file at \""+bsPath!+"\" errno = \(errno)\n")
// memory map the parameters
let hdrW = mmap(nil, Int(sizeWeights), PROT_READ, MAP_FILE | MAP_SHARED, fd_w, 0)
let hdrB = mmap(nil, Int(sizeBias), PROT_READ, MAP_FILE | MAP_SHARED, fd_b, 0)
// cast Void pointers to Float
let w = UnsafePointer(hdrW!.bindMemory(to: Float.self, capacity: Int(sizeWeights)))
let b = UnsafePointer(hdrB!.bindMemory(to: Float.self, capacity: Int(sizeBias)))
assert(w != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
assert(b != UnsafePointer<Float>(bitPattern: -1), "mmap failed with errno = \(errno)")
// create appropriate convolution descriptor (in fully connected, stride is always 1)
let convDesc = MPSCNNConvolutionDescriptor(kernelWidth: Int(kernelWidth),
kernelHeight: Int(kernelHeight),
inputFeatureChannels: Int(inputFeatureChannels),
outputFeatureChannels: Int(outputFeatureChannels),
neuronFilter: neuronFilter)
// initialize the convolution layer by calling the parent's (MPSCNNFullyConnected's) initializer
super.init(device: device,
convolutionDescriptor: convDesc,
kernelWeights: w,
biasTerms: b,
flags: MPSCNNConvolutionFlags.none)
self.destinationFeatureChannelOffset = Int(destinationFeatureChannelOffset)
// unmap files at initialization of MPSCNNFullyConnected, the weights are copied and packed internally we no longer require these
assert(munmap(hdrW, Int(sizeWeights)) == 0, "munmap failed with errno = \(errno)")
assert(munmap(hdrB, Int(sizeBias)) == 0, "munmap failed with errno = \(errno)")
// close file descriptors
close(fd_w)
close(fd_b)
}
}
| 022decfb66a7cbcd2f1f9f82c8e35f7e | 54.930233 | 317 | 0.64341 | false | false | false | false |
esttorhe/RxSwift | refs/heads/feature/swift2.0 | RxSwift/RxSwift/Observables/Implementations/ObserveSingleOn.swift | mit | 1 | //
// ObserveSingleOn.swift
// Rx
//
// Created by Krunoslav Zaher on 3/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
let ObserveSingleOnMoreThenOneElement = "Observed sequence was expected to have more then one element, and `observeSingleOn` operator works on sequences with at most one element."
// This class is used to forward sequence of AT MOST ONE observed element to
// another schedule.
//
// In case sequence contains more then one element, it will fire an exception.
class ObserveSingleOnObserver<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.Element
typealias Parent = ObserveSingleOn<Element>
let parent: Parent
var lastElement: Event<Element>? = nil
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
var elementToForward: Event<Element>?
var stopEventToForward: Event<Element>?
_ = self.parent.scheduler
switch event {
case .Next:
if self.lastElement != nil {
rxFatalError(ObserveSingleOnMoreThenOneElement)
}
self.lastElement = event
case .Error:
if self.lastElement != nil {
rxFatalError(ObserveSingleOnMoreThenOneElement)
}
stopEventToForward = event
case .Completed:
elementToForward = self.lastElement
stopEventToForward = event
}
if let stopEventToForward = stopEventToForward {
self.parent.scheduler.schedule(()) { (_) in
if let elementToForward = elementToForward {
trySend(self.observer, elementToForward)
}
trySend(self.observer, stopEventToForward)
self.dispose()
return NopDisposableResult
}
}
}
func run() -> Disposable {
return self.parent.source.subscribeSafe(self)
}
}
class ObserveSingleOn<Element> : Producer<Element> {
let scheduler: ImmediateScheduler
let source: Observable<Element>
init(source: Observable<Element>, scheduler: ImmediateScheduler) {
self.source = source
self.scheduler = scheduler
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = ObserveSingleOnObserver(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | 8cc7d4a5476dba0d37b0da75465b2fa2 | 30.306818 | 179 | 0.6122 | false | false | false | false |
why19910522/ExtXcode8 | refs/heads/master | ExtXcode8/ExtXcode/FoundationExt.swift | mit | 1 | //
// FoundationExt.swift
// ExtXcode8
//
// Created by 王洪运 on 2016/9/28.
// Copyright © 2016年 王洪运. All rights reserved.
//
import Foundation
extension String {
/// 检查是否是 OC 的方法
///
/// - returns: 是否是 OC 的方法
func hasMethod() -> Bool {
let str = replacingOccurrences(of: " ", with: "")
let pattern = "[-,+]\\(\\S*\\)"
let regular = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let results = regular.matches(in: str, options: .reportProgress, range: NSMakeRange(0, str.characters.count))
if results.count == 1 {
if let range = results.first?.range, range.location == 0 {
return true
}
}
return false
}
/// 检查是否是 OC 的属性
///
/// - returns: 是否是 OC 的属性
func hasProperty() -> Bool {
return contains("@property")
}
/// 解析 Swift 方法参数
///
/// - returns: 参数名数组
func parserFuncStrParameter() -> Array<String> {
var arr = [String]()
let startIdx = range(of: "(")!.upperBound
let endIdx = range(of: ")")!.lowerBound
if startIdx != endIdx {
let paramStr = substring(with: startIdx..<endIdx)
for paramItem in paramStr.components(separatedBy: ",") {
var paramName = paramItem.components(separatedBy: ":").first!.trimmingCharacters(in: .whitespacesAndNewlines)
if paramName.contains(" ") {
let paramNames = paramName.components(separatedBy: " ")
if paramNames.first!.contains("_") {
paramName = paramNames.last!
}else {
paramName = paramNames.first!
}
}
paramName = paramName.replacingOccurrences(of: ";", with: "")
arr.append(paramName)
}
}
return arr
}
/// 检查 Swift 是否有返回值
///
/// - returns: Swift 是否有返回值
func funcStrHasReturnValue() -> Bool {
let tempIndex = range(of: ")")!.lowerBound
let returnTypeStr = substring(from: tempIndex).replacingOccurrences(of: " ", with: "")
if returnTypeStr.contains("->Void") {
return false
} else if returnTypeStr.contains("->") {
return true
}else {
return false
}
}
/// 检查是否是 Swift 的方法
///
/// - returns: 是否是 Swift 的方法
func hasFuncMethod() -> Bool {
return contains("func ")
}
/// 检查是否是 Swift 的变量或常量
///
/// - returns: 是否是 Swift 的变量或常量
func hasVarOrLet() -> Bool {
return contains("var ") || contains("let ")
}
}
| 7dab350cf977205fc92ef9d01a8219bc | 24.560748 | 126 | 0.516271 | false | false | false | false |
xusader/firefox-ios | refs/heads/master | Client/Frontend/Browser/SearchViewController.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
private let SuggestionBackgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)
private let SuggestionBorderColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
private let SuggestionBorderWidth: CGFloat = 0.5
private let SuggestionCornerRadius: CGFloat = 2
private let SuggestionFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 12)
private let SuggestionInsets = UIEdgeInsetsMake(5, 5, 5, 5)
private let SuggestionMargin: CGFloat = 4
private let SuggestionCellVerticalPadding: CGFloat = 8
private let SuggestionCellMaxRows = 2
private let PromptColor = UIColor(rgb: 0xeef0f3)
private let PromptFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 12)
private let PromptYesFont = UIFont(name: "HelveticaNeue-Bold", size: 15)
private let PromptNoFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Medium" : "HelveticaNeue", size: 15)
private let PromptInsets = UIEdgeInsetsMake(15, 12, 15, 12)
private let PromptButtonColor = UIColor(rgb: 0x007aff)
private let SearchImage = "search"
// searchEngineScrollViewContent is the button container. It has a gray background color,
// so with insets applied to its buttons, the background becomes the button border.
private let EngineButtonInsets = UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5)
// TODO: This should use ToolbarHeight in BVC. Fix this when we create a shared theming file.
private let EngineButtonHeight: Float = 44
private let EngineButtonWidth = EngineButtonHeight * 1.5
private let PromptMessage = NSLocalizedString("Turn on search suggestions?", tableName: "search", comment: "Prompt shown before enabling provider search queries")
private let PromptYes = NSLocalizedString("Yes", tableName: "search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private let PromptNo = NSLocalizedString("No", tableName: "search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private enum SearchListSection: Int {
case SearchSuggestions
case BookmarksAndHistory
static let Count = 2
}
protocol SearchViewControllerDelegate: class {
func searchViewController(searchViewController: SearchViewController, didSelectURL url: NSURL)
}
class SearchViewController: SiteTableViewController, KeyboardHelperDelegate, LoaderListener {
var searchDelegate: SearchViewControllerDelegate?
private var suggestClient: SearchSuggestClient?
// Views for displaying the bottom scrollable search engine list. searchEngineScrollView is the
// scrollable container; searchEngineScrollViewContent contains the actual set of search engine buttons.
private let searchEngineScrollView = ButtonScrollView()
private let searchEngineScrollViewContent = UIView()
// Cell for the suggestion flow layout. Since heightForHeaderInSection is called *before*
// cellForRowAtIndexPath, we create the cell to find its height before it's added to the table.
private let suggestionCell = SuggestionCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
private var suggestionPrompt: UIView?
convenience init() {
self.init(nibName: nil, bundle: nil)
}
required override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
KeyboardHelper.defaultHelper.addDelegate(self)
searchEngineScrollView.layer.backgroundColor = tableView.backgroundColor?.CGColor
searchEngineScrollView.decelerationRate = UIScrollViewDecelerationRateFast
view.addSubview(searchEngineScrollView)
searchEngineScrollViewContent.layer.backgroundColor = tableView.separatorColor.CGColor
searchEngineScrollView.addSubview(searchEngineScrollViewContent)
layoutTable()
layoutSearchEngineScrollView()
searchEngineScrollViewContent.snp_makeConstraints { make in
make.center.equalTo(self.searchEngineScrollView).priorityLow()
make.left.greaterThanOrEqualTo(self.searchEngineScrollView).priorityHigh()
make.right.lessThanOrEqualTo(self.searchEngineScrollView).priorityHigh()
make.top.bottom.equalTo(self.searchEngineScrollView)
}
suggestionCell.delegate = self
}
private func layoutSearchEngineScrollView() {
let keyboardHeight = KeyboardHelper.defaultHelper.currentState?.height ?? 0
searchEngineScrollView.snp_remakeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view).offset(-keyboardHeight)
}
}
var searchEngines: SearchEngines! {
didSet {
suggestClient?.cancelPendingRequest()
// Query and reload the table with new search suggestions.
querySuggestClient()
// Show the default search engine first.
suggestClient = SearchSuggestClient(searchEngine: searchEngines.defaultEngine)
// Reload the footer list of search engines.
reloadSearchEngines()
layoutSuggestionsOptInPrompt()
}
}
private func layoutSuggestionsOptInPrompt() {
if !(searchEngines?.shouldShowSearchSuggestionsOptIn ?? false) {
view.layoutIfNeeded()
suggestionPrompt = nil
layoutTable()
UIView.animateWithDuration(0.2,
animations: {
self.view.layoutIfNeeded()
},
completion: { _ in
self.suggestionPrompt?.removeFromSuperview()
return
})
return
}
let prompt = UIView()
prompt.backgroundColor = PromptColor
// Insert behind the tableView so the tableView slides on top of it
// when the prompt is dismissed.
view.insertSubview(prompt, belowSubview: tableView)
suggestionPrompt = prompt
let promptImage = UIImageView()
promptImage.image = UIImage(named: SearchImage)
prompt.addSubview(promptImage)
let promptLabel = UILabel()
promptLabel.text = PromptMessage
promptLabel.font = PromptFont
promptLabel.numberOfLines = 0
promptLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
prompt.addSubview(promptLabel)
let promptYesButton = InsetButton()
promptYesButton.setTitle(PromptYes, forState: UIControlState.Normal)
promptYesButton.setTitleColor(PromptButtonColor, forState: UIControlState.Normal)
promptYesButton.titleLabel?.font = PromptYesFont
promptYesButton.titleEdgeInsets = PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptYesButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
promptYesButton.addTarget(self, action: "SELdidClickOptInYes", forControlEvents: UIControlEvents.TouchUpInside)
prompt.addSubview(promptYesButton)
let promptNoButton = InsetButton()
promptNoButton.setTitle(PromptNo, forState: UIControlState.Normal)
promptNoButton.setTitleColor(PromptButtonColor, forState: UIControlState.Normal)
promptNoButton.titleLabel?.font = PromptNoFont
promptNoButton.titleEdgeInsets = PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptNoButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
promptNoButton.addTarget(self, action: "SELdidClickOptInNo", forControlEvents: UIControlEvents.TouchUpInside)
prompt.addSubview(promptNoButton)
promptImage.snp_makeConstraints { make in
make.left.equalTo(prompt).offset(PromptInsets.left)
make.centerY.equalTo(prompt)
}
promptLabel.snp_makeConstraints { make in
make.left.equalTo(promptImage.snp_right).offset(PromptInsets.left)
make.top.bottom.equalTo(prompt).insets(PromptInsets)
make.right.lessThanOrEqualTo(promptYesButton.snp_left)
return
}
promptNoButton.snp_makeConstraints { make in
make.right.equalTo(prompt).insets(PromptInsets)
make.centerY.equalTo(prompt)
}
promptYesButton.snp_makeConstraints { make in
make.right.equalTo(promptNoButton.snp_leading).insets(PromptInsets)
make.centerY.equalTo(prompt)
}
prompt.snp_makeConstraints { make in
make.top.leading.trailing.equalTo(self.view)
return
}
layoutTable()
}
var searchQuery: String = "" {
didSet {
// Reload the tableView to show the updated text in each engine.
reloadData()
}
}
override func reloadData() {
querySuggestClient()
}
private func layoutTable() {
tableView.snp_remakeConstraints { make in
make.top.equalTo(self.suggestionPrompt?.snp_bottom ?? self.view.snp_top)
make.leading.trailing.equalTo(self.view)
make.bottom.equalTo(self.searchEngineScrollView.snp_top)
}
}
private func reloadSearchEngines() {
searchEngineScrollViewContent.subviews.map({ $0.removeFromSuperview() })
var leftEdge = searchEngineScrollViewContent.snp_left
for engine in searchEngines.quickSearchEngines {
let engineButton = UIButton()
engineButton.setImage(engine.image, forState: UIControlState.Normal)
engineButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
engineButton.layer.backgroundColor = UIColor.whiteColor().CGColor
engineButton.addTarget(self, action: "SELdidSelectEngine:", forControlEvents: UIControlEvents.TouchUpInside)
engineButton.accessibilityLabel = String(format: NSLocalizedString("%@ search", comment: "Label for search engine buttons. The argument corresponds to the name of the search engine."), engine.shortName)
engineButton.imageView?.snp_makeConstraints { make in
make.width.height.equalTo(OpenSearchEngine.PreferredIconSize)
return
}
searchEngineScrollViewContent.addSubview(engineButton)
engineButton.snp_makeConstraints { make in
make.width.equalTo(EngineButtonWidth)
make.height.equalTo(EngineButtonHeight)
make.left.equalTo(leftEdge).offset(EngineButtonInsets.left)
make.top.bottom.equalTo(self.searchEngineScrollViewContent).insets(EngineButtonInsets)
if engine === self.searchEngines.quickSearchEngines.last {
make.right.equalTo(self.searchEngineScrollViewContent).offset(-EngineButtonInsets.right)
}
}
leftEdge = engineButton.snp_right
}
}
func SELdidSelectEngine(sender: UIButton) {
// The UIButtons are the same cardinality and order as the array of quick search engines.
for i in 0..<searchEngineScrollViewContent.subviews.count {
if let button = searchEngineScrollViewContent.subviews[i] as? UIButton {
if button === sender {
if let url = searchEngines.quickSearchEngines[i].searchURLForQuery(searchQuery) {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
}
}
func SELdidClickOptInYes() {
searchEngines.shouldShowSearchSuggestions = true
searchEngines.shouldShowSearchSuggestionsOptIn = false
querySuggestClient()
layoutSuggestionsOptInPrompt()
}
func SELdidClickOptInNo() {
searchEngines.shouldShowSearchSuggestions = false
searchEngines.shouldShowSearchSuggestionsOptIn = false
layoutSuggestionsOptInPrompt()
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
func keyboardHelper(keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
private func animateSearchEnginesWithKeyboard(keyboardState: KeyboardState) {
layoutSearchEngineScrollView()
UIView.animateWithDuration(keyboardState.animationDuration, animations: {
UIView.setAnimationCurve(keyboardState.animationCurve)
self.view.layoutIfNeeded()
})
}
private func querySuggestClient() {
suggestClient?.cancelPendingRequest()
if searchQuery.isEmpty || !searchEngines.shouldShowSearchSuggestions {
suggestionCell.suggestions = []
return
}
suggestClient?.query(searchQuery, callback: { suggestions, error in
if let error = error {
let isSuggestClientError = error.domain == SearchSuggestClientErrorDomain
switch error.code {
case NSURLErrorCancelled where error.domain == NSURLErrorDomain:
// Request was cancelled. Do nothing.
break
case SearchSuggestClientErrorInvalidEngine where isSuggestClientError:
// Engine does not support search suggestions. Do nothing.
break
case SearchSuggestClientErrorInvalidResponse where isSuggestClientError:
println("Error: Invalid search suggestion data")
default:
println("Error: \(error.description)")
}
} else {
self.suggestionCell.suggestions = suggestions!
}
// If there are no suggestions, just use whatever the user typed.
if suggestions?.isEmpty ?? true {
self.suggestionCell.suggestions = [self.searchQuery]
}
// Reload the tableView to show the new list of search suggestions.
self.tableView.reloadData()
})
}
func loader(dataLoaded data: Cursor) {
self.data = data
tableView.reloadData()
}
}
extension SearchViewController: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = SearchListSection(rawValue: indexPath.section)!
if section == SearchListSection.BookmarksAndHistory {
if let site = data[indexPath.row] as? Site {
if let url = NSURL(string: site.url) {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let currentSection = SearchListSection(rawValue: indexPath.section) {
switch currentSection {
case .SearchSuggestions:
// heightForRowAtIndexPath is called *before* the cell is created, so to get the height,
// force a layout pass first.
suggestionCell.layoutIfNeeded()
return suggestionCell.frame.height
default:
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
return 0
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
}
extension SearchViewController: UITableViewDataSource {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch SearchListSection(rawValue: indexPath.section)! {
case .SearchSuggestions:
suggestionCell.imageView?.image = searchEngines.defaultEngine.image
return suggestionCell
case .BookmarksAndHistory:
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let site = data[indexPath.row] as? Site {
if let cell = cell as? TwoLineTableViewCell {
cell.setLines(site.title, detailText: site.url)
if let img = site.icon {
let imgUrl = NSURL(string: img.url)
cell.imageView?.sd_setImageWithURL(imgUrl, placeholderImage: self.profile.favicons.defaultIcon)
} else {
cell.imageView?.image = self.profile.favicons.defaultIcon
}
}
}
return cell
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch SearchListSection(rawValue: section)! {
case .SearchSuggestions:
return searchEngines.shouldShowSearchSuggestions ? 1 : 0
case .BookmarksAndHistory:
return data.count
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return SearchListSection.Count
}
}
extension SearchViewController: SuggestionCellDelegate {
private func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) {
var url = URIFixup().getURL(suggestion)
if url == nil {
// Assume that only the default search engine can provide search suggestions.
url = searchEngines?.defaultEngine.searchURLForQuery(suggestion)
}
if let url = url {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
/**
* UIScrollView that prevents buttons from interfering with scroll.
*/
private class ButtonScrollView: UIScrollView {
private override func touchesShouldCancelInContentView(view: UIView!) -> Bool {
return true
}
}
private protocol SuggestionCellDelegate: class {
func suggestionCell(suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String)
}
/**
* Cell that wraps a list of search suggestion buttons.
*/
private class SuggestionCell: UITableViewCell {
weak var delegate: SuggestionCellDelegate?
let container = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = false
accessibilityLabel = nil
layoutMargins = UIEdgeInsetsZero
separatorInset = UIEdgeInsetsZero
selectionStyle = UITableViewCellSelectionStyle.None
contentView.addSubview(container)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var suggestions: [String] = [] {
didSet {
for view in container.subviews {
view.removeFromSuperview()
}
for suggestion in suggestions {
let button = SuggestionButton()
button.setTitle(suggestion, forState: UIControlState.Normal)
button.addTarget(self, action: "SELdidSelectSuggestion:", forControlEvents: UIControlEvents.TouchUpInside)
// If this is the first image, add the search icon.
if container.subviews.isEmpty {
let image = UIImage(named: SearchImage)
button.setImage(image, forState: UIControlState.Normal)
button.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0)
}
container.addSubview(button)
}
setNeedsLayout()
}
}
@objc
func SELdidSelectSuggestion(sender: UIButton) {
delegate?.suggestionCell(self, didSelectSuggestion: sender.titleLabel!.text!)
}
private override func layoutSubviews() {
super.layoutSubviews()
// The left bounds of the suggestions align with where text would be displayed.
let textLeft: CGFloat = 44
// The maximum width of the container, after which suggestions will wrap to the next line.
let maxWidth = contentView.frame.width
// The height of the suggestions container (minus margins), used to determine the frame.
var height: CGFloat = 0
var currentLeft = textLeft
var currentTop = SuggestionCellVerticalPadding
var currentRow = 0
for view in container.subviews {
let button = view as! UIButton
var buttonSize = button.intrinsicContentSize()
if height == 0 {
height = buttonSize.height
}
var width = currentLeft + buttonSize.width + SuggestionMargin
if width > maxWidth {
// Only move to the next row if there's already a suggestion on this row.
// Otherwise, the suggestion is too big to fit and will be resized below.
if currentLeft > textLeft {
currentRow++
if currentRow >= SuggestionCellMaxRows {
// Don't draw this button if it doesn't fit on the row.
button.frame = CGRectZero
continue
}
currentLeft = textLeft
currentTop += buttonSize.height + SuggestionMargin
height += buttonSize.height + SuggestionMargin
width = currentLeft + buttonSize.width + SuggestionMargin
}
// If the suggestion is too wide to fit on its own row, shrink it.
if width > maxWidth {
buttonSize.width = maxWidth - currentLeft - SuggestionMargin
}
}
button.frame = CGRectMake(currentLeft, currentTop, buttonSize.width, buttonSize.height)
currentLeft += buttonSize.width + SuggestionMargin
}
frame.size.height = height + 2 * SuggestionCellVerticalPadding
contentView.frame = frame
container.frame = frame
let imageY = (frame.size.height - 24) / 2
imageView!.frame = CGRectMake(10, imageY, 24, 24)
}
}
/**
* Rounded search suggestion button that highlights when selected.
*/
private class SuggestionButton: InsetButton {
override init(frame: CGRect) {
super.init(frame: frame)
setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
titleLabel?.font = SuggestionFont
backgroundColor = SuggestionBackgroundColor
layer.borderColor = SuggestionBackgroundColor.CGColor
layer.borderWidth = SuggestionBorderWidth
layer.cornerRadius = SuggestionCornerRadius
contentEdgeInsets = SuggestionInsets
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
override var highlighted: Bool {
didSet {
backgroundColor = highlighted ? UIColor.grayColor() : SuggestionBackgroundColor
}
}
}
| 0a144c96768d46cc681b3961d3ac3f98 | 39.204738 | 214 | 0.664156 | false | false | false | false |
aschwaighofer/swift | refs/heads/master | test/Sema/availability_versions_multi.swift | apache-2.0 | 11 | // RUN: %swift -typecheck -primary-file %s %S/Inputs/availability_multi_other.swift -verify
// REQUIRES: OS=macosx
func callToEnsureNotInScriptMode() { }
// Add an expected error to express expectation that we're not in script mode
callToEnsureNotInScriptMode() // expected-error {{expressions are not allowed at the top level}}
@available(OSX, introduced: 10.9)
var globalAvailableOn10_9: Int = 9
@available(OSX, introduced: 10.51)
var globalAvailableOn10_51: Int = 10
@available(OSX, introduced: 10.52)
var globalAvailableOn10_52: Int = 11
// Top level should reflect the minimum deployment target.
let ignored1: Int = globalAvailableOn10_9
let ignored2: Int = globalAvailableOn10_51 // expected-error {{'globalAvailableOn10_51' is only available in macOS 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing let}}
let ignored3: Int = globalAvailableOn10_52 // expected-error {{'globalAvailableOn10_52' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing let}}
@available(OSX, introduced: 10.51)
func useFromOtherOn10_51() {
// This will trigger validation of OtherIntroduced10_51 in
// in availability_multi_other.swift
let o10_51 = OtherIntroduced10_51()
o10_51.extensionMethodOnOtherIntroduced10_51()
let o10_9 = OtherIntroduced10_9()
o10_9.extensionMethodOnOtherIntroduced10_9AvailableOn10_51(o10_51)
_ = o10_51.returns10_52Introduced10_52() // expected-error {{'returns10_52Introduced10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
_ = OtherIntroduced10_52()
// expected-error@-1 {{'OtherIntroduced10_52' is only available in macOS 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}}
o10_51.extensionMethodOnOtherIntroduced10_51AvailableOn10_52() // expected-error {{'extensionMethodOnOtherIntroduced10_51AvailableOn10_52()' is only available in macOS 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
_ = OtherIntroduced10_51.NestedIntroduced10_52()
// expected-error@-1 {{'NestedIntroduced10_52' is only available in macOS 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}}
}
@available(OSX, introduced: 10.52)
func useFromOtherOn10_52() {
_ = OtherIntroduced10_52()
let n10_52 = OtherIntroduced10_51.NestedIntroduced10_52()
_ = n10_52.returns10_52()
_ = n10_52.returns10_53() // expected-error {{'returns10_53()' is only available in macOS 10.53 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// This will trigger validation of the global in availability_in_multi_other.swift
_ = globalFromOtherOn10_52
}
| 4a0ad01cc865e5f218d1cbeb010ba855 | 44 | 186 | 0.730419 | false | false | false | false |
chitaranjan/Album | refs/heads/master | MYAlbum/Pods/SABlurImageView/SABlurImageView/SABlurImageView.swift | mit | 2 | //
// UIImageView+BlurEffect.swift
// SABlurImageView
//
// Created by 鈴木大貴 on 2015/03/27.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
import Foundation
import QuartzCore
open class SABlurImageView: UIImageView {
//MARK: - Static Properties
fileprivate struct Const {
static let fadeAnimationKey = "FadeAnimationKey"
static let maxImageCount: Int = 10
static let contentsAnimationKey = "contents"
}
//MARK: - Instance Properties
fileprivate var cgImages: [CGImage] = [CGImage]()
fileprivate var nextBlurLayer: CALayer?
fileprivate var previousImageIndex: Int = -1
fileprivate var previousPercentage: CGFloat = 0.0
open fileprivate(set) var isBlurAnimating: Bool = false
deinit {
clearMemory()
}
//MARK: - Life Cycle
open override func layoutSubviews() {
super.layoutSubviews()
nextBlurLayer?.frame = bounds
}
open func configrationForBlurAnimation(_ boxSize: CGFloat = 100) {
guard let image = image else { return }
let baseBoxSize = max(min(boxSize, 200), 0)
let baseNumber = sqrt(CGFloat(baseBoxSize)) / CGFloat(Const.maxImageCount)
let baseCGImages = [image].flatMap { $0.cgImage }
cgImages = bluredCGImages(baseCGImages, sourceImage: image, at: 0, to: Const.maxImageCount, baseNumber: baseNumber)
}
fileprivate func bluredCGImages(_ images: [CGImage], sourceImage: UIImage?, at index: Int, to limit: Int, baseNumber: CGFloat) -> [CGImage] {
guard index < limit else { return images }
let newImage = sourceImage?.blurEffect(pow(CGFloat(index) * baseNumber, 2))
let newImages = images + [newImage].flatMap { $0?.cgImage }
return bluredCGImages(newImages, sourceImage: newImage, at: index + 1, to: limit, baseNumber: baseNumber)
}
open func clearMemory() {
cgImages.removeAll(keepingCapacity: false)
nextBlurLayer?.removeFromSuperlayer()
nextBlurLayer = nil
previousImageIndex = -1
previousPercentage = 0.0
layer.removeAllAnimations()
}
//MARK: - Add single blur
open func addBlurEffect(_ boxSize: CGFloat, times: UInt = 1) {
guard let image = image else { return }
self.image = addBlurEffectTo(image, boxSize: boxSize, remainTimes: times)
}
fileprivate func addBlurEffectTo(_ image: UIImage, boxSize: CGFloat, remainTimes: UInt) -> UIImage {
guard let blurImage = image.blurEffect(boxSize) else { return image }
return remainTimes > 0 ? addBlurEffectTo(blurImage, boxSize: boxSize, remainTimes: remainTimes - 1) : image
}
//MARK: - Percentage blur
open func blur(_ percentage: CGFloat) {
let percentage = min(max(percentage, 0.0), 0.99)
if previousPercentage - percentage > 0 {
let index = Int(floor(percentage * 10)) + 1
if index > 0 {
setLayers(index, percentage: percentage, currentIndex: index - 1, nextIndex: index)
}
} else {
let index = Int(floor(percentage * 10))
if index < cgImages.count - 1 {
setLayers(index, percentage: percentage, currentIndex: index, nextIndex: index + 1)
}
}
previousPercentage = percentage
}
fileprivate func setLayers(_ index: Int, percentage: CGFloat, currentIndex: Int, nextIndex: Int) {
if index != previousImageIndex {
CATransaction.animationWithDuration(0) { layer.contents = self.cgImages[currentIndex] }
if nextBlurLayer == nil {
let nextBlurLayer = CALayer()
nextBlurLayer.frame = bounds
layer.addSublayer(nextBlurLayer)
self.nextBlurLayer = nextBlurLayer
}
CATransaction.animationWithDuration(0) {
self.nextBlurLayer?.contents = self.cgImages[nextIndex]
self.nextBlurLayer?.opacity = 1.0
}
}
previousImageIndex = index
let minPercentage = percentage * 100.0
let alpha = min(max((minPercentage - CGFloat(Int(minPercentage / 10.0) * 10)) / 10.0, 0.0), 1.0)
CATransaction.animationWithDuration(0) { self.nextBlurLayer?.opacity = Float(alpha) }
}
//MARK: - Animation blur
open func startBlurAnimation(_ duration: TimeInterval) {
if isBlurAnimating { return }
isBlurAnimating = true
let count = cgImages.count
let group = CAAnimationGroup()
group.animations = cgImages.enumerated().flatMap {
guard $0.offset < count - 1 else { return nil }
let anim = CABasicAnimation(keyPath: Const.contentsAnimationKey)
anim.fromValue = $0.element
anim.toValue = cgImages[$0.offset + 1]
anim.fillMode = kCAFillModeForwards
anim.isRemovedOnCompletion = false
anim.duration = duration / TimeInterval(count)
anim.beginTime = anim.duration * TimeInterval($0.offset)
return anim
}
group.duration = duration
group.delegate = self
group.isRemovedOnCompletion = false
group.fillMode = kCAFillModeForwards
layer.add(group, forKey: Const.fadeAnimationKey)
cgImages = cgImages.reversed()
}
}
extension SABlurImageView: CAAnimationDelegate {
open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
guard let _ = anim as? CAAnimationGroup else { return }
layer.removeAnimation(forKey: Const.fadeAnimationKey)
isBlurAnimating = false
guard let cgImage = cgImages.first else { return }
image = UIImage(cgImage: cgImage)
}
}
| fd9457e713201d8ebec3616c140e832d | 38.367347 | 145 | 0.63107 | false | false | false | false |
jmcur/JCVideoPlayer | refs/heads/master | JCVideoPlayer/Constants.swift | mit | 1 | //
// Constants.swift
// JCVideoPlayer
//
// Created by Juan Curti on 5/4/17.
// Copyright © 2017 Juan Curti. All rights reserved.
//
import Foundation
import UIKit
class Constants{
static let ANIMATION_DURATION = 0.2 //Duration of animations at showing
static let CONTROL_IMAGES_ALPHA_VALUE:CGFloat = 0.7 //Alpha value of images shown as alerts
static let TRANSITION_ANIMATION_FINAL_SIZE = CGSize(width: 10.0, height: 10.0) //Initial Transition Image Size
static let TRANSITION_ANIMATION_DURATION = 0.25 //Duration of the transition (eg to FullScreen)
static let TRANSITION_CONTROL_BAR_DURATION = 0.4 //Duration of animation at showing/hiding control bar
static let NOTIF_NAME_PROGRESS_DOWNLOAD = "PROGRESS_DOWNLOAD_LOADER"
static let NOTIF_NAME_PROGRESS_DOWNLOAD_DONE = "PROGRESS_DOWNLOAD_LOADER_DONE"
static let LOADER_SIZE = CGSize(width: 150.0, height: 150.0)
static let CLOSE_ICON_SIZE:CGSize = CGSize(width: 50.0, height: 50.0)
static let SHARE_ICON_SIZE:CGSize = CGSize(width: 50.0, height: 50.0)
}
| d7b6c73c87bf5c2ddfcef40031bc9325 | 46.269231 | 125 | 0.627339 | false | false | false | false |
CharlesVu/Smart-iPad | refs/heads/master | Persistance/Persistance/RealmModels/RealmJourney.swift | mit | 1 | //
// Journey.swift
// Persistance
//
// Created by Charles Vu on 05/06/2019.
// Copyright © 2019 Charles Vu. All rights reserved.
//
import Foundation
import RealmSwift
@objcMembers public final class RealmJourney: Object {
public dynamic var id: String! = UUID().uuidString
public dynamic var originCRS: String! = ""
public dynamic var destinationCRS: String! = ""
convenience public init(originCRS: String, destinationCRS: String) {
self.init()
self.originCRS = originCRS
self.destinationCRS = destinationCRS
self.id = originCRS + destinationCRS
}
override public static func primaryKey() -> String? {
return "id"
}
convenience init(journey: Journey) {
self.init()
self.originCRS = journey.originCRS
self.destinationCRS = journey.destinationCRS
}
}
| e34c1f77784d4020426b3698005f9382 | 25.090909 | 72 | 0.664344 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Incremental/Dependencies/struct-member-fine.swift | apache-2.0 | 15 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-OLD
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main | %FileCheck %s -check-prefix=CHECK-NEW
// RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps
private struct Wrapper {
static func test() -> InterestingType { fatalError() }
}
// CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int
// CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double
public var x = Wrapper.test() + 0
/// CHECK-DEPS: topLevel interface '' InterestingType false
| fda6e0dc26eedb03460afecea79cada3 | 53 | 203 | 0.719577 | false | true | false | false |
Rep2/IRSocket | refs/heads/master | IRSocket/IRSockaddr.swift | mit | 1 | //
// IRSockaddr.swift
// RASUSLabos
//
// Created by Rep on 12/14/15.
// Copyright © 2015 Rep. All rights reserved.
//
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
class IRSockaddr{
var cSockaddr:sockaddr_in
init(ip: UInt32 = 0, port: UInt16 = 0, domain:Int32 = AF_INET){
cSockaddr = sockaddr_in(
sin_len: __uint8_t(sizeof(sockaddr_in)),
sin_family: sa_family_t(domain),
sin_port: htons(port),
sin_addr: in_addr(s_addr: ip),
sin_zero: ( 0, 0, 0, 0, 0, 0, 0, 0 )
)
}
init(socket: sockaddr_in){
cSockaddr = socket
}
func toString() -> String{
return "127.0.0.1 \(ntohs(cSockaddr.sin_port))"
}
} | e1b20c7955d538caaa69195f102fd151 | 20.243243 | 67 | 0.53758 | false | false | false | false |
iHunterX/SocketIODemo | refs/heads/master | DemoSocketIO/Utils/PAPermissions/Classes/PAPermissionsTableViewCell.swift | gpl-3.0 | 1 | //
// PAPermissionsTableViewCell.swift
// PAPermissionsApp
//
// Created by Pasquale Ambrosini on 05/09/16.
// Copyright © 2016 Pasquale Ambrosini. All rights reserved.
//
import UIKit
class PAPermissionsTableViewCell: UITableViewCell {
var didSelectItem: ((PAPermissionsItem) -> ())?
weak var iconImageView: UIImageView!
weak var titleLabel: UILabel!
weak var detailsLabel: UILabel!
weak var permission: PAPermissionsItem!
fileprivate weak var rightDetailsContainer: UIView!
fileprivate weak var enableButton: UIButton!
fileprivate weak var checkingIndicator: UIActivityIndicatorView!
fileprivate var _permissionStatus = PAPermissionsStatus.disabled
var permissionStatus: PAPermissionsStatus {
get {
return self._permissionStatus
}
set(newStatus) {
self._permissionStatus = newStatus
self.setupEnableButton(newStatus)
}
}
override var tintColor: UIColor! {
get {
return super.tintColor
}
set(newTintColor) {
super.tintColor = newTintColor
self.updateTintColor()
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func updateTintColor() {
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupEnableButton(self.permissionStatus)
}
fileprivate func setupUI() {
self.backgroundColor = UIColor.clear
self.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupRightDetailsContainer()
let views = ["iconImageView": self.iconImageView,
"titleLabel": self.titleLabel,
"detailsLabel": self.detailsLabel,
"rightDetailsContainer": self.rightDetailsContainer] as [String:UIView]
let allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:|-2-[iconImageView]-2-|",
"H:|-0-[iconImageView(15)]",
"V:|-2-[rightDetailsContainer]-2-|",
"H:[rightDetailsContainer(58)]-0-|",
"V:|-8-[titleLabel(18)]-2-[detailsLabel(13)]",
"H:[iconImageView]-8-[titleLabel]-4-[rightDetailsContainer]",
"H:[iconImageView]-8-[detailsLabel]-4-[rightDetailsContainer]"
], views: views)
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.addConstraints(allConstraints)
}
self.setupEnableButton(.disabled)
}
fileprivate func setupImageView() {
if self.iconImageView == nil {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
self.addSubview(imageView)
self.iconImageView = imageView
self.iconImageView.backgroundColor = UIColor.clear
self.iconImageView.translatesAutoresizingMaskIntoConstraints = false
}
self.iconImageView.tintColor = self.tintColor
}
fileprivate func setupTitleLabel() {
if self.titleLabel == nil {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(titleLabel)
self.titleLabel = titleLabel
self.titleLabel.text = "Title"
self.titleLabel.adjustsFontSizeToFitWidth = true
}
self.titleLabel.font = UIFont(name: "HelveticaNeue-Light", size: 15)
self.titleLabel.minimumScaleFactor = 0.1
self.titleLabel.textColor = self.tintColor
}
fileprivate func setupDetailsLabel() {
if self.detailsLabel == nil {
let detailsLabel = UILabel()
detailsLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(detailsLabel)
self.detailsLabel = detailsLabel
self.detailsLabel.text = "details"
self.detailsLabel.adjustsFontSizeToFitWidth = true
}
self.detailsLabel.font = UIFont(name: "HelveticaNeue-Light", size: 11)
self.detailsLabel.minimumScaleFactor = 0.1
self.detailsLabel.textColor = self.tintColor
}
fileprivate func setupRightDetailsContainer() {
if self.rightDetailsContainer == nil {
let rightDetailsContainer = UIView()
rightDetailsContainer.backgroundColor = UIColor.clear
rightDetailsContainer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(rightDetailsContainer)
self.rightDetailsContainer = rightDetailsContainer
self.rightDetailsContainer.backgroundColor = UIColor.clear
}
}
fileprivate func setupEnableButton(_ status: PAPermissionsStatus) {
if self.enableButton == nil {
let enableButton = UIButton(type: .system)
enableButton.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(enableButton)
self.enableButton = enableButton
self.enableButton.backgroundColor = UIColor.red
self.enableButton.addTarget(self, action: #selector(PAPermissionsTableViewCell._didSelectItem), for: .touchUpInside)
let checkingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
checkingIndicator.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(checkingIndicator)
self.checkingIndicator = checkingIndicator
let views = ["enableButton": self.enableButton,
"checkingIndicator": self.checkingIndicator] as [String : UIView]
var allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:[enableButton(30)]",
"H:|-2-[enableButton]-2-|",
"V:|-0-[checkingIndicator]-0-|",
"H:|-0-[checkingIndicator]-0-|"
], views: views)
allConstraints.append(NSLayoutConstraint.init(item: self.enableButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.enableButton.superview, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0))
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.rightDetailsContainer.addConstraints(allConstraints)
}
}
self.enableButton.tintColor = self.tintColor
if status == .enabled {
if !self.permission.canBeDisabled {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_checkmark_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}else{
self.setupEnableDisableButton(title: "Disable")
}
}else if status == .disabled || status == .denied {
self.setupEnableDisableButton(title: "Enable")
}else if status == .checking {
self.enableButton.isHidden = true
self.checkingIndicator.isHidden = false
self.checkingIndicator.startAnimating()
}else if status == .unavailable {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_cancel_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}
}
private func setupEnableDisableButton(title: String) {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle(NSLocalizedString(title, comment: ""), for: UIControlState())
self.enableButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
self.enableButton.setImage(nil, for: UIControlState())
self.enableButton.titleLabel?.minimumScaleFactor = 0.1
self.enableButton.titleLabel?.adjustsFontSizeToFitWidth = true
self.enableButton.setTitleColor(self.tintColor, for: UIControlState())
self.enableButton.backgroundColor = UIColor.clear
self.enableButton.layer.cornerRadius = 2.0
self.enableButton.layer.borderColor = self.tintColor.cgColor
self.enableButton.layer.borderWidth = 1.0
self.enableButton.clipsToBounds = true
self.enableButton.isUserInteractionEnabled = true
}
@objc fileprivate func _didSelectItem() {
if self.didSelectItem != nil {
self.didSelectItem!(self.permission)
}
}
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
}
}
| 084896fad33a76a1cd1dc54a5b30064a | 34.289683 | 254 | 0.752614 | false | false | false | false |
shaoyihe/100-Days-of-IOS | refs/heads/master | 24 - CUSTOM COLLECTION VIEW/24 - CUSTOM COLLECTION VIEW/ViewController.swift | mit | 1 | //
// ViewController.swift
// 24 - CUSTOM COLLECTION VIEW
//
// Created by heshaoyi on 4/4/16.
// Copyright © 2016 heshaoyi. All rights reserved.
//
import UIKit
import Photos
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var phResult: PHFetchResult?
@IBOutlet var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let opt = PHFetchOptions()
// let desc = NSSortDescriptor(key: "startDate", ascending: true)
// opt.sortDescriptors = [desc]
self.phResult = PHAsset.fetchAssetsWithOptions(opt)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return (self.phResult?.count)!
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("image", forIndexPath: indexPath) as! ImageCollectionViewCell
let asset = phResult?.objectAtIndex(indexPath.row) as! PHAsset
PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: cell.frame.size, contentMode: .AspectFill, options: nil, resultHandler: {
(im:UIImage?, info:[NSObject : AnyObject]?) in
if let im = im {
cell.imageView.image = im
}
})
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
let width = view.frame.size.width / 3
return CGSize(width: width, height: 100)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator){
collectionView.collectionViewLayout.invalidateLayout()
}
}
| a6d380d195567dcb7b22d90e21edbb3d | 36.214286 | 168 | 0.696737 | false | false | false | false |
simonnarang/Fandom | refs/heads/master | Desktop/Fandom-IOS-master/Fandomm/RedisClient.swift | unlicense | 2 | //
// RedisClient.swift
// Redis-Framework
//
// Copyright (c) 2015, Eric Orion Anderson
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
public let RedisErrorDomain = "com.rareairconsulting.redis"
public enum RedisLogSeverity:String
{
case Info = "Info"
case Debug = "Debug"
case Error = "Error"
case Critical = "Critical"
}
public typealias RedisLoggingBlock = ((redisClient:AnyObject, message:String, severity:RedisLogSeverity) -> Void)?
public typealias RedisCommandStringBlock = ((string:String!, error:NSError!)->Void)
public typealias RedisCommandIntegerBlock = ((int:Int!, error:NSError!)->Void)
public typealias RedisCommandArrayBlock = ((array:[AnyObject]!, error:NSError!)->Void)
public typealias RedisCommandDataBlock = ((data:NSData!, error:NSError!)->Void)
/// RedisClient
///
/// A simple redis client that can be extended for supported Redis commands.
/// This client expects a response for each request and acts as a serial queue.
/// See: RedisPubSubClient for publish/subscribe functionality.
public class RedisClient
{
private let _loggingBlock:RedisLoggingBlock
private let _delegateQueue:NSOperationQueue!
private let _serverHost:String!
private let _serverPort:Int!
lazy private var _commander:RESPCommander = RESPCommander(redisClient: self)
internal var closeExpected:Bool = false {
didSet {
self._commander._closeExpected = self.closeExpected
}
}
public var host:String {
return self._serverHost
}
public var port:Int {
return self._serverPort
}
internal func performBlockOnDelegateQueue(block:dispatch_block_t) -> Void {
self._delegateQueue.addOperationWithBlock(block)
}
public init(host:String, port:Int, loggingBlock:RedisLoggingBlock? = nil, delegateQueue:NSOperationQueue? = nil)
{
self._serverHost = host
self._serverPort = port
if loggingBlock == nil
{
self._loggingBlock = {(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
switch(severity)
{
case .Critical, .Error:
print(message)
default: break
}
}
}
else {
self._loggingBlock = loggingBlock!
}
if delegateQueue == nil {
self._delegateQueue = NSOperationQueue.mainQueue()
}
else {
self._delegateQueue = delegateQueue
}
}
public func sendCommandWithArrayResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandArrayBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(array: nil, error: error)
}
else {
let parsingResults:(array:[AnyObject]!, error:NSError!) = RESPUtilities.respArrayFromData(data)
completionHandler(array: parsingResults.array, error: parsingResults.error)
}
})
})
}
public func sendCommandWithIntegerResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandIntegerBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(int: nil, error: error)
}
else {
let parsingResults:(int:Int!, error:NSError!) = RESPUtilities.respIntegerFromData(data)
completionHandler(int: parsingResults.int, error: parsingResults.error)
}
})
})
}
public func sendCommandWithStringResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandStringBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), data:data, completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
if error != nil {
completionHandler(string: nil, error: error)
}
else {
let parsingResults = RESPUtilities.respStringFromData(data)
completionHandler(string: parsingResults.string, error: parsingResults.error)
}
})
})
}
public func sendCommandWithDataResponse(command: String, data:NSData? = nil, completionHandler: RedisCommandDataBlock)
{
self._commander.sendCommand(RESPUtilities.commandToRequestString(command, data:(data != nil)), completionHandler: { (data, error) -> Void in
self.performBlockOnDelegateQueue({ () -> Void in
completionHandler(data: data, error: error)
})
})
}
private func log(message:String, severity:RedisLogSeverity)
{
if NSThread.isMainThread() {
self._loggingBlock!(redisClient: self, message: message, severity: severity)
}
else {
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self._loggingBlock!(redisClient: self, message: message, severity: severity)
})
}
}
}
private class RESPCommander:NSObject, NSStreamDelegate
{
private let _redisClient:RedisClient!
private var _inputStream:NSInputStream!
private var _outputStream:NSOutputStream!
private let _operationQueue:NSOperationQueue!
private let _commandLock:dispatch_semaphore_t!
private let _queueLock:dispatch_semaphore_t!
private var _incomingData:NSMutableData!
private let operationLock:String = "RedisOperationLock"
private var _queuedCommand:String! = nil
private var _queuedData:NSData! = nil
private var _error:NSError?
private var _closeExpected:Bool = false
private func _closeStreams()
{
if self._inputStream != nil
{
self._inputStream.close()
self._inputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream = nil
}
if self._outputStream != nil
{
self._outputStream.close()
self._outputStream.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream = nil
}
}
private func _openStreams()
{
self._closeStreams()
var readStream:NSInputStream? = nil
var writeStream:NSOutputStream? = nil
NSStream.getStreamsToHostWithName(self._redisClient._serverHost, port: self._redisClient._serverPort, inputStream: &readStream, outputStream: &writeStream)
self._inputStream = readStream
self._outputStream = writeStream
self._inputStream.delegate = self
self._outputStream.delegate = self
self._inputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._outputStream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self._inputStream.open()
self._outputStream.open()
}
init(redisClient: RedisClient)
{
self._commandLock = dispatch_semaphore_create(0);
self._queueLock = dispatch_semaphore_create(1)
self._operationQueue = NSOperationQueue()
self._redisClient = redisClient
super.init()
self._openStreams()
}
@objc func stream(theStream: NSStream, handleEvent streamEvent: NSStreamEvent)
{
switch(streamEvent)
{
case NSStreamEvent.HasBytesAvailable:
if self._inputStream === theStream //reading
{
self._redisClient.log("\tHasBytesAvailable", severity: .Debug)
self._redisClient.log("\t--READING COMMAND RESPONSE---", severity: .Debug)
let bufferSize:Int = 1024
var buffer = [UInt8](count: bufferSize, repeatedValue: 0)
let bytesRead:Int = self._inputStream.read(&buffer, maxLength: bufferSize)
self._redisClient.log("\tbytes read:\(bytesRead)", severity: .Debug)
let data = NSData(bytes: buffer, length: bytesRead)
if bytesRead == bufferSize && self._inputStream.hasBytesAvailable //reached the end of the buffer, more to come
{
if self._incomingData != nil { //there was existing data
self._incomingData.appendData(data)
}
else {
self._incomingData = NSMutableData(data: data)
}
}
else if bytesRead > 0 //finished
{
if self._incomingData != nil //there was existing data
{
self._incomingData.appendData(data)
}
else { //got it all in one shot
self._incomingData = NSMutableData(data: data)
}
self._redisClient.log("\tfinished reading", severity: .Debug)
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
else
{
if !self._closeExpected
{
self._error = NSError(domain: "com.rareairconsulting.resp", code: 0, userInfo: [NSLocalizedDescriptionKey:"Error occured while reading."])
dispatch_semaphore_signal(self._commandLock) //signal we are done
}
}
}
case NSStreamEvent.HasSpaceAvailable:
self._redisClient.log("\tHasSpaceAvailable", severity: .Debug)
if theStream === self._outputStream && self._queuedCommand != nil { //writing
self._sendQueuedCommand()
}
case NSStreamEvent.OpenCompleted:
self._redisClient.log("\tOpenCompleted", severity: .Debug)
case NSStreamEvent.ErrorOccurred:
self._redisClient.log("\tErrorOccurred", severity: .Debug)
self._error = theStream.streamError
dispatch_semaphore_signal(self._commandLock) //signal we are done
case NSStreamEvent.EndEncountered: //cleanup
self._redisClient.log("\tEndEncountered", severity: .Debug)
self._closeStreams()
default:
break
}
}
private func _sendQueuedCommand()
{
let queuedCommand = self._queuedCommand
self._queuedCommand = nil
if queuedCommand != nil && !queuedCommand.isEmpty
{
self._redisClient.log("\t--SENDING COMMAND (\(queuedCommand))---", severity: .Debug)
let commandStringData:NSMutableData = NSMutableData(data: queuedCommand.dataUsingEncoding(NSUTF8StringEncoding)!)
if self._queuedData != nil
{
commandStringData.appendData("$\(self._queuedData.length)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
commandStringData.appendData(self._queuedData)
commandStringData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
self._queuedData = nil
}
self._incomingData = nil
let bytesWritten = self._outputStream.write(UnsafePointer<UInt8>(commandStringData.bytes), maxLength: commandStringData.length)
self._redisClient.log("\tbytes sent: \(bytesWritten)", severity: .Debug)
}
}
private func sendCommand(command:NSString, data:NSData? = nil, completionHandler:RedisCommandDataBlock)
{
//could probably use gcd barriers for this but this seems good for now
self._operationQueue.addOperationWithBlock { [unowned self] () -> Void in
self._redisClient.log("***Adding to the command queue***", severity: .Debug)
dispatch_semaphore_wait(self._queueLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***New command starting off queue***", severity: .Debug)
self._queuedCommand = command as String
self._queuedData = data
if self._inputStream != nil
{
switch(self._inputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
default: break
}
}
else {
self._openStreams()
}
switch(self._outputStream.streamStatus)
{
case NSStreamStatus.Closed, NSStreamStatus.Error: //try opening it if closed
self._openStreams()
case NSStreamStatus.Open:
self._sendQueuedCommand()
default: break
}
dispatch_semaphore_wait(self._commandLock, DISPATCH_TIME_FOREVER)
self._redisClient.log("***Releasing command queue lock***", severity: .Debug)
completionHandler(data: self._incomingData, error: self._error)
dispatch_semaphore_signal(self._queueLock)
}
}
}
| e90c115f434ea2e988a8cfa001aada9d | 42.381356 | 166 | 0.598359 | false | false | false | false |
X8/CocoaMarkdown | refs/heads/master | Example/Pods/Nimble/Sources/Nimble/Matchers/SatisfyAllOf.swift | mit | 7 | import Foundation
/// A Nimble matcher that succeeds when the actual value matches with all of the matchers
/// provided in the variable list of matchers.
public func satisfyAllOf<T, U>(_ matchers: U...) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return satisfyAllOf(matchers)
}
/// Deprecated. Please use `satisfyAnyOf<T>(_) -> Predicate<T>` instead.
internal func satisfyAllOf<T, U>(_ matchers: [U]) -> Predicate<T>
where U: Matcher, U.ValueType == T {
return NonNilMatcherFunc<T> { actualExpression, failureMessage in
let postfixMessages = NSMutableArray()
var matches = true
for matcher in matchers {
if try matcher.doesNotMatch(actualExpression, failureMessage: failureMessage) {
matches = false
}
postfixMessages.add(NSString(string: "{\(failureMessage.postfixMessage)}"))
}
failureMessage.postfixMessage = "match all of: " + postfixMessages.componentsJoined(by: ", and ")
if let actualValue = try actualExpression.evaluate() {
failureMessage.actualValue = "\(actualValue)"
}
return matches
}.predicate
}
internal func satisfyAllOf<T>(_ predicates: [Predicate<T>]) -> Predicate<T> {
return Predicate { actualExpression in
var postfixMessages = [String]()
var matches = true
for predicate in predicates {
let result = try predicate.satisfies(actualExpression)
if result.toBoolean(expectation: .toNotMatch) {
matches = false
}
postfixMessages.append("{\(result.message.expectedMessage)}")
}
var msg: ExpectationMessage
if let actualValue = try actualExpression.evaluate() {
msg = .expectedCustomValueTo(
"match all of: " + postfixMessages.joined(separator: ", and "),
"\(actualValue)"
)
} else {
msg = .expectedActualValueTo(
"match all of: " + postfixMessages.joined(separator: ", and ")
)
}
return PredicateResult(
bool: matches,
message: msg
)
}.requireNonNil
}
public func && <T>(left: Predicate<T>, right: Predicate<T>) -> Predicate<T> {
return satisfyAllOf(left, right)
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func satisfyAllOfMatcher(_ matchers: [NMBMatcher]) -> NMBPredicate {
return NMBPredicate { actualExpression in
if matchers.isEmpty {
return NMBPredicateResult(
status: NMBPredicateStatus.fail,
message: NMBExpectationMessage(
fail: "satisfyAllOf must be called with at least one matcher"
)
)
}
var elementEvaluators = [Predicate<NSObject>]()
for matcher in matchers {
let elementEvaluator = Predicate<NSObject> { expression in
if let predicate = matcher as? NMBPredicate {
// swiftlint:disable:next line_length
return predicate.satisfies({ try! expression.evaluate() }, location: actualExpression.location).toSwift()
} else {
let failureMessage = FailureMessage()
// swiftlint:disable:next line_length
let success = matcher.matches({ try! expression.evaluate() }, failureMessage: failureMessage, location: actualExpression.location)
return PredicateResult(bool: success, message: failureMessage.toExpectationMessage())
}
}
elementEvaluators.append(elementEvaluator)
}
return try! satisfyAllOf(elementEvaluators).satisfies(actualExpression).toObjectiveC()
}
}
}
#endif
| 8e60fd77909f53c6f3b0886cf50bcf48 | 38.782178 | 154 | 0.580139 | false | false | false | false |
CraigZheng/KomicaViewer | refs/heads/master | KomicaViewer/KomicaViewer/ViewController/ForumTextInputViewController.swift | mit | 1 | //
// ForumTextInputViewController.swift
// KomicaViewer
//
// Created by Craig Zheng on 21/08/2016.
// Copyright © 2016 Craig. All rights reserved.
//
import UIKit
protocol ForumTextInputViewControllerProtocol {
func forumDetailEntered(_ inputViewController: ForumTextInputViewController, enteredDetails: String, forField: ForumField)
}
class ForumTextInputViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var insertBarButtonItem: UIBarButtonItem!
@IBOutlet weak var saveBarButtonItem: UIBarButtonItem!
var allowEditing = true
var delegate: ForumTextInputViewControllerProtocol?
var prefilledString: String?
var pageSpecifier: String?
var field: ForumField! {
didSet {
self.title = field.rawValue
switch field! {
case ForumField.listURL:
pageSpecifier = "<PAGE>"
case ForumField.responseURL:
pageSpecifier = "<ID>"
default:
break;
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let prefilledString = prefilledString {
textView.text = prefilledString
}
// Keyboard events observer.
NotificationCenter.default.addObserver(self, selector: #selector(ForumTextInputViewController.handlekeyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ForumTextInputViewController.handleKeyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// Configure the text view.
insertBarButtonItem.isEnabled = pageSpecifier?.isEmpty == false
if !allowEditing {
textView.isEditable = false
insertBarButtonItem.isEnabled = false
saveBarButtonItem.isEnabled = false
} else {
textView.becomeFirstResponder()
}
}
}
extension ForumTextInputViewController: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
}
func textViewDidChange(_ textView: UITextView) {
// When page specifier is not empty.
if let pageSpecifier = pageSpecifier, !pageSpecifier.isEmpty
{
// Insert button enables itself when the textView.text does not contain the page specifier.
insertBarButtonItem.isEnabled = (textView.text as NSString).range(of: pageSpecifier).location == NSNotFound
}
}
}
// MARK: UI actions.
extension ForumTextInputViewController {
@IBAction func saveAction(_ sender: AnyObject) {
textView.resignFirstResponder()
if let enteredText = textView.text, !enteredText.isEmpty {
// If page specifier is not empty and the enteredText does not contain it, show a warning.
if let pageSpecifier = pageSpecifier, !pageSpecifier.isEmpty && !enteredText.contains(pageSpecifier) {
ProgressHUD.showMessage("Cannot save, \(pageSpecifier) is required.")
} else {
delegate?.forumDetailEntered(self, enteredDetails: enteredText, forField: field)
_ = navigationController?.popViewController(animated: true)
}
}
}
@IBAction func insertAction(_ sender: AnyObject) {
let alertController = UIAlertController(title: "Insert \(pageSpecifier ?? "")", message: "Insert the tag specifier to the current position", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: {_ in
if let pageSpecifier = self.pageSpecifier, !pageSpecifier.isEmpty {
let generalPasteboard = UIPasteboard.general
let items = generalPasteboard.items
generalPasteboard.string = pageSpecifier
self.textView.paste(self)
generalPasteboard.items = items
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
if let topViewController = UIApplication.topViewController {
topViewController.present(alertController, animated: true, completion: nil)
}
}
}
// MARK: keyboard events.
extension ForumTextInputViewController {
func handlekeyboardWillShow(_ notification: Notification) {
if let keyboardValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue
{
let keyboardRect = view.convert(keyboardValue.cgRectValue, from: nil)
textViewBottomConstraint.constant = keyboardRect.size.height
toolbarBottomConstraint.constant = keyboardRect.size.height
}
}
func handleKeyboardWillHide(_ notification: Notification) {
textViewBottomConstraint.constant = 0
toolbarBottomConstraint.constant = 0
}
}
| d2dfc2605e44fc3f0ea0ee26f563f6cd | 38.938462 | 189 | 0.672188 | false | false | false | false |
hzalaz/analytics-ios | refs/heads/master | Example/Tests/FileStorageTest.swift | mit | 1 | //
// FileStorageTest.swift
// Analytics
//
// Copyright © 2016 Segment. All rights reserved.
//
import Quick
import Nimble
import Analytics
class FileStorageTest : QuickSpec {
override func spec() {
var storage : SEGFileStorage!
beforeEach {
let url = SEGFileStorage.applicationSupportDirectoryURL()
expect(url).toNot(beNil())
expect(url?.lastPathComponent) == "Application Support"
storage = SEGFileStorage(folder: url!, crypto: nil)
}
it("creates folder if none exists") {
let tempDir = NSURL(fileURLWithPath: NSTemporaryDirectory())
let url = tempDir.URLByAppendingPathComponent(NSUUID().UUIDString)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
_ = SEGFileStorage(folder: url, crypto: nil)
var isDir: ObjCBool = false
let exists = NSFileManager.defaultManager().fileExistsAtPath(url.path!, isDirectory: &isDir)
expect(exists) == true
expect(Bool(isDir)) == true
}
it("persists and loads data") {
let dataIn = "segment".dataUsingEncoding(NSUTF8StringEncoding)!
storage.setData(dataIn, forKey: "mydata")
let dataOut = storage.dataForKey("mydata")
expect(dataOut) == dataIn
let strOut = String(data: dataOut!, encoding: NSUTF8StringEncoding)
expect(strOut) == "segment"
}
it("persists and loads string") {
let str = "san francisco"
storage.setString(str, forKey: "city")
expect(storage.stringForKey("city")) == str
storage.removeKey("city")
expect(storage.stringForKey("city")).to(beNil())
}
it("persists and loads array") {
let array = [
"san francisco",
"new york",
"tallinn",
]
storage.setArray(array, forKey: "cities")
expect(storage.arrayForKey("cities") as? Array<String>) == array
storage.removeKey("cities")
expect(storage.arrayForKey("cities")).to(beNil())
}
it("persists and loads dictionary") {
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
storage.setDictionary(dict, forKey: "cityMap")
expect(storage.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
storage.removeKey("cityMap")
expect(storage.dictionaryForKey("cityMap")).to(beNil())
}
it("saves file to disk and removes from disk") {
let key = "input.txt"
let url = storage.urlForKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
storage.setString("sloth", forKey: key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == true
storage.removeKey(key)
expect(url.checkResourceIsReachableAndReturnError(nil)) == false
}
it("should be binary compatible with old SDKs") {
let key = "traits.plist"
let dictIn = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
(dictIn as NSDictionary).writeToURL(storage.urlForKey(key), atomically: true)
let dictOut = storage.dictionaryForKey(key)
expect(dictOut as? [String: String]) == dictIn
}
it("should work with crypto") {
let url = SEGFileStorage.applicationSupportDirectoryURL()
let crypto = SEGAES256Crypto(password: "thetrees")
let s = SEGFileStorage(folder: url!, crypto: crypto)
let dict = [
"san francisco": "tech",
"new york": "finance",
"paris": "fashion",
]
s.setDictionary(dict, forKey: "cityMap")
expect(s.dictionaryForKey("cityMap") as? Dictionary<String, String>) == dict
s.removeKey("cityMap")
expect(s.dictionaryForKey("cityMap")).to(beNil())
}
afterEach {
storage.resetAll()
}
}
}
| 5698080d03fbc544dd9dbb8159836b1e | 30.430894 | 98 | 0.622866 | false | false | false | false |
chuhlomin/football | refs/heads/master | football/Game.swift | mit | 1 | //
// Game.swift
// football
//
// Created by Konstantin Chukhlomin on 14/02/15.
// Copyright (c) 2015 Konstantin Chukhlomin. All rights reserved.
//
import Foundation
class Game
{
let PLAYER_ALICE = 1
let PLAYER_BOB = 2
var isRun: Bool
var board: Board
var lastDot: (Int, Int)
var currentPlayer: Int
var possibleMoves: [(Int, Int)] = []
init(board: Board) {
self.board = board
currentPlayer = PLAYER_ALICE
lastDot = board.getMiddleDotIndex()
board.board[lastDot.0][lastDot.1] = currentPlayer
self.isRun = false
possibleMoves = getPossibleMoves()
}
func start() {
isRun = true
}
func stop() {
isRun = false
}
func makeMove(location: (Int, Int)) -> Bool {
if !isRun {
return false
}
let filtered = possibleMoves.filter { self.board.compareTuples($0, tupleTwo: location)}
if (filtered.count > 0) {
board.addLine(lastDot, locationTo: location, player: currentPlayer)
board.board[location.0][location.1] = currentPlayer
lastDot = location
possibleMoves = getPossibleMoves()
return true
}
return false
}
func isMovePossible(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if (destinationIsReachable(pointTo) == false) {
return false
}
if (moveHasCorrectLenght(pointFrom, pointTo: pointTo) == false) {
return false
}
if (isLineExist(pointFrom, pointTo: pointTo) == true) {
return false
}
return true
}
func moveHasCorrectLenght(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if abs(pointFrom.0 - pointTo.0) > 1 {
return false
}
if abs(pointFrom.1 - pointTo.1) > 1 {
return false
}
if (pointFrom.0 - pointTo.0 == 0 &&
pointFrom.1 - pointTo.1 == 0) {
return false
}
return true
}
func isLineExist(pointFrom: (Int, Int), pointTo: (Int, Int)) -> Bool {
if let line = board.searchLine(pointFrom, pointTo: pointTo) {
return true
}
return false
}
func getPossibleMoves() -> [(Int, Int)] {
var result: [(Int, Int)] = []
for dX in -1...1 {
for dY in -1...1 {
if dX == 0 && dY == 0 {
continue
}
let nextDot = (lastDot.0 + dX, lastDot.1 + dY)
if (isMovePossible(lastDot, pointTo: nextDot) == true) {
result.append(nextDot)
if (dX > 0 && dY > 0) {
print("↗︎")
}
if (dX > 0 && dY < 0) {
print("↘︎")
}
if (dX > 0 && dY == 0) {
print("→")
}
if (dX == 0 && dY > 0) {
print("↑")
}
if (dX == 0 && dY < 0) {
print("↓")
}
if (dX < 0 && dY > 0) {
print("↖︎")
}
if (dX < 0 && dY < 0) {
print("↙︎")
}
if (dX < 0 && dY == 0) {
print("←")
}
}
}
}
println("")
return result
}
func destinationIsReachable(destination: (Int, Int)) -> Bool {
if (board.getDot(destination) == board.UNREACHABLE) {
return false
}
return true
}
func isMoveOver(dot: Int) -> Bool {
if (dot == board.EMPTY ||
dot == board.GOAL_ALICE ||
dot == board.GOAL_BOB) {
return true
}
return false
}
func getWinner(dot: Int) -> Int? {
if dot == board.GOAL_ALICE {
return PLAYER_BOB
}
if dot == board.GOAL_BOB {
return PLAYER_ALICE
}
return nil
}
func switchPlayer() -> Int {
if currentPlayer == PLAYER_ALICE {
currentPlayer = PLAYER_BOB
} else {
currentPlayer = PLAYER_ALICE
}
return currentPlayer
}
func restart() -> Void {
currentPlayer = PLAYER_ALICE
lastDot = board.getMiddleDotIndex()
board.board[lastDot.0][lastDot.1] = currentPlayer
possibleMoves = getPossibleMoves()
self.isRun = true
}
} | 20d7535ecae2574229800c8ef6a8e0b3 | 24.952381 | 95 | 0.429241 | false | false | false | false |
prolificinteractive/Yoshi | refs/heads/master | Yoshi/Yoshi/Menus/YoshiDateSelectorMenu/YoshiDateSelectorMenuCellDataSource.swift | mit | 1 | //
// YoshiDateSelectorMenuCellDataSource.swift
// Yoshi
//
// Created by Kanglei Fang on 24/02/2017.
// Copyright © 2017 Prolific Interactive. All rights reserved.
//
/// Cell data source defining the layout for YoshiDateSelectorMenu's cell
struct YoshiDateSelectorMenuCellDataSource: YoshiReusableCellDataSource {
private let title: String
private let date: Date
private var dateFormatter: DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter
}
/// Intialize the YoshiDateSelectorMenuCellDataSource instance
///
/// - Parameters:
/// - title: Main title for the cell
/// - date: Selected Date
init(title: String, date: Date) {
self.title = title
self.date = date
}
func cellFor(tableView: UITableView) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier) ??
UITableViewCell(style: .subtitle, reuseIdentifier: YoshiDateSelectorMenuCellDataSource.reuseIdentifier)
cell.textLabel?.text = title
cell.detailTextLabel?.text = dateFormatter.string(from: date)
cell.accessoryType = .disclosureIndicator
return cell
}
}
| f6d5630905984a3570dc166ab40ab6cc | 28.955556 | 120 | 0.697329 | false | false | false | false |
wayfair/brickkit-ios | refs/heads/master | Tests/Behaviors/OffsetLayoutBehaviorTests.swift | apache-2.0 | 1 | //
// OffsetLayoutBehaviorTests.swift
// BrickKit
//
// Created by Justin Shiiba on 6/8/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import XCTest
@testable import BrickKit
class OffsetLayoutBehaviorTests: BrickFlowLayoutBaseTests {
var behavior:OffsetLayoutBehavior!
override func setUp() {
super.setUp()
layout.zIndexBehavior = .bottomUp
}
func testEmptyCollectionView() {
behavior = OffsetLayoutBehavior(dataSource: FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil))
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: []), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
XCTAssertFalse(behavior.hasInvalidatableAttributes())
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertNil(attributes?.frame)
}
func testOriginOffset() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: nil)
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 320, height: 300))
}
func testSizeOffset() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: nil, sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 0, y: 0, width: 280, height: 320))
}
func testOriginAndSizeOffset() {
let fixedOffsetLayoutBehavior = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayoutBehavior)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
}
func testOffsetAfterScroll() {
let fixedOffsetLayout = FixedOffsetLayoutBehaviorDataSource(originOffset: CGSize(width: 20, height: -40), sizeOffset: CGSize(width: -40, height: 20))
behavior = OffsetLayoutBehavior(dataSource: fixedOffsetLayout)
self.layout.behaviors.insert(behavior)
setDataSources(SectionsCollectionViewDataSource(sections: [1]), brickLayoutDataSource: FixedBrickLayoutDataSource(widthRatio: 1, height: 300))
let attributes = layout.layoutAttributesForItem(at: IndexPath(item: 0, section: 0))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
layout.collectionView?.contentOffset.y = 60
XCTAssertTrue(behavior.hasInvalidatableAttributes())
layout.invalidateLayout(with: BrickLayoutInvalidationContext(type: .scrolling))
XCTAssertEqual(attributes?.frame, CGRect(x: 20, y: -40, width: 280, height: 320))
}
}
| 0e4f251bd2d6b3dd87eaf5b428eb7241 | 50.106667 | 165 | 0.733107 | false | true | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Managers/Model/CustomEmojiManager.swift | mit | 1 | //
// CustomEmojiManager.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 11/6/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import RealmSwift
struct CustomEmojiManager {
static func sync(realm: Realm? = Realm.current) {
CustomEmoji.cachedEmojis = nil
API.current(realm: realm)?.fetch(CustomEmojiRequest()) { response in
switch response {
case .resource(let resource):
guard resource.success else {
return Log.debug(resource.errorMessage)
}
realm?.execute({ realm in
realm.delete(realm.objects(CustomEmoji.self))
let emoji = List<CustomEmoji>()
resource.customEmoji.forEach({ customEmoji in
let realmCustomEmoji = realm.create(CustomEmoji.self, value: customEmoji, update: true)
emoji.append(realmCustomEmoji)
})
realm.add(emoji, update: true)
})
case .error(let error):
switch error {
case .version:
// For Rocket.Chat < 0.75.0
oldSync(realm: realm)
default:
break
}
}
}
}
private static func oldSync(realm: Realm? = Realm.current) {
CustomEmoji.cachedEmojis = nil
API.current(realm: realm)?.fetch(CustomEmojiRequestOld()) { response in
if case let .resource(resource) = response {
guard resource.success else {
return Log.debug(resource.errorMessage)
}
realm?.execute({ realm in
realm.delete(realm.objects(CustomEmoji.self))
let emoji = List<CustomEmoji>()
resource.customEmoji.forEach({ customEmoji in
let realmCustomEmoji = realm.create(CustomEmoji.self, value: customEmoji, update: true)
emoji.append(realmCustomEmoji)
})
realm.add(emoji, update: true)
})
}
}
}
}
| f042908af9f3cd7dda496881e9dbcc7f | 31.142857 | 111 | 0.512444 | false | false | false | false |
swift102016team5/mefocus | refs/heads/master | MeFocus/MeFocus/SessionPickMonitorViewController.swift | mit | 1 | //
// SessionPickMonitorViewController.swift
// MeFocus
//
// Created by Hao on 11/28/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
class SessionPickMonitorViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
var users:[User] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
Api.shared?.fetch(
name: "",
completion: { (users:[User]) in
self.users = users
self.tableView.reloadData()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let identifier = segue.identifier {
if identifier == "Choose" {
let user = users[(tableView.indexPathForSelectedRow?.row)!]
let navigation = segue.destination as! UINavigationController
let start = navigation.topViewController as! SessionStartViewController
start.coach = user
}
}
}
}
extension SessionPickMonitorViewController:UITableViewDelegate,UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MonitorTableViewCell") as! MonitorTableViewCell
let user = users[indexPath.row]
cell.user = user
return cell
}
}
| 2c66c98286c273ca1891b49a68f42e07 | 27.987342 | 113 | 0.610044 | false | false | false | false |
vchuo/Photoasis | refs/heads/master | Photoasis/Classes/Views/ViewControllers/POHomeViewController.swift | mit | 1 | //
// POHomeViewController.swift
// ホームビューコントローラ。
//
// Created by Vernon Chuo Chian Khye on 2017/02/25.
// Copyright © 2017 Vernon Chuo Chian Khye. All rights reserved.
//
import UIKit
import RxSwift
import ChuoUtil
import Kingfisher
class POHomeViewController: UIViewController {
// MARK: - Public Properties
// MARK: - Private Properties
private let homeViewModel = POHomeViewModel()
private let disposeBag = DisposeBag()
private var photosTableView = POHomePhotosTableView()
private let homeNavigationButton = POHomeNavigationButtonView()
private let savedPhotosNavigationButtonView = POSavedPhotosNavigationButtonView()
private let loadingIndicator = UIActivityIndicatorView()
// MARK: - Lifecycle Events
override func viewDidLoad() {
super.viewDidLoad()
// フォトテーブルビュー
photosTableView.setup()
view.addSubview(photosTableView)
// ナビボタン
homeNavigationButton.buttonAction = {
if self.homeViewModel.numberOfDisplayedPhotos() != 0 {
self.photosTableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: .Top, animated: true)
}
}
savedPhotosNavigationButtonView.backgroundColor = POColors.NavigationButtonUnselectedStateBackgroundColor
savedPhotosNavigationButtonView.buttonAction = {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewControllerWithIdentifier("POSavedPhotosViewController") as? POSavedPhotosViewController {
self.presentViewController(vc, animated: false, completion: nil)
}
}
view.addSubview(homeNavigationButton)
view.addSubview(savedPhotosNavigationButtonView)
// ローディングインジケータ
loadingIndicator.activityIndicatorViewStyle = .WhiteLarge
loadingIndicator.sizeToFit()
loadingIndicator.color = POColors.HomeViewLoadingIndicatorColor
loadingIndicator.center = CUHelper.centerPointOf(view)
loadingIndicator.hidden = true
view.addSubview(loadingIndicator)
subscribeToObservables()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadingIndicator.startAnimating()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
photosTableView.delegate = self
photosTableView.dataSource = self
homeViewModel.prepareDataForViewDisplay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
ImageCache.defaultCache.clearMemoryCache()
}
// MARK: - Private Functions
/**
オブザーバブルにサブスクライブする。
*/
private func subscribeToObservables() {
// コンテンツをリロードするかを監視
homeViewModel.shouldReloadContent.asObservable().subscribeNext({ [unowned self](shouldReload) in
self.loadingIndicator.stopAnimating()
if let indexPaths = self.photosTableView.indexPathsForVisibleRows {
self.photosTableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: .Fade)
}
}).addDisposableTo(disposeBag)
// 新しいフォトが保存されたかを監視
homeViewModel.newPhotoSaved.asObservable()
.subscribeNext({ [unowned self](photoItem) in
self.executeAnimationForNewPhotoSaved(photoItem)
}).addDisposableTo(disposeBag)
// フォトが未保存されたかを監視
homeViewModel.photoUnsaved.asObservable()
.subscribeNext({ [unowned self](photoItem) in
self.executeAnimationForPhotoUnsaved(photoItem)
}).addDisposableTo(disposeBag)
}
/**
新しいフォトが保存されたアニメーションを実行。
- parameter photoItem: 新しい保存されたフォト
*/
private func executeAnimationForNewPhotoSaved(photoItem: POPhotoDisplayItem) {
self.photosTableView.visibleCells.flatMap{ $0 as? POHomeTableViewCell }.forEach { cell in
if cell.recycledCellData.imageURL == photoItem.photoURL {
// フォト保存する時にアニメーションするイメージビュー
let animatedImageView = UIImageView()
if let image = cell.photo.image {
animatedImageView.image = image
} else {
animatedImageView.backgroundColor = POColors.NoImageBackgroundColor
}
animatedImageView.bounds.size.width = POConstants.HomeTableViewCellPhotoWidth
animatedImageView.layer.anchorPoint = CGPointZero
animatedImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
animatedImageView.clipsToBounds = true
animatedImageView.bounds.size = cell.photo.bounds.size
animatedImageView.frame.origin = cell.convertPoint(cell.photo.frame.origin, toView: self.view)
animatedImageView.userInteractionEnabled = false
self.view.addSubview(animatedImageView)
CUHelper.animateKeyframes(
POConstants.HomeViewPhotoSavedAnimationDuration,
options: .CalculationModeCubic,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1) {
animatedImageView.center = self.savedPhotosNavigationButtonView.center
}
UIView.addKeyframeWithRelativeStartTime(0.2, relativeDuration: 0.7) {
animatedImageView.transform = CGAffineTransformMakeScale(0.1, 0.1)
}
UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.4) {
animatedImageView.alpha = 0.4
}
UIView.addKeyframeWithRelativeStartTime(0.9, relativeDuration: 0.1) {
animatedImageView.transform = CGAffineTransformMakeScale(0.01, 0.01)
animatedImageView.alpha = 0
}
}
) { _ in
self.savedPhotosNavigationButtonView.executePhotoSavedAnimation()
animatedImageView.removeFromSuperview()
}
}
}
self.homeViewModel.updateNewPhotoSaved(nil)
}
/**
フォトが未保存されたアニメーションを実行。
- parameter photoItem: 未保存されたフォト
*/
private func executeAnimationForPhotoUnsaved(photoItem: POPhotoDisplayItem) {
self.photosTableView.visibleCells.flatMap{ $0 as? POHomeTableViewCell }.forEach { cell in
if cell.recycledCellData.imageURL == photoItem.photoURL {
// フォトが未保存する時にアニメーションするイメージビュー
let animatedImageView = UIImageView()
if let image = cell.photo.image {
animatedImageView.image = image
} else {
animatedImageView.backgroundColor = POColors.NoImageBackgroundColor
}
animatedImageView.bounds.size.width = POConstants.HomeTableViewCellPhotoWidth
animatedImageView.layer.anchorPoint = CGPointZero
animatedImageView.layer.cornerRadius = POConstants.HomeTableViewCellPhotoCornerRadius
animatedImageView.clipsToBounds = true
animatedImageView.bounds.size = cell.photo.bounds.size
animatedImageView.center = self.savedPhotosNavigationButtonView.center
animatedImageView.transform = CGAffineTransformMakeScale(0.01, 0.01)
animatedImageView.userInteractionEnabled = false
let photoViewOrigin = cell.convertPoint(cell.photo.frame.origin, toView: self.view)
self.view.addSubview(animatedImageView)
CUHelper.animateKeyframes(
POConstants.HomeViewPhotoUnsavedAnimationDuration,
animations: {
UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 1.0) {
animatedImageView.frame.origin = photoViewOrigin
animatedImageView.transform = CGAffineTransformMakeScale(1, 1)
}
UIView.addKeyframeWithRelativeStartTime(0.85, relativeDuration: 0.15) {
animatedImageView.alpha = 0
}
}
) { _ in animatedImageView.removeFromSuperview() }
}
}
self.homeViewModel.updatePhotoUnsaved(nil)
}
}
extension POHomeViewController: UITableViewDelegate {}
extension POHomeViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homeViewModel.numberOfDisplayedPhotos()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(POStrings.HomeTableViewCellIdentifier) as! POHomeTableViewCell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
guard let cell = cell as? POHomeTableViewCell else {
return
}
cell.photo.image = nil
cell.itemIndex = indexPath.row
cell.updateSerialOperationQueueWith {
guard let photo = self.homeViewModel.getDisplayedPhotoAt(indexPath.row) else {
return
}
let photoURL = photo.photoURL,
photoAspectRatio = photo.photoAspectRatio,
isSaved = photo.isSaved
cell.recycledCellData.imageURL = photoURL
cell.photo.photoAuthorName = photo.authorName
CUHelper.executeOnBackgroundThread {
let photoHeight = POConstants.HomeTableViewCellPhotoWidth / CGFloat(photoAspectRatio),
cellHeight = photoHeight + POConstants.HomeTableViewCellVerticalContentInset * 2
CUImageManager.loadRecycledCellImageFrom(
photoURL,
imageView: cell.photo,
recycledCellData: cell.recycledCellData,
noImageBackgroundColor: POColors.NoImageBackgroundColor,
fadeIn: true
)
CUHelper.executeOnMainThread {
cell.photo.updateSize(height: photoHeight)
cell.bounds.size.height = cellHeight
cell.toggleSaveButton.defaultBackgroundColor = isSaved ?
POColors.HomeTableViewCellToggleSaveButtonSavedStateDefaultBackgroundColor :
POColors.HomeTableViewCellToggleSaveButtonNotSavedStateDefaultBackgroundColor
cell.toggleSaveButton.title = isSaved ?
POStrings.HomeTableViewCellToggleSaveButtonSavedText :
POStrings.HomeTableViewCellToggleSaveButtonSaveText
}
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return getHeightForRow(indexPath.row)
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return getHeightForRow(indexPath.row)
}
/**
行の高さを返す。
- parameter row: 行インデックス
- returns: 行の高さ
*/
private func getHeightForRow(row: Int) -> CGFloat {
if let photo = homeViewModel.getDisplayedPhotoAt(row) {
return POConstants.HomeTableViewCellPhotoWidth / CGFloat(photo.photoAspectRatio)
+ POConstants.HomeTableViewCellVerticalContentInset * 2
}
return 0
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
headerView.bounds.size = POConstants.HomeTableViewHeaderViewSize
headerView.frame.origin = CGPointZero
headerView.userInteractionEnabled = false
return headerView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return POConstants.HomeTableViewHeaderViewSize.height
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.bounds.size = POConstants.HomeTableViewFooterViewSize
footerView.frame.origin = CGPointZero
footerView.userInteractionEnabled = false
return footerView
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return POConstants.HomeTableViewFooterViewSize.height
}
}
| 869e6994cbc61561e00b92a98f740ea8 | 41.859477 | 139 | 0.632101 | false | false | false | false |
ludwigschubert/cs376-project | refs/heads/master | DesktopHeartRateMonitor/DesktopHeartRateMonitor/FFT.swift | mit | 3 | // FFT.swift
//
// Copyright (c) 2014–2015 Mattt Thompson (http://mattt.me)
//
// 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 Accelerate
// MARK: Fast Fourier Transform
public func fft(_ input: [Float]) -> [Float] {
var real = [Float](input)
var imaginary = [Float](repeating: 0.0, count: input.count)
var splitComplex = DSPSplitComplex(realp: &real, imagp: &imaginary)
let length = vDSP_Length(floor(log2(Float(input.count))))
let radix = FFTRadix(kFFTRadix2)
let weights = vDSP_create_fftsetup(length, radix)
vDSP_fft_zip(weights!, &splitComplex, 1, length, FFTDirection(FFT_FORWARD))
var magnitudes = [Float](repeating: 0.0, count: input.count)
vDSP_zvmags(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count))
var normalizedMagnitudes = [Float](repeating: 0.0, count: input.count)
vDSP_vsmul(sqrt(magnitudes), 1, [2.0 / Float(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count))
vDSP_destroy_fftsetup(weights)
return normalizedMagnitudes
}
public func fft(_ input: [Double]) -> [Double] {
var real = [Double](input)
var imaginary = [Double](repeating: 0.0, count: input.count)
var splitComplex = DSPDoubleSplitComplex(realp: &real, imagp: &imaginary)
let length = vDSP_Length(floor(log2(Float(input.count))))
let radix = FFTRadix(kFFTRadix2)
let weights = vDSP_create_fftsetupD(length, radix)
vDSP_fft_zipD(weights!, &splitComplex, 1, length, FFTDirection(FFT_FORWARD))
var magnitudes = [Double](repeating: 0.0, count: input.count)
vDSP_zvmagsD(&splitComplex, 1, &magnitudes, 1, vDSP_Length(input.count))
var normalizedMagnitudes = [Double](repeating: 0.0, count: input.count)
vDSP_vsmulD(sqrt(magnitudes), 1, [2.0 / Double(input.count)], &normalizedMagnitudes, 1, vDSP_Length(input.count))
vDSP_destroy_fftsetupD(weights)
return normalizedMagnitudes
}
| 33bfead7a84524d79c354d246ca1f81b | 42.686567 | 117 | 0.724291 | false | false | false | false |
fnky/drawling-components | refs/heads/master | DrawlingComponents/ViewController.swift | gpl-2.0 | 1 | //
// ViewController.swift
// DrawlingComponents
//
// Created by Christian Petersen
// Copyright (c) 2015 Reversebox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var scroller = RBScrollView(frame: CGRectMake(0, 100, 640, 80))
var smallScroller: RBScrollView = RBScrollView(frame: CGRectMake(0, 200, 640, 80))
override func viewDidLoad() {
scroller.backgroundColor = UIColor.clearColor()
smallScroller.backgroundColor = UIColor.clearColor()
//scroller.contentSize = CGSizeMake(1136, 64)
for (var i = 0; i < 10; i++) {
// (current * (size + margin) + offset)
var avatar: RBAvatarView = RBAvatarView(frame: CGRectMake(CGFloat(i * 48), 16, 48, 48),
image: UIImage(named: "avatarStd")!)
//(size + (size / 2)) + offset
var avatarSmall: RBAvatarView = RBAvatarView(frame: CGRectMake(CGFloat(i * 32), 16, 32, 32),
image: UIImage(named: "avatarStd")!)
let rotation: CGFloat = ( i % 2 == 0) ? 0.00 : -0.00
avatar.rotation = rotation
avatarSmall.rotation = rotation
scroller.addSubview(avatar)
smallScroller.addSubview(avatarSmall)
}
self.view.addSubview(scroller)
self.view.addSubview(smallScroller)
super.viewDidLoad()
}
override func viewDidLayoutSubviews() {
}
}
| 2c8d56dafe24dda5040b2bc4e825aa32 | 25.538462 | 98 | 0.636957 | false | false | false | false |
Ivacker/swift | refs/heads/master | validation-test/stdlib/MicroStdlib.swift | apache-2.0 | 10 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-build-swift -c -force-single-frontend-invocation -parse-as-library -parse-stdlib -module-name Swift -emit-module -emit-module-path %t/Swift.swiftmodule -o %t/Swift.o %s
// RUN: ls %t/Swift.swiftmodule
// RUN: ls %t/Swift.swiftdoc
// RUN: ls %t/Swift.o
// REQUIRES: executable_test
//
// A bare-bones Swift standard library
//
public typealias IntegerLiteralType = Int
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
public protocol _BuiltinIntegerLiteralConvertible {
init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType)
}
public protocol _BuiltinFloatLiteralConvertible {
init(_builtinFloatLiteral value: _MaxBuiltinFloatType)
}
public protocol IntegerLiteralConvertible {
typealias IntegerLiteralType : _BuiltinIntegerLiteralConvertible
init(integerLiteral value: IntegerLiteralType)
}
public protocol FloatLiteralConvertible {
typealias FloatLiteralType : _BuiltinFloatLiteralConvertible
init(floatLiteral value: FloatLiteralType)
}
public struct Int : _BuiltinIntegerLiteralConvertible, IntegerLiteralConvertible {
var value: Builtin.Word
public init() {
self = 0
}
public init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {
let builtinValue = Builtin.truncOrBitCast_Int2048_Word(value)
self.value = builtinValue
}
public init(integerLiteral value: IntegerLiteralType) {
self = value
}
}
public struct Int32 : _BuiltinIntegerLiteralConvertible, IntegerLiteralConvertible {
var value: Builtin.Int32
public init() {
self.init(integerLiteral: 0)
}
public init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {
let builtinValue = Builtin.truncOrBitCast_Int2048_Int32(value)
self.value = builtinValue
}
public init(integerLiteral value: IntegerLiteralType) {
let builtinValue = Builtin.truncOrBitCast_Word_Int32(value.value)
self.value = builtinValue
}
}
public struct Int8 : _BuiltinIntegerLiteralConvertible, IntegerLiteralConvertible {
var value: Builtin.Int8
public init() {
self.init(integerLiteral: 0)
}
public init(_builtinIntegerLiteral value: _MaxBuiltinIntegerType) {
let builtinValue = Builtin.truncOrBitCast_Int2048_Int8(value)
self.value = builtinValue
}
public init(integerLiteral value: IntegerLiteralType) {
let builtinValue = Builtin.truncOrBitCast_Word_Int8(value.value)
self.value = builtinValue
}
}
public struct UnsafeMutablePointer<T> {
var value: Builtin.RawPointer
public init() {
self.value = Builtin.inttoptr_Word(0.value)
}
}
public typealias CInt = Int32
public typealias CChar = Int8
//public var C_ARGC: CInt = CInt()
//public var C_ARGV: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> = UnsafeMutablePointer()
| 36e05c417f2a4d7ee8df1f11719f2469 | 29.923077 | 184 | 0.764748 | false | false | false | false |
qinting513/WeiBo-Swift | refs/heads/master | WeiBo_V3/WeiBo/Classes/View[视图跟控制器]/Main/OAuth/WBOAuthViewController.swift | apache-2.0 | 1 | //
// WBOAuthViewController.swift
// WeiBo
//
// Created by Qinting on 16/9/8.
// Copyright © 2016年 Qinting. All rights reserved.
//
import UIKit
import SVProgressHUD
//通过webView登录
class WBOAuthViewController: UIViewController {
private lazy var webView = UIWebView()
override func loadView() {
view = webView
webView.delegate = self
webView.scrollView.isScrollEnabled = false
view.backgroundColor = UIColor.white()
title = "登录新浪微博"
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", normalColor:UIColor.black(), highlightedColor: UIColor.orange(), target: self, action: #selector(close))
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
}
override func viewDidLoad() {
super.viewDidLoad()
let urlStr = "https://api.weibo.com/oauth2/authorize?redirect_uri=\(WBRedirectURI)&client_id=\(WBAppKey)"
guard let url = URL.init(string: urlStr) else {
return
}
webView.loadRequest(URLRequest.init(url: url))
}
@objc private func close(){
SVProgressHUD.dismiss()
dismiss(animated: true, completion: nil)
}
/// 自动填充 - webView的注入 直接通过 js 修改‘本地浏览器中的缓存’的页面内容
/// 点击登录 执行 submit() 将本地数据提交给服务器 注意啊 有分号区别
//js 语句一定要写对
@objc private func autoFill() {
let js = "document.getElementById('userId').value = '[email protected]' ; " + "document.getElementById('passwd').value = 'Chunwoaini7758'; "
webView.stringByEvaluatingJavaScript(from: js)
}
}
extension WBOAuthViewController : UIWebViewDelegate {
/// 是否加载request
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//确认思路
//1.如果请求地址包含 http://baidu.com 不加载页面 / 否则加载页面
print("加载请求---\(request.url?.absoluteString)")
if request.url?.absoluteString?.hasPrefix(WBRedirectURI) == false {
return true
}
//2. 如果回调地址的 '查询' 字符串中查找 'code=' query 就是URL中 ‘?’后面的所有部分
if request.url?.query?.hasPrefix("code=" ) == false{
print("取消授权")
close()
return false
}
//3.如果有 则授权成功,如果没有授权失败
//来到此处 url中肯定包含 ‘ code =’
let str = (request.url?.absoluteString)! as NSString
var code : String?
if str.length > 0 {
let ra = str.range(of: "code=")
code = str.substring(from: (ra.location + ra.length) ?? 0 )
}
// let code = request.url?.absoluteString?.substring(from:"code=".endIndex) ?? ""
//4.用授权码获取accessToken
print("授权码:\(code)")
guard code != "" else {
print("授权码为空:\(code)")
close()
return false
}
//能够到这一步 说明code是非空的字符串
WBNetworkManager.shared.loadAccessToken(code: code!) { (isSuccess) in
if !isSuccess {
SVProgressHUD.showInfo(withStatus: "网络请求失败")
}else{
//登录成功,通过通知跳转界面,关闭窗口
NotificationCenter.default().post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
self.close()
return
}
}
return false
}
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
func webView(_ webView: UIWebView, didFailLoadWithError error: NSError?) {
SVProgressHUD.dismiss()
}
}
| 517ce85887d877c1772f9574ce4a07c2 | 31.903509 | 176 | 0.589709 | false | false | false | false |
VladiMihaylenko/omim | refs/heads/master | iphone/Maps/Classes/Components/ExpandableReviewView/ExpandableReviewView.swift | apache-2.0 | 2 | import UIKit
final class ExpandableReviewView: UIView {
var contentLabel: UILabel = {
let label = UILabel(frame: .zero)
label.numberOfLines = 0
label.clipsToBounds = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var moreLabel: UILabel = {
let label = UILabel(frame: .zero)
label.clipsToBounds = true
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var moreLabelZeroHeight: NSLayoutConstraint!
private var settings: ExpandableReviewSettings = ExpandableReviewSettings()
private var isExpanded = false
private var onUpdateHandler: (() -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
configureContent()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureContent()
}
override func layoutSubviews() {
super.layoutSubviews()
updateRepresentation()
}
func configureContent() {
self.addSubview(contentLabel)
self.addSubview(moreLabel)
let labels: [String: Any] = ["contentLabel": contentLabel, "moreLabel": moreLabel]
var contentConstraints: [NSLayoutConstraint] = []
let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|[contentLabel][moreLabel]",
metrics: nil,
views: labels)
contentConstraints += verticalConstraints
let moreBottomConstraint = bottomAnchor.constraint(equalTo: moreLabel.bottomAnchor)
moreBottomConstraint.priority = .defaultLow
contentConstraints.append(moreBottomConstraint)
let contentHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[contentLabel]|",
metrics: nil,
views: labels)
contentConstraints += contentHorizontalConstraints
let moreHorizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|[moreLabel]|",
metrics: nil,
views: labels)
contentConstraints += moreHorizontalConstraints
NSLayoutConstraint.activate(contentConstraints)
moreLabelZeroHeight = moreLabel.heightAnchor.constraint(equalToConstant: 0.0)
apply(settings: settings)
layer.backgroundColor = UIColor.clear.cgColor
isOpaque = true
gestureRecognizers = nil
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap)))
}
func apply(settings: ExpandableReviewSettings) {
self.settings = settings
self.contentLabel.textColor = settings.textColor
self.contentLabel.font = settings.textFont
self.moreLabel.font = settings.textFont
self.moreLabel.textColor = settings.expandTextColor
self.moreLabel.text = settings.expandText
}
override func mwm_refreshUI() {
super.mwm_refreshUI()
settings.textColor = settings.textColor.opposite()
settings.expandTextColor = settings.expandTextColor.opposite()
}
func configure(text: String, isExpanded: Bool, onUpdate: @escaping () -> Void) {
contentLabel.text = text
self.isExpanded = isExpanded
contentLabel.numberOfLines = isExpanded ? 0 : settings.numberOfCompactLines
onUpdateHandler = onUpdate
}
@objc private func onTap() {
if !isExpanded {
isExpanded = true
updateRepresentation()
contentLabel.numberOfLines = 0
onUpdateHandler?()
}
}
func updateRepresentation() {
if let text = contentLabel.text, !text.isEmpty, !isExpanded {
let height = (text as NSString).boundingRect(with: CGSize(width: contentLabel.bounds.width,
height: .greatestFiniteMagnitude),
options: .usesLineFragmentOrigin,
attributes: [.font: contentLabel.font],
context: nil).height
if height > contentLabel.bounds.height {
moreLabelZeroHeight.isActive = false
return
}
}
moreLabelZeroHeight.isActive = true
}
}
| 98eee83b00ec31352e5a85a50f5f813a | 37.078261 | 110 | 0.629367 | false | false | false | false |
intel-isl/MiDaS | refs/heads/master | mobile/ios/Midas/ViewControllers/ViewController.swift | mit | 1 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AVFoundation
import UIKit
import os
public struct PixelData {
var a: UInt8
var r: UInt8
var g: UInt8
var b: UInt8
}
extension UIImage {
convenience init?(pixels: [PixelData], width: Int, height: Int) {
guard width > 0 && height > 0, pixels.count == width * height else { return nil }
var data = pixels
guard let providerRef = CGDataProvider(data: Data(bytes: &data, count: data.count * MemoryLayout<PixelData>.size) as CFData)
else { return nil }
guard let cgim = CGImage(
width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: width * MemoryLayout<PixelData>.size,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue),
provider: providerRef,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent)
else { return nil }
self.init(cgImage: cgim)
}
}
class ViewController: UIViewController {
// MARK: Storyboards Connections
@IBOutlet weak var previewView: PreviewView!
//@IBOutlet weak var overlayView: OverlayView!
@IBOutlet weak var overlayView: UIImageView!
private var imageView : UIImageView = UIImageView(frame:CGRect(x:0, y:0, width:400, height:400))
private var imageViewInitialized: Bool = false
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var cameraUnavailableLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var threadCountLabel: UILabel!
@IBOutlet weak var threadCountStepper: UIStepper!
@IBOutlet weak var delegatesControl: UISegmentedControl!
// MARK: ModelDataHandler traits
var threadCount: Int = Constants.defaultThreadCount
var delegate: Delegates = Constants.defaultDelegate
// MARK: Result Variables
// Inferenced data to render.
private var inferencedData: InferencedData?
// Minimum score to render the result.
private let minimumScore: Float = 0.5
private var avg_latency: Double = 0.0
// Relative location of `overlayView` to `previewView`.
private var overlayViewFrame: CGRect?
private var previewViewFrame: CGRect?
// MARK: Controllers that manage functionality
// Handles all the camera related functionality
private lazy var cameraCapture = CameraFeedManager(previewView: previewView)
// Handles all data preprocessing and makes calls to run inference.
private var modelDataHandler: ModelDataHandler?
// MARK: View Handling Methods
override func viewDidLoad() {
super.viewDidLoad()
do {
modelDataHandler = try ModelDataHandler()
} catch let error {
fatalError(error.localizedDescription)
}
cameraCapture.delegate = self
tableView.delegate = self
tableView.dataSource = self
// MARK: UI Initialization
// Setup thread count stepper with white color.
// https://forums.developer.apple.com/thread/121495
threadCountStepper.setDecrementImage(
threadCountStepper.decrementImage(for: .normal), for: .normal)
threadCountStepper.setIncrementImage(
threadCountStepper.incrementImage(for: .normal), for: .normal)
// Setup initial stepper value and its label.
threadCountStepper.value = Double(Constants.defaultThreadCount)
threadCountLabel.text = Constants.defaultThreadCount.description
// Setup segmented controller's color.
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.lightGray],
for: .normal)
delegatesControl.setTitleTextAttributes(
[NSAttributedString.Key.foregroundColor: UIColor.black],
for: .selected)
// Remove existing segments to initialize it with `Delegates` entries.
delegatesControl.removeAllSegments()
Delegates.allCases.forEach { delegate in
delegatesControl.insertSegment(
withTitle: delegate.description,
at: delegate.rawValue,
animated: false)
}
delegatesControl.selectedSegmentIndex = 0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cameraCapture.checkCameraConfigurationAndStartSession()
}
override func viewWillDisappear(_ animated: Bool) {
cameraCapture.stopSession()
}
override func viewDidLayoutSubviews() {
overlayViewFrame = overlayView.frame
previewViewFrame = previewView.frame
}
// MARK: Button Actions
@IBAction func didChangeThreadCount(_ sender: UIStepper) {
let changedCount = Int(sender.value)
if threadCountLabel.text == changedCount.description {
return
}
do {
modelDataHandler = try ModelDataHandler(threadCount: changedCount, delegate: delegate)
} catch let error {
fatalError(error.localizedDescription)
}
threadCount = changedCount
threadCountLabel.text = changedCount.description
os_log("Thread count is changed to: %d", threadCount)
}
@IBAction func didChangeDelegate(_ sender: UISegmentedControl) {
guard let changedDelegate = Delegates(rawValue: delegatesControl.selectedSegmentIndex) else {
fatalError("Unexpected value from delegates segemented controller.")
}
do {
modelDataHandler = try ModelDataHandler(threadCount: threadCount, delegate: changedDelegate)
} catch let error {
fatalError(error.localizedDescription)
}
delegate = changedDelegate
os_log("Delegate is changed to: %s", delegate.description)
}
@IBAction func didTapResumeButton(_ sender: Any) {
cameraCapture.resumeInterruptedSession { complete in
if complete {
self.resumeButton.isHidden = true
self.cameraUnavailableLabel.isHidden = true
} else {
self.presentUnableToResumeSessionAlert()
}
}
}
func presentUnableToResumeSessionAlert() {
let alert = UIAlertController(
title: "Unable to Resume Session",
message: "There was an error while attempting to resume session.",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
// MARK: - CameraFeedManagerDelegate Methods
extension ViewController: CameraFeedManagerDelegate {
func cameraFeedManager(_ manager: CameraFeedManager, didOutput pixelBuffer: CVPixelBuffer) {
runModel(on: pixelBuffer)
}
// MARK: Session Handling Alerts
func cameraFeedManagerDidEncounterSessionRunTimeError(_ manager: CameraFeedManager) {
// Handles session run time error by updating the UI and providing a button if session can be
// manually resumed.
self.resumeButton.isHidden = false
}
func cameraFeedManager(
_ manager: CameraFeedManager, sessionWasInterrupted canResumeManually: Bool
) {
// Updates the UI when session is interupted.
if canResumeManually {
self.resumeButton.isHidden = false
} else {
self.cameraUnavailableLabel.isHidden = false
}
}
func cameraFeedManagerDidEndSessionInterruption(_ manager: CameraFeedManager) {
// Updates UI once session interruption has ended.
self.cameraUnavailableLabel.isHidden = true
self.resumeButton.isHidden = true
}
func presentVideoConfigurationErrorAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Confirguration Failed", message: "Configuration of camera has failed.",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
func presentCameraPermissionsDeniedAlert(_ manager: CameraFeedManager) {
let alertController = UIAlertController(
title: "Camera Permissions Denied",
message:
"Camera permissions have been denied for this app. You can change this by going to Settings",
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { action in
if let url = URL.init(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
present(alertController, animated: true, completion: nil)
}
@objc func runModel(on pixelBuffer: CVPixelBuffer) {
guard let overlayViewFrame = overlayViewFrame, let previewViewFrame = previewViewFrame
else {
return
}
// To put `overlayView` area as model input, transform `overlayViewFrame` following transform
// from `previewView` to `pixelBuffer`. `previewView` area is transformed to fit in
// `pixelBuffer`, because `pixelBuffer` as a camera output is resized to fill `previewView`.
// https://developer.apple.com/documentation/avfoundation/avlayervideogravity/1385607-resizeaspectfill
let modelInputRange = overlayViewFrame.applying(
previewViewFrame.size.transformKeepAspect(toFitIn: pixelBuffer.size))
// Run Midas model.
guard
let (result, width, height, times) = self.modelDataHandler?.runMidas(
on: pixelBuffer,
from: modelInputRange,
to: overlayViewFrame.size)
else {
os_log("Cannot get inference result.", type: .error)
return
}
if avg_latency == 0 {
avg_latency = times.inference
} else {
avg_latency = times.inference*0.1 + avg_latency*0.9
}
// Udpate `inferencedData` to render data in `tableView`.
inferencedData = InferencedData(score: Float(avg_latency), times: times)
//let height = 256
//let width = 256
let outputs = result
let outputs_size = width * height;
var multiplier : Float = 1.0;
let max_val : Float = outputs.max() ?? 0
let min_val : Float = outputs.min() ?? 0
if((max_val - min_val) > 0) {
multiplier = 255 / (max_val - min_val);
}
// Draw result.
DispatchQueue.main.async {
self.tableView.reloadData()
var pixels: [PixelData] = .init(repeating: .init(a: 255, r: 0, g: 0, b: 0), count: width * height)
for i in pixels.indices {
//if(i < 1000)
//{
let val = UInt8((outputs[i] - min_val) * multiplier)
pixels[i].r = val
pixels[i].g = val
pixels[i].b = val
//}
}
/*
pixels[i].a = 255
pixels[i].r = .random(in: 0...255)
pixels[i].g = .random(in: 0...255)
pixels[i].b = .random(in: 0...255)
}
*/
DispatchQueue.main.async {
let image = UIImage(pixels: pixels, width: width, height: height)
self.imageView.image = image
if (self.imageViewInitialized == false) {
self.imageViewInitialized = true
self.overlayView.addSubview(self.imageView)
self.overlayView.setNeedsDisplay()
}
}
/*
let image = UIImage(pixels: pixels, width: width, height: height)
var imageView : UIImageView
imageView = UIImageView(frame:CGRect(x:0, y:0, width:400, height:400));
imageView.image = image
self.overlayView.addSubview(imageView)
self.overlayView.setNeedsDisplay()
*/
}
}
/*
func drawResult(of result: Result) {
self.overlayView.dots = result.dots
self.overlayView.lines = result.lines
self.overlayView.setNeedsDisplay()
}
func clearResult() {
self.overlayView.clear()
self.overlayView.setNeedsDisplay()
}
*/
}
// MARK: - TableViewDelegate, TableViewDataSource Methods
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return InferenceSections.allCases.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let section = InferenceSections(rawValue: section) else {
return 0
}
return section.subcaseCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell") as! InfoCell
guard let section = InferenceSections(rawValue: indexPath.section) else {
return cell
}
guard let data = inferencedData else { return cell }
var fieldName: String
var info: String
switch section {
case .Score:
fieldName = section.description
info = String(format: "%.3f", data.score)
case .Time:
guard let row = ProcessingTimes(rawValue: indexPath.row) else {
return cell
}
var time: Double
switch row {
case .InferenceTime:
time = data.times.inference
}
fieldName = row.description
info = String(format: "%.2fms", time)
}
cell.fieldNameLabel.text = fieldName
cell.infoLabel.text = info
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let section = InferenceSections(rawValue: indexPath.section) else {
return 0
}
var height = Traits.normalCellHeight
if indexPath.row == section.subcaseCount - 1 {
height = Traits.separatorCellHeight + Traits.bottomSpacing
}
return height
}
}
// MARK: - Private enums
/// UI coinstraint values
fileprivate enum Traits {
static let normalCellHeight: CGFloat = 35.0
static let separatorCellHeight: CGFloat = 25.0
static let bottomSpacing: CGFloat = 30.0
}
fileprivate struct InferencedData {
var score: Float
var times: Times
}
/// Type of sections in Info Cell
fileprivate enum InferenceSections: Int, CaseIterable {
case Score
case Time
var description: String {
switch self {
case .Score:
return "Average"
case .Time:
return "Processing Time"
}
}
var subcaseCount: Int {
switch self {
case .Score:
return 1
case .Time:
return ProcessingTimes.allCases.count
}
}
}
/// Type of processing times in Time section in Info Cell
fileprivate enum ProcessingTimes: Int, CaseIterable {
case InferenceTime
var description: String {
switch self {
case .InferenceTime:
return "Inference Time"
}
}
}
| 3d04e0139f653f647ba5bed065819ad0 | 30.102249 | 132 | 0.679598 | false | false | false | false |
richardpiazza/XCServerCoreData | refs/heads/master | Tests/CoreDataVersion.swift | mit | 1 | import Foundation
import CoreData
import XCServerCoreData
class CoreDataVersion {
public static var v_1_2_0 = CoreDataVersion(with: "XCServerCoreData_1.2.0")
public static var v_1_2_0_empty = CoreDataVersion(with: "XCServerCoreData_1.2.0_empty")
public static var v_2_0_0_empty = CoreDataVersion(with: "XCServerCoreData_2.0.0_empty")
public static var v_2_0_1 = CoreDataVersion(with: "XCServerCoreData_2.0.1")
public var resource: String
public init(with resource: String) {
self.resource = resource
}
static var documentsDirectory: URL {
do {
return try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
} catch {
fatalError("Failed to find documents directory")
}
}
static var tempDirectory: URL {
return documentsDirectory.appendingPathComponent("temp")
}
static var baseResource: String = "XCServerCoreData"
static var documentsSQLite: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.sqlite.rawValue)
}
static var documentsSHM: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.shm.rawValue)
}
static var documentsWAL: URL {
return documentsDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.wal.rawValue)
}
static var tempSQLite: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.sqlite.rawValue)
}
static var tempSHM: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.shm.rawValue)
}
static var tempWAL: URL {
return tempDirectory.appendingPathComponent(baseResource).appendingPathExtension(CoreDataExtension.wal.rawValue)
}
static func overwriteSQL(withVersion version: CoreDataVersion) -> Bool {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: tempDirectory.path) {
do {
print("Creating TEMP directory")
try fileManager.createDirectory(at: tempDirectory, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
return false
}
}
print("Clearing TEMP directory")
do {
if fileManager.fileExists(atPath: tempSQLite.path) {
try fileManager.removeItem(at: tempSQLite)
}
if fileManager.fileExists(atPath: tempSHM.path) {
try fileManager.removeItem(at: tempSHM)
}
if fileManager.fileExists(atPath: tempWAL.path) {
try fileManager.removeItem(at: tempWAL)
}
} catch {
print(error)
return false
}
let replacementOptions = FileManager.ItemReplacementOptions()
print("Copying/Overwriting SQLite File")
do {
try fileManager.copyItem(at: version.bundleSQLite!, to: tempSQLite)
try fileManager.replaceItem(at: documentsSQLite, withItemAt: tempSQLite, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
return false
}
if let url = version.bundleSHM {
print("Copying/Overwriting SHM File")
do {
try fileManager.copyItem(at: url, to: tempSHM)
try fileManager.replaceItem(at: documentsSHM, withItemAt: tempSHM, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
}
}
if let url = version.bundleWAL {
print("Copying/Overwriting WAL File")
do {
try fileManager.copyItem(at: url, to: tempWAL)
try fileManager.replaceItem(at: documentsWAL, withItemAt: tempWAL, backupItemName: nil, options: replacementOptions, resultingItemURL: nil)
} catch {
print(error)
}
}
return true
}
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
static var persistentContainer: NSPersistentContainer {
let fileManager = FileManager.default
var modelURL: URL
let bundle = Bundle(for: XCServerCoreData.self)
if let url = bundle.url(forResource: "XCServerCoreData", withExtension: "momd") {
modelURL = url
} else {
modelURL = URL(fileURLWithPath: fileManager.currentDirectoryPath).appendingPathComponent("Tests").appendingPathComponent("XCServerCoreData.momd")
}
guard fileManager.fileExists(atPath: modelURL.path) else {
fatalError("Failed to locate XCServerCoreData.momd\n\(modelURL.path)")
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Failed to load XCServerCoreData Model")
}
var storeURL: URL
do {
var searchPathDirectory: FileManager.SearchPathDirectory
#if os(tvOS)
searchPathDirectory = .cachesDirectory
#else
searchPathDirectory = .documentDirectory
#endif
storeURL = try FileManager.default.url(for: searchPathDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("XCServerCoreData.sqlite")
} catch {
print(error)
fatalError(error.localizedDescription)
}
let instance = NSPersistentContainer(name: "XCServerCoreData", managedObjectModel: model)
let description = NSPersistentStoreDescription(url: storeURL)
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
instance.persistentStoreDescriptions = [description]
instance.viewContext.automaticallyMergesChangesFromParent = true
return instance
}
}
enum CoreDataExtension: String {
case sqlite = "sqlite"
case shm = "sqlite-shm"
case wal = "sqlite-wal"
}
extension CoreDataVersion {
func url(for res: String, extension ext: CoreDataExtension) -> URL? {
let bundle = Bundle(for: CoreDataVersion.self)
if let url = bundle.url(forResource: res, withExtension: ext.rawValue) {
return url
}
let path = FileManager.default.currentDirectoryPath
let url = URL(fileURLWithPath: path).appendingPathComponent("Tests").appendingPathComponent(res).appendingPathExtension(ext.rawValue)
if !FileManager.default.fileExists(atPath: url.path) {
print("Unable to locate resource \(res).\(ext.rawValue)")
return nil
}
return url
}
var bundleSQLite: URL? {
return self.url(for: resource, extension: .sqlite)
}
var bundleSHM: URL? {
return self.url(for: resource, extension: .shm)
}
var bundleWAL: URL? {
return self.url(for: resource, extension: .wal)
}
}
| e66a1f81389442bf976f7e37da6c9b13 | 36.659898 | 182 | 0.633509 | false | false | false | false |
BennyKJohnson/OpenCloudKit | refs/heads/master | Sources/Bridging.swift | mit | 1 | //
// Bridging.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 20/07/2016.
//
//
import Foundation
public protocol _OCKBridgable {
associatedtype ObjectType
func bridge() -> ObjectType
}
public protocol CKNumberValueType: CKRecordValue {}
extension CKNumberValueType where Self: _OCKBridgable, Self.ObjectType == NSNumber {
public var recordFieldDictionary: [String: Any] {
return ["value": self.bridge()]
}
}
extension String: _OCKBridgable {
public typealias ObjectType = NSString
public func bridge() -> NSString {
return NSString(string: self)
}
}
extension Int: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension UInt: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Float: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Double: _OCKBridgable {
public typealias ObjectType = NSNumber
public func bridge() -> NSNumber {
return NSNumber(value: self)
}
}
extension Dictionary {
func bridge() -> NSDictionary {
var newDictionary: [NSString: Any] = [:]
for (key,value) in self {
if let stringKey = key as? String {
newDictionary[stringKey.bridge()] = value
} else if let nsstringKey = key as? NSString {
newDictionary[nsstringKey] = value
}
}
return newDictionary._bridgeToObjectiveC()
}
}
#if !os(Linux)
typealias NSErrorUserInfoType = [AnyHashable: Any]
public extension NSString {
func bridge() -> String {
return self as String
}
}
extension NSArray {
func bridge() -> Array<Any> {
return self as! Array<Any>
}
}
extension NSDictionary {
public func bridge() -> [NSObject: Any] {
return self as [NSObject: AnyObject]
}
}
extension Array {
func bridge() -> NSArray {
return self as NSArray
}
}
extension Date {
func bridge() -> NSDate {
return self as NSDate
}
}
extension NSDate {
func bridge() -> Date {
return self as Date
}
}
extension NSData {
func bridge() -> Data {
return self as Data
}
}
#elseif os(Linux)
typealias NSErrorUserInfoType = [String: Any]
public extension NSString {
func bridge() -> String {
return self._bridgeToSwift()
}
}
extension NSArray {
public func bridge() -> Array<Any> {
return self._bridgeToSwift()
}
}
extension NSDictionary {
public func bridge() -> [AnyHashable: Any] {
return self._bridgeToSwift()
}
}
extension Array {
public func bridge() -> NSArray {
return self._bridgeToObjectiveC()
}
}
extension NSData {
public func bridge() -> Data {
return self._bridgeToSwift()
}
}
extension Date {
public func bridge() -> NSDate {
return self._bridgeToObjectiveC()
}
}
extension NSDate {
public func bridge() -> Date {
return self._bridgeToSwift()
}
}
#endif
extension NSError {
public convenience init(error: Error) {
var userInfo: [String : Any] = [:]
var code: Int = 0
// Retrieve custom userInfo information.
if let customUserInfoError = error as? CustomNSError {
userInfo = customUserInfoError.errorUserInfo
code = customUserInfoError.errorCode
}
if let localizedError = error as? LocalizedError {
if let description = localizedError.errorDescription {
userInfo[NSLocalizedDescriptionKey] = description
}
if let reason = localizedError.failureReason {
userInfo[NSLocalizedFailureReasonErrorKey] = reason
}
if let suggestion = localizedError.recoverySuggestion {
userInfo[NSLocalizedRecoverySuggestionErrorKey] = suggestion
}
if let helpAnchor = localizedError.helpAnchor {
userInfo[NSHelpAnchorErrorKey] = helpAnchor
}
}
if let recoverableError = error as? RecoverableError {
userInfo[NSLocalizedRecoveryOptionsErrorKey] = recoverableError.recoveryOptions
// userInfo[NSRecoveryAttempterErrorKey] = recoverableError
}
self.init(domain: "OpenCloudKit", code: code, userInfo: userInfo)
}
}
| 7e263570640b80341a4a18259dfd3be0 | 21.799107 | 91 | 0.558449 | false | false | false | false |
ddaguro/clintonconcord | refs/heads/master | OIMApp/Controls/Spring/TransitionZoom.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([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.
import UIKit
public class TransitionZoom: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
var isPresenting = true
var duration = 0.4
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView()
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
if isPresenting {
container!.addSubview(fromView)
container!.addSubview(toView)
toView.alpha = 0
toView.transform = CGAffineTransformMakeScale(2, 2)
springEaseInOut(duration) {
fromView.transform = CGAffineTransformMakeScale(0.5, 0.5)
fromView.alpha = 0
toView.transform = CGAffineTransformIdentity
toView.alpha = 1
}
}
else {
container!.addSubview(toView)
container!.addSubview(fromView)
springEaseInOut(duration) {
fromView.transform = CGAffineTransformMakeScale(2, 2)
fromView.alpha = 0
toView.transform = CGAffineTransformMakeScale(1, 1)
toView.alpha = 1
}
}
delay(duration, closure: {
transitionContext.completeTransition(true)
})
}
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = true
return self
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
isPresenting = false
return self
}
} | b5d832572f11e41af6690490ac887ad2 | 41.102564 | 224 | 0.689309 | false | false | false | false |
yanif/circator | refs/heads/master | MetabolicCompassKit/PopulationHealthManager.swift | apache-2.0 | 1 | //
// PopulationHealthManager.swift
// MetabolicCompass
//
// Created by Yanif Ahmad on 1/31/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import Foundation
import HealthKit
import Async
import MCCircadianQueries
/**
This is the manager of information for the comparison population.
By providing this comparison we provide our study participants with a greater ability to view themselves in context.
Initially this is defined by the NHANES data.
With sufficient enrolled subjects, this will be determined by aggregates over the ongoing study population.
- remark: pulls from PostgreSQL store (AWS RDS) -- see MCRouter --
*/
public class PopulationHealthManager {
public static let sharedManager = PopulationHealthManager()
public var aggregateRefreshDate : NSDate = NSDate()
public var mostRecentAggregates = [HKSampleType: [MCSample]]() {
didSet {
aggregateRefreshDate = NSDate()
}
}
// MARK: - Population query execution.
// Clear all aggregates.
public func resetAggregates() { mostRecentAggregates = [:] }
// Retrieve aggregates for all previewed rows.
// TODO: enable input of start time, end time and columns retrieved in the query view controllers.
public func fetchAggregates() {
var columnIndex = 0
var columns : [String:AnyObject] = [:]
var tstart : NSDate = NSDate(timeIntervalSince1970: 0)
var tend : NSDate = NSDate()
var userfilter : [String:AnyObject] = [:]
// Add population filter parameters.
let popQueryIndex = QueryManager.sharedManager.getSelectedQuery()
let popQueries = QueryManager.sharedManager.getQueries()
if popQueryIndex >= 0 && popQueryIndex < popQueries.count {
let popQuery = popQueries[popQueryIndex]
switch popQuery.1 {
case Query.ConjunctiveQuery(let qstartOpt, let qendOpt, let qcolsOpt, let aggpreds):
if let qstart = qstartOpt { tstart = qstart }
if let qend = qendOpt { tend = qend }
if let qcols = qcolsOpt {
for (hksType, mealActivityInfoOpt) in qcols {
if hksType.identifier == HKObjectType.workoutType().identifier && mealActivityInfoOpt != nil {
if let mealActivityInfo = mealActivityInfoOpt {
switch mealActivityInfo {
case .MCQueryMeal(let meal_type):
columns[String(columnIndex)] = ["meal_duration": meal_type]
columnIndex += 1
case .MCQueryActivity(let hkWorkoutType, let mcActivityValueType):
if let mcActivityType = HMConstants.sharedInstance.hkActivityToMCDB[hkWorkoutType] {
if mcActivityValueType == .Duration {
columns[String(columnIndex)] = ["activity_duration": mcActivityType]
columnIndex += 1
} else {
let quantity = mcActivityValueType == .Distance ? "distance" : "kcal_burned"
columns[String(columnIndex)] = ["activity_value": [mcActivityType: quantity]]
columnIndex += 1
}
}
}
}
} else {
if let column = HMConstants.sharedInstance.hkToMCDB[hksType.identifier] {
columns[String(columnIndex)] = column
columnIndex += 1
} else if hksType.identifier == HKCorrelationTypeIdentifierBloodPressure {
// Issue queries for both systolic and diastolic.
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureDiastolic]!
columnIndex += 1
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureSystolic]!
columnIndex += 1
} else {
log.info("Cannot perform population query for \(hksType.identifier)")
}
}
}
}
let units : UnitsSystem = UserManager.sharedManager.useMetricUnits() ? .Metric : .Imperial
let convert : (String, Int) -> Int = { (type, value) in
return Int((type == HKQuantityTypeIdentifierHeight) ?
UnitsUtils.heightValueInDefaultSystem(fromValue: Float(value), inUnitsSystem: units)
: UnitsUtils.weightValueInDefaultSystem(fromValue: Float(value), inUnitsSystem: units))
}
let predArray = aggpreds.map {
let predicateType = $0.1.0.identifier
if HMConstants.sharedInstance.healthKitTypesWithCustomMetrics.contains(predicateType) {
if let lower = $0.2, upper = $0.3, lowerInt = Int(lower), upperInt = Int(upper) {
return ($0.0, $0.1, String(convert(predicateType, lowerInt)), String(convert(predicateType, upperInt)))
}
return $0
} else {
return $0
}
}.map(serializeMCQueryPredicateREST)
for pred in predArray {
for (k,v) in pred {
userfilter.updateValue(v, forKey: k)
}
}
}
}
if columns.isEmpty {
for hksType in PreviewManager.supportedTypes {
if let column = HMConstants.sharedInstance.hkToMCDB[hksType.identifier] {
columns[String(columnIndex)] = column
columnIndex += 1
}
else if let (activity_category, quantity) = HMConstants.sharedInstance.hkQuantityToMCDBActivity[hksType.identifier] {
columns[String(columnIndex)] = ["activity_value": [activity_category:quantity]]
columnIndex += 1
}
else if hksType.identifier == HKCorrelationTypeIdentifierBloodPressure {
// Issue queries for both systolic and diastolic.
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureDiastolic]!
columnIndex += 1
columns[String(columnIndex)] = HMConstants.sharedInstance.hkToMCDB[HKQuantityTypeIdentifierBloodPressureSystolic]!
columnIndex += 1
}
else {
log.warning("No population query column available for \(hksType.identifier)")
}
}
}
let params : [String:AnyObject] = [
"tstart" : Int(floor(tstart.timeIntervalSince1970)),
"tend" : Int(ceil(tend.timeIntervalSince1970)),
"columns" : columns,
"userfilter" : userfilter
]
// log.info("Running popquery \(params)")
Service.json(MCRouter.AggregateMeasures(params), statusCode: 200..<300, tag: "AGGPOST") {
_, response, result in
guard !result.isSuccess else {
self.refreshAggregatesFromMsg(result.value)
return
}
}
}
// TODO: the current implementation of population aggregates is not sufficiently precise to distinguish between meals/activities.
// These values are all treated as workout types, and thus produce a single population aggregate given mostRecentAggregtes is indexed
// by a HKSampleType.
//
// We need to reimplement mostRecentAggregates as a mapping between a triple of (HKSampleType, MCDBType, Quantity) => value
// where MCDBType is a union type, MCDBType = HKWorkoutActivityType | String (e.g., for meals)
// and Quantity is a String (e.g., distance, kcal_burned, step_count, flights)
//
func refreshAggregatesFromMsg(payload: AnyObject?) {
var populationAggregates : [HKSampleType: [MCSample]] = [:]
if let response = payload as? [String:AnyObject],
aggregates = response["items"] as? [[String:AnyObject]]
{
var failed = false
for sample in aggregates {
for (column, val) in sample {
if !failed {
log.verbose("Refreshing population aggregate for \(column)")
// Handle meal_duration/activity_duration/activity_value columns.
// TODO: this only supports activity values that are HealthKit quantities for now (step count, flights climbed, distance/walking/running)
// We should support all MCDB meals/activity categories.
if HMConstants.sharedInstance.mcdbCategorized.contains(column) {
let categoryQuantities: [String: (String, String)] = column == "activity_value" ? HMConstants.sharedInstance.mcdbActivityToHKQuantity : [:]
if let categorizedVals = val as? [String:AnyObject] {
for (category, catval) in categorizedVals {
if let (mcdbQuantity, hkQuantity) = categoryQuantities[category],
sampleType = HKObjectType.quantityTypeForIdentifier(hkQuantity),
categoryValues = catval as? [String: AnyObject]
{
if let sampleValue = categoryValues[mcdbQuantity] as? Double {
populationAggregates[sampleType] = [doubleAsAggregate(sampleType, sampleValue: sampleValue)]
} else {
populationAggregates[sampleType] = []
}
}
else {
failed = true
log.error("Invalid MCDB categorized quantity in popquery response: \(category) \(catval)")
}
}
}
else {
failed = true
log.error("Invalid MCDB categorized values in popquery response: \(val)")
}
}
else if let typeIdentifier = HMConstants.sharedInstance.mcdbToHK[column]
{
var sampleType: HKSampleType! = nil
switch typeIdentifier {
case HKCategoryTypeIdentifierSleepAnalysis:
sampleType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierSleepAnalysis)!
case HKCategoryTypeIdentifierAppleStandHour:
sampleType = HKObjectType.categoryTypeForIdentifier(HKCategoryTypeIdentifierAppleStandHour)!
default:
sampleType = HKObjectType.quantityTypeForIdentifier(typeIdentifier)!
}
if let sampleValue = val as? Double {
let agg = doubleAsAggregate(sampleType, sampleValue: sampleValue)
populationAggregates[sampleType] = [agg]
// Population correlation type entry for systolic/diastolic blood pressure sample.
if typeIdentifier == HKQuantityTypeIdentifierBloodPressureSystolic
|| typeIdentifier == HKQuantityTypeIdentifierBloodPressureDiastolic
{
let bpType = HKObjectType.correlationTypeForIdentifier(HKCorrelationTypeIdentifierBloodPressure)!
let sType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureSystolic)!
let dType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBloodPressureDiastolic)!
let bpIndex = typeIdentifier == HKQuantityTypeIdentifierBloodPressureSystolic ? 0 : 1
if populationAggregates[bpType] == nil {
populationAggregates[bpType] = [
MCAggregateSample(value: Double.quietNaN, sampleType: sType, op: sType.aggregationOptions),
MCAggregateSample(value: Double.quietNaN, sampleType: dType, op: dType.aggregationOptions),
]
}
populationAggregates[bpType]![bpIndex] = agg
}
} else {
populationAggregates[sampleType] = []
}
}
else {
failed = true
// let err = NSError(domain: "App error", code: 0, userInfo: [NSLocalizedDescriptionKey:kvdict.description])
// let dict = ["title":"population data error", "error":err]
// NSNotificationCenter.defaultCenter().postNotificationName("ncAppLogNotification", object: nil, userInfo: dict)
}
}
}
}
if ( !failed ) {
Async.main {
// let dict = ["title":"population data", "obj":populationAggregates.description ?? ""]
// NSNotificationCenter.defaultCenter().postNotificationName("ncAppLogNotification", object: nil, userInfo: dict)
self.mostRecentAggregates = populationAggregates
NSNotificationCenter.defaultCenter().postNotificationName(HMDidUpdateRecentSamplesNotification, object: self)
}
}
else {
log.error("Failed to retrieve population aggregates from response: \(response)")
}
}
else {
log.error("Failed to deserialize population query response")
}
}
func doubleAsAggregate(sampleType: HKSampleType, sampleValue: Double) -> MCAggregateSample {
let convertedSampleValue = HKQuantity(unit: sampleType.serviceUnit!, doubleValue: sampleValue).doubleValueForUnit(sampleType.defaultUnit!)
log.info("Popquery \(sampleType.displayText ?? sampleType.identifier) \(sampleValue) \(convertedSampleValue)")
return MCAggregateSample(value: convertedSampleValue, sampleType: sampleType, op: sampleType.aggregationOptions)
}
// MARK : - Study stats queries
public func fetchStudyStats(completion: (Bool, AnyObject?) -> Void) {
Service.json(MCRouter.StudyStats, statusCode: 200..<300, tag: "GETSTUDYSTATS") {
_, response, result in
completion(result.isSuccess, result.value)
}
}
} | 5c81929fb729c6050ed97f77a610ef3f | 52.73064 | 167 | 0.532306 | false | false | false | false |
mgadda/swift-parse | refs/heads/master | Sources/SwiftParse/Operators.swift | mit | 1 | //
// Operators.swift
// SwiftParse
//
// Created by Matt Gadda on 11/30/19.
//
// MARK: ~ (compose)
infix operator ~: MultiplicationPrecedence
public func ~<T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, (LeftParsedValue, RightParsedValue), V> {
return compose(left(), right())
}
public func ~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<
ParserTU.InputType.Element,
(ParserTU.ParsedValueType, ParserUV.ParsedValueType),
ParserUV.OutputType.Element> where
ParserTU.OutputType == ParserUV.InputType
{
return compose(left, right)
}
func ~<T, U, LeftParsedValue, ParserUV: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: ParserUV
) -> Parser<T, (LeftParsedValue, ParserUV.ParsedValueType), ParserUV.OutputType.Element> where
U == ParserUV.InputType.Element
{
return compose(left(), right)
}
func ~<ParserTU: ParserConvertible, U, V, RightParsedValue>(
_ left: ParserTU,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<ParserTU.InputType.Element, (ParserTU.ParsedValueType, RightParsedValue), V> where
ParserTU.OutputType.Element == U
{
return compose(left, right())
}
// MARK: ~> (compose, ignore right)
infix operator ~>: MultiplicationPrecedence
public func ~><T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, LeftParsedValue, V> {
return map(compose(left(), right())) { (left, _) in left }
}
public func ~><ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<ParserTU.InputType.Element, ParserTU.ParsedValueType, ParserUV.OutputType.Element>
where ParserTU.OutputType == ParserUV.InputType {
left.mkParser() ~> right.mkParser()
}
public func ~><ParserLike: ParserConvertible, V, RightParsedValue>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V>
) -> Parser<ParserLike.InputType.Element, ParserLike.ParsedValueType, V> {
left.mkParser() ~> right()
}
public func ~><T, LeftParsedValue, ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>,
_ right: ParserLike
) -> Parser<T, LeftParsedValue, ParserLike.OutputType.Element> {
left() ~> right.mkParser()
}
// MARK: <~ (compose, ignore left)
infix operator <~: MultiplicationPrecedence
public func <~ <T, U, V, LeftParsedValue, RightParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<U, RightParsedValue, V>
) -> Parser<T, RightParsedValue, V> {
return map(compose(left(), right())) { (_, right) in right }
}
public func <~<ParserTU: ParserConvertible, ParserUV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserUV
) -> Parser<ParserTU.InputType.Element, ParserUV.ParsedValueType, ParserUV.OutputType.Element>
where ParserTU.OutputType == ParserUV.InputType {
left.mkParser() <~ right.mkParser()
}
public func <~<ParserLike: ParserConvertible, V, RightParsedValue>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> Parser<ParserLike.OutputType.Element, RightParsedValue, V>
) -> Parser<ParserLike.InputType.Element, RightParsedValue, V> {
left.mkParser() <~ right()
}
public func <~<T, LeftParsedValue, ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<T, LeftParsedValue, ParserLike.InputType.Element>,
_ right: ParserLike
) -> Parser<T, ParserLike.ParsedValueType, ParserLike.OutputType.Element> {
left() <~ right.mkParser()
}
// MARK: | (or)
public func |<T, U, ParsedValue>(
_ left: @autoclosure @escaping () -> Parser<T, ParsedValue, U>,
_ right: @autoclosure @escaping () -> Parser<T, ParsedValue, U>
) -> Parser<T, ParsedValue, U> {
return or(left(), right())
}
public func |<ParserLike: ParserConvertible>(
_ left: ParserLike,
_ right: ParserLike
) -> ParserFrom<ParserLike> {
or(left, right)
}
public func |<ParserLike: ParserConvertible>(
_ left: @autoclosure @escaping () -> ParserFrom<ParserLike>,
_ right: ParserLike
) -> ParserFrom<ParserLike> {
or(left(), right)
}
public func |<ParserLike: ParserConvertible>(
_ left: ParserLike,
_ right: @autoclosure @escaping () -> ParserFrom<ParserLike>
) -> ParserFrom<ParserLike> {
or(left, right())
}
// MARK: ^^ (map)
precedencegroup MapGroup {
higherThan: AssignmentPrecedence
lowerThan: AdditionPrecedence
}
infix operator ^^: MapGroup
public func ^^<T, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, T, OutputElement>,
fn: @escaping (T) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element> {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((T1, T2), T3), OutputElement>,
fn: @escaping (T1, T2, T3) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((T1, T2), T3) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((T1, T2), T3), T4), OutputElement>,
fn: @escaping (T1, T2, T3, T4) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((T1, T2), T3), T4) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((((T1, T2), T3), T4), T5), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((((T1, T2), T3), T4), T5) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((((T1, T2), T3), T4), T5), T6), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((((T1, T2), T3), T4), T5), T6) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, ((((((T1, T2), T3), T4), T5), T6), T7), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6, T7) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == ((((((T1, T2), T3), T4), T5), T6), T7) {
map(parser, fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, InputElement, OutputElement>(
_ parser: @autoclosure @escaping () -> Parser<InputElement, (((((((T1, T2), T3), T4), T5), T6), T7), T8), OutputElement>,
fn: @escaping (T1, T2, T3, T4, T5, T6, T7, T8) -> U
) -> Parser<InputElement, U, OutputElement> {
return map(parser(), fn: fn)
}
public func ^^<T1, T2, T3, T4, T5, T6, T7, T8, U, ParserLike: ParserConvertible>(
_ parser: ParserLike,
fn: @escaping (ParserLike.ParsedValueType) -> U
) -> Parser<ParserLike.InputType.Element, U, ParserLike.OutputType.Element>
where ParserLike.ParsedValueType == (((((((T1, T2), T3), T4), T5), T6), T7), T8) {
map(parser, fn: fn)
}
// MARK: * (rep)
postfix operator *
public postfix func *<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> {
rep(parser())
}
public postfix func *<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]>
where ParserLike.InputType == ParserLike.OutputType
{
rep(parser.mkParser())
}
// MARK: + (rep1)
postfix operator +
public postfix func +<T, InputElement>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, [T], InputElement> {
return rep1(parser())
}
public postfix func +<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, [ParserLike.ParsedValueType]>
where ParserLike.InputType == ParserLike.OutputType {
rep1(parser)
}
// MARK: *? (opt)
postfix operator *?
public postfix func *?<InputElement, T>(_ parser: @autoclosure @escaping () -> Parser<InputElement, T, InputElement>) -> Parser<InputElement, T?, InputElement> {
return opt(parser())
}
public postfix func *?<ParserLike: ParserConvertible>(
_ parser: ParserLike
) -> StandardParser<ParserLike.InputType, ParserLike.ParsedValueType?>
where ParserLike.InputType == ParserLike.OutputType {
return opt(parser)
}
// MARK: & (and)
infix operator &: MultiplicationPrecedence
public func &<T, U, V, LeftValue, RightValue>(
_ left: @autoclosure @escaping () -> Parser<T, LeftValue, U>,
_ right: @autoclosure @escaping () -> Parser<T, RightValue, V>) -> Parser<T, LeftValue, U> {
and(left(), right())
}
public func &<V, RightValue, ParserTU: ParserConvertible>(
_ left: ParserTU,
_ right: @autoclosure @escaping () -> Parser<ParserTU.InputType.Element, RightValue, V>
) -> ParserFrom<ParserTU> {
and(left, right())
}
public func &<U, LeftValue, ParserTV: ParserConvertible>(
_ left: @autoclosure @escaping () -> Parser<ParserTV.InputType.Element, LeftValue, U>,
_ right: ParserTV
) -> Parser<ParserTV.InputType.Element, LeftValue, U> {
and(left(), right)
}
public func &<ParserTU: ParserConvertible, ParserTV: ParserConvertible>(
_ left: ParserTU,
_ right: ParserTV) -> ParserFrom<ParserTU>
where ParserTU.InputType == ParserTV.InputType
{
and(left, right)
}
| 60f337197e527d4badf1b938798ffefd | 33.692073 | 161 | 0.686088 | false | false | false | false |
Detailscool/YHFanfou | refs/heads/master | Example/Pods/CryptoSwift/Sources/CryptoSwift/Rabbit.swift | gpl-3.0 | 6 | //
// Rabbit.swift
// CryptoSwift
//
// Created by Dima Kalachov on 12/11/15.
// Copyright © 2015 Marcin Krzyzanowski. All rights reserved.
//
private typealias Key = SecureBytes
final public class Rabbit: BlockCipher {
/// Size of IV in bytes
public static let ivSize = 64 / 8
/// Size of key in bytes
public static let keySize = 128 / 8
/// Size of block in bytes
public static let blockSize = 128 / 8
/// Key
private let key: Key
/// IV (optional)
private let iv: [UInt8]?
/// State variables
private var x = [UInt32](count: 8, repeatedValue: 0)
/// Counter variables
private var c = [UInt32](count: 8, repeatedValue: 0)
/// Counter carry
private var p7: UInt32 = 0
/// 'a' constants
private var a: [UInt32] = [
0x4D34D34D,
0xD34D34D3,
0x34D34D34,
0x4D34D34D,
0xD34D34D3,
0x34D34D34,
0x4D34D34D,
0xD34D34D3,
]
// MARK: - Initializers
convenience public init?(key:[UInt8]) {
self.init(key: key, iv: nil)
}
public init?(key:[UInt8], iv:[UInt8]?) {
self.key = Key(bytes: key)
self.iv = iv
guard key.count == Rabbit.keySize && (iv == nil || iv!.count == Rabbit.ivSize) else {
return nil
}
}
// MARK: -
private func setup() {
p7 = 0
// Key divided into 8 subkeys
var k = [UInt32](count: 8, repeatedValue: 0)
for j in 0..<8 {
k[j] = UInt32(key[Rabbit.blockSize - (2*j + 1)]) | (UInt32(key[Rabbit.blockSize - (2*j + 2)]) << 8)
}
// Initialize state and counter variables from subkeys
for j in 0..<8 {
if j % 2 == 0 {
x[j] = (k[(j+1) % 8] << 16) | k[j]
c[j] = (k[(j+4) % 8] << 16) | k[(j+5) % 8]
} else {
x[j] = (k[(j+5) % 8] << 16) | k[(j+4) % 8]
c[j] = (k[j] << 16) | k[(j+1) % 8]
}
}
// Iterate system four times
nextState()
nextState()
nextState()
nextState()
// Reinitialize counter variables
for j in 0..<8 {
c[j] = c[j] ^ x[(j+4) % 8]
}
if let iv = iv {
setupIV(iv)
}
}
private func setupIV(iv: [UInt8]) {
// 63...56 55...48 47...40 39...32 31...24 23...16 15...8 7...0 IV bits
// 0 1 2 3 4 5 6 7 IV bytes in array
let iv0: UInt32 = integerWithBytes([iv[4], iv[5], iv[6], iv[7]])
let iv1: UInt32 = integerWithBytes([iv[0], iv[1], iv[4], iv[5]])
let iv2: UInt32 = integerWithBytes([iv[0], iv[1], iv[2], iv[3]])
let iv3: UInt32 = integerWithBytes([iv[2], iv[3], iv[6], iv[7]])
// Modify the counter state as function of the IV
c[0] = c[0] ^ iv0
c[1] = c[1] ^ iv1
c[2] = c[2] ^ iv2
c[3] = c[3] ^ iv3
c[4] = c[4] ^ iv0
c[5] = c[5] ^ iv1
c[6] = c[6] ^ iv2
c[7] = c[7] ^ iv3
// Iterate system four times
nextState()
nextState()
nextState()
nextState()
}
private func nextState() {
// Before an iteration the counters are incremented
var carry = p7
for j in 0..<8 {
let prev = c[j]
c[j] = prev &+ a[j] &+ carry
carry = prev > c[j] ? 1 : 0 // detect overflow
}
p7 = carry // save last carry bit
// Iteration of the system
var newX = [UInt32](count: 8, repeatedValue: 0)
newX[0] = g(0) &+ rotateLeft(g(7), 16) &+ rotateLeft(g(6), 16)
newX[1] = g(1) &+ rotateLeft(g(0), 8) &+ g(7)
newX[2] = g(2) &+ rotateLeft(g(1), 16) &+ rotateLeft(g(0), 16)
newX[3] = g(3) &+ rotateLeft(g(2), 8) &+ g(1)
newX[4] = g(4) &+ rotateLeft(g(3), 16) &+ rotateLeft(g(2), 16)
newX[5] = g(5) &+ rotateLeft(g(4), 8) &+ g(3)
newX[6] = g(6) &+ rotateLeft(g(5), 16) &+ rotateLeft(g(4), 16)
newX[7] = g(7) &+ rotateLeft(g(6), 8) &+ g(5)
x = newX
}
private func g(j: Int) -> UInt32 {
let sum = x[j] &+ c[j]
let square = UInt64(sum) * UInt64(sum)
return UInt32(truncatingBitPattern: square ^ (square >> 32))
}
private func nextOutput() -> [UInt8] {
nextState()
var output16 = [UInt16](count: Rabbit.blockSize / 2, repeatedValue: 0)
output16[7] = UInt16(truncatingBitPattern: x[0]) ^ UInt16(truncatingBitPattern: x[5] >> 16)
output16[6] = UInt16(truncatingBitPattern: x[0] >> 16) ^ UInt16(truncatingBitPattern: x[3])
output16[5] = UInt16(truncatingBitPattern: x[2]) ^ UInt16(truncatingBitPattern: x[7] >> 16)
output16[4] = UInt16(truncatingBitPattern: x[2] >> 16) ^ UInt16(truncatingBitPattern: x[5])
output16[3] = UInt16(truncatingBitPattern: x[4]) ^ UInt16(truncatingBitPattern: x[1] >> 16)
output16[2] = UInt16(truncatingBitPattern: x[4] >> 16) ^ UInt16(truncatingBitPattern: x[7])
output16[1] = UInt16(truncatingBitPattern: x[6]) ^ UInt16(truncatingBitPattern: x[3] >> 16)
output16[0] = UInt16(truncatingBitPattern: x[6] >> 16) ^ UInt16(truncatingBitPattern: x[1])
var output8 = [UInt8](count: Rabbit.blockSize, repeatedValue: 0)
for j in 0..<output16.count {
output8[j * 2] = UInt8(truncatingBitPattern: output16[j] >> 8)
output8[j * 2 + 1] = UInt8(truncatingBitPattern: output16[j])
}
return output8
}
// MARK: - Public
public func encrypt(bytes: [UInt8]) -> [UInt8] {
setup()
var result = [UInt8](count: bytes.count, repeatedValue: 0)
var output = nextOutput()
var byteIdx = 0
var outputIdx = 0
while byteIdx < bytes.count {
if (outputIdx == Rabbit.blockSize) {
output = nextOutput()
outputIdx = 0
}
result[byteIdx] = bytes[byteIdx] ^ output[outputIdx]
byteIdx += 1
outputIdx += 1
}
return result
}
public func decrypt(bytes: [UInt8]) -> [UInt8] {
return encrypt(bytes)
}
}
// MARK: - CipherType
extension Rabbit: CipherProtocol {
public func cipherEncrypt(bytes:[UInt8]) -> [UInt8] {
return self.encrypt(bytes)
}
public func cipherDecrypt(bytes: [UInt8]) -> [UInt8] {
return self.decrypt(bytes)
}
}
| b17216f27bfa8f4dc4fd103a0aa0fe7e | 30.389671 | 111 | 0.499701 | false | false | false | false |
hfutrell/BezierKit | refs/heads/master | BezierKit/BezierKitTests/Path+ProjectionTests.swift | mit | 1 | //
// Path+ProjectionTests.swift
// BezierKit
//
// Created by Holmes Futrell on 11/23/20.
// Copyright © 2020 Holmes Futrell. All rights reserved.
//
@testable import BezierKit
import XCTest
#if canImport(CoreGraphics)
import CoreGraphics
class PathProjectionTests: XCTestCase {
func testProjection() {
XCTAssertNil(Path().project(CGPoint.zero), "projection requires non-empty path.")
let triangle1 = { () -> Path in
let cgPath = CGMutablePath()
cgPath.addLines(between: [CGPoint(x: 0, y: 2),
CGPoint(x: 2, y: 4),
CGPoint(x: 0, y: 4)])
cgPath.closeSubpath()
return Path(cgPath: cgPath)
}()
let triangle2 = { () -> Path in
let cgPath = CGMutablePath()
cgPath.addLines(between: [CGPoint(x: 2, y: 1),
CGPoint(x: 3, y: 1),
CGPoint(x: 3, y: 2)])
cgPath.closeSubpath()
return Path(cgPath: cgPath)
}()
let square = Path(rect: CGRect(x: 3, y: 3, width: 1, height: 1))
let path = Path(components: triangle1.components + triangle2.components + square.components)
let projection = path.project(CGPoint(x: 2, y: 2))
XCTAssertEqual(projection?.location, IndexedPathLocation(componentIndex: 1, elementIndex: 2, t: 0.5))
XCTAssertEqual(projection?.point, CGPoint(x: 2.5, y: 1.5))
}
func testPointIsWithinDistanceOfBoundary() {
let circleCGPath = CGMutablePath()
circleCGPath.addEllipse(in: CGRect(origin: CGPoint(x: -1.0, y: -1.0), size: CGSize(width: 2.0, height: 2.0)))
let circlePath = Path(cgPath: circleCGPath) // a circle centered at origin with radius 1
let d = CGFloat(0.1)
let p1 = CGPoint(x: -3.0, y: 0.0)
let p2 = CGPoint(x: -0.9, y: 0.9)
let p3 = CGPoint(x: 0.75, y: 0.75)
let p4 = CGPoint(x: 0.5, y: 0.5)
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p1, distance: d)) // no, path bounding box isn't even within that distance
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p2, distance: d)) // no, within bounding box, but no individual curves are within that distance
XCTAssertTrue(circlePath.pointIsWithinDistanceOfBoundary(p3, distance: d)) // yes, one of the curves that makes up the circle is within that distance
XCTAssertTrue(circlePath.pointIsWithinDistanceOfBoundary(p3, distance: CGFloat(10.0))) // yes, so obviously within that distance implementation should early return yes
XCTAssertFalse(circlePath.pointIsWithinDistanceOfBoundary(p4, distance: d)) // no, we are inside the path but too far from the boundary
}
}
#endif
| e6ecdef563155830b4acdc3b6cf265e4 | 44.467742 | 176 | 0.620788 | false | true | false | false |
QuarkWorks/RealmModelGenerator | refs/heads/master | RealmModelGenerator/RealmSchemaDocument.swift | mit | 1 | //
// RealmSchemaDocument.swift
// RealmModelGenerator
//
// Created by Zhaolong Zhong on 3/14/16.
// Copyright © 2016 QuarkWorks. All rights reserved.
//
import Cocoa
class RealmSchemaDocument: NSDocument {
static let TAG = String(describing: RealmSchemaDocument.self)
let MAIN: NSStoryboard.Name = NSStoryboard.Name(rawValue: "Main")
let DOCUMENT_WINDOW_CONTROLLER: NSStoryboard.SceneIdentifier = NSStoryboard.SceneIdentifier(rawValue: "Document Window Controller")
private var mainVC: MainVC!
private var schema = Schema()
private var windowController:NSWindowController?
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override func windowControllerDidLoadNib(_ aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
}
override class var autosavesInPlace: Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: MAIN, bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: DOCUMENT_WINDOW_CONTROLLER) as! NSWindowController
if let v = windowController.contentViewController as? MainVC {
mainVC = v
mainVC.schema = schema
}
self.addWindowController(windowController)
}
override func data(ofType: String) throws -> Data {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
var arrayOfDictionaries = [[String:Any]]()
let schemaDict = mainVC.schema!.toDictionary()
arrayOfDictionaries.append(schemaDict)
let data: Data? = try JSONSerialization.data(withJSONObject: arrayOfDictionaries, options: [])
if let value = data {
return value
}
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override func read(from data: Data, ofType typeName: String) throws {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return false if the contents are lazily loaded.
do {
try parseSchemaJson(data: data)
return
} catch GeneratorError.InvalidFileContent(let errorMsg) {
// MARK: - correct print function?
Swift.print("Invalid JSON format: \(errorMsg)")
}
Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Invalid content")
}
func parseSchemaJson(data: Data) throws {
if let arrayOfDictionaries = try! JSONSerialization.jsonObject(with: data, options: []) as? [[String:Any]]{
guard let dictionary = arrayOfDictionaries.first else {
throw GeneratorError.InvalidFileContent(errorMsg: RealmSchemaDocument.TAG + ": No schema in this file")
}
try schema.map(dictionary: dictionary )
return
}
}
}
| d4b6b68054570f30345e0dfcd7885d5f | 39.020619 | 186 | 0.659196 | false | false | false | false |
pattogato/WGUtils | refs/heads/master | WGUtils/WGDateUtils.swift | mit | 1 | //
// DateUtils.swift
// WGUtils
//
// Created by Bence Pattogato on 18/02/16.
// Copyright © 2016 Wintergarden. All rights reserved.
//
import UIKit
class DateUtils: NSObject {
// Takes a String and a Format and converts it to an NSDate?
static func stringToDate(string: String, _ format: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
let date = dateFormatter.dateFromString(string)
return date
}
//Converts an NSDate into a string with the given format
static func dateToString(format: String, date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = format
let string = dateFormatter.stringFromDate(date)
return string
}
}
// MARK: - Date Extension
extension NSDate {
/// Init NSDate with day, month and year
class func initDate(day: Int, month: Int, year: Int) -> NSDate? {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: NSDate())
components.year = year
components.month = month
components.day = day
return calendar.dateFromComponents(components)
}
/// Returns if the NSDate instance is on a same day parameter date
func isOnSameDay(date: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let componentsForFirstDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
let componentsForSecondDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
return componentsForFirstDate.year == componentsForSecondDate.year &&
componentsForFirstDate.month == componentsForSecondDate.month &&
componentsForFirstDate.day == componentsForSecondDate.day
}
/// Returns if the NSDate instance is on a same month parameter date
func inInSameMonth(date: NSDate) -> Bool {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let componentsForFirstDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
let componentsForSecondDate = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
return componentsForFirstDate.year == componentsForSecondDate.year &&
componentsForFirstDate.month == componentsForSecondDate.month
}
/// Returns the beginning of the given date (hour, min, sec)
func beginningOfDay() -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second ], fromDate: self)
components.hour = 0
components.minute = 0
components.second = 0
return calendar.dateFromComponents(components) ?? self
}
/// Returns the end of the given date (hour, min, sec)
func endOfDay(isStartOfNextDay isStartOfNextDay: Bool = false) -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second ], fromDate: self)
if isStartOfNextDay {
components.hour = 24
components.minute = 0
components.second = 0
} else {
components.hour = 23
components.minute = 59
components.second = 59
}
return calendar.dateFromComponents(components) ?? self
}
/// Returns the month name as string
func monthName() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.stringFromDate(self)
}
/// Returns the years name as string
func yearString() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY"
return dateFormatter.stringFromDate(self)
}
/// Returns the days of the month's days
func getMonthsDays() -> [NSDate] {
let nextCalendar = NSCalendar.currentCalendar()
let nextComponents = nextCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.WeekOfMonth, NSCalendarUnit.Weekday], fromDate: self)
nextComponents.day = 0
guard let monthBeginningDate = nextCalendar.dateFromComponents(nextComponents) else {
return [NSDate]()
}
nextComponents.month = nextComponents.month + 1
nextComponents.day = 0
guard let monthEndDate = nextCalendar.dateFromComponents(nextComponents) else {
return [NSDate]()
}
let monthDays = NSDate.daysBetweenDates(monthBeginningDate, endDate: monthEndDate)
return monthDays
}
/// Returns an NSDate array between startDate and endDate
class func daysBetweenDates(startDate: NSDate!, endDate: NSDate!) -> [NSDate] {
var date = startDate
// date for the loop
let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = NSDateComponents()
dateComponents.year = 1
// Create an array to hold *all* the returned
// results for the year
var datesArray = [NSDate]()
// Loop through each date until the ending date is
// reached
while date.compare(endDate) != NSComparisonResult.OrderedDescending {
// increment the date by 1 day
let dateComponents = NSDateComponents()
dateComponents.day = 1
date = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: NSCalendarOptions.MatchFirst)
datesArray.append(date)
}
datesArray.removeAtIndex(datesArray.count - 1)
return datesArray
}
/// Returns the next month's date
func nextMonthDate() -> NSDate {
let nextCalendar = NSCalendar.currentCalendar()
let nextComponents = nextCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
nextComponents.month = nextComponents.month + 1
guard let nextMonth = nextCalendar.dateFromComponents(nextComponents) else {
return NSDate()
}
return nextMonth
}
/// Returns the previous month's date
func previousMonthDate() -> NSDate {
let prevCalendar = NSCalendar.currentCalendar()
let prevComponents = prevCalendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
prevComponents.month = prevComponents.month - 1
guard let prevMonth = prevCalendar.dateFromComponents(prevComponents) else {
return NSDate()
}
return prevMonth
}
/// Returns the month's first day
func getMonthFirstDay() -> NSDate? {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.systemTimeZone()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
components.day = 1
return calendar.dateFromComponents(components)
}
/// Returns a touple(year, month, day) as the date's components
func components() -> (year: Int, month: Int, day: Int) {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: self)
return (components.year, components.month, components.day)
}
/// Returns the number of days in the month
func numberOfDaysInMonth() -> Int {
let calendar = NSCalendar.currentCalendar()
let daysRange = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: self)
return daysRange.length
}
}
extension NSDate: Comparable {}
public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 == rhs.timeIntervalSince1970
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
} | 3e49606c8838d24930f6c74ca311e92b | 37.168776 | 193 | 0.654395 | false | false | false | false |
butterproject/butter-ios | refs/heads/master | Butter/API/ButterAPIManager.swift | gpl-3.0 | 1 | //
// ButterAPIManager.swift
// Butter
//
// Created by DjinnGA on 24/07/2015.
// Copyright (c) 2015 Butter Project. All rights reserved.
//
import Foundation
class ButterAPIManager: NSObject {
static let sharedInstance = ButterAPIManager()
let moviesAPIEndpoint: String = "http://vodo.net/popcorn" // ToDo: Add Vodo
let moviesAPIEndpointCloudFlareHost : String = ""
let TVShowsAPIEndpoint: String = ""
let animeAPIEndpoint: String = ""
var isSearching = false
var cachedMovies = OrderedDictionary<String,ButterItem>()
var cachedTVShows = OrderedDictionary<String,ButterItem>()
var cachedAnime = OrderedDictionary<String,ButterItem>()
var moviesPage = 0
var showsPage = 0
var searchPage = 0
static let languages = [
"ar": "Arabic",
"eu": "Basque",
"bs": "Bosnian",
"br": "Breton",
"bg": "Bulgarian",
"zh": "Chinese",
"hr": "Croatian",
"cs": "Czech",
"da": "Danish",
"nl": "Dutch",
"en": "English",
"et": "Estonian",
"fi": "Finnish",
"fr": "French",
"de": "German",
"el": "Greek",
"he": "Hebrew",
"hu": "Hungarian",
"it": "Italian",
"lt": "Lithuanian",
"mk": "Macedonian",
"fa": "Persian",
"pl": "Polish",
"pt": "Portuguese",
"ro": "Romanian",
"ru": "Russian",
"sr": "Serbian",
"sl": "Slovene",
"es": "Spanish",
"sv": "Swedish",
"th": "Thai",
"tr": "Turkish",
"uk": "Ukrainian"
]
var searchResults = OrderedDictionary<String,ButterItem>()
var amountToLoad: Int = 50
var mgenres: [String] = ["All"]
var genres: [String] {
set(newValue) {
self.mgenres = newValue
if (newValue[0] != "All") {
isSearching = true
searchPage = 0
} else {
isSearching = false
}
}
get {
return self.mgenres
}
}
var quality: String = "All"
private var msearchString: String = ""
var searchString: String {
set(newValue) {
self.msearchString = newValue.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
searchResults = OrderedDictionary<String,ButterItem>()
if (newValue != "") {
isSearching = true
searchPage = 0
} else {
isSearching = false
}
}
get {
return self.msearchString
}
}
func loadMovies(onCompletion: (newItems : Bool) -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++moviesPage
}
MovieAPI.sharedInstance.load(page) { (newItems) in
onCompletion(newItems: newItems)
}
}
func loadTVShows(onCompletion: (newItems : Bool) -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++showsPage
}
TVAPI.sharedInstance.load(page) { (newItems) in
onCompletion(newItems: newItems)
}
}
func loadAnime(onCompletion: () -> Void) {
var page : Int!
if isSearching {
page = ++searchPage
} else {
page = ++showsPage
}
AnimeAPI.sharedInstance.load(page, onCompletion: {
onCompletion()
})
}
func makeMagnetLink(torrHash:String, title: String)-> String {
let torrentHash = torrHash
let movieTitle = title
let demoniiTracker = "udp://open.demonii.com:1337"
let istoleTracker = "udp://tracker.istole.it:80"
let yifyTracker = "http://tracker.yify-torrents.com/announce"
let publicbtTracker = "udp://tracker.publicbt.com:80"
let openBTTracker = "udp://tracker.openbittorrent.com:80"
let copperTracker = "udp://tracker.coppersurfer.tk:6969"
let desync1Tracker = "udp://exodus.desync.com:6969"
let desync2Tracker = "http://exodus.desync.com:6969/announce"
let magnetURL = "magnet:?xt=urn:btih:\(torrentHash)&dn=\(movieTitle)&tr=\(demoniiTracker)&tr=\(istoleTracker)&tr=\(yifyTracker)&tr=\(publicbtTracker)&tr=\(openBTTracker)&tr=\(copperTracker)&tr=\(desync1Tracker)&tr=\(desync2Tracker)"
return magnetURL
}
} | f2f3157291f86c630b78a4b19477d16e | 25.980892 | 240 | 0.578512 | false | false | false | false |
gtsif21/PushNotificationHandler | refs/heads/master | PushNotificationHandler/PushNotificationHandler.swift | mit | 1 | //
// PushNotificationHandler.swift
//
// Created by George Tsifrikas on 16/06/16.
// Copyright © 2016 George Tsifrikas. All rights reserved.
//
import Foundation
struct WeakContainer<T: AnyObject> {
weak var _value : T?
init (value: T) {
_value = value
}
func get() -> T? {
return _value
}
}
public class PushNotificationHandler {
public static let sharedInstance = PushNotificationHandler()
private var subscribers: [WeakContainer<UIViewController>] = []
private var apnsToken: String?
public typealias NewTokenHandlerArguments = (tokenData: Data?, token: String?, error: Error?)
private var newTokenHandler: (NewTokenHandlerArguments) -> Void = {_,_,_ in}
private func alreadySubscribedIndex(potentialSubscriber: PushNotificationSubscriber) -> Int? {
return subscribers.index(where: { (weakSubscriber) -> Bool in
guard let validPotentialSubscriber = potentialSubscriber as? UIViewController,
let validWeakSubscriber = weakSubscriber.get() else {
return false
}
return validPotentialSubscriber === validWeakSubscriber
})
}
public func registerNewAPNSTokenHandler(handler: @escaping (NewTokenHandlerArguments) -> Void) {
newTokenHandler = handler
}
public func subscribeForPushNotifications<T: PushNotificationSubscriber>(subscriber: T) {
if let validSubscriber = subscriber as? UIViewController {
if alreadySubscribedIndex(potentialSubscriber: subscriber) == nil {
subscribers += [WeakContainer(value: validSubscriber)]
}
}
}
public func unsubscribeForPushNotifications<T: PushNotificationSubscriber>(subscriber: T) {
if let index = alreadySubscribedIndex(potentialSubscriber: subscriber) {
subscribers.remove(at: index)
}
}
public func registerForPushNotifications(application: UIApplication) {
let notificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
}
public func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != .none {
application.registerForRemoteNotifications()
}
}
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
apnsToken = tokenString
newTokenHandler((tokenData: deviceToken, token: tokenString, error: nil))
}
public func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
newTokenHandler((tokenData: nil, token: nil, error: error))
print("Failed to register:", error)
}
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
let aps = userInfo["aps"]
handleAPNS(aps: aps as! [AnyHashable : Any])
}
private func handleAPNS(aps: [AnyHashable : Any]) {
for containerOfSubscriber in subscribers {
(containerOfSubscriber.get() as? PushNotificationSubscriber)?.newPushNotificationReceived(aps: aps)
}
}
public func handleApplicationStartWith(application: UIApplication, launchOptions: [UIApplicationLaunchOptionsKey : Any]?) {
if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {
if let aps = notification["aps"] as? [String: AnyObject] {
handleAPNS(aps: aps)
}
}
}
}
public protocol PushNotificationSubscriber {
func newPushNotificationReceived(aps: [AnyHashable : Any])
}
| 729c23dad3fb740c1a20c8664be43a55 | 37.037736 | 127 | 0.670635 | false | false | false | false |
iadmir/Signal-iOS | refs/heads/master | Signal/src/views/AudioProgressView.swift | gpl-3.0 | 2 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import UIKit
@objc class AudioProgressView: UIView {
override var bounds: CGRect {
didSet {
if oldValue != bounds {
updateSubviews()
}
}
}
override var frame: CGRect {
didSet {
if oldValue != frame {
updateSubviews()
}
}
}
var horizontalBarColor = UIColor.black {
didSet {
updateContent()
}
}
var progressColor = UIColor.blue {
didSet {
updateContent()
}
}
private let horizontalBarLayer: CAShapeLayer
private let progressLayer: CAShapeLayer
var progress: CGFloat = 0 {
didSet {
if oldValue != progress {
updateContent()
}
}
}
@available(*, unavailable, message:"use other constructor instead.")
required init?(coder aDecoder: NSCoder) {
fatalError("\(#function) is unimplemented.")
}
public required init() {
self.horizontalBarLayer = CAShapeLayer()
self.progressLayer = CAShapeLayer()
super.init(frame:CGRect.zero)
self.layer.addSublayer(self.horizontalBarLayer)
self.layer.addSublayer(self.progressLayer)
}
internal func updateSubviews() {
AssertIsOnMainThread()
self.horizontalBarLayer.frame = self.bounds
self.progressLayer.frame = self.bounds
updateContent()
}
internal func updateContent() {
AssertIsOnMainThread()
let horizontalBarPath = UIBezierPath()
let horizontalBarHeightFraction = CGFloat(0.25)
let horizontalBarHeight = bounds.size.height * horizontalBarHeightFraction
horizontalBarPath.append(UIBezierPath(rect: CGRect(x: 0, y:(bounds.size.height - horizontalBarHeight) * 0.5, width:bounds.size.width, height:horizontalBarHeight)))
horizontalBarLayer.path = horizontalBarPath.cgPath
horizontalBarLayer.fillColor = horizontalBarColor.cgColor
let progressHeight = bounds.self.height
let progressWidth = progressHeight * 0.15
let progressX = (bounds.self.width - progressWidth) * max(0.0, min(1.0, progress))
let progressBounds = CGRect(x:progressX, y:0, width:progressWidth, height:progressHeight)
let progressCornerRadius = progressWidth * 0.5
let progressPath = UIBezierPath()
progressPath.append(UIBezierPath(roundedRect: progressBounds, cornerRadius: progressCornerRadius))
progressLayer.path = progressPath.cgPath
progressLayer.fillColor = progressColor.cgColor
}
}
| c427436ee3690a6bc2641861072022a5 | 28.25 | 171 | 0.632479 | false | false | false | false |
rcobelli/GameOfficials | refs/heads/master | Game Officials/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// Game Officials
//
// Created by Ryan Cobelli on 1/2/17.
// Copyright © 2017 Rybel LLC. All rights reserved.
//
import UIKit
import Eureka
import Alamofire
import MessageUI
class GameViewController: FormViewController, MFMailComposeViewControllerDelegate {
var json : JSON = ""
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
let params : Parameters = ["username" : UserDefaults.standard.string(forKey: "username")!, "password": UserDefaults.standard.string(forKey: "password")!]
Alamofire.request("https://rybel-llc.com/game-officials/otherOfficialsInfo.php?id=" + json["GameID"].string!, method: .post, parameters: params)
.responseString { response in
if response.result.isSuccess {
if let dataFromString = response.result.value?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
let info = JSON(data: dataFromString)
if info["REF"].array != nil {
if (info["REF"].array?.count)! > 1 {
self.createOfficial(position: "Ref", email: info["REF"][1].string, phone: info["REF"][0].string)
}
else {
if info["REF"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "Ref", email: nil, phone: info["REF"][0].string)
}
else {
self.createOfficial(position: "Ref", email: info["REF"][0].string, phone: nil)
}
}
}
if info["AR1"].array != nil {
if (info["AR1"].array?.count)! > 1 {
self.createOfficial(position: "AR1", email: info["AR1"][1].string, phone: info["AR1"][0].string)
}
else {
if info["AR1"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "AR1", email: nil, phone: info["AR1"][0].string)
}
else {
self.createOfficial(position: "AR1", email: info["AR1"][0].string, phone: nil)
}
}
}
if info["AR2"].array != nil {
if (info["AR2"].array?.count)! > 1 {
self.createOfficial(position: "AR2", email: info["AR2"][1].string, phone: info["AR2"][0].string)
}
else {
if info["AR2"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "AR2", email: nil, phone: info["AR2"][0].string)
}
else {
self.createOfficial(position: "AR2", email: info["AR2"][0].string, phone: nil)
}
}
}
if info["FOURTH"].array != nil {
if (info["FOURTH"].array?.count)! > 1 {
self.createOfficial(position: "4th", email: info["FOURTH"][1].string, phone: info["FOURTH"][0].string)
}
else {
if info["FOURTH"][0].string?.range(of: "[") != nil {
self.createOfficial(position: "4th", email: nil, phone: info["FOURTH"][0].string)
}
else {
self.createOfficial(position: "4th", email: info["FOURTH"][0].string, phone: nil)
}
}
}
}
else {
print("Can not encode")
}
}
else {
print("Could Not Load Data")
}
}
self.title = "Game #: " + String(describing: json["GameNumber"]).replacingOccurrences(of: " ", with: "")
let teams = String(describing: json["Teams"]).components(separatedBy: " vs. ")
let info = Section("Game Info")
<<< LabelRow(){ row in
row.title = (String(describing: json["DateAndTime"]).components(separatedBy: " "))[0].replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = (String(describing: json["Venue"]).components(separatedBy: " "))[0]
}
<<< LabelRow(){ row in
row.title = String(describing: json["League"]).replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = String(describing: json["Division"]).replacingOccurrences(of: " ", with: "")
}
<<< LabelRow(){ row in
row.title = "Home Team: " + teams[0]
}
<<< LabelRow(){ row in
row.title = "Away Team: " + teams[1]
}
form += [info]
}
func createOfficial(position: String, email: String?, phone: String?) {
var section = Section(position)
<<< LabelRow(){ row in
row.title = json["Officials"][position].string?.replacingOccurrences(of: " ", with: "")
}
if email != nil {
let button = ButtonRow(){ row in
row.title = email!
}.onCellSelection { cell, row in
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([email!])
self.present(mail, animated: true, completion: nil)
}
else {
DispatchQueue.global().async {
UIPasteboard.general.string = email!
}
let alert = UIAlertController(title: "Unable To Send Email", message: "The mail app is not setup, so we copied the email address to your clipboard instead", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
section += [button]
}
if phone != nil {
let button = ButtonRow(){ row in
row.title = phone!
}.onCellSelection { cell, row in
let correctedNumber = phone!.digits
print(correctedNumber)
if let url = URL(string:"tel://\(correctedNumber)"), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
else {
DispatchQueue.global().async {
UIPasteboard.general.string = email!
}
let alert = UIAlertController(title: "Unable To Make Call", message: "We were unable to complete the call, so we copied the phone number to your clipboard instead", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
section += [button]
}
form += [section]
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
| ddd2d2201a2fa61e8574b1768466cc21 | 34.171271 | 216 | 0.614515 | false | false | false | false |
cfilipov/MuscleBook | refs/heads/master | MuscleBook/DB+Calculations.swift | gpl-3.0 | 1 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import SQLite
extension DB {
func get(type: PersonalRecord.Type, input: Workset.Input) -> [PersonalRecord] {
guard let exerciseID = input.exerciseID else { return [] }
var records: [PersonalRecord] = []
let calculations = input.calculations
if let weight = input.weight,
w = maxReps(exerciseID: exerciseID, weight: weight, todate: input.startTime) {
records.append(
.MaxReps(
worksetID: w.worksetID,
maxReps: w.input.reps!,
curReps: input.reps))
}
if let w = maxRM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxWeight(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
if let w = max1RM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.Max1RM(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
if let w = maxE1RM(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxE1RM(
worksetID: w.worksetID,
maxWeight: w.calculations.e1RM!,
curWeight: calculations.findmap {
if case let .E1RM(val) = $0 { return val }
return nil
}))
}
if let w = maxVolume(exerciseID: exerciseID, todate: input.startTime) {
records.append(
.MaxVolume(
worksetID: w.worksetID,
maxVolume: w.calculations.volume!,
curVolume: calculations.findmap {
if case let .Volume(val) = $0 { return val }
return nil
}))
}
if let reps = input.reps,
w = maxXRM(exerciseID: exerciseID, reps: reps, todate: input.startTime) {
records.append(
.MaxXRM(
worksetID: w.worksetID,
maxWeight: w.input.weight!,
curWeight: input.weight))
}
return records
}
func get(type: Records.Type, input: Workset.Input) -> Records? {
guard let exerciseID = input.exerciseID else { return nil }
var perf = Records()
perf.maxReps = input.weight.flatMap { self.maxReps(exerciseID: exerciseID, weight: $0, todate: input.startTime) }
perf.maxWeight = maxRM(exerciseID: exerciseID, todate: input.startTime)
perf.max1RM = max1RM(exerciseID: exerciseID, todate: input.startTime)
perf.maxE1RM = maxE1RM(exerciseID: exerciseID, todate: input.startTime)
perf.maxVolume = maxVolume(exerciseID: exerciseID, todate: input.startTime)
perf.maxXRM = input.reps.flatMap { maxXRM(exerciseID: exerciseID, reps: $0, todate: input.startTime) }
return perf
}
func maxRM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1))
}
func maxReps(exerciseID exerciseID: Int64, weight: Double, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight >= weight &&
Workset.Schema.reps != nil)
.order(Workset.Schema.reps.desc)
.limit(1)
)
}
func max1RM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.reps == 1 &&
W.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1))
}
func maxE1RM(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.e1RM != nil)
.order(W.e1RM.desc)
.limit(1))
}
func maxXRM(exerciseID exerciseID: Int64, reps: Int, todate date: NSDate = NSDate()) -> Workset? {
typealias W = Workset.Schema
return db.pluck(W.table
.filter(
W.startTime.localDay < date.localDay &&
W.exerciseID == exerciseID &&
W.exerciseID != nil &&
W.reps == reps &&
W.weight != nil)
.order(Workset.Schema.weight.desc)
.limit(1)
)
}
func maxVolume(exerciseID exerciseID: Int64, todate date: NSDate = NSDate()) -> Workset? {
return db.pluck(
Workset.Schema.table
.filter(
Workset.Schema.startTime.localDay < date.localDay &&
Workset.Schema.exerciseID == exerciseID &&
Workset.Schema.exerciseID != nil &&
Workset.Schema.weight != nil &&
Workset.Schema.volume != nil)
.order(Workset.Schema.volume.desc)
.limit(1))
}
func maxSquat(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 973))
}
func maxDeadlift(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 723))
}
func maxBench(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.weight.max)
.filter(
W.startTime.localDay >= date &&
W.exerciseID == 482))
}
func recalculateAll(after startTime: NSDate = NSDate(timeIntervalSince1970: 0)) throws {
typealias W = Workset.Schema
for workset: Workset in try db.prepare(W.table.filter(W.startTime >= startTime)) {
guard let records = get(Records.self, input: workset.input) else { continue }
let relRecords = RelativeRecords(input: workset.input, records: records)
let newWorkset = workset.copy(input: workset.input, calculations: relRecords.calculations)
try update(newWorkset)
try recalculate(workoutID: workset.workoutID)
}
}
func totalActiveDuration(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.duration.sum)
.filter(W.startTime.localDay >= date))
}
func totalSets(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.worksetID.count)
.filter(W.startTime.localDay >= date))
}
func totalReps(sinceDate date: NSDate) -> Int? {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.reps.sum)
.filter(W.startTime.localDay >= date))
}
func totalVolume(sinceDate date: NSDate) -> Double? {
typealias W = Workset.Schema
let query: ScalarQuery = W.table.select(W.volume.sum)
return db.scalar(query.filter(W.startTime.localDay >= date))
}
func totalPRs(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.worksetID.count)
.filter(W.startTime.localDay >= date &&
(W.intensity > 1.0 || W.intensity > 1.0)))
}
func volumeByDay() throws -> [(NSDate, Double)] {
let cal = NSCalendar.currentCalendar()
return try all(Workout).map { workout in
let date = cal.startOfDayForDate(workout.startTime)
return (date, workout.volume ?? 0)
}
}
}
| fce59cbfe451a094071db0b672047686 | 37.753968 | 121 | 0.54915 | false | false | false | false |
abunur/quran-ios | refs/heads/master | Quran/QuranImageHighlightingView.swift | gpl-3.0 | 1 | //
// QuranImageHighlightingView.swift
// Quran
//
// Created by Mohamed Afifi on 4/24/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
// This class is expected to be implemented using CoreAnimation with CAShapeLayers.
// It's also expected to reuse layers instead of dropping & creating new ones.
class QuranImageHighlightingView: UIView {
var highlights: [QuranHighlightType: Set<AyahNumber>] = [:] {
didSet { updateRectangleBounds() }
}
var ayahInfoData: [AyahNumber: [AyahInfo]]? {
didSet { updateRectangleBounds() }
}
var imageScale: CGRect.Scale = .zero {
didSet { updateRectangleBounds() }
}
var highlightedPosition: AyahWord.Position? {
didSet { updateRectangleBounds() }
}
var highlightingRectangles: [QuranHighlightType: [CGRect]] = [:]
func reset() {
highlights = [:]
ayahInfoData = nil
imageScale = .zero
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard !highlights.isEmpty else { return }
let context = UIGraphicsGetCurrentContext()
for (highlightType, rectangles) in highlightingRectangles {
context?.setFillColor(highlightType.color.cgColor)
for rect in rectangles {
context?.fill(rect)
}
}
}
private func updateRectangleBounds() {
highlightingRectangles.removeAll()
var filteredHighlightAyats: [QuranHighlightType: Set<AyahNumber>] = [:]
for type in QuranHighlightType.sortedTypes {
let existingAyahts = filteredHighlightAyats.reduce(Set<AyahNumber>()) { $0.union($1.value) }
var ayats = highlights[type] ?? Set<AyahNumber>()
ayats.subtract(existingAyahts)
filteredHighlightAyats[type] = ayats
}
for (type, ayat) in filteredHighlightAyats {
var rectangles: [CGRect] = []
for ayah in ayat {
guard let ayahInfo = ayahInfoData?[ayah] else { continue }
for piece in ayahInfo {
let rectangle = piece.rect.scaled(by: imageScale)
rectangles.append(rectangle)
}
}
highlightingRectangles[type] = rectangles
}
if let position = highlightedPosition, let infos = ayahInfoData?[position.ayah] {
for info in infos where info.position == position.position {
highlightingRectangles[.wordByWord] = [info.rect.scaled(by: imageScale)]
break
}
}
setNeedsDisplay()
}
// MARK: - Location of ayah
func ayahWordPosition(at location: CGPoint, view: UIView) -> AyahWord.Position? {
guard let ayahInfoData = ayahInfoData else { return nil }
for (ayahNumber, ayahInfos) in ayahInfoData {
for piece in ayahInfos {
let rectangle = piece.rect.scaled(by: imageScale)
if rectangle.contains(location) {
return AyahWord.Position(ayah: ayahNumber, position: piece.position, frame: convert(rectangle, to: view))
}
}
}
return nil
}
}
| ec0f19f8af7f46018dd597d87b3553c9 | 33.354545 | 125 | 0.622122 | false | false | false | false |
brentvatne/react-native-video | refs/heads/master | ios/Video/Features/RCTVideoSave.swift | mit | 1 | import AVFoundation
enum RCTVideoSave {
static func save(
options:NSDictionary!,
resolve: @escaping RCTPromiseResolveBlock,
reject:@escaping RCTPromiseRejectBlock,
playerItem: AVPlayerItem?
) {
let asset:AVAsset! = playerItem?.asset
guard asset != nil else {
reject("ERROR_ASSET_NIL", "Asset is nil", nil)
return
}
guard let exportSession = AVAssetExportSession(asset: asset, presetName:AVAssetExportPresetHighestQuality) else {
reject("ERROR_COULD_NOT_CREATE_EXPORT_SESSION", "Could not create export session", nil)
return
}
var path:String! = nil
path = RCTVideoSave.generatePathInDirectory(
directory: URL(fileURLWithPath: RCTVideoSave.cacheDirectoryPath() ?? "").appendingPathComponent("Videos").path,
withExtension: ".mp4")
let url:NSURL! = NSURL.fileURL(withPath: path) as NSURL
exportSession.outputFileType = AVFileType.mp4
exportSession.outputURL = url as URL?
exportSession.videoComposition = playerItem?.videoComposition
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously(completionHandler: {
switch (exportSession.status) {
case .failed:
reject("ERROR_COULD_NOT_EXPORT_VIDEO", "Could not export video", exportSession.error)
break
case .cancelled:
reject("ERROR_EXPORT_SESSION_CANCELLED", "Export session was cancelled", exportSession.error)
break
default:
resolve(["uri": url.absoluteString])
break
}
})
}
static func generatePathInDirectory(directory: String?, withExtension `extension`: String?) -> String? {
let fileName = UUID().uuidString + (`extension` ?? "")
RCTVideoSave.ensureDirExists(withPath: directory)
return URL(fileURLWithPath: directory ?? "").appendingPathComponent(fileName).path
}
static func cacheDirectoryPath() -> String? {
let array = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).map(\.path)
return array[0]
}
static func ensureDirExists(withPath path: String?) -> Bool {
var isDir: ObjCBool = false
var error: Error?
let exists = FileManager.default.fileExists(atPath: path ?? "", isDirectory: &isDir)
if !(exists && isDir.boolValue) {
do {
try FileManager.default.createDirectory(atPath: path ?? "", withIntermediateDirectories: true, attributes: nil)
} catch {
}
if error != nil {
return false
}
}
return true
}
}
| b4318b1bbd048f286a645e77ab005358 | 37.226667 | 127 | 0.598884 | false | false | false | false |
yarshure/Surf | refs/heads/UIKitForMac | Surf/CheckTableViewController.swift | bsd-3-clause | 1 | //
// CheckTableViewController.swift
// Surf
//
// Created by yarshure on 2018/1/13.
// Copyright © 2018年 A.BIG.T. All rights reserved.
//
import UIKit
class CheckTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| ffc9dcd193d29841e3c2a6df813d596f | 31.852632 | 136 | 0.670298 | false | false | false | false |
raptorxcz/Rubicon | refs/heads/main | Rubicon/FileReaderImpl.swift | mit | 1 | //
// FileReaderImpl.swift
// Rubicon
//
// Created by Kryštof Matěj on 08/05/2017.
// Copyright © 2017 Kryštof Matěj. All rights reserved.
//
import Foundation
public class FileReaderImpl: FileReader {
public func readFiles(at path: String) -> [String] {
let fileNames = findFileNames(at: path)
let contentOfFiles = fileNames.compactMap({ try? String(contentsOfFile: $0, encoding: .utf8) })
return contentOfFiles
}
private func findFileNames(at path: String) -> [String] {
let fileManager = FileManager.default
var fileNames = [String]()
let items = try! FileManager.default.contentsOfDirectory(atPath: path)
for fileName in items {
let itemPath = path + "/" + fileName
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: itemPath, isDirectory: &isDir) {
if isDir.boolValue {
fileNames += findFileNames(at: itemPath)
} else {
if fileName.hasSuffix(".swift") {
fileNames.append(itemPath)
}
}
}
}
return fileNames
}
}
| 84485b5c56e76520012d7ff40e5b364c | 27.093023 | 103 | 0.570364 | false | false | false | false |
CodaFi/swift | refs/heads/main | stdlib/public/Platform/TiocConstants.swift | apache-2.0 | 40 | //===----------------------------------------------------------------------===//
//
// 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(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(FreeBSD) || os(Haiku)
/// 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(macOS) || 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
| ebdb6da60b23f44801536f52146ba479 | 34.545455 | 80 | 0.711157 | false | false | false | false |
xmartlabs/Bender | refs/heads/master | Sources/Core/ParameterDataSource.swift | mit | 1 | //
// ParameterDataSource.swift
// MetalBender
//
// Created by Mathias Claassen on 4/2/18.
//
import MetalPerformanceShaders
@available(iOS 11.0, *)
public class ConvolutionDataSource: NSObject, MPSCNNConvolutionDataSource {
public func copy(with zone: NSZone? = nil) -> Any {
if let parameterLoader = parameterLoader {
return ConvolutionDataSource(cnnDescriptor: cnnDescriptor, parameterLoader: parameterLoader, layerId: layerId, weightCount: weightCount, biasCount: biasCount, useHalf: useHalf)
} else {
return ConvolutionDataSource(cnnDescriptor: cnnDescriptor, weights: weightsPointer, bias: biasPointer, useHalf: useHalf)
}
}
var useHalf: Bool
var cnnDescriptor: MPSCNNConvolutionDescriptor
var weightsPointer: UnsafeMutableRawPointer?
var biasPointer: UnsafeMutablePointer<Float>?
var parameterLoader: ParameterLoader?
var layerId: String = ""
var weightCount: Int = -1, biasCount: Int = -1
public init(cnnDescriptor: MPSCNNConvolutionDescriptor, weights: UnsafeMutableRawPointer?,
bias: UnsafeMutablePointer<Float>?, useHalf: Bool = false) {
self.useHalf = useHalf
self.cnnDescriptor = cnnDescriptor
self.weightsPointer = weights
self.biasPointer = bias
}
public init(cnnDescriptor: MPSCNNConvolutionDescriptor, parameterLoader: ParameterLoader, layerId: String,
weightCount: Int, biasCount: Int, useHalf: Bool = false) {
self.useHalf = useHalf
self.cnnDescriptor = cnnDescriptor
self.layerId = layerId
self.weightCount = weightCount
self.biasCount = biasCount
self.parameterLoader = parameterLoader
}
public func dataType() -> MPSDataType {
return useHalf ? .float16 : .float32
}
public func weights() -> UnsafeMutableRawPointer {
return weightsPointer!
}
public func descriptor() -> MPSCNNConvolutionDescriptor {
return cnnDescriptor
}
public func biasTerms() -> UnsafeMutablePointer<Float>? {
guard let bias = biasPointer else {
return nil
}
return bias
}
public func load() -> Bool {
if let parameterLoader = parameterLoader {
biasPointer = UnsafeMutablePointer(mutating: parameterLoader.loadWeights(for: layerId,
modifier: Convolution.biasModifier,
size: biasCount))
weightsPointer = UnsafeMutableRawPointer(mutating: parameterLoader.loadWeights(for: layerId,
modifier: Convolution.weightModifier,
size: weightCount))
}
return true
}
public func purge() {
if parameterLoader != nil {
biasPointer = nil
weightsPointer = nil
}
}
public func label() -> String? {
return nil
}
}
| 8f14ea1f24c2d2886fb7878ccf669f15 | 34.355556 | 188 | 0.59648 | false | false | false | false |
qingcai518/MyReader_ios | refs/heads/develop | MyReader/CloudController.swift | mit | 1 | //
// CloudController.swift
// MyReader
//
// Created by RN-079 on 2017/02/20.
// Copyright © 2017年 RN-079. All rights reserved.
//
import UIKit
import MJRefresh
import Kingfisher
class CloudController: ViewController {
@IBOutlet weak var tableView : UITableView!
let model = CloudModel()
var header : MJRefreshGifHeader!
var footer : MJRefreshAutoNormalFooter!
var currentInfo : CloudBookInfo!
override func viewDidLoad() {
super.viewDidLoad()
createIndicator()
setRefreshHeaderAndFooter()
setTableView()
getData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
private func setRefreshHeaderAndFooter() {
header = MJRefreshGifHeader(refreshingTarget: self, refreshingAction: #selector(getData))
footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(getMoreData))
header.setImages(AppUtility.getIdleImages(), for: .idle)
header.setImages(AppUtility.getPullingImages(), for: .pulling)
header.setImages(AppUtility.getRefreshingImages(), duration: 1, for: .refreshing)
footer.isHidden = true
tableView.mj_header = header
tableView.mj_footer = footer
}
private func setTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
func getData() {
startIndicator()
model.getCloudBooks { [weak self] msg in
self?.header.endRefreshing()
self?.stopIndicator()
if let errorMsg = msg {
print("error = \(errorMsg)")
} else {
self?.footer.isHidden = false
}
self?.tableView.reloadData()
}
}
func getMoreData() {
model.getMoreCloudBooks { [weak self] (msg, isLast) in
self?.footer.endRefreshing()
self?.footer.isHidden = isLast
if let errorMsg = msg {
print("error = \(errorMsg)")
}
self?.tableView.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "ToCloudDetail") {
guard let next = segue.destination as? CloudDetailController else {
return
}
next.bookInfo = currentInfo
next.hidesBottomBarWhenPushed = true
}
}
}
extension CloudController : UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 144
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
currentInfo = model.cloudBooks[indexPath.row]
self.performSegue(withIdentifier: "ToCloudDetail", sender: nil)
}
}
extension CloudController : UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.cloudBooks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let info = model.cloudBooks[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "CloudCell", for: indexPath) as! CloudCell
cell.bookNameLbl.text = info.bookName
cell.bookImgView.kf.setImage(with: URL(string: info.bookImgUrl))
cell.authorNameLbl.text = info.authorName
cell.detailLbl.text = info.detail
cell.cosmosView.rating = info.rating
cell.cosmosView.text = String(info.rating)
return cell
}
}
| 380ca86776be28f86ef304fda63901d2 | 29.607692 | 108 | 0.615481 | false | false | false | false |
3drobotics/HanekeSwift | refs/heads/AlamofireFetcher | Badger/Haneke/UIView+Haneke.swift | apache-2.0 | 60 | //
// UIView+Haneke.swift
// Haneke
//
// Created by Joan Romano on 15/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
public extension HanekeGlobals {
public struct UIKit {
static func formatWithSize(size : CGSize, scaleMode : ImageResizer.ScaleMode, allowUpscaling: Bool = true) -> Format<UIImage> {
let name = "auto-\(size.width)x\(size.height)-\(scaleMode.rawValue)"
let cache = Shared.imageCache
if let (format,_,_) = cache.formats[name] {
return format
}
var format = Format<UIImage>(name: name,
diskCapacity: HanekeGlobals.UIKit.DefaultFormat.DiskCapacity) {
let resizer = ImageResizer(size:size,
scaleMode: scaleMode,
allowUpscaling: allowUpscaling,
compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
return resizer.resizeImage($0)
}
format.convertToData = {(image : UIImage) -> NSData in
image.hnk_data(compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
}
return format
}
public struct DefaultFormat {
public static let DiskCapacity : UInt64 = 10 * 1024 * 1024
public static let CompressionQuality : Float = 0.75
}
static var SetImageFetcherKey = 0
static var SetBackgroundImageFetcherKey = 1
}
}
| 2ed1a207357d17537e6b2b88aa2933ac | 33.212766 | 135 | 0.566542 | false | false | false | false |
mas-cli/mas | refs/heads/main | Sources/MasKit/Controllers/MasAppLibrary.swift | mit | 1 | //
// MasAppLibrary.swift
// MasKit
//
// Created by Ben Chatelain on 12/27/18.
// Copyright © 2018 mas-cli. All rights reserved.
//
import CommerceKit
/// Utility for managing installed apps.
class MasAppLibrary: AppLibrary {
/// CommerceKit's singleton manager of installed software.
private let softwareMap: SoftwareMap
/// Array of installed software products.
lazy var installedApps: [SoftwareProduct] = softwareMap.allSoftwareProducts().filter { product in
product.bundlePath.starts(with: "/Applications/")
}
/// Internal initializer for providing a mock software map.
/// - Parameter softwareMap: SoftwareMap to use
init(softwareMap: SoftwareMap = CKSoftwareMap.shared()) {
self.softwareMap = softwareMap
}
/// Finds an app using a bundle identifier.
///
/// - Parameter bundleId: Bundle identifier of app.
/// - Returns: Software Product of app if found; nil otherwise.
func installedApp(forBundleId bundleId: String) -> SoftwareProduct? {
softwareMap.product(for: bundleId)
}
/// Uninstalls an app.
///
/// - Parameter app: App to be removed.
/// - Throws: Error if there is a problem.
func uninstallApp(app: SoftwareProduct) throws {
if !userIsRoot() {
printWarning("Apps installed from the Mac App Store require root permission to remove.")
}
let appUrl = URL(fileURLWithPath: app.bundlePath)
do {
// Move item to trash
var trashUrl: NSURL?
try FileManager().trashItem(at: appUrl, resultingItemURL: &trashUrl)
if let path = trashUrl?.path {
printInfo("App moved to trash: \(path)")
}
} catch {
printError("Unable to move app to trash.")
throw MASError.uninstallFailed
}
}
/// Detects whether the current user is root.
///
/// - Returns: true if the current user is root; false otherwise
private func userIsRoot() -> Bool {
NSUserName() == "root"
}
}
| 01808ed22bd5e5788aace1b0a5981925 | 31.328125 | 101 | 0.630739 | false | false | false | false |
AnthonyMDev/AmazonS3RequestManager | refs/heads/develop | Source/AmazonS3RequestManager/Region.swift | mit | 2 | //
// Region.swift
//
// Created by Anthony Miller on 1/17/17.
// Copyright (c) 2017 App-Order, LLC. All rights reserved.
//
import Foundation
/**
MARK: Amazon S3 Regions
The possible Amazon Web Service regions for the client.
- USStandard: N. Virginia or Pacific Northwest
- USWest1: Oregon
- USWest2: N. California
- EUWest1: Ireland
- EUCentral1: Frankfurt
- APSoutheast1: Singapore
- APSoutheast2: Sydney
- APNortheast1: Toyko
- APNortheast2: Seoul
- SAEast1: Sao Paulo
*/
public enum Region: Equatable {
case USStandard,
USWest1,
USWest2,
EUWest1,
EUCentral1,
APSoutheast1,
APSoutheast2,
APNortheast1,
APNortheast2,
SAEast1,
custom(hostName: String, endpoint: String)
var hostName: String {
switch self {
case .USStandard: return "us-east-1"
case .USWest1: return "us-west-1"
case .USWest2: return "us-west-2"
case .EUWest1: return "eu-west-1"
case .EUCentral1: return "eu-central-1"
case .APSoutheast1: return "ap-southeast-1"
case .APSoutheast2: return "ap-southeast-2"
case .APNortheast1: return "ap-northeast-1"
case .APNortheast2: return "ap-northeast-2"
case .SAEast1: return "sa-east-1"
case .custom(let hostName, _): return hostName
}
}
var endpoint: String {
switch self {
case .USStandard: return "s3.amazonaws.com"
case .USWest1: return "s3-us-west-1.amazonaws.com"
case .USWest2: return "s3-us-west-2.amazonaws.com"
case .EUWest1: return "s3-eu-west-1.amazonaws.com"
case .EUCentral1: return "s3-eu-central-1.amazonaws.com"
case .APSoutheast1: return "s3-ap-southeast-1.amazonaws.com"
case .APSoutheast2: return "s3-ap-southeast-2.amazonaws.com"
case .APNortheast1: return "s3-ap-northeast-1.amazonaws.com"
case .APNortheast2: return "s3-ap-northeast-2.amazonaws.com"
case .SAEast1: return "s3-sa-east-1.amazonaws.com"
case .custom(_, let endpoint): return endpoint
}
}
}
public func ==(lhs: Region, rhs: Region) -> Bool {
switch (lhs, rhs) {
case (.USStandard, .USStandard),
(.USWest1, .USWest1),
(.USWest2, .USWest2),
(.EUWest1, .EUWest1),
(.EUCentral1, .EUCentral1),
(.APSoutheast1, .APSoutheast1),
(.APSoutheast2, .APSoutheast2),
(.APNortheast1, .APNortheast1),
(.APNortheast2, .APNortheast2),
(.SAEast1, .SAEast1):
return true
case (.custom(let host1, let endpoint1), .custom(let host2, let endpoint2)):
return host1 == host2 && endpoint1 == endpoint2
default:
return false
}
}
| 825623c3cec4407032a71e8f44f25d17 | 29.247312 | 80 | 0.605759 | false | false | false | false |
netprotections/atonecon-ios | refs/heads/master | AtoneConTests/StringTests.swift | mit | 1 | //
// StringTest.swift
// AtoneCon
//
// Created by Pham Ngoc Hanh on 8/18/17.
// Copyright © 2017 AsianTech Inc. All rights reserved.
//
import XCTest
@testable import AtoneCon
final class StringTests: XCTestCase {
func testLocalizedShouldReturnStringResultWhenItWasDefinedInLocalizableString() {
// When "okay" was defined is "OK" in localizable.strings
let okay = "okay"
let network = "network"
let cancel = "cancel"
let close = "close"
let quitPayment = "quitPayment"
let networkError = "networkError"
// Then
XCTAssertEqual(okay.localized(), "OK")
XCTAssertEqual(network.localized(), "ネットワーク")
XCTAssertEqual(cancel.localized(), "キャンセル")
XCTAssertEqual(close.localized(), "閉じる")
XCTAssertEqual(quitPayment.localized(), "決済が終了します。よろしいでしょうか?")
XCTAssertEqual(networkError.localized(), "ネットワークが圏外です")
}
}
| 08a4ae813481930e5248993bd8f5b5b0 | 29.16129 | 85 | 0.657754 | false | true | false | false |
prachigauriar/PropertyListEditor | refs/heads/master | PropertyListEditor/Extensions/NSNumber+Types.swift | mit | 1 | //
// NSNumber+Types.swift
// PropertyListEditor
//
// Created by Prachi Gauriar on 7/22/2015.
// Copyright © 2015 Quantum Lens Cap. 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
extension NSNumber {
/// Returns whether the instance was initialized using a boolean.
var isBoolean: Bool {
return NSNumber(value: true).objCType == objCType
}
/// Returns whether the instance is an integer, i.e., it has no fractional part.
var isInteger: Bool {
let doubleValue = self.doubleValue
return trunc(doubleValue) == doubleValue
}
}
| ffc510fec5b331b8c4ef396e16060487 | 38.666667 | 84 | 0.728691 | false | false | false | false |
tapglue/ios_sdk | refs/heads/master | Sources/RxTapglue.swift | apache-2.0 | 2 | //
// Tapglue.swift
// Tapglue
//
// Created by John Nilsen on 6/27/16.
// Copyright © 2016 Tapglue. All rights reserved.
//
import Foundation
import RxSwift
/// Provides a RxSwift interface to the tapglue sdk
open class RxTapglue {
var userStore = UserStore()
var network: Network
open fileprivate(set) var currentUser: User? {
get {
return userStore.user
}
set {
userStore.user = newValue
}
}
/// Constructs instance of RxTapglue
/// - parameter configuration: Configuration to be used
public init(configuration: Configuration) {
Router.configuration = configuration
Log.isDebug = configuration.log
network = Network()
if let sessionToken = currentUser?.sessionToken {
Router.sessionToken = sessionToken
}
}
/// creates a user on tapglue
/// - parameter user: user to be created
/// - parameter inviteConnections: optional - if user has been invited through friend/follow
/// - Note: username or email is required, password is required
/// - Note: does not login user
/// - Note: inviteConnection may be used when providing social_ids to the user object
/// to create a pending connection to people who invited that specific social id
open func createUser(_ user: User, inviteConnections: String? = nil) -> Observable<User> {
return network.createUser(user, inviteConnections: inviteConnections)
}
/// logs in user on tapglue
/// - parameter username: username of the user to be logged in
/// - parameter password: password of the user to be logged in
open func loginUser(_ username: String, password: String) -> Observable<User> {
return network.loginUser(username, password: password).map(toCurrentUserMap)
}
/// logs in user on tapglue
/// - parameter email: email of the user to be logged in
/// - parameter password: password of the user to be logged in
open func loginUserWithEmail(_ email: String, password: String) -> Observable<User> {
return network.loginUserWithEmail(email, password: password).map(toCurrentUserMap)
}
/// update information on the current user by providing a user entity
/// - parameter user: entity with the information to be updated
open func updateCurrentUser(_ user: User) -> Observable<User> {
return network.updateCurrentUser(user).map(toCurrentUserMap)
}
/// refreshes locally stored copy of the current user
open func refreshCurrentUser() -> Observable<User> {
return network.refreshCurrentUser().map(toCurrentUserMap)
}
/// creates an invite with a socialid key and value
/// - parameter key: social id name or custom key
/// - parameter key: social id value or custom value
open func createInvite(_ key: String, _ value: String) -> Observable<Void> {
return network.createInvite(key, value)
}
/// logs out the current user
open func logout() -> Observable<Void> {
return network.logout().do(onCompleted: {
self.currentUser = nil
})
}
/// deletes current user from tapglue
open func deleteCurrentUser() -> Observable<Void> {
return network.deleteCurrentUser().do(onCompleted: {
self.currentUser = nil
})
}
/// search for users on tapglue
/// - parameter searchTerm: term to search for
@available(*, deprecated: 2.1)
open func searchUsersForSearchTerm(_ term: String) -> Observable<[User]> {
return network.searchUsers(forSearchTerm: term)
}
/// Search tapglue for users with emails
/// - parameter emails: search tapglue for users with emails within this list
@available(*, deprecated: 2.1)
open func searchEmails(_ emails: [String]) -> Observable<[User]> {
return network.searchEmails(emails)
}
/// Search tapglue for users with social ids
/// - parameter ids: list of ids to search for
/// - parameter platform: platform name for which the search is performed
@available(*, deprecated: 2.1)
open func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<[User]> {
return network.searchSocialIds(ids, onPlatform: platform)
}
/// create connection on tapglue
/// - parameter connection: connection to be created
open func createConnection(_ connection: Connection) -> Observable<Connection> {
return network.createConnection(connection)
}
/// delete connection on tapglue
/// - parameter userId: user id of the user the connection is
/// - parameter type: the type of connection to be deleted
open func deleteConnection(toUserId userId: String, type: ConnectionType)
-> Observable<Void> {
return network.deleteConnection(toUserId: userId, type: type)
}
/// create connections to users by using their ids from another platform
/// - parameter socialConnections: contains the platform name and list of ids
@available(*, deprecated: 2.1)
open func createSocialConnections(_ socialConnections: SocialConnections) ->
Observable<[User]> {
return network.createSocialConnections(socialConnections)
}
/// retrieves the followers of the current user
@available(*, deprecated: 2.1)
open func retrieveFollowers() -> Observable<[User]> {
return network.retrieveFollowers()
}
/// retrieves the users followed by the current user
@available(*, deprecated: 2.1)
open func retrieveFollowings() -> Observable<[User]> {
return network.retrieveFollowings()
}
/// retrieves followers for a given user
/// - parameter id: followers of the user of the given id
@available(*, deprecated: 2.1)
open func retrieveFollowersForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFollowersForUserId(id)
}
/// retrieves users followed by a given user
/// - parameter id: followings of the user of the given id
@available(*, deprecated: 2.1)
open func retrieveFollowingsForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFollowingsForUserId(id)
}
/// retrieve friends for current user
@available(*, deprecated: 2.1)
open func retrieveFriends() -> Observable<[User]> {
return network.retrieveFriends()
}
/// Retrieve friends for a given user
/// - parameter id: friends of the user with the given id
@available(*, deprecated: 2.1)
open func retrieveFriendsForUserId(_ id: String) -> Observable<[User]> {
return network.retrieveFriendsForUserId(id)
}
/// retrieve pending connections
@available(*, deprecated: 2.1)
open func retrievePendingConnections() -> Observable<Connections> {
return network.retrievePendingConnections()
}
/// retrieve rejected connections
@available(*, deprecated: 2.1)
open func retrieveRejectedConnections() -> Observable<Connections> {
return network.retrieveRejectedConnections()
}
/// retrieve a user
/// - parameter id: id of the user to be retrieved
open func retrieveUser(_ id: String) -> Observable<User> {
return network.retrieveUser(id)
}
/// creates post
/// - parameter post: post to be created
open func createPost(_ post: Post) -> Observable<Post> {
return network.createPost(post)
}
/// retrieve a post
/// - parameter id: id of the post to be retrieved
open func retrievePost(_ id: String) -> Observable<Post> {
return network.retrievePost(id)
}
/// update post
/// - parameter post: the post to replace the old one
/// - note: post id must be set on the post object
open func updatePost(_ id: String, post: Post) -> Observable<Post> {
return network.updatePost(id, post: post)
}
/// delete post
/// - parameter id: id of the post to be deleted
open func deletePost(_ id: String) -> Observable<Void> {
return network.deletePost(id)
}
/// retrieve posts created by a user
/// - parameter userId: id of the user from whom the posts will be retrieved
@available(*, deprecated: 2.1)
open func retrievePostsByUser(_ userId: String) -> Observable<[Post]> {
return network.retrievePostsByUser(userId)
}
/// retrieves all public and global posts
@available(*, deprecated: 2.1)
open func retrieveAllPosts() -> Observable<[Post]> {
return network.retrieveAllPosts()
}
/// Retrieves posts that have all the tags in the tags list. The query behaves like a logical
/// `and` operation
/// - parameter tags: tags to filter
@available(*, deprecated: 2.1)
open func filterPostsByTags(_ tags: [String]) -> Observable<[Post]> {
return network.filterPostsByTags(tags)
}
/// Creates a comment on a post
open func createComment(_ comment: Comment) -> Observable<Comment> {
return network.createComment(comment)
}
/// retrieve comments on a post
@available(*, deprecated: 2.1)
open func retrieveComments(_ postId: String) -> Observable<[Comment]> {
return network.retrieveComments(postId)
}
/// updates comment
/// - parameter postId: post to which the comment belongs
/// - parameter commentId: id of the comment to be updated
/// - parameter comment: the new comment to replace the old
open func updateComment(_ postId: String, commentId: String, comment: Comment) ->
Observable<Comment> {
return network.updateComment(postId, commentId: commentId, comment: comment)
}
/// deletes comment
/// - parameter postId: post to which the comment belongs
/// - parameter commentId: id of the comment to be deleted
open func deleteComment(forPostId postId: String, commentId: String) -> Observable<Void> {
return network.deleteComment(postId, commentId: commentId)
}
/// creates like
/// - parameter postId: post to be liked
@available(*, deprecated: 2.2)
open func createLike(forPostId postId: String) -> Observable<Like> {
return network.createLike(forPostId: postId)
}
/// creates reaction on a post
/// - parameter reaction: the reaction to be created. Check corresponding class for more
/// information
/// - forPostId: post on which the reaction is created
open func createReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return network.createReaction(reaction, forPostId: postId);
}
/// deletes reaction
/// - parameter reaction: the reaction to be deleted. Check corresponding class for more
/// information
/// - forPostId: post on which the reaction is deleted
open func deleteReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return network.deleteReaction(reaction, forPostId: postId)
}
/// retrieves likes on a post
/// - parameter postId: id of the post
@available(*, deprecated: 2.1)
open func retrieveLikes(_ postId: String) -> Observable<[Like]> {
return network.retrieveLikes(postId)
}
/// delete like on a post
/// - parameter postId: post that was liked
open func deleteLike(forPostId postId: String) -> Observable<Void> {
return network.deleteLike(forPostId: postId)
}
@available(*, deprecated: 2.1)
open func retrieveLikesByUser(_ userId: String) -> Observable<[Like]> {
return network.retrieveLikesByUser(userId)
}
/// Retrieves activities created by a user
/// - parameter userId: user from whom you want the activities
@available(*, deprecated: 2.1)
open func retrieveActivitiesByUser(_ userId: String) -> Observable<[Activity]> {
return network.retrieveActivitiesByUser(userId)
}
/// retrieves post feed
@available(*, deprecated: 2.1)
open func retrievePostFeed() -> Observable<[Post]> {
return network.retrievePostFeed()
}
/// retrieves activity feed
/// - note: event feed on the api documentation
@available(*, deprecated: 2.1)
open func retrieveActivityFeed() -> Observable<[Activity]> {
return network.retrieveActivityFeed()
}
/// retrieves news feed
@available(*, deprecated: 2.1)
open func retrieveNewsFeed() -> Observable<NewsFeed> {
return network.retrieveNewsFeed()
}
/// retrieves a feed of activities tageting the current user
@available(*, deprecated: 2.1)
open func retrieveMeFeed() -> Observable<[Activity]> {
return network.retrieveMeFeed()
}
/// search for users on tapglue
/// - parameter searchTerm: term to search for
open func searchUsersForSearchTerm(_ term: String) -> Observable<RxPage<User>> {
return network.searchUsers(forSearchTerm: term)
}
/// Search tapglue for users with emails
/// - parameter emails: search tapglue for users with emails within this list
open func searchEmails(_ emails: [String]) -> Observable<RxPage<User>> {
return network.searchEmails(emails)
}
/// Search tapglue for users with social ids
/// - parameter ids: list of ids to search for
/// - parameter platform: platform name for which the search is performed
open func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<RxPage<User>> {
return network.searchSocialIds(ids, onPlatform: platform)
}
/// create connections to users by using their ids from another platform
/// - parameter socialConnections: contains the platform name and list of ids
open func createSocialConnections(_ socialConnections: SocialConnections) ->
Observable<RxPage<User>> {
return network.createSocialConnections(socialConnections)
}
/// retrieves the followers of the current user
open func retrieveFollowers() -> Observable<RxPage<User>> {
return network.retrieveFollowers()
}
/// retrieves the users followed by the current user
open func retrieveFollowings() -> Observable<RxPage<User>> {
return network.retrieveFollowings()
}
/// retrieves followers for a given user
/// - parameter id: followers of the user of the given id
open func retrieveFollowersForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFollowersForUserId(id)
}
/// retrieves users followed by a given user
/// - parameter id: followings of the user of the given id
open func retrieveFollowingsForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFollowingsForUserId(id)
}
/// retrieve friends for current user
open func retrieveFriends() -> Observable<RxPage<User>> {
return network.retrieveFriends()
}
/// Retrieve friends for a given user
/// - parameter id: friends of the user with the given id
open func retrieveFriendsForUserId(_ id: String) -> Observable<RxPage<User>> {
return network.retrieveFriendsForUserId(id)
}
/// retrieve pending connections
open func retrievePendingConnections() -> Observable<RxCompositePage<Connections>> {
return network.retrievePendingConnections()
}
/// retrieve rejected connections
open func retrieveRejectedConnections() -> Observable<RxCompositePage<Connections>> {
return network.retrieveRejectedConnections()
}
/// retrieve posts created by a user
/// - parameter userId: id of the user from whom the posts will be retrieved
open func retrievePostsByUser(_ userId: String) -> Observable<RxPage<Post>> {
return network.retrievePostsByUser(userId)
}
/// retrieves all public and global posts
open func retrieveAllPosts() -> Observable<RxPage<Post>> {
return network.retrieveAllPosts()
}
/// Retrieves posts that have all the tags in the tags list. The query behaves like a logical
/// `and` operation
/// - parameter tags: tags to filter
open func filterPostsByTags(_ tags: [String]) -> Observable<RxPage<Post>> {
return network.filterPostsByTags(tags)
}
/// retrieve comments on a post
open func retrieveComments(_ postId: String) -> Observable<RxPage<Comment>> {
return network.retrieveComments(postId)
}
/// retrieves likes on a post
/// - parameter postId: id of the post
open func retrieveLikes(_ postId: String) -> Observable<RxPage<Like>> {
return network.retrieveLikes(postId)
}
open func retrieveLikesByUser(_ userId: String) -> Observable<RxPage<Like>> {
return network.retrieveLikesByUser(userId)
}
/// retrieves post feed
open func retrievePostFeed() -> Observable<RxPage<Post>> {
return network.retrievePostFeed()
}
/// retrieves activity feed
/// - note: event feed on the api documentation
open func retrieveActivityFeed() -> Observable<RxPage<Activity>> {
return network.retrieveActivityFeed()
}
/// retrieves a feed of activities tageting the current user
open func retrieveMeFeed() -> Observable<RxPage<Activity>> {
return network.retrieveMeFeed()
}
/// retrieves news feed
open func retrieveNewsFeed() -> Observable<RxCompositePage<NewsFeed>> {
return network.retrieveNewsFeed()
}
/// update count to backend
open func updateCount(newCount: Int, withNameSpace nameSpace: String) -> Observable<Void> {
return network.updateCount(newCount, nameSpace)
}
/// get count to backend
open func getCount(withNameSpace nameSpace: String) -> Observable<Count> {
return network.getCount(nameSpace)
}
fileprivate func toCurrentUserMap(_ user: User) -> User {
currentUser = user
return user
}
}
| 8b05be90378e3d56adf537d720524d9d | 41.315166 | 98 | 0.671221 | false | false | false | false |
zhugejunwei/LeetCode | refs/heads/master | 64. Minimum Path Sum.swift | mit | 1 | import Darwin
func minPathSum(grid: [[Int]]) -> Int {
var record = grid
let m = grid.count, n = grid[0].count
var i = 1
while i < m {
record[i][0] += record[i-1][0]
i += 1
}
var j = 1
while j < n {
record[0][j] += record[0][j-1]
j += 1
}
var row = 1
while row < m {
var col = 1
while col < n {
record[row][col] += min(record[row-1][col], record[row][col-1])
col += 1
}
row += 1
}
return record[m-1][n-1]
}
var a = [[1,5],[3,2]]
minPathSum(a) | 8bea29e7a6c6de836e105f2225cdb061 | 18.366667 | 75 | 0.432759 | false | false | false | false |
iOSWizards/AwesomeMedia | refs/heads/master | AwesomeMedia/Classes/Controllers/AwesomeMediaVideoViewController.swift | mit | 1 | //
// AwesomeMediaVideoViewController.swift
// AwesomeMedia
//
// Created by Evandro Harrison Hoffmann on 4/4/18.
//
import UIKit
public class AwesomeMediaVideoViewController: UIViewController {
public static var presentingVideoInFullscreen = false
@IBOutlet public weak var playerView: AwesomeMediaView!
// Public variables
public var mediaParams = AwesomeMediaParams()
var controls: AwesomeMediaVideoControls = .all
var titleViewVisible: Bool = true
public override func viewDidLoad() {
super.viewDidLoad()
playerView.configure(withMediaParams: mediaParams,
controls: controls,
states: .standard,
trackingSource: .videoFullscreen,
titleViewVisible: titleViewVisible)
playerView.controlView?.fullscreenCallback = { [weak self] in
self?.close()
// track event
track(event: .toggleFullscreen, source: .videoFullscreen)
}
playerView.controlView?.jumpToCallback = { [weak self] in
guard let self = self else { return }
self.showMarkers(self.mediaParams.markers) { (mediaMarker) in
if let mediaMarker = mediaMarker {
sharedAVPlayer.seek(toTime: mediaMarker.time)
sharedAVPlayer.play()
}
}
}
playerView.titleView?.closeCallback = { [weak self] in
sharedAVPlayer.stop()
self?.close()
// track event
track(event: .closeFullscreen, source: .videoFullscreen)
track(event: .stoppedPlaying, source: .videoFullscreen)
}
playerView.finishedPlayingCallback = { [weak self] in
self?.close()
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// adds player layer in case it's not visible
playerView.addPlayerLayer()
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
AwesomeMediaVideoViewController.presentingVideoInFullscreen = false
// remove observers when leaving
playerView.removeObservers()
}
public override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// track event
track(event: .changedOrientation, source: .audioFullscreen, value: UIApplication.shared.statusBarOrientation)
}
// MARK: Events
@IBAction func toggleControlsButtonPressed(_ sender: Any) {
playerView.controlView?.toggleViewIfPossible()
}
// MARK: - Marker Selected
public func markerSelected(marker: AwesomeMediaMarker) {
}
//to hide the bottom bar on iPhone X+ after a few seconds
override public var prefersHomeIndicatorAutoHidden: Bool {
return true
}
}
extension AwesomeMediaVideoViewController {
fileprivate func close() {
dismiss(animated: true) {
if AwesomeMedia.shouldStopVideoWhenCloseFullScreen {
sharedAVPlayer.stop()
AwesomeMedia.shouldStopVideoWhenCloseFullScreen = false
}
AwesomeMediaVideoViewController.presentingVideoInFullscreen = false
}
}
}
// MARK: - ViewController Initialization
extension AwesomeMediaVideoViewController {
public static var newInstance: AwesomeMediaVideoViewController {
let storyboard = UIStoryboard(name: "AwesomeMedia", bundle: AwesomeMedia.bundle)
return storyboard.instantiateViewController(withIdentifier: "AwesomeMediaVideoViewController") as! AwesomeMediaVideoViewController
}
}
extension UIViewController {
public func presentVideoFullscreen(withMediaParams mediaParams: AwesomeMediaParams,
withControls controls: AwesomeMediaVideoControls = .all,
titleViewVisible: Bool = true) {
guard !AwesomeMediaVideoViewController.presentingVideoInFullscreen else {
return
}
AwesomeMediaPlayerType.type = .video
AwesomeMediaVideoViewController.presentingVideoInFullscreen = true
let viewController = AwesomeMediaVideoViewController.newInstance
viewController.mediaParams = mediaParams
viewController.controls = controls
viewController.titleViewVisible = titleViewVisible
interactor = AwesomeMediaInteractor()
viewController.modalPresentationStyle = .fullScreen
viewController.transitioningDelegate = self
viewController.interactor = interactor
self.present(viewController, animated: true, completion: nil)
}
}
| 5e73db34cf6bb429d9f6c295d5498012 | 34.330935 | 138 | 0.643861 | false | false | false | false |
crazypoo/ArcheryScoreBoard | refs/heads/master | OCAndSwift/SwiftClass/DetailledTarget.swift | mit | 1 | //
// DetailledTarget.swift
// ReperageFleche
//
// Created by Rémy Vermeersch on 23/04/2016.
// Copyright © 2016 Rémy Vermeersch . All rights reserved.
//
import UIKit
class DetailledTarget: BaseViewController {
var arrow : Arrow!
var reperageViews = [CrossMarkerView]()
var targetImageView: UIImageView!
var endCountLabel: UILabel!
var scoreLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
updateUI()
}
func updateUI() {
self.title = "箭落点: \((arrow?.arrowId)!+1)"
targetImageView = UIImageView.init(frame: CGRect.init(x: 20, y: 84, width: self.view.frame.size.width-40, height: self.view.frame.size.width-40))
targetImageView.image = UIImage.init(named: "TargetImage")
self.view.addSubview(targetImageView)
var scoreTotal : Int = 0
for i in (arrow?.shots)! {
let x:NSString = String(i.value) as NSString
if x.isEqual(to: "11") {
scoreTotal += 10
}
else
{
scoreTotal += i.value
}
}
endCountLabel = UILabel.init()
endCountLabel.textAlignment = .center
endCountLabel.text = "射击点数量: " + String(arrow.shots.count)
self.view.addSubview(endCountLabel)
endCountLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.bottom.equalTo(self.view.snp.bottom).offset(-150)
}
scoreLabel = UILabel.init()
scoreLabel.textAlignment = .center
scoreLabel.text = "得分 : \(scoreTotal)"
self.view.addSubview(scoreLabel)
scoreLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self.view)
make.height.equalTo(30)
make.top.equalTo(endCountLabel.snp.bottom)
}
updateMarkers((arrow?.shots)!)
}
func updateMarkers(_ shots : [Shot]){
for i in reperageViews {
i.removeFromSuperview()
}
reperageViews.removeAll()
for currentShot in shots {
reperageViews.append(CrossMarkerView(shot: currentShot, frame: targetImageView.bounds))
targetImageView.addSubview(reperageViews.last!)
}
}
}
| 050a2d15bba923952056743699ddfb90 | 26.655914 | 153 | 0.577372 | false | false | false | false |
williamshowalter/DOTlog_iOS | refs/heads/master | DOTlog/Error Handling/ErrorFactory.swift | mit | 1 | //
// ErrorFactory.swift
// DOTlog
//
// Created by William Showalter on 15/05/02.
// Copyright (c) 2015 UAF CS Capstone 2015. All rights reserved.
//
import Foundation
import UIKit
import CoreData
class ErrorFactory {
// Class that creates alerts given internally designated error codes and a view controller to present the errors to.
class func ErrorAlert (error: NSError, caller: UIViewController) -> UIAlertController {
let code = error.code
var errorTitle = "Unable to Sync"
var errorDetailTitle = "Error Code: \(code)"
var errorMessage : String? = "Contact Regional Aviation Office If Problem Persists."
var errorDetailMessage = error.localizedDescription
if let detailMessage : [NSObject : AnyObject] = error.userInfo {
if let errorDetailMessageText = detailMessage["NSLocalizedDescriptionKey"] as? String {
errorDetailMessage = "\(errorDetailMessageText)"
}
}
if code == 401 {
errorTitle = error.domain
errorMessage = nil
}
if code == 430 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "User does not have access to airports they are submitting for."
}
if code == 431 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "Airport not found in database."
}
if code == 432 {
errorTitle = "Delete all events and sync before recreating"
errorMessage = "Category not found in database."
}
if code == 445 {
errorTitle = "Contact Supervisor - Account does not have access to DOTlog"
errorMessage = nil
}
if code == -1003 {
errorTitle = "Bad Address" // Needs to match page wording
errorMessage = "Confirm Address in Account Settings"
}
let errorAlert = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
let errorAlertDetail = UIAlertController(title: errorDetailTitle, message: errorDetailMessage as String, preferredStyle: UIAlertControllerStyle.Alert)
errorAlert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler:{ (ACTION :UIAlertAction!)in }))
errorAlert.addAction(UIAlertAction(title: "Details", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in caller.presentViewController(errorAlertDetail, animated: true, completion: nil)}))
errorAlertDetail.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler:{ (ACTION :UIAlertAction!)in }))
return errorAlert
}
} | ae57533347910a38a4567858b7f218f6 | 34.371429 | 209 | 0.742222 | false | false | false | false |
TonnyTao/Acornote | refs/heads/master | Acornote_iOS/Pods/SugarRecord/SugarRecord/Source/CoreData/Entities/CoreDataObservable.swift | apache-2.0 | 1 | import Foundation
import CoreData
#if os(iOS) || os(tvOS) || os(watchOS)
public class CoreDataObservable<T: NSManagedObject>: RequestObservable<T>, NSFetchedResultsControllerDelegate where T:Equatable {
// MARK: - Attributes
internal let fetchRequest: NSFetchRequest<NSFetchRequestResult>
internal var observer: ((ObservableChange<T>) -> Void)?
internal let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>
private var batchChanges: [CoreDataChange<T>] = []
// MARK: - Init
internal init(request: FetchRequest<T>, context: NSManagedObjectContext) {
let fetchRequest: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: T.entityName)
if let predicate = request.predicate {
fetchRequest.predicate = predicate
}
if let sortDescriptor = request.sortDescriptor {
fetchRequest.sortDescriptors = [sortDescriptor]
}
fetchRequest.fetchBatchSize = 0
self.fetchRequest = fetchRequest
self.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
super.init(request: request)
self.fetchedResultsController.delegate = self
}
// MARK: - Observable
public override func observe(_ closure: @escaping (ObservableChange<T>) -> Void) {
assert(self.observer == nil, "Observable can be observed only once")
let initial = try! self.fetchedResultsController.managedObjectContext.fetch(self.fetchRequest) as! [T]
closure(ObservableChange.initial(initial))
self.observer = closure
_ = try? self.fetchedResultsController.performFetch()
}
// MARK: - Dipose Method
override func dispose() {
self.fetchedResultsController.delegate = nil
}
// MARK: - NSFetchedResultsControllerDelegate
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
self.batchChanges.append(.delete(indexPath![0], anObject as! T))
case .insert:
self.batchChanges.append(.insert(newIndexPath![0], anObject as! T))
case .update:
self.batchChanges.append(.update(indexPath![0], anObject as! T))
default: break
}
}
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.batchChanges = []
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
let deleted = self.batchChanges.filter { $0.isDeletion }.map { $0.index() }
let inserted = self.batchChanges.filter { $0.isInsertion }.map { (index: $0.index(), element: $0.object()) }
let updated = self.batchChanges.filter { $0.isUpdate }.map { (index: $0.index(), element: $0.object()) }
self.observer?(ObservableChange.update(deletions: deleted, insertions: inserted, modifications: updated))
}
}
#endif
| 5e7b3859f1cb5d5a8e78a9b81a689520 | 40.025641 | 207 | 0.695625 | false | false | false | false |
aksalj/Helium | refs/heads/master | Helium/HeliumShareExtension/ShareViewController.swift | mit | 1 | //
// ShareViewController.swift
// Share
//
// Created by Kyle Carson on 10/30/15.
// Copyright © 2015 Jaden Geller. All rights reserved.
//
import Cocoa
class ShareViewController: NSViewController {
override var nibName: String? {
return "ShareViewController"
}
override func viewDidLoad() {
if let item = self.extensionContext!.inputItems.first as? NSExtensionItem,
let attachment = item.attachments?.first as? NSItemProvider
where attachment.hasItemConformingToTypeIdentifier("public.url")
{
attachment.loadItemForTypeIdentifier("public.url", options: nil)
{
(url, error) in
if let url = url as? NSURL,
let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false)
{
components.scheme = "helium"
let heliumURL = components.URL!
NSWorkspace.sharedWorkspace().openURL( heliumURL )
}
}
self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil)
return
}
let error = NSError(domain: NSCocoaErrorDomain, code: NSURLErrorBadURL, userInfo: nil)
self.extensionContext!.cancelRequestWithError(error)
}
@IBAction func send(sender: AnyObject?) {
let outputItem = NSExtensionItem()
// Complete implementation by setting the appropriate value on the output item
let outputItems = [outputItem]
self.extensionContext!.completeRequestReturningItems(outputItems, completionHandler: nil)
}
@IBAction func cancel(sender: AnyObject?) {
let cancelError = NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError, userInfo: nil)
self.extensionContext!.cancelRequestWithError(cancelError)
}
}
| 4850292a12b128d47305aa82c2533454 | 26.459016 | 98 | 0.721791 | false | false | false | false |
XCEssentials/UniFlow | refs/heads/master | .setup/Setup/main.swift | mit | 2 | import PathKit
import XCERepoConfigurator
// MARK: - PRE-script invocation output
print("\n")
print("--- BEGIN of '\(Executable.name)' script ---")
// MARK: -
// MARK: Parameters
Spec.BuildSettings.swiftVersion.value = "5.3"
let localRepo = try Spec.LocalRepo.current()
let remoteRepo = try Spec.RemoteRepo(
accountName: localRepo.context,
name: localRepo.name
)
let travisCI = (
address: "https://travis-ci.com/\(remoteRepo.accountName)/\(remoteRepo.name)",
branch: "master"
)
let company = (
prefix: "XCE",
name: remoteRepo.accountName
)
let project = (
name: remoteRepo.name,
summary: "Uni-directional data flow & finite state machine merged together",
copyrightYear: 2016
)
let productName = company.prefix + project.name
let authors = [
("Maxim Khatskevich", "[email protected]")
]
typealias PerSubSpec<T> = (
core: T,
tests: T
)
let subSpecs: PerSubSpec = (
"Core",
"AllTests"
)
let targetNames: PerSubSpec = (
productName,
productName + subSpecs.tests
)
let sourcesLocations: PerSubSpec = (
Spec.Locations.sources + subSpecs.core,
Spec.Locations.tests + subSpecs.tests
)
// MARK: Parameters - Summary
localRepo.report()
remoteRepo.report()
// MARK: -
// MARK: Write - ReadMe
try ReadMe()
.addGitHubLicenseBadge(
account: company.name,
repo: project.name
)
.addGitHubTagBadge(
account: company.name,
repo: project.name
)
.addSwiftPMCompatibleBadge()
.addWrittenInSwiftBadge(
version: Spec.BuildSettings.swiftVersion.value
)
.addStaticShieldsBadge(
"platforms",
status: "macOS | iOS | tvOS | watchOS | Linux",
color: "blue",
title: "Supported platforms",
link: "Package.swift"
)
.add("""
[.svg?branch=\(travisCI.branch))](\(travisCI.address))
"""
)
.add("""
# \(project.name)
\(project.summary)
"""
)
.prepare(
removeRepeatingEmptyLines: false
)
.writeToFileSystem(
ifFileExists: .skip
)
// MARK: Write - License
try License
.MIT(
copyrightYear: UInt(project.copyrightYear),
copyrightEntity: authors.map{ $0.0 }.joined(separator: ", ")
)
.prepare()
.writeToFileSystem()
// MARK: Write - GitHub - PagesConfig
try GitHub
.PagesConfig()
.prepare()
.writeToFileSystem()
// MARK: Write - Git - .gitignore
try Git
.RepoIgnore()
.addMacOSSection()
.addCocoaSection()
.addSwiftPackageManagerSection(ignoreSources: true)
.add(
"""
# we don't need to store project file,
# as we generate it on-demand
*.\(Xcode.Project.extension)
"""
)
.prepare()
.writeToFileSystem()
// MARK: Write - Package.swift
let dependencies = (
requirement: (
name: """
XCERequirement
""",
swiftPM: """
.package(name: "XCERequirement", url: "https://github.com/XCEssentials/Requirement", from: "2.0.0")
"""
),
pipeline: (
name: """
XCEPipeline
""",
swiftPM: """
.package(name: "XCEPipeline", url: "https://github.com/XCEssentials/Pipeline", from: "3.0.0")
"""
),
swiftHamcrest: (
name: """
SwiftHamcrest
""",
swiftPM: """
.package(name: "SwiftHamcrest", url: "https://github.com/nschum/SwiftHamcrest", from: "2.1.1")
"""
)
)
try CustomTextFile("""
// swift-tools-version:\(Spec.BuildSettings.swiftVersion.value)
import PackageDescription
let package = Package(
name: "\(productName)",
products: [
.library(
name: "\(productName)",
targets: [
"\(targetNames.core)"
]
)
],
dependencies: [
\(dependencies.requirement.swiftPM),
\(dependencies.pipeline.swiftPM),
\(dependencies.swiftHamcrest.swiftPM)
],
targets: [
.target(
name: "\(targetNames.core)",
dependencies: [
"\(dependencies.requirement.name)",
"\(dependencies.pipeline.name)"
],
path: "\(sourcesLocations.core)"
),
.testTarget(
name: "\(targetNames.tests)",
dependencies: [
"\(targetNames.core)",
"\(dependencies.requirement.name)",
"\(dependencies.pipeline.name)",
"\(dependencies.swiftHamcrest.name)"
],
path: "\(sourcesLocations.tests)"
),
]
)
"""
)
.prepare(
at: ["Package.swift"]
)
.writeToFileSystem()
// MARK: - POST-script invocation output
print("--- END of '\(Executable.name)' script ---")
| 7bcfa86e46efec2455a3a051f1bc3e0e | 21.269912 | 111 | 0.546791 | false | false | false | false |
groomsy/odot-ios | refs/heads/master | OdOt/AuthenticationViewController.swift | mit | 1 | //
// AuthenticationViewController.swift
// OdOt
//
// Created by Todd Grooms on 9/25/14.
// Copyright (c) 2014 Todd Grooms. All rights reserved.
//
import Alamofire
import UIKit
class AuthenticationViewController: UITableViewController, UITextFieldDelegate {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var endpoint: String!
var authenticateUserDelegate: AuthenticateUserProtocol?
func contentSizeCategoryChanged(notification: NSNotification) {
self.tableView.reloadData()
}
func dismiss() {
if let delegate = self.authenticateUserDelegate {
delegate.authenticatedUser(User(id: "some_id"))
}
}
func submitRequest() {
self.tableView.deselectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 1), animated: true)
self.usernameTextField.resignFirstResponder()
self.passwordTextField.resignFirstResponder()
self.tableView.userInteractionEnabled = false
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let delay = 2 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
let parameters = [
"username": self.usernameTextField.text,
"password": self.passwordTextField.text
]
Alamofire.request(.POST, self.endpoint, parameters: parameters)
.responseJSON({ (NSURLRequest request, NSHTTPURLResponse response, JSON json, NSError error) -> Void in
self.tableView.userInteractionEnabled = true
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
self.dismiss()
})
}
}
func userInformationPresent() -> Bool {
return countElements(self.usernameTextField.text) > 0 && countElements(self.passwordTextField.text) > 0
}
// MARK: View Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.estimatedRowHeight = 44
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contentSizeCategoryChanged:", name: UIContentSizeCategoryDidChangeNotification, object: nil)
self.tableView.reloadData()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIContentSizeCategoryDidChangeNotification, object: nil)
}
// MARK: UITableViewDelegate Methods
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
if ( indexPath.section == 1 && self.userInformationPresent() ) || indexPath.section == 2 {
return indexPath
}
return nil
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
if indexPath.item == 0 {
self.usernameTextField.becomeFirstResponder()
} else {
self.passwordTextField.becomeFirstResponder()
}
} else if indexPath.section == 1 {
self.submitRequest()
}
}
// MARK: UITextFieldDelegate Methods
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == self.usernameTextField {
self.passwordTextField.becomeFirstResponder()
} else {
self.passwordTextField.resignFirstResponder()
self.submitRequest()
}
return true
}
}
| ade9828e050992e026d8620852148362 | 33.681034 | 166 | 0.642555 | false | false | false | false |
calkinssean/TIY-Assignments | refs/heads/master | Day 21/SpotifyAPI/Pods/StarWars/StarWars/StarWarsGLAnimator/ViewTexture.swift | cc0-1.0 | 4 | //
// Created by Artem Sidorenko on 10/9/15.
// Copyright © 2015 Yalantis. All rights reserved.
//
// Licensed under the MIT license: http://opensource.org/licenses/MIT
// Latest version can be found at https://github.com/Yalantis/StarWars.iOS
//
import UIKit
class ViewTexture {
var name: GLuint = 0
var width: GLsizei = 0
var height: GLsizei = 0
func setupOpenGL() {
glGenTextures(1, &name)
glBindTexture(GLenum(GL_TEXTURE_2D), name)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GLint(GL_LINEAR))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GLint(GL_CLAMP_TO_EDGE))
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GLint(GL_CLAMP_TO_EDGE))
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
deinit {
if name != 0 {
glDeleteTextures(1, &name)
}
}
func renderView(view: UIView) {
let scale = UIScreen.mainScreen().scale
width = GLsizei(view.layer.bounds.size.width * scale)
height = GLsizei(view.layer.bounds.size.height * scale)
var texturePixelBuffer = [GLubyte](count: Int(height * width * 4), repeatedValue: 0)
let colorSpace = CGColorSpaceCreateDeviceRGB()
withUnsafeMutablePointer(&texturePixelBuffer[0]) { texturePixelBuffer in
let context = CGBitmapContextCreate(texturePixelBuffer,
Int(width), Int(height), 8, Int(width * 4), colorSpace,
CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue)!
CGContextScaleCTM(context, scale, scale)
UIGraphicsPushContext(context)
view.drawViewHierarchyInRect(view.layer.bounds, afterScreenUpdates: false)
UIGraphicsPopContext()
glBindTexture(GLenum(GL_TEXTURE_2D), name);
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GLint(GL_RGBA), width, height, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), texturePixelBuffer)
glBindTexture(GLenum(GL_TEXTURE_2D), 0);
}
}
}
| 8470d64384a4f8560ca7f1345a93bf94 | 38.189655 | 147 | 0.635284 | false | false | false | false |
hfutrell/BezierKit | refs/heads/master | BezierKit/Library/BezierCurve.swift | mit | 1 | //
// BezierCurve.swift
// BezierKit
//
// Created by Holmes Futrell on 2/19/17.
// Copyright © 2017 Holmes Futrell. All rights reserved.
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
import Foundation
public struct Subcurve<CurveType> where CurveType: BezierCurve {
public let t1: CGFloat
public let t2: CGFloat
public let curve: CurveType
internal var canSplit: Bool {
let mid = 0.5 * (self.t1 + self.t2)
return mid > self.t1 && mid < self.t2
}
internal init(curve: CurveType) {
self.t1 = 0.0
self.t2 = 1.0
self.curve = curve
}
internal init(t1: CGFloat, t2: CGFloat, curve: CurveType) {
self.t1 = t1
self.t2 = t2
self.curve = curve
}
internal func split(from t1: CGFloat, to t2: CGFloat) -> Subcurve<CurveType> {
let curve: CurveType = self.curve.split(from: t1, to: t2)
return Subcurve<CurveType>(t1: Utils.map(t1, 0, 1, self.t1, self.t2),
t2: Utils.map(t2, 0, 1, self.t1, self.t2),
curve: curve)
}
internal func split(at t: CGFloat) -> (left: Subcurve<CurveType>, right: Subcurve<CurveType>) {
let (left, right) = curve.split(at: t)
let t1 = self.t1
let t2 = self.t2
let tSplit = Utils.map(t, 0, 1, t1, t2)
let subcurveLeft = Subcurve<CurveType>(t1: t1, t2: tSplit, curve: left)
let subcurveRight = Subcurve<CurveType>(t1: tSplit, t2: t2, curve: right)
return (left: subcurveLeft, right: subcurveRight)
}
}
extension Subcurve: Equatable where CurveType: Equatable {
// extension exists for automatic Equatable synthesis
}
// MARK: -
extension BezierCurve {
/*
Calculates the length of this Bezier curve. Length is calculated using numerical approximation, specifically the Legendre-Gauss quadrature algorithm.
*/
public func length() -> CGFloat {
return Utils.length({(_ t: CGFloat) in self.derivative(at: t)})
}
// MARK: -
public func hull(_ t: CGFloat) -> [CGPoint] {
return Utils.hull(self.points, t)
}
public func lookupTable(steps: Int = 100) -> [CGPoint] {
assert(steps >= 0)
return (0 ... steps).map {
let t = CGFloat($0) / CGFloat(steps)
return self.point(at: t)
}
}
// MARK: -
/*
Reduces a curve to a collection of "simple" subcurves, where a simpleness is defined as having all control points on the same side of the baseline (cubics having the additional constraint that the control-to-end-point lines may not cross), and an angle between the end point normals no greater than 60 degrees.
The main reason this function exists is to make it possible to scale curves. As mentioned in the offset function, curves cannot be offset without cheating, and the cheating is implemented in this function. The array of simple curves that this function yields can safely be scaled.
*/
public func reduce() -> [Subcurve<Self>] {
let step: CGFloat = BezierKit.reduceStepSize
var extrema: [CGFloat] = []
self.extrema().all.forEach {
if $0 < step {
return // filter out extreme points very close to 0.0
} else if (1.0 - $0) < step {
return // filter out extreme points very close to 1.0
} else if let last = extrema.last, $0 - last < step {
return
}
return extrema.append($0)
}
// aritifically add 0.0 and 1.0 to our extreme points
extrema.insert(0.0, at: 0)
extrema.append(1.0)
// first pass: split on extrema
let pass1: [Subcurve<Self>] = (0..<extrema.count-1).map {
let t1 = extrema[$0]
let t2 = extrema[$0+1]
let curve = self.split(from: t1, to: t2)
return Subcurve(t1: t1, t2: t2, curve: curve)
}
func bisectionMethod(min: CGFloat, max: CGFloat, tolerance: CGFloat, callback: (_ value: CGFloat) -> Bool) -> CGFloat {
var lb = min // lower bound (callback(x <= lb) should return true
var ub = max // upper bound (callback(x >= ub) should return false
while (ub - lb) > tolerance {
let val = 0.5 * (lb + ub)
if callback(val) {
lb = val
} else {
ub = val
}
}
return lb
}
// second pass: further reduce these segments to simple segments
var pass2: [Subcurve<Self>] = []
pass2.reserveCapacity(pass1.count)
pass1.forEach({(p1: Subcurve<Self>) in
let adjustedStep = step / (p1.t2 - p1.t1)
var t1: CGFloat = 0.0
while t1 < 1.0 {
let fullSegment = p1.split(from: t1, to: 1.0)
if (1.0 - t1) <= adjustedStep || fullSegment.curve.simple {
// if the step is small or the full segment is simple, use it
pass2.append(fullSegment)
t1 = 1.0
} else {
// otherwise use bisection method to find a suitable step size
let t2 = bisectionMethod(min: t1 + adjustedStep, max: 1.0, tolerance: adjustedStep) {
return p1.split(from: t1, to: $0).curve.simple
}
let partialSegment = p1.split(from: t1, to: t2)
pass2.append(partialSegment)
t1 = t2
}
}
})
return pass2
}
// MARK: -
/// Scales a curve with respect to the intersection between the end point normals. Note that this will only work if that intersection point exists, which is only guaranteed for simple segments.
/// - Parameter distance: desired distance the resulting curve should fall from the original (in the direction of its normals).
public func scale(distance: CGFloat) -> Self? {
let order = self.order
assert(order < 4, "only works with cubic or lower order")
guard order > 0 else { return self } // points cannot be scaled
let points = self.points
let n1 = self.normal(at: 0)
let n2 = self.normal(at: 1)
guard n1.x.isFinite, n1.y.isFinite, n2.x.isFinite, n2.y.isFinite else { return nil }
let origin = Utils.linesIntersection(self.startingPoint, self.startingPoint + n1, self.endingPoint, self.endingPoint - n2)
func scaledPoint(index: Int) -> CGPoint {
let referencePointIsStart = (index < 2 && order > 1) || (index == 0 && order == 1)
let referenceT: CGFloat = referencePointIsStart ? 0.0 : 1.0
let referenceIndex = referencePointIsStart ? 0 : self.order
let referencePoint = self.offset(t: referenceT, distance: distance)
switch index {
case 0, self.order:
return referencePoint
default:
let tangent = self.normal(at: referenceT).perpendicular
if let origin = origin, let intersection = Utils.linesIntersection(referencePoint, referencePoint + tangent, origin, points[index]) {
return intersection
} else {
// no origin to scale control points through, just use start and end points as a reference
return referencePoint + (points[index] - points[referenceIndex])
}
}
}
let scaledPoints = (0..<self.points.count).map(scaledPoint)
return type(of: self).init(points: scaledPoints)
}
// MARK: -
public func offset(distance d: CGFloat) -> [BezierCurve] {
// for non-linear curves we need to create a set of curves
var result: [BezierCurve] = self.reduce().compactMap { $0.curve.scale(distance: d) }
ensureContinuous(&result)
return result
}
public func offset(t: CGFloat, distance: CGFloat) -> CGPoint {
return self.point(at: t) + distance * self.normal(at: t)
}
// MARK: - outlines
public func outline(distance d1: CGFloat) -> PathComponent {
return internalOutline(d1: d1, d2: d1)
}
public func outline(distanceAlongNormal d1: CGFloat, distanceOppositeNormal d2: CGFloat) -> PathComponent {
return internalOutline(d1: d1, d2: d2)
}
private func ensureContinuous(_ curves: inout [BezierCurve]) {
for i in 0..<curves.count {
if i > 0 {
curves[i].startingPoint = curves[i-1].endingPoint
}
if i < curves.count-1 {
curves[i].endingPoint = 0.5 * ( curves[i].endingPoint + curves[i+1].startingPoint )
}
}
}
private func internalOutline(d1: CGFloat, d2: CGFloat) -> PathComponent {
let reduced = self.reduce()
let length = reduced.count
var forwardCurves: [BezierCurve] = reduced.compactMap { $0.curve.scale(distance: d1) }
var backCurves: [BezierCurve] = reduced.compactMap { $0.curve.scale(distance: -d2) }
ensureContinuous(&forwardCurves)
ensureContinuous(&backCurves)
// reverse the "return" outline
backCurves = backCurves.reversed().map { $0.reversed() }
// form the endcaps as lines
let forwardStart = forwardCurves[0].points[0]
let forwardEnd = forwardCurves[length-1].points[forwardCurves[length-1].points.count-1]
let backStart = backCurves[length-1].points[backCurves[length-1].points.count-1]
let backEnd = backCurves[0].points[0]
let lineStart = LineSegment(p0: backStart, p1: forwardStart)
let lineEnd = LineSegment(p0: forwardEnd, p1: backEnd)
let segments = [lineStart] + forwardCurves + [lineEnd] + backCurves
return PathComponent(curves: segments)
}
// MARK: shapes
public func outlineShapes(distance d1: CGFloat, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [Shape] {
return self.outlineShapes(distanceAlongNormal: d1, distanceOppositeNormal: d1, accuracy: accuracy)
}
public func outlineShapes(distanceAlongNormal d1: CGFloat, distanceOppositeNormal d2: CGFloat, accuracy: CGFloat = BezierKit.defaultIntersectionAccuracy) -> [Shape] {
let outline = self.outline(distanceAlongNormal: d1, distanceOppositeNormal: d2)
var shapes: [Shape] = []
let len = outline.numberOfElements
for i in 1..<len/2 {
let shape = Shape(outline.element(at: i), outline.element(at: len-i), i > 1, i < len/2-1)
shapes.append(shape)
}
return shapes
}
}
public let defaultIntersectionAccuracy = CGFloat(0.5)
internal let reduceStepSize: CGFloat = 0.01
public func == (left: BezierCurve, right: BezierCurve) -> Bool {
return left.points == right.points
}
public protocol BoundingBoxProtocol {
var boundingBox: BoundingBox { get }
}
public protocol Transformable {
func copy(using: CGAffineTransform) -> Self
}
public protocol Reversible {
func reversed() -> Self
}
public protocol BezierCurve: BoundingBoxProtocol, Transformable, Reversible {
var simple: Bool { get }
var points: [CGPoint] { get }
var startingPoint: CGPoint { get set }
var endingPoint: CGPoint { get set }
var order: Int { get }
init(points: [CGPoint])
func point(at t: CGFloat) -> CGPoint
func derivative(at t: CGFloat) -> CGPoint
func normal(at t: CGFloat) -> CGPoint
func split(from t1: CGFloat, to t2: CGFloat) -> Self
func split(at t: CGFloat) -> (left: Self, right: Self)
func length() -> CGFloat
func extrema() -> (x: [CGFloat], y: [CGFloat], all: [CGFloat])
func lookupTable(steps: Int) -> [CGPoint]
func project(_ point: CGPoint) -> (point: CGPoint, t: CGFloat)
// intersection routines
var selfIntersects: Bool { get }
var selfIntersections: [Intersection] { get }
func intersects(_ line: LineSegment) -> Bool
func intersects(_ curve: BezierCurve, accuracy: CGFloat) -> Bool
func intersections(with line: LineSegment) -> [Intersection]
func intersections(with curve: BezierCurve, accuracy: CGFloat) -> [Intersection]
}
internal protocol NonlinearBezierCurve: BezierCurve, ComponentPolynomials, Implicitizeable {
// intentionally empty, just declare conformance if you're not a line
}
public protocol Flatness: BezierCurve {
// the flatness of a curve is defined as the square of the maximum distance it is from a line connecting its endpoints https://jeremykun.com/2013/05/11/bezier-curves-and-picasso/
var flatnessSquared: CGFloat { get }
var flatness: CGFloat { get }
}
public extension Flatness {
var flatness: CGFloat {
return sqrt(flatnessSquared)
}
}
| 3908faf756c26a401953df0fc2e3d1af | 38.722222 | 315 | 0.610878 | false | false | false | false |
Gunmer/EmojiLog | refs/heads/master | EmojiLog/Classes/TraceBuilder.swift | mit | 1 |
public protocol TraceBuilder {
func add(emoji: String) -> Self
func add(level: LogLevel) -> Self
func add(date: Date) -> Self
func add(className: String) -> Self
func add(functionName: String) -> Self
func add(message: String) -> Self
func add(dateFormat: String) -> Self
func add(line: Int) -> Self
func build() -> String
}
class TraceBuilderDefault: TraceBuilder {
fileprivate var className = ""
fileprivate var date = Date()
fileprivate var emoji = ""
fileprivate var functionName = ""
fileprivate var level = LogLevel.debug
fileprivate var message = ""
fileprivate var dateFormat = "dd/MM/yyyy HH:mm:ss:SSS"
fileprivate var line = 0
func add(className: String) -> Self {
self.className = className
return self
}
func add(date: Date) -> Self {
self.date = date
return self
}
func add(emoji: String) -> Self {
self.emoji = emoji
return self
}
func add(functionName: String) -> Self {
if functionName.hasSuffix("()") {
self.functionName = functionName.replacingOccurrences(of: "()", with: "")
} else {
self.functionName = functionName
}
return self
}
func add(level: LogLevel) -> Self {
self.level = level
return self
}
func add(message: String) -> Self {
self.message = message
return self
}
func add(dateFormat: String) -> Self {
self.dateFormat = dateFormat
return self
}
func add(line: Int) -> Self {
self.line = line
return self
}
func build() -> String {
let formater = DateFormatter()
formater.dateFormat = dateFormat
let stringDate = formater.string(from: date)
return "\(emoji) |\(level.initial)| \(stringDate) -> \(className).\(functionName)[\(line)]: \(message)"
}
}
| 0fb5e1c7fdc530ec7441d30c7856dcf2 | 25.105263 | 111 | 0.569556 | false | false | false | false |
svanimpe/around-the-table | refs/heads/master | Sources/AroundTheTable/Services/NotificationService.swift | bsd-2-clause | 1 | /**
A service that sends notifications to users.
*/
public class NotificationService {
/// The persistence layer.
private let persistence: Persistence
/**
Initializes a notification service.
*/
init(persistence: Persistence) {
self.persistence = persistence
}
/**
Sends a notification to inform a player that his registration for an activity was automatically approved.
*/
func notify(_ player: User, ofAutomaticApprovalFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.registrationWasAutoApproved(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host approved his registration for an activity.
*/
func notify(_ player: User, thatHostApprovedRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostApprovedRegistration(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host cancelled an activity.
*/
func notify(_ player: User, thatHostCancelled activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostCancelled(activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host cancelled his registration for an activity.
*/
func notify(_ player: User, thatHostCancelledRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostCancelledRegistration(for: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host changed the location of an activity.
*/
func notify(_ player: User, thatHostChangedAddressFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostChangedAddress(of: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a player that a host changed the date or time of an activity.
*/
func notify(_ player: User, thatHostChangedDateFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.hostChangedDate(of: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: player, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player cancelled his registration for an activity.
*/
func notify(_ host: User, that player: User, cancelledRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, cancelledRegistrationFor: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player's registration for an activity was automatically approved.
*/
func notify(_ host: User, that player: User, joined activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, joined: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
/**
Sends a notification to inform a host that a player submitted a registration for an activity.
*/
func notify(_ host: User, that player: User, sentRegistrationFor activity: Activity) throws {
guard let id = activity.id else {
throw log(ServerError.unpersistedEntity)
}
let message = Strings.player(player, sentRegistrationFor: activity)
let link = "activity/\(id)"
let notification = Notification(recipient: host, message: message, link: link)
try persistence.add(notification)
}
}
| ed16bb20f2e36cd68f25258bb873710f | 39.265152 | 115 | 0.655315 | false | false | false | false |
michael-yuji/YSMessagePack | refs/heads/master | YSMessagePack/Classes/pack.swift | bsd-2-clause | 1 | //
// pack.swift
// MessagePack2.0
//
// Created by yuuji on 4/3/16.
// Copyright © 2016 yuuji. All rights reserved.
//
import Foundation
public enum MsgPackTypes {
case Bool, Uint, Int, Float, String, Array, Dictionary, Data, Custom, Nil
}
public protocol Packable {
func packFormat() -> [Packable]
func msgtype() -> MsgPackTypes
}
public class Nil : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Nil
}
}
/**Pack items in the array by each's type and map into a single byte-array
- Warning: USE MASK(YOUR_ITEM) if $YOUR_ITEM is Bool, Uint64/32/16/8, Int64/32/16/8 or your custom structs / classes
- parameter thingsToPack: an array of objects you want to pack
- parameter withOptions packing options
*/
public func pack(items: [Packable?], withOptions options: packOptions = [.PackWithASCIIStringEncoding]) -> NSData
{
var byteArray = ByteArray()
for item in items
{
pack(item: item, appendToBytes: &byteArray, withOptions: options)
}
return byteArray.dataValue()
}
private func pack(item: Packable?, appendToBytes byteArray: inout [UInt8], withOptions options: packOptions = [.PackWithASCIIStringEncoding])
{
if item == nil {
byteArray += [0xc0]
return
}
switch item!.msgtype()
{
case .Custom:
for i in item!.packFormat() {
pack(item: i, appendToBytes: &byteArray)
}
case .String:
let str = item as! String
var encoding: String.Encoding = .ascii
if options.rawValue & packOptions.PackWithASCIIStringEncoding.rawValue == 0 {
if options.rawValue & packOptions.PackWithUTF8StringEncoding.rawValue != 0 {
encoding = .utf8
}
}
try! byteArray += str.pack(withEncoding: encoding)!.byteArrayValue()
case .Int:
var int = item as! Int
if options.rawValue & packOptions.PackAllPossitiveIntAsUInt.rawValue != 0 || options.rawValue & packOptions.PackIntegersAsUInt.rawValue != 0 {
if int >= 0 {
fallthrough
} else {
if options.rawValue & packOptions.PackIntegersAsUInt.rawValue != 0 {
int = 0
}
}
}
byteArray += int.packed().byteArrayValue()
case .Uint:
let uint = item as! UInt64
byteArray += uint.packed().byteArrayValue()
case .Float:
byteArray += (item as! Double).packed().byteArrayValue()
case .Bool:
byteArray += (item as! Bool).packed().byteArrayValue()
case .Data:
byteArray += (item as! NSData).packed().byteArrayValue()
case .Array:
byteArray += (item as! [AnyObject]).packed().byteArrayValue()
case .Dictionary:
byteArray += (item as! NSDictionary).packed().byteArrayValue()
case .Nil:
byteArray += [0xc0]
}
}
private func calculateSizeAfterPack<T>(forItem item: T) -> Int {
var i = 0
switch item {
case is String:
let str = item as! String
#if swift(>=3)
try! i += str.pack(withEncoding: .ascii)!.byteArray.count
#else
try! i += str.pack(withEncoding: NSASCIIStringEncoding)!.byteArrayValue().count
#endif
case is Int:
let int = item as! Int
i += int.packed().byteArrayValue().count
case is NSData:
i += (item as! NSData).byteArrayValue().count
default: break
}
return i
}
//MARK: Bool
extension Bool : Packable {
public func packed() -> NSData {
switch self {
case true: return [0xc3].dataValue()
case false: return [0xc2].dataValue()
}
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Bool
}
}
//MARK: String
extension StringLiteralType : Packable {
func pack(withEncoding encoding: String.Encoding) throws -> NSData?
{
let data = self.data(using: encoding)
if let data = data {
var mirror = [UInt8](repeatElement(0, count: data.count))
data.copyBytes(to: &mirror, count: data.count)
var prefix: UInt8!
var lengthByte: [UInt8] = []
#if arch(arm) || arch(i386)
switch data.length {
case (0b00000...0b11111) : prefix = UInt8(0b101_00000 + data.length)
case (0b100000...0xFF) : prefix = 0xd9; lengthByte.append(UInt8(data.length))
case (0x100...0xFFFF) : prefix = 0xda; lengthByte += [UInt8(data.length / 0x100),
UInt8(data.length % 0x100)]
default: throw PackingError.dataEncodingError
}
#else
switch data.count {
case (0b00000...0b11111) : prefix = UInt8(0b101_00000 + data.count)
case (0b100000...0xFF) : prefix = 0xd9; lengthByte.append(UInt8(data.count))
case (0x100...0xFFFF) : prefix = 0xda; lengthByte += [UInt8(data.count / 0x100),
UInt8(data.count % 0x100)]
case (0x10000...0xFFFFFFFF):
prefix = 0xdb
let buf = [UInt8(data.count / 0x10000), UInt8(data.count % 0x10000 / 0x100), UInt8(data.count % 0x10000 % 0x100)]
lengthByte += buf
default: throw PackingError.dataEncodingError
}
#endif
mirror.insert(prefix, at: 0)
return NSData(bytes: mirror, length: mirror.count)
} else {
throw PackingError.dataEncodingError
}
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .String
}
}
//MARK: Integers
public extension UnsignedIntegerType
{
public func packed() -> NSData
{
var value = self
var param: (prefix: UInt8, size: size_t)!
switch self {
case (0..<0xFF),0xff: param = (0xcc, 1);
case (0x100..<0xFFFF),0xFFFF: param = (0xcd, 2);
case (0x10000..<0xFFFFFFFF),0xFFFFFFFF: param = (0xce, 4);
case (0x100000000 ..< 0xFFFFFFFFFFFFFFFF),0xFFFFFFFFFFFFFFFF: param = (0xcf, 8);
default: break
}
let data = NSData(bytes: &value, length: param.size)
var data_mirror = data.byteArrayValue()
data_mirror.flip()
#if swift(>=3)
data_mirror.insert(param.prefix, at: 0)
#else
data_mirror.insert(param.prefix, atIndex: 0)
#endif
return data_mirror.dataValue()
}
public func packFormat() -> [Packable] {
return []
}
}
public extension SignedIntegerType {
public func packed() -> NSData
{
var value = self
var param: (prefix: UInt8, size: size_t)!
switch self {
case (0..<0x7F), 0x7F,
(-0x7F...0): param = (0xd0, 1);
case (0x0..<0x7FFF), 0x7FFF,
(-0x7FFF...0): param = (0xd1, 2);
case (0..<0x7FFFFFFF), 0x7FFFFFFF,
(-0x7FFFFFFF...0): param = (0xd2, 4);
case (0x0 ..< 0x7FFFFFFFFFFFFFFF),
(0x7FFFFFFFFFFFFFFF),
(-0x7FFFFFFFFFFFFFFF ... 0): param = (0xd3, 8);
default: break
}
if (value < 0 && value >= -1 * 0b0001_1111) {
var dummy = abs(value)
dummy = dummy | 0b1110_0000
return NSData(bytes: &dummy, length: MemoryLayout<Int8>.size)
}
let data = NSData(bytes: &value, length: param.size)
var data_mirror = data.byteArrayValue()
data_mirror.flip()
if !(0 <= value && value <= 0b01111111) {
#if swift(>=3)
data_mirror.insert(param.prefix, at: 0)
#else
data_mirror.insert(param.prefix, atIndex: 0)
#endif
}
return data_mirror.dataValue()
}
}
//MARK: Floating Point
extension FloatingPointType {
public func packed() -> NSData
{
var value = self
var param: (prefix: UInt8, size: size_t)!
switch self {
case is Float32: param = (0xca, 4)
case is Float64: param = (0xcb, 8)
default: break
}
let data = NSMutableData(bytes: &value, length: param.size)
var data_mirror = data.byteArrayValue()
data_mirror.flip()
#if swift(>=3)
data_mirror.insert(param.prefix, at: 0)
#else
data_mirror.insert(param.prefix, atIndex: 0)
#endif
return data_mirror.dataValue()
}
}
extension Double : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Float
}
}
extension Float : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Float
}
}
extension Int : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Int
}
}
extension Int8 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Int
}
}
extension Int16 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Int
}
}
extension Int32 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Int
}
}
extension Int64 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Int
}
}
extension UInt : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Uint
}
}
extension UInt8 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Uint
}
}
extension UInt16 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Uint
}
}
extension UInt32 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Uint
}
}
extension UInt64 : Packable {
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Uint
}
}
//MARK: Binary
public extension NSData {
public func packed() -> NSData
{
var prefix: UInt8!
var temp = self.length.packed().byteArrayValue()
#if arch(arm) || arch(i386)
switch self.length {
case (0..<0xFF), 0xff: prefix = (0xc4);
case (0x100..<0xFFFF), 0xffff: prefix = (0xc5);
default: break
}
#else
switch self.length {
case (0..<0xFF), 0xff: prefix = (0xc4);
case (0x100..<0xFFFF), 0xffff: prefix = (0xc5);
case (0x10000..<0xFFFFFFFF), 0xffffffff: prefix = (0xc6);
default: break
}
#endif
temp[0] = prefix
temp += self.byteArray
return temp.dataValue()
}
public func msgtype() -> MsgPackTypes {
return .Data
}
}
//MARK: Dictionary/Map
extension NSDictionary : Packable
{
public func packed() -> NSData
{
var byteArray = ByteArray()
#if arch(arm) || arch(i386)
switch self.count {
case 0...15:
byteArray.append(UInt8(0b1000_0000 | self.count))
case 16...0xffff:
byteArray.append(0xde)
byteArray += self.count._16_bit_array
default: break
}
#else
switch self.count {
case 0...15:
byteArray.append(UInt8(0b1000_0000 | self.count))
case 16...0xffff:
byteArray.append(0xde)
byteArray += self.count._16_bit_array
case 0x10000...0xffffffff:
byteArray.append(0xdf)
byteArray += self.count._32_bit_array
default: break
}
#endif
for (key, value) in self {
pack(item: key as? Packable, appendToBytes: &byteArray)
pack(item: value as? Packable, appendToBytes: &byteArray)
}
return byteArray.dataValue()
}
private var byteArray_length: size_t {
var i = 0
for (key, value) in self {
i += calculateSizeAfterPack(forItem: key)
i += calculateSizeAfterPack(forItem: value)
}
return i
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Dictionary
}
}
extension Dictionary : Packable
{
public func packed() -> NSData
{
var byteArray = ByteArray()
#if arch(arm) || arch(i386)
switch self.count {
case 0...15:
byteArray.append(UInt8(0b1000_0000 | self.count))
case 16...0xffff:
byteArray.append(0xde)
byteArray += self.count._16_bit_array
default: break
}
#else
switch self.count {
case 0...15:
byteArray.append(UInt8(0b1000_0000 | self.count))
case 16...0xffff:
byteArray.append(0xde)
byteArray += self.count._16_bit_array
case 0x10000...0xffffffff:
byteArray.append(0xdf)
byteArray += self.count._32_bit_array
default: break
}
#endif
for (key, value) in self {
pack(item: key as? Packable, appendToBytes: &byteArray)
// pack(&byteArray, item: value as? Packable)
pack(item: value as? Packable, appendToBytes: &byteArray)
}
return byteArray.dataValue()
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Dictionary
}
}
//MARK: Array
extension NSArray : Packable
{
public func packed() -> NSData
{
var byteArray = ByteArray()
#if arch(arm) || arch(i386)
switch self.count {
case 0...15:
byteArray.append(UInt8(0b10010000 | self.count))
case 16...0xffff:
byteArray.append(0xdc)
byteArray += self.count._16_bit_array
default: break
}
#else
switch self.count {
case 0...15:
byteArray.append(UInt8(0b10010000 | self.count))
case 16...0xffff:
byteArray.append(0xdc)
byteArray += self.count._16_bit_array
case 0x10000...0xffffffff:
byteArray.append(0xdd)
byteArray += self.count._32_bit_array
default: break
}
#endif
for value in self {
pack(item: value as? Packable, appendToBytes: &byteArray)
}
return byteArray.dataValue()
}
private var byteArray_length: size_t {
var i = 0
for item in self {
i += calculateSizeAfterPack(forItem: item)
}
return i
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Array
}
}
extension Array : Packable
{
public func packed() -> NSData
{
var byteArray = ByteArray()
#if arch(arm) || arch(i386)
switch self.count {
case 0...15:
byteArray.append(UInt8(0b10010000 | self.count))
case 16...0xffff:
byteArray.append(0xdc)
byteArray += self.count._16_bit_array
default: break
}
#else
switch self.count {
case 0...15:
byteArray.append(UInt8(0b10010000 | self.count))
case 16...0xffff:
byteArray.append(0xdc)
byteArray += self.count._16_bit_array
case 0x10000...0xffffffff:
byteArray.append(0xdd)
byteArray += self.count._32_bit_array
default: break
}
#endif
for value in self {
pack(item: value as? Packable, appendToBytes: &byteArray)
}
return byteArray.dataValue()
}
private var byteArray_length: size_t {
var i = 0
for item in self {
i += calculateSizeAfterPack(forItem: item)
}
return i
}
public func packFormat() -> [Packable] {
return []
}
public func msgtype() -> MsgPackTypes {
return .Array
}
}
| acd1d2b06a994ae602a9437a47214cbf | 26.186186 | 150 | 0.509997 | false | false | false | false |
varshylmobile/VMXMLParser | refs/heads/master | VMXMLParser.swift | mit | 1 | //
// VMXMLParser.swift
// XMLParserTest
//
// Created by Jimmy Jose on 22/08/14.
//
// 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
// Todo: Add documentation
class VMXMLParser: NSObject,NSXMLParserDelegate{
private let kParserError = "Parser Error"
private var activeElement = ""
private var previousElement = "-1"
private var previousElementValue = ""
private var arrayFinalXML = NSMutableArray()
private var dictFinalXML = NSMutableDictionary()
private var completionHandler:((tags:NSArray?, error:String?)->Void)?
var lameMode = true
var reoccuringTag:NSString = ""
/**
Initializes a new parser with url of NSURL type.
- parameter url: The url of xml file to be parsed
- parameter completionHandler: The completion handler
- returns: Void.
*/
override init() {
super.init()
}
func parseXMLFromURL(url:NSURL,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
VMXMLParser().initWithURL(url, completionHandler: completionHandler)
}
func parseXMLFromURLString(urlString:NSString,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
initWithURLString(urlString, completionHandler: completionHandler)
}
func parseXMLFromData(data:NSData,takeChildOfTag:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.reoccuringTag = takeChildOfTag
initWithContentsOfData(data, completionHandler:completionHandler)
}
class func initParserWithURL(url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithURL(url, completionHandler: completionHandler)
}
class func initParserWithURLString(urlString:NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithURLString(urlString, completionHandler: completionHandler)
}
class func initParserWithData(data:NSData,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
VMXMLParser().initWithContentsOfData(data, completionHandler:completionHandler)
}
private func initWithURL(url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
parseXMLForUrl(url :url, completionHandler: completionHandler)
return self
}
private func initWithURLString(urlString :NSString,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
let url = NSURL(string: urlString as String)!
parseXMLForUrl(url :url, completionHandler: completionHandler)
return self
}
private func initWithContentsOfData(data:NSData,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil) -> AnyObject {
initParserWith(data: data)
return self
}
private func parseXMLForUrl(url url:NSURL,completionHandler:((tags:NSArray?, error:String?)->Void)? = nil){
self.completionHandler = completionHandler
beginParsingXMLForUrl(url)
}
private func beginParsingXMLForUrl(url:NSURL){
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in
if(error != nil){
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:error!.localizedDescription)
}
}else{
self.initParserWith(data: data!)
}})
}
private func initParserWith(data data:NSData){
let parser = NSXMLParser(data: data)
parser.delegate = self
let success:Bool = parser.parse()
if success {
if(self.arrayFinalXML.count > 0){
if(self.completionHandler != nil){
self.completionHandler?(tags:self.arrayFinalXML,error:nil)
}
}
} else {
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:kParserError)
}
}
}
internal func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
activeElement = elementName;
if(reoccuringTag.isEqualToString(elementName)){
dictFinalXML = NSMutableDictionary()
}
}
internal func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if(reoccuringTag.length == 0){
if((dictFinalXML.objectForKey(activeElement)) != nil){
arrayFinalXML.addObject(dictFinalXML)
dictFinalXML = NSMutableDictionary()
}else{
dictFinalXML.setValue(previousElementValue, forKey: activeElement)
}
}else{
//println(elementName)
if(reoccuringTag.isEqualToString(elementName)){
arrayFinalXML.addObject(dictFinalXML)
dictFinalXML = NSMutableDictionary()
}else{
dictFinalXML.setValue(previousElementValue, forKey: activeElement)
}
}
previousElement = "-1"
previousElementValue = ""
}
internal func parser(parser: NSXMLParser, foundCharacters string: String) {
if var str = string as NSString? {
str = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if((previousElement as NSString).isEqualToString("-1")){
previousElement = activeElement
previousElementValue = str as String
}else{
if((previousElement as NSString).isEqualToString(activeElement)){
previousElementValue = previousElementValue + (str as String)
}else{
previousElement = activeElement
previousElementValue = str as String
}
}
}
}
internal func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if(self.completionHandler != nil){
self.completionHandler?(tags:nil,error:parseError.localizedDescription)
}
}
} | 707a3fb5da03825ee969a24127f278b7 | 32.428 | 182 | 0.604356 | false | false | false | false |
tjw/swift | refs/heads/master | stdlib/public/core/NewtypeWrapper.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// An implementation detail used to implement support importing
/// (Objective-)C entities marked with the swift_newtype Clang
/// attribute.
public protocol _SwiftNewtypeWrapper : RawRepresentable { }
extension _SwiftNewtypeWrapper where Self: Hashable, Self.RawValue : Hashable {
@inlinable // FIXME(sil-serialize-all)
public var hashValue: Int {
return rawValue.hashValue
}
@inlinable // FIXME(sil-serialize-all)
public func _hash(into hasher: inout _Hasher) {
hasher.combine(rawValue)
}
}
#if _runtime(_ObjC)
extension _SwiftNewtypeWrapper where Self.RawValue : _ObjectiveCBridgeable {
// Note: This is the only default typealias for _ObjectiveCType, because
// constrained extensions aren't allowed to define types in different ways.
// Fortunately the others don't need it.
public typealias _ObjectiveCType = Self.RawValue._ObjectiveCType
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> Self.RawValue._ObjectiveCType {
return rawValue._bridgeToObjectiveC()
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType,
result: inout Self?
) {
var innerResult: Self.RawValue?
Self.RawValue._forceBridgeFromObjectiveC(source, result: &innerResult)
result = innerResult.flatMap { Self(rawValue: $0) }
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType,
result: inout Self?
) -> Bool {
var innerResult: Self.RawValue?
let success = Self.RawValue._conditionallyBridgeFromObjectiveC(
source,
result: &innerResult)
result = innerResult.flatMap { Self(rawValue: $0) }
return success
}
@inlinable // FIXME(sil-serialize-all)
public static func _unconditionallyBridgeFromObjectiveC(
_ source: Self.RawValue._ObjectiveCType?
) -> Self {
return Self(
rawValue: Self.RawValue._unconditionallyBridgeFromObjectiveC(source))!
}
}
extension _SwiftNewtypeWrapper where Self.RawValue: AnyObject {
@inlinable // FIXME(sil-serialize-all)
public func _bridgeToObjectiveC() -> Self.RawValue {
return rawValue
}
@inlinable // FIXME(sil-serialize-all)
public static func _forceBridgeFromObjectiveC(
_ source: Self.RawValue,
result: inout Self?
) {
result = Self(rawValue: source)
}
@inlinable // FIXME(sil-serialize-all)
public static func _conditionallyBridgeFromObjectiveC(
_ source: Self.RawValue,
result: inout Self?
) -> Bool {
result = Self(rawValue: source)
return result != nil
}
@inlinable // FIXME(sil-serialize-all)
public static func _unconditionallyBridgeFromObjectiveC(
_ source: Self.RawValue?
) -> Self {
return Self(rawValue: source!)!
}
}
#endif
| 5c6affbc9e3d4fe916b83cf668ce359b | 31.298077 | 80 | 0.685621 | false | false | false | false |
izhuster/TechnicalTest | refs/heads/master | TechnicalTest/TechnicalTest/ViewControllers/Home/PokemonDataSource.swift | mit | 2 | //
// PokemonDataSource.swift
// TechnicalTest
//
// Created by Alejandro Cárdenas on 11/28/16.
// Copyright © 2016 alekscbarragan. All rights reserved.
//
import UIKit
protocol PokemonDataSourceDelegate {
func shouldUpdateTableView(sender: PokemonDataSource)
func shouldShowLoadingView(show: Bool)
func pokemonDataSource(dataSource: PokemonDataSource, didSelectPhotos object: AnyObject?)
func pokemonDataSource(dataSource: PokemonDataSource, didSelectPokemon pokemon: Pokemon)
}
// MARK: - Data source class
class PokemonDataSource: NSObject {
var delegate: PokemonDataSourceDelegate?
var pokemonFetcher: PokemonFetcher!
var pokemons = [Pokemon]()
override init() {
super.init()
}
func requestPokemons() {
delegate?.shouldShowLoadingView(true)
let pokemons = DataAccessor.sharedInstance.currentPokemons()
if pokemons.count > 0 {
self.pokemons = pokemons
delegate?.shouldUpdateTableView(self)
delegate?.shouldShowLoadingView(false)
} else {
pokemonFetcher.requestPokemons { (finished) in
if (finished) {
NSOperationQueue.mainQueue().addOperationWithBlock({
DataAccessor.sharedInstance.saveContext()
})
self.pokemons = DataAccessor.sharedInstance.currentPokemons()
self.delegate?.shouldUpdateTableView(self)
self.delegate?.shouldShowLoadingView(false)
}
}
}
}
}
// MARK: - Pokemon cell delegate
extension PokemonDataSource: PokemonTableViewCellDelegate {
func cell(cell: PokemonTableViewCell, didSelectPhotos sender: AnyObject) {
delegate?.pokemonDataSource(self, didSelectPhotos: cell)
}
}
// MARK: - table view data source
extension PokemonDataSource: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pokemons.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = String(PokemonTableViewCell)
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! PokemonTableViewCell
let pokemon = pokemons[indexPath.row]
cell.nameLabel.text = pokemon.name
cell.delegate = self
return cell
}
}
// MARK: - Table view delegate
extension PokemonDataSource: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let pokemon = pokemons[indexPath.row]
delegate?.pokemonDataSource(self, didSelectPokemon: pokemon)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| b01994e0d888f5c8877944ba16b25e06 | 27.073684 | 120 | 0.732283 | false | false | false | false |
evan-liu/GitHubExplorer | refs/heads/master | GitHubExplorer/UI.swift | mit | 1 | import UIKit
import FormationLayout
typealias LayoutBlock = (ConstraintMaker) -> Void
/// Helper class to build UI
class UI {
/// Only for getting `view` and `topLayoutGuide/bottomLayoutGuide`
unowned let controller: UIViewController
init(controller: UIViewController) {
self.controller = controller
view.backgroundColor = .sceneBackground
build()
}
lazy var view: UIView = self.controller.view
lazy var layout: FormationLayout = FormationLayout(rootView: self.view)
var topLayoutGuide: UILayoutSupport {
return controller.topLayoutGuide
}
var bottomLayoutGuide: UILayoutSupport {
return controller.bottomLayoutGuide
}
func build() {
}
}
/// App level ui helper
protocol AppUI {
/// App root controller
var controller: UIViewController { get }
}
extension UI: AppUI { }
| 86251ba990addb1dd64d8740a650f1c9 | 22.026316 | 75 | 0.692571 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/User Profile Sheet/UserProfileSheetViewController.swift | gpl-2.0 | 1 | class UserProfileSheetViewController: UITableViewController {
// MARK: - Properties
private let user: LikeUser
// Used for the `source` property in Stats when a Blog is previewed by URL (that is, in a WebView).
var blogUrlPreviewedSource: String?
private lazy var mainContext = {
return ContextManager.sharedInstance().mainContext
}()
private lazy var contentCoordinator: ContentCoordinator = {
return DefaultContentCoordinator(controller: self, context: mainContext)
}()
// MARK: - Init
init(user: LikeUser) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View
override func viewDidLoad() {
super.viewDidLoad()
configureTable()
registerTableCells()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var size = tableView.contentSize
// Apply a slight padding to the bottom of the view to give it some space to breathe
// when being presented in a popover or bottom sheet
let bottomPadding = WPDeviceIdentification.isiPad() ? Constants.iPadBottomPadding : Constants.iPhoneBottomPadding
size.height += bottomPadding
preferredContentSize = size
presentedVC?.presentedView?.layoutIfNeeded()
}
}
// MARK: - DrawerPresentable Extension
extension UserProfileSheetViewController: DrawerPresentable {
var collapsedHeight: DrawerHeight {
if traitCollection.verticalSizeClass == .compact {
return .maxHeight
}
// Force the table layout to update so the Bottom Sheet gets the right height.
tableView.layoutIfNeeded()
return .intrinsicHeight
}
var scrollableView: UIScrollView? {
return tableView
}
}
// MARK: - UITableViewDataSource methods
extension UserProfileSheetViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return user.preferredBlog != nil ? 2 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case Constants.userInfoSection:
return userInfoCell()
default:
return siteCell()
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show section header for User Info
guard section != Constants.userInfoSection,
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: UserProfileSectionHeader.defaultReuseID) as? UserProfileSectionHeader else {
return nil
}
header.titleLabel.text = Constants.siteSectionTitle
return header
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.section == Constants.userInfoSection ? UserProfileUserInfoCell.estimatedRowHeight :
UserProfileSiteCell.estimatedRowHeight
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == Constants.userInfoSection ? 0 : UITableView.automaticDimension
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section != Constants.userInfoSection else {
return
}
showSite()
tableView.deselectRow(at: indexPath, animated: true)
}
}
// MARK: - Private Extension
private extension UserProfileSheetViewController {
func showSite() {
WPAnalytics.track(.userProfileSheetSiteShown)
guard let blog = user.preferredBlog else {
return
}
guard blog.blogID > 0 else {
showSiteWebView(withUrl: blog.blogUrl)
return
}
showSiteTopicWithID(NSNumber(value: blog.blogID))
}
func showSiteTopicWithID(_ siteID: NSNumber) {
let controller = ReaderStreamViewController.controllerWithSiteID(siteID, isFeed: false)
controller.statSource = ReaderStreamViewController.StatSource.notif_like_list_user_profile
let navController = UINavigationController(rootViewController: controller)
present(navController, animated: true)
}
func showSiteWebView(withUrl url: String?) {
guard let urlString = url,
!urlString.isEmpty,
let siteURL = URL(string: urlString) else {
DDLogError("User Profile: Error creating URL from site string.")
return
}
WPAnalytics.track(.blogUrlPreviewed, properties: ["source": blogUrlPreviewedSource as Any])
contentCoordinator.displayWebViewWithURL(siteURL)
}
func configureTable() {
tableView.backgroundColor = .basicBackground
tableView.separatorStyle = .none
}
func registerTableCells() {
tableView.register(UserProfileUserInfoCell.defaultNib,
forCellReuseIdentifier: UserProfileUserInfoCell.defaultReuseID)
tableView.register(UserProfileSiteCell.defaultNib,
forCellReuseIdentifier: UserProfileSiteCell.defaultReuseID)
tableView.register(UserProfileSectionHeader.defaultNib,
forHeaderFooterViewReuseIdentifier: UserProfileSectionHeader.defaultReuseID)
}
func userInfoCell() -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: UserProfileUserInfoCell.defaultReuseID) as? UserProfileUserInfoCell else {
return UITableViewCell()
}
cell.configure(withUser: user)
return cell
}
func siteCell() -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: UserProfileSiteCell.defaultReuseID) as? UserProfileSiteCell,
let blog = user.preferredBlog else {
return UITableViewCell()
}
cell.configure(withBlog: blog)
return cell
}
enum Constants {
static let userInfoSection = 0
static let siteSectionTitle = NSLocalizedString("Site", comment: "Header for a single site, shown in Notification user profile.").localizedUppercase
static let iPadBottomPadding: CGFloat = 10
static let iPhoneBottomPadding: CGFloat = 40
}
}
| 60de531998adbf1c1a4a58aa21b2d84a | 31.826291 | 161 | 0.672626 | false | false | false | false |
a497500306/yijia_kuanjia | refs/heads/master | 医家/医家/主项目/MLTabBarController/MLTabBarController.swift | apache-2.0 | 1 | //
// MLTabBarController.swift
// 医家
//
// Created by 洛耳 on 15/12/21.
// Copyright © 2015年 workorz. All rights reserved.
//
import UIKit
class MLTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
let item = self.tabBar.items![0]
let image = UIImage(named: "首页_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage = UIImage(named: "首页_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item.selectedImage = seleImage
item.image = image
item.title = "首页"
let attributes = NSMutableDictionary()
attributes.setValue(UIColor(red: 3/255.0, green: 166/255.0, blue: 116/255.0, alpha: 1), forKey: NSForegroundColorAttributeName)
item.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item1 = self.tabBar.items![1]
let image1 = UIImage(named: "论坛_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage1 = UIImage(named: "论坛_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item1.selectedImage = seleImage1
item1.image = image1
item1.title = "论坛"
item1.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item2 = self.tabBar.items![2]
let image2 = UIImage(named: "测试_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage2 = UIImage(named: "测试_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item2.selectedImage = seleImage2
item2.title = "测试"
item2.image = image2
item2.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
let item3 = self.tabBar.items![3]
let image3 = UIImage(named: "消息_nor")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let seleImage3 = UIImage(named: "消息_pre")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
item3.selectedImage = seleImage3
item3.image = image3
item3.title = "消息"
item3.setTitleTextAttributes(attributes as NSDictionary as? [String : AnyObject], forState: UIControlState.Selected)
}
}
| ff636c9adaf432e700ee00813520725f | 45.711538 | 135 | 0.690819 | false | false | false | false |
parthdubal/MyNewyorkTimes | refs/heads/master | MyNewyorkTimes/Common/Reachability/Reachability.swift | mit | 1 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged()
}
}
class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
public var currentReachabilityStatus: NetworkStatus {
guard isReachable else { return .notReachable }
if isReachableViaWiFi {
return .reachableViaWiFi
}
if isRunningOnDevice {
return .reachableViaWWAN
}
return .notReachable
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate var reachabilityRef: SCNetworkReachability?
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard let reachabilityRef = reachabilityRef, !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an intial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
let flags = reachabilityFlags
guard previousFlags != flags else { return }
let block = isReachable ? whenReachable : whenUnreachable
block?(self)
self.notificationCenter.post(name: ReachabilityChangedNotification, object:self)
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return reachabilityFlags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return reachabilityFlags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return reachabilityFlags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return reachabilityFlags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return reachabilityFlags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
| a5e2c9192fd9797c5f69278df197fac6 | 33.084746 | 137 | 0.658279 | false | false | false | false |
AlDrago/SwiftyJSON | refs/heads/master | Tests/RawTests.swift | mit | 1 | // RawTests.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import SwiftyJSON3
class RawTests: XCTestCase {
func testRawData() {
let json: JSON = ["somekey" : "some string value"]
let expectedRawData = "{\"somekey\":\"some string value\"}".data(using: String.Encoding.utf8)
do {
let data: Data = try json.rawData()
XCTAssertEqual(expectedRawData, data)
} catch _ {
XCTFail()
}
}
func testInvalidJSONForRawData() {
let json: JSON = "...<nonsense>xyz</nonsense>"
do {
_ = try json.rawData()
} catch let error as NSError {
XCTAssertEqual(error.code, ErrorInvalidJSON)
}
}
func testArray() {
let json:JSON = [1, "2", 3.12, NSNull(), true, ["name": "Jack"]]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testDictionary() {
let json:JSON = ["number":111111.23456789, "name":"Jack", "list":[1,2,3,4], "bool":false, "null":NSNull()]
let data: Data?
do {
data = try json.rawData()
} catch _ {
data = nil
}
let string = json.rawString()
XCTAssertTrue (data != nil)
XCTAssertTrue (string!.lengthOfBytes(using: String.Encoding.utf8) > 0)
print(string!)
}
func testString() {
let json:JSON = "I'm a json"
print(json.rawString())
XCTAssertTrue(json.rawString() == "I'm a json")
}
func testNumber() {
let json:JSON = 123456789.123
print(json.rawString())
XCTAssertTrue(json.rawString() == "123456789.123")
}
func testBool() {
let json:JSON = true
print(json.rawString())
XCTAssertTrue(json.rawString() == "true")
}
func testNull() {
let json:JSON = nil
print(json.rawString())
XCTAssertTrue(json.rawString() == "null")
}
}
| 986a864aecb5fb0d964f88700e1784f5 | 32.424242 | 114 | 0.60411 | false | true | false | false |
ljshj/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Managed Runtime/AAManagedTable.swift | agpl-3.0 | 2 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
public class AAManagedTable {
//------------------------------------------------------------------------//
// Controller of table
public let controller: UIViewController
// Table view
public let style: AAContentTableStyle
public let tableView: UITableView
public var tableViewDelegate: UITableViewDelegate { get { return baseDelegate } }
public var tableViewDataSource: UITableViewDataSource { get { return baseDelegate } }
// Scrolling closure
public var tableScrollClosure: ((tableView: UITableView) -> ())?
// Is fade in/out animated
public var fadeShowing = false
// Sections of table
public var sections: [AAManagedSection] = [AAManagedSection]()
// Fixed Height
public var fixedHeight: CGFloat?
// Can Edit All rows
public var canEditAll: Bool?
// Can Delete All rows
public var canDeleteAll: Bool?
// Is Table in editing mode
public var isEditing: Bool {
get {
return tableView.editing
}
}
// Is updating sections
private var isUpdating = false
// Reference to table view delegate/data source
private var baseDelegate: AMBaseTableDelegate!
// Search
private var isSearchInited: Bool = false
private var isSearchAutoHide: Bool = false
private var searchDisplayController: UISearchDisplayController!
private var searchManagedController: AnyObject!
//------------------------------------------------------------------------//
public init(style: AAContentTableStyle, tableView: UITableView, controller: UIViewController) {
self.style = style
self.controller = controller
self.tableView = tableView
if style == .SettingsGrouped {
self.baseDelegate = AMGrouppedTableDelegate(data: self)
} else {
self.baseDelegate = AMPlainTableDelegate(data: self)
}
self.tableView.dataSource = self.baseDelegate
self.tableView.delegate = self.baseDelegate
}
//------------------------------------------------------------------------//
// Entry point to adding
public func beginUpdates() {
if isUpdating {
fatalError("Already updating table")
}
isUpdating = true
}
public func addSection(autoSeparator: Bool = false) -> AAManagedSection {
if !isUpdating {
fatalError("Table is not in updating mode")
}
let res = AAManagedSection(table: self, index: sections.count)
res.autoSeparators = autoSeparator
sections.append(res)
return res
}
public func search<C where C: AABindedSearchCell, C: UITableViewCell>(cell: C.Type, @noescape closure: (s: AAManagedSearchConfig<C>) -> ()) {
if !isUpdating {
fatalError("Table is not in updating mode")
}
if isSearchInited {
fatalError("Search already inited")
}
isSearchInited = true
// Configuring search source
let config = AAManagedSearchConfig<C>()
closure(s: config)
// Creating search source
let searchSource = AAManagedSearchController<C>(config: config, controller: controller, tableView: tableView)
self.searchDisplayController = searchSource.searchDisplay
self.searchManagedController = searchSource
self.isSearchAutoHide = config.isSearchAutoHide
}
public func endUpdates() {
if !isUpdating {
fatalError("Table is not in editable mode")
}
isUpdating = false
}
// Reloading table
public func reload() {
self.tableView.reloadData()
}
public func reload(section: Int) {
self.tableView.reloadSections(NSIndexSet(index: section), withRowAnimation: .Automatic)
}
// Binding methods
public func bind(binder: AABinder) {
for s in sections {
s.bind(self, binder: binder)
}
}
public func unbind(binder: AABinder) {
for s in sections {
s.unbind(self, binder: binder)
}
}
// Show/hide table
public func showTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 1
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 1
})
}
}
public func hideTable() {
if isUpdating || !fadeShowing {
self.tableView.alpha = 0
} else {
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 0
})
}
}
// Controller callbacks
public func controllerViewWillDisappear(animated: Bool) {
// Auto close search on leaving controller
if isSearchAutoHide {
//dispatchOnUi { () -> Void in
searchDisplayController?.setActive(false, animated: false)
//}
}
}
public func controllerViewDidDisappear(animated: Bool) {
// Auto close search on leaving controller
// searchDisplayController?.setActive(false, animated: animated)
}
public func controllerViewWillAppear(animated: Bool) {
// Search bar dissapear fixing
// Hack No 1
if searchDisplayController != nil {
let searchBar = searchDisplayController!.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
}
// Hack No 2
tableView.tableHeaderView?.setNeedsLayout()
tableView.tableFooterView?.setNeedsLayout()
// Status bar styles
if (searchDisplayController != nil && searchDisplayController!.active) {
// If search is active: apply search status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
} else {
// If search is not active: apply main status bar style
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
}
}
// Closure based extension
public extension AAManagedTable {
public func section(closure: (s: AAManagedSection) -> ()){
closure(s: addSection(true))
}
}
// Table view delegates and data sources
private class AMPlainTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].headerHeight)
}
@objc func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat(data.sections[section].footerHeight)
}
@objc func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if (data.sections[section].headerText == nil) {
return UIView()
} else {
return nil
}
}
@objc func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if (data.sections[section].footerText == nil) {
return UIView()
} else {
return nil
}
}
}
private class AMGrouppedTableDelegate: AMBaseTableDelegate {
@objc func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellHeaderColor
}
@objc func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = ActorSDK.sharedActor().style.cellFooterColor
}
}
private class AMBaseTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate {
unowned private let data: AAManagedTable
init(data: AAManagedTable) {
self.data = data
}
@objc func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.sections.count
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.sections[section].numberOfItems(data)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return data.sections[indexPath.section].cellForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let text = data.sections[section].headerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
let text = data.sections[section].footerText
if text != nil {
return AALocalized(text!)
} else {
return text
}
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if data.fixedHeight != nil {
return data.fixedHeight!
}
return data.sections[indexPath.section].cellHeightForItem(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
if data.canEditAll != nil {
return data.canEditAll!
}
return (data.sections[indexPath.section].numberOfItems(data) > 0 ? data.sections[indexPath.section].canDelete(data, indexPath: indexPath) : false)
}
@objc func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
@objc func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if data.canDeleteAll != nil {
if data.canDeleteAll! {
return .Delete
} else {
return .None
}
}
return data.sections[indexPath.section].canDelete(data, indexPath: indexPath) ? .Delete : .None
}
@objc func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
return data.sections[indexPath.section].delete(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let section = data.sections[indexPath.section]
if section.canSelect(data, indexPath: indexPath) {
if section.select(data, indexPath: indexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} else {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
@objc func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
return false
}
@objc func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
let section = data.sections[indexPath.section]
return section.canCopy(data, indexPath: indexPath)
}
@objc func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == "copy:" {
let section = data.sections[indexPath.section]
if section.canCopy(data, indexPath: indexPath) {
section.copy(data, indexPath: indexPath)
}
}
}
@objc func scrollViewDidScroll(scrollView: UIScrollView) {
if (data.tableView == scrollView) {
data.tableScrollClosure?(tableView: data.tableView)
}
}
}
public class AAManagedSearchConfig<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell> {
public var searchList: ARBindedDisplayList!
public var selectAction: ((BindCell.BindData) -> ())?
public var isSearchAutoHide: Bool = true
public var didBind: ((c: BindCell, d: BindCell.BindData) -> ())?
}
private class AAManagedSearchController<BindCell where BindCell: AABindedSearchCell, BindCell: UITableViewCell>: NSObject, UISearchBarDelegate, UISearchDisplayDelegate, UITableViewDataSource, UITableViewDelegate, ARDisplayList_Listener {
let config: AAManagedSearchConfig<BindCell>
let displayList: ARBindedDisplayList
let searchDisplay: UISearchDisplayController
init(config: AAManagedSearchConfig<BindCell>, controller: UIViewController, tableView: UITableView) {
self.config = config
self.displayList = config.searchList
let style = ActorSDK.sharedActor().style
let searchBar = UISearchBar()
// Styling Search bar
searchBar.searchBarStyle = UISearchBarStyle.Default
searchBar.translucent = false
searchBar.placeholder = "" // SearchBar placeholder animation fix
// SearchBar background color
searchBar.barTintColor = style.searchBackgroundColor.forTransparentBar()
searchBar.setBackgroundImage(Imaging.imageWithColor(style.searchBackgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: .Any, barMetrics: .Default)
searchBar.backgroundColor = style.searchBackgroundColor
// SearchBar cancel color
searchBar.tintColor = style.searchCancelColor
// Apply keyboard color
searchBar.keyboardAppearance = style.isDarkApp ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
// SearchBar field color
let fieldBg = Imaging.imageWithColor(style.searchFieldBgColor, size: CGSize(width: 14,height: 28))
.roundCorners(14, h: 28, roundSize: 4)
searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal)
// SearchBar field text color
for subView in searchBar.subviews {
for secondLevelSubview in subView.subviews {
if let tf = secondLevelSubview as? UITextField {
tf.textColor = style.searchFieldTextColor
break
}
}
}
self.searchDisplay = UISearchDisplayController(searchBar: searchBar, contentsController: controller)
super.init()
// Creating Search Display Controller
self.searchDisplay.searchBar.delegate = self
self.searchDisplay.searchResultsDataSource = self
self.searchDisplay.searchResultsDelegate = self
self.searchDisplay.delegate = self
// Styling search list
self.searchDisplay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.searchDisplay.searchResultsTableView.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
// Adding search to table header
let header = AATableViewHeader(frame: CGRectMake(0, 0, 320, 44))
header.addSubview(self.searchDisplay.searchBar)
tableView.tableHeaderView = header
// Start receiving events
self.displayList.addListener(self)
}
// Model
func objectAtIndexPath(indexPath: NSIndexPath) -> BindCell.BindData {
return displayList.itemWithIndex(jint(indexPath.row)) as! BindCell.BindData
}
@objc func onCollectionChanged() {
searchDisplay.searchResultsTableView.reloadData()
}
// Table view data
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int(displayList.size());
}
@objc func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let item = objectAtIndexPath(indexPath)
return BindCell.self.bindedCellHeight(item)
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = objectAtIndexPath(indexPath)
let cell = tableView.dequeueCell(BindCell.self, indexPath: indexPath) as! BindCell
cell.bind(item, search: nil)
return cell
}
@objc func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = objectAtIndexPath(indexPath)
config.selectAction!(item)
// MainAppTheme.navigation.applyStatusBar()
}
// Search updating
@objc func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
let normalized = searchText.trim().lowercaseString
if (normalized.length > 0) {
displayList.initSearchWithQuery(normalized, withRefresh: false)
} else {
displayList.initEmpty()
}
}
// Search styling
@objc func searchDisplayControllerWillBeginSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.searchStatusBarStyle, animated: true)
}
@objc func searchDisplayControllerWillEndSearch(controller: UISearchDisplayController) {
UIApplication.sharedApplication().setStatusBarStyle(ActorSDK.sharedActor().style.vcStatusBarStyle, animated: true)
}
@objc func searchDisplayController(controller: UISearchDisplayController, didShowSearchResultsTableView tableView: UITableView) {
for v in tableView.subviews {
if (v is UIImageView) {
(v as! UIImageView).alpha = 0;
}
}
}
}
| 6cd9496530ead6f7d8da522009676683 | 33.314545 | 237 | 0.633074 | false | false | false | false |
vitormesquita/Malert | refs/heads/master | Malert/Classes/MalertView/MalertView.swift | mit | 1 | //
// MalertView.swift
// Pods
//
// Created by Vitor Mesquita on 31/10/16.
//
//
import UIKit
public class MalertView: UIView {
private lazy var titleLabel = UILabel.ilimitNumberOfLines()
private lazy var buttonsStackView = UIStackView.defaultStack(axis: .vertical)
private var stackConstraints: [NSLayoutConstraint] = []
private var titleLabelConstraints: [NSLayoutConstraint] = []
private var customViewConstraints: [NSLayoutConstraint] = []
private var _buttonsHeight: CGFloat = 44
private var _buttonsSeparetorColor: UIColor = UIColor(white: 0.8, alpha: 1)
private var _buttonsFont: UIFont = UIFont.systemFont(ofSize: 16)
private var inset: CGFloat = 0 {
didSet { refreshViews() }
}
private var stackSideInset: CGFloat = 0 {
didSet { updateButtonsStackViewConstraints() }
}
private var stackBottomInset: CGFloat = 0 {
didSet { updateButtonsStackViewConstraints() }
}
private var customView: UIView? {
didSet {
if let oldValue = oldValue {
oldValue.removeFromSuperview()
}
}
}
// MARK: - Init
init() {
super.init(frame: .zero)
clipsToBounds = true
margin = 0
cornerRadius = 6
backgroundColor = .white
textColor = .black
textAlign = .left
titleFont = UIFont.systemFont(ofSize: 14)
buttonsSpace = 0
buttonsSideMargin = 0
buttonsAxis = .vertical
}
@available(*, unavailable)
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK - Utils
private var hasButtons: Bool {
guard buttonsStackView.isDescendant(of: self) else { return false }
return !buttonsStackView.arrangedSubviews.isEmpty
}
private func refreshViews() {
updateTitleLabelConstraints()
updateCustomViewConstraints()
updateButtonsStackViewConstraints()
}
}
// MARK: - Extensions to setUp Views in alert
extension MalertView {
func seTitle(_ title: String?) {
if let title = title {
titleLabel.text = title
if !titleLabel.isDescendant(of: self) {
self.addSubview(titleLabel)
refreshViews()
}
}
}
func setCustomView(_ customView: UIView?) {
guard let customView = customView else { return }
self.customView = customView
self.addSubview(customView)
refreshViews()
}
func addButton(_ button: MalertAction, actionCallback: MalertActionCallbackProtocol?) {
let buttonView = MalertButtonView(type: .system)
buttonView.height = _buttonsHeight
buttonView.titleFont = _buttonsFont
buttonView.separetorColor = _buttonsSeparetorColor
buttonView.callback = actionCallback
buttonView.setUpBy(action: button)
buttonView.setUp(index: buttonsStackView.arrangedSubviews.count, hasMargin: buttonsSpace > 0, isHorizontalAxis: buttonsAxis == .horizontal)
buttonsStackView.addArrangedSubview(buttonView)
if !buttonsStackView.isDescendant(of: self) {
self.addSubview(buttonsStackView)
refreshViews()
}
}
}
/**
* Extensios that implements Malert constraints to:
* - Title Label
* - Custom View
* - Buttons Stack View
*/
extension MalertView {
private func updateTitleLabelConstraints() {
NSLayoutConstraint.deactivate(titleLabelConstraints)
guard titleLabel.isDescendant(of: self) else { return }
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabelConstraints = [
titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: inset),
titleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -inset),
titleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: inset)
]
NSLayoutConstraint.activate(titleLabelConstraints)
}
private func updateCustomViewConstraints() {
guard let customView = customView else { return }
NSLayoutConstraint.deactivate(customViewConstraints)
customView.translatesAutoresizingMaskIntoConstraints = false
customViewConstraints = [
customView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -inset),
customView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: inset)
]
if titleLabel.isDescendant(of: self) {
customViewConstraints.append(customView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: inset))
} else {
customViewConstraints.append(customView.topAnchor.constraint(equalTo: self.topAnchor, constant: inset))
}
if !hasButtons {
customViewConstraints.append(customView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -inset))
}
NSLayoutConstraint.activate(customViewConstraints)
}
private func updateButtonsStackViewConstraints() {
guard hasButtons else { return }
NSLayoutConstraint.deactivate(stackConstraints)
buttonsStackView.translatesAutoresizingMaskIntoConstraints = false
stackConstraints = [
buttonsStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -stackSideInset),
buttonsStackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: stackSideInset),
buttonsStackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -stackBottomInset)
]
if let customView = customView {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: customView.bottomAnchor, constant: inset))
} else if titleLabel.isDescendant(of: self) {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: inset))
} else {
stackConstraints.append(buttonsStackView.topAnchor.constraint(equalTo: self.topAnchor, constant: inset))
}
NSLayoutConstraint.activate(stackConstraints)
}
}
// MARK: - Appearance
extension MalertView {
/// Dialog view corner radius
@objc public dynamic var cornerRadius: CGFloat {
get { return layer.cornerRadius }
set { layer.cornerRadius = newValue }
}
/// Title text color
@objc public dynamic var textColor: UIColor {
get { return titleLabel.textColor }
set { titleLabel.textColor = newValue }
}
/// Title text Align
@objc public dynamic var textAlign: NSTextAlignment {
get { return titleLabel.textAlignment }
set { titleLabel.textAlignment = newValue }
}
/// Title font
@objc public dynamic var titleFont: UIFont {
get { return titleLabel.font }
set { titleLabel.font = newValue }
}
/// Buttons distribution in stack view
@objc public dynamic var buttonsDistribution: UIStackView.Distribution {
get { return buttonsStackView.distribution }
set { buttonsStackView.distribution = newValue }
}
/// Buttons aligns in stack view
@objc public dynamic var buttonsAligment: UIStackView.Alignment {
get { return buttonsStackView.alignment }
set { buttonsStackView.alignment = newValue }
}
/// Buttons axis in stack view
@objc public dynamic var buttonsAxis: NSLayoutConstraint.Axis {
get { return buttonsStackView.axis }
set { buttonsStackView.axis = newValue }
}
/// Margin inset to titleLabel and CustomView
@objc public dynamic var margin: CGFloat {
get { return inset }
set { inset = newValue }
}
/// Trailing and Leading margin inset to StackView buttons
@objc public dynamic var buttonsSideMargin: CGFloat {
get { return stackSideInset }
set { stackSideInset = newValue }
}
/// Bottom margin inset to StackView buttons
@objc public dynamic var buttonsBottomMargin: CGFloat {
get { return stackBottomInset }
set { stackBottomInset = newValue }
}
/// Margin inset between buttons
@objc public dynamic var buttonsSpace: CGFloat {
get { return buttonsStackView.spacing }
set { buttonsStackView.spacing = newValue }
}
///
@objc public dynamic var buttonsHeight: CGFloat {
get { return _buttonsHeight }
set { _buttonsHeight = newValue }
}
///
@objc public dynamic var separetorColor: UIColor {
get { return _buttonsSeparetorColor }
set { _buttonsSeparetorColor = newValue }
}
///
@objc public dynamic var buttonsFont: UIFont {
get { return _buttonsFont }
set { _buttonsFont = newValue }
}
}
| 7fb652424c95953a0de14b2780c127be | 32.145455 | 147 | 0.646956 | false | false | false | false |
kiliankoe/DVB | refs/heads/master | Sources/DVB/Models/RouteChange/RouteChange.swift | mit | 1 | import Foundation
public struct RouteChange {
public let id: String
public let kind: Kind
public let tripRequestInclude: Bool?
public let title: String
public let htmlDescription: String
public let validityPeriods: [ValidityPeriod]
public let lineIds: [String]
public let publishDate: Date
}
extension RouteChange: Decodable {
private enum CodingKeys: String, CodingKey {
case id = "Id"
case kind = "Type"
case tripRequestInclude = "TripRequestInclude"
case title = "Title"
case htmlDescription = "Description"
case validityPeriods = "ValidityPeriods"
case lineIds = "LineIds"
case publishDate = "PublishDate"
}
}
extension RouteChange: Equatable {}
extension RouteChange: Hashable {}
// MARK: - API
extension RouteChange {
public static func get(shortTerm: Bool = true,
session: URLSession = .shared,
completion: @escaping (Result<RouteChangeResponse>) -> Void) {
let data = [
"shortterm": shortTerm,
]
post(Endpoint.routeChanges, data: data, session: session, completion: completion)
}
}
// MARK: - Utiliy
extension RouteChange: CustomStringConvertible {
public var description: String {
return self.title
}
}
| 546eee6a71419b452bdbd7fc1ee83651 | 25.254902 | 89 | 0.64227 | false | false | false | false |
kevinup7/S4HeaderExtensions | refs/heads/master | Sources/S4HeaderExtensions/MessageHeaders/TransferEncoding.swift | mit | 1 | import S4
extension Headers {
/**
The `Transfer-Encoding` header field lists the transfer coding names
corresponding to the sequence of transfer codings that have been (or
will be) applied to the payload body in order to form the message
body.
## Example Headers
`Transfer-Encoding: gzip, chunked`
`Transfer-Encoding: gzip`
## Examples
var response = Response()
response.headers.transferEncoding = [.gzip, .chunked]
var response = Response()
response.headers.transferEncoding = [.gzip]
- seealso: [RFC7230](http://tools.ietf.org/html/rfc7230#section-3.3.1)
*/
public var transferEncoding: [Encoding]? {
get {
return Encoding.values(fromHeader: headers["Transfer-Encoding"])
}
set {
headers["Transfer-Encoding"] = newValue?.headerValue
}
}
} | d9bb0b167f4773637140e4bba107a8a4 | 26.735294 | 78 | 0.597665 | false | false | false | false |
weirdindiankid/Tinder-Clone | refs/heads/master | TinderClone/ViewController.swift | mit | 1 | //
// ViewController.swift
// TinderClone
//
// Created by Dharmesh Tarapore on 19/01/2015.
// Copyright (c) 2015 Dharmesh Tarapore. All rights reserved.
//
import UIKit
class ViewController: UIViewController, FBLoginViewDelegate,PFLogInViewControllerDelegate, UITextFieldDelegate {
// var profilePictureView:FBProfilePictureView = FBProfilePictureView()
var fbloginView:FBLoginView = FBLoginView()
var facebookLogin:Bool = false
@IBOutlet weak var textfieldUserName: UITextField!
@IBOutlet weak var textfieldPassword: UITextField!
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var signUpButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
println("viewDidLoad");
fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
fbloginView.delegate = self
/*fbloginView.readPermissions = ["email",
"basic_info",
"user_location",
"user_birthday",
"user_likes"]*/
self.view.addSubview(fbloginView)
// profilePictureView = FBProfilePictureView(frame: CGRectMake(70.0, fbloginView.frame.size.height + fbloginView.frame.origin.y, 180.0, 200.0))
// self.view.addSubview(profilePictureView)
GlobalVariableSharedInstance.initLocationManager()
}
// Add in an NSRunLoop to make this faster
override func viewWillAppear(animated: Bool)
{
println("viewWillAppear");
//fbloginView.frame = CGRectMake(60.0, 450.0, 200.0, 44.0)
//profilePictureView.frame = CGRectMake(70.0, 450.0, 180.0, 200.0)
let user = PFUser.currentUser() as PFUser!
if (user != nil) //if (self.facebookLogin == true)//if (FBSession.activeSession().isOpen)
{
NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("displayTabs"), userInfo: nil, repeats: false)
self.facebookLogin = false
}
else {
FBSession.activeSession().closeAndClearTokenInformation()
}
}
@IBAction func signIn(sender: UIButton)
{
println("signIn");
// self.displayTabs()
self.signInButton.enabled = false
self.signUpButton.enabled = false
var message = ""
if (self.textfieldPassword.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "Password should not be empty"
}
if (self.textfieldUserName.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
message = "User Name should not be empty"
}
if (message.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0)
{
var alert:UIAlertView = UIAlertView(title: "Message", message: message, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
else
{
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
PFUser.logInWithUsernameInBackground(self.textfieldUserName.text , password:self.textfieldPassword.text)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
self.displayTabs()
}
else
{
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
}
}
override func viewWillLayoutSubviews()
{
super.viewWillAppear(false)
//println("viewWillLayoutSubviews")
}
func loginViewFetchedUserInfo(loginView: FBLoginView!, user: FBGraphUser!)
{
//self.profilePictureView.profileID = user.id
println("loginViewFetchedUserInfo")
var query = PFUser.query()
query.whereKey("fbID", equalTo: user.id)
//
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
query.findObjectsInBackgroundWithBlock({(NSArray objects, NSError error) in
if (error != nil) {
MBProgressHUD.hideHUDForView(self.view, animated:false)
}
else{
if (objects.count == 0)
{
/* fbloginView.readPermissions = ["email"];
var me:FBRequest = FBRequest.requestForMe()
me.startWithCompletionHandler({(NSArray my, NSError error) in*/
println(user)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let imageUploaderView = storyboard.instantiateViewControllerWithIdentifier("ImageSelectorViewController") as ImageSelectorViewController
var email:String? = user.objectForKey("email") as String?
var birthday:String? = user.birthday
if (email==nil) {
email = user.first_name + "@user.com"
}
if (birthday==nil) {
birthday = "10/10/1987"
}
imageUploaderView.setUserName(user.name, password: user.id, Email: email!, andDateOfBirth: birthday!)
imageUploaderView.facebookLogin = true
self.facebookLogin = true
imageUploaderView.user = user
MBProgressHUD.hideHUDForView(self.view, animated:false)
imageUploaderView.loginScreen = self;
self.navigationController!.pushViewController(imageUploaderView, animated: true)
}
else
{
PFUser.logInWithUsernameInBackground(user.name , password:user.id)
{
(user: PFUser!, error: NSError!) -> Void in
if (user != nil)
{
/*
var alert:UIAlertView = UIAlertView(title: "Message", message: "Hi " + user.username + ". You logged in", delegate: nil, cancelButtonTitle: "Ok")
alert.show()
*/
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.displayTabs()
}
else
{
MBProgressHUD.hideHUDForView(self.view, animated:false)
if let errorString = error.userInfo?["error"] as? NSString
{
var alert:UIAlertView = UIAlertView(title: "Error", message: errorString, delegate: nil, cancelButtonTitle: "Ok")
alert.show()
}
}
self.signInButton.enabled = true
self.signUpButton.enabled = true
}
}
}
})
}
func loginViewShowingLoggedInUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedInUser")
}
func loginViewShowingLoggedOutUser(loginView: FBLoginView!)
{
println("loginViewShowingLoggedOutUser")
// self.profilePictureView.profileID = nil
}
func displayTabs()
{
println("displayTabs")
MBProgressHUD.showHUDAddedTo(self.view, animated:true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
var tabbarController = UITabBarController()
let profileSelectorViewController = storyboard.instantiateViewControllerWithIdentifier("ProfileSelectorViewController") as ProfileSelectorViewController
let chatViewController = storyboard.instantiateViewControllerWithIdentifier("ChatViewController") as ChatViewController
let settingsViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsViewController") as SettingsViewController
let profileSelectorNavigationController = UINavigationController(rootViewController: profileSelectorViewController)
let chatNavigationController = UINavigationController(rootViewController: chatViewController)
tabbarController.viewControllers = [ profileSelectorNavigationController, chatNavigationController, settingsViewController]
var tabbarItem = tabbarController.tabBar.items![0] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("groups", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![1] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("chat", ofType: "png")!)
tabbarItem.title = nil
tabbarItem = tabbarController.tabBar.items![2] as UITabBarItem;
tabbarItem.image = UIImage(contentsOfFile: NSBundle.mainBundle().pathForResource("settings", ofType: "png")!)
tabbarItem.title = nil
//println(tabbarController.viewControllers)
MBProgressHUD.hideHUDForView(self.view, animated:false)
self.presentViewController(tabbarController, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField!) -> Bool
{
textField.resignFirstResponder()
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| cf674a8a996d1b70f9d4088a09ca4798 | 38.809701 | 177 | 0.55516 | false | false | false | false |
skyfe79/SwiftImageProcessing | refs/heads/master | 09_Brightness.playground/Sources/ByteImage.swift | mit | 1 | import UIKit
/**
* 1byte크기의 화소 배열로 이뤄진 이미지
*/
public struct BytePixel {
private var value: UInt8
public init(value : UInt8) {
self.value = value
}
//red
public var C: UInt8 {
get { return value }
set {
let v = max(min(newValue, 255), 0)
value = v
}
}
public var Cf: Double {
get { return Double(self.C) / 255.0 }
set { self.C = UInt8(max(min(newValue, 1.0), 0.0) * 255.0) }
}
}
public struct ByteImage {
public var pixels: UnsafeMutableBufferPointer<BytePixel>
public var width: Int
public var height: Int
public init?(image: UIImage) {
// CGImage로 변환이 가능해야 한다.
guard let cgImage = image.cgImage else {
return nil
}
// 주소 계산을 위해서 Float을 Int로 저장한다.
width = Int(image.size.width)
height = Int(image.size.height)
// 1 * width * height 크기의 버퍼를 생성한다.
let bytesPerRow = width * 1
let imageData = UnsafeMutablePointer<BytePixel>.allocate(capacity: width * height)
// 색상공간은 Device의 것을 따른다
let colorSpace = CGColorSpaceCreateDeviceGray()
// BGRA로 비트맵을 만든다
let bitmapInfo: UInt32 = CGBitmapInfo().rawValue
// 비트맵 생성
guard let imageContext = CGContext(data: imageData, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) else {
return nil
}
// cgImage를 imageData에 채운다.
imageContext.draw(cgImage, in: CGRect(origin: .zero, size: image.size))
// 이미지 화소의 배열 주소를 pixels에 담는다
pixels = UnsafeMutableBufferPointer<BytePixel>(start: imageData, count: width * height)
}
public init(width: Int, height: Int) {
let image = ByteImage.newUIImage(width: width, height: height)
self.init(image: image)!
}
public func clone() -> ByteImage {
let cloneImage = ByteImage(width: self.width, height: self.height)
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
cloneImage.pixels[index] = self.pixels[index]
}
}
return cloneImage
}
public func toUIImage() -> UIImage? {
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapInfo: UInt32 = CGBitmapInfo().rawValue
let bytesPerRow = width * 1
guard let imageContext = CGContext(data: pixels.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo, releaseCallback: nil, releaseInfo: nil) else {
return nil
}
guard let cgImage = imageContext.makeImage() else {
return nil
}
let image = UIImage(cgImage: cgImage)
return image
}
public func pixel(_ x : Int, _ y : Int) -> BytePixel? {
guard x >= 0 && x < width && y >= 0 && y < height else {
return nil
}
let address = y * width + x
return pixels[address]
}
public mutating func pixel(_ x : Int, _ y : Int, _ pixel: BytePixel) {
guard x >= 0 && x < width && y >= 0 && y < height else {
return
}
let address = y * width + x
pixels[address] = pixel
}
public mutating func process( functor : ((BytePixel) -> BytePixel) ) {
for y in 0..<height {
for x in 0..<width {
let index = y * width + x
pixels[index] = functor(pixels[index])
}
}
}
private static func newUIImage(width: Int, height: Int) -> UIImage {
let size = CGSize(width: CGFloat(width), height: CGFloat(height));
UIGraphicsBeginImageContextWithOptions(size, true, 0);
UIColor.black.setFill()
UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!
}
}
extension UInt8 {
public func toBytePixel() -> BytePixel {
return BytePixel(value: self)
}
}
| ff63ef9581b6f9bc6611331d9f25d9ca | 29.352113 | 235 | 0.559165 | false | false | false | false |
bradhilton/TableViewSource | refs/heads/master | TableViewSource/TableViewInterfaceSource/TableViewInterfaceSource.swift | mit | 1 | //
// TableViewInterfaceSource.swift
// TableViewSource
//
// Created by Bradley Hilton on 2/9/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
let defaultTableView = UITableView()
protocol TableViewInterfaceSource : TableViewSource, TableViewInterface {}
extension TableViewInterfaceSource {
var rowHeight: CGFloat {
get {
return _interface.rowHeight
}
set {
interface?.rowHeight = newValue
}
}
var sectionHeaderHeight: CGFloat {
get {
return _interface.sectionHeaderHeight
}
set {
interface?.sectionHeaderHeight = newValue
}
}
var sectionFooterHeight: CGFloat {
get {
return _interface.sectionFooterHeight
}
set {
interface?.sectionFooterHeight = newValue
}
}
var estimatedRowHeight: CGFloat {
get {
return _interface.estimatedRowHeight
}
set {
interface?.estimatedRowHeight = newValue
}
}
var estimatedSectionHeaderHeight: CGFloat {
get {
return _interface.estimatedSectionHeaderHeight
}
set {
interface?.estimatedSectionHeaderHeight = newValue
}
}
var estimatedSectionFooterHeight: CGFloat {
get {
return _interface.estimatedSectionFooterHeight
}
set {
interface?.estimatedSectionFooterHeight = newValue
}
}
var separatorInset: UIEdgeInsets {
get {
return _interface.separatorInset
}
set {
interface?.separatorInset = newValue
}
}
var backgroundView: UIView? {
get {
return interface?.backgroundView
}
set {
interface?.backgroundView = newValue
}
}
func reloadData() {
interface?.reloadData()
}
func reloadSectionIndexTitles() {
interface?.reloadSectionIndexTitles()
}
func numberOfSectionsForSource(source: TableViewSource) -> Int {
return _interface.numberOfSectionsForSource(source)
}
func source(source: TableViewSource, numberOfRowsInSection section: Int) -> Int {
return _interface.source(source, numberOfRowsInSection: section)
}
func source(source: TableViewSource, rectForSection section: Int) -> CGRect {
return _interface.source(source, rectForSection: section)
}
func source(source: TableViewSource, rectForHeaderInSection section: Int) -> CGRect {
return _interface.source(source, rectForHeaderInSection: section)
}
func source(source: TableViewSource, rectForFooterInSection section: Int) -> CGRect {
return _interface.source(source, rectForFooterInSection: section)
}
func source(source: TableViewSource, rectForRowAtIndexPath indexPath: NSIndexPath) -> CGRect {
return _interface.source(source, rectForRowAtIndexPath: indexPath)
}
func source(source: TableViewSource, indexPathForRowAtPoint point: CGPoint) -> NSIndexPath? {
return interface?.source(source, indexPathForRowAtPoint: point)
}
func source(source: TableViewSource, indexPathForCell cell: UITableViewCell) -> NSIndexPath? {
return interface?.source(source, indexPathForCell: cell)
}
func source(source: TableViewSource, indexPathsForRowsInRect rect: CGRect) -> [NSIndexPath]? {
return interface?.source(source, indexPathsForRowsInRect: rect)
}
func source(source: TableViewSource, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell? {
return interface?.source(source, cellForRowAtIndexPath: indexPath)
}
var visibleCells: [UITableViewCell] {
return _interface.visibleCells
}
func indexPathsForVisibleRowsForSource(source: TableViewSource) -> [NSIndexPath]? {
return interface?.indexPathsForVisibleRowsForSource(source)
}
func source(source: TableViewSource, headerViewForSection section: Int) -> UITableViewHeaderFooterView? {
return interface?.source(source, headerViewForSection: section)
}
func source(source: TableViewSource, footerViewForSection section: Int) -> UITableViewHeaderFooterView? {
return interface?.source(source, footerViewForSection: section)
}
func source(source: TableViewSource, scrollToRowAtIndexPath indexPath: NSIndexPath, atScrollPosition scrollPosition: UITableViewScrollPosition, animated: Bool) {
interface?.source(source, scrollToRowAtIndexPath: indexPath, atScrollPosition: scrollPosition, animated: animated)
}
func scrollToNearestSelectedRowAtScrollPosition(scrollPosition: UITableViewScrollPosition, animated: Bool) {
interface?.scrollToNearestSelectedRowAtScrollPosition(scrollPosition, animated: animated)
}
func beginUpdates() {
interface?.beginUpdates()
}
func endUpdates() {
interface?.endUpdates()
}
func source(source: TableViewSource, insertSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, insertSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, deleteSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, deleteSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, reloadSections sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, reloadSections: sections, withRowAnimation: animation)
}
func source(source: TableViewSource, moveSection section: Int, toSection newSection: Int) {
interface?.source(source, moveSection: section, toSection: newSection)
}
func source(source: TableViewSource, insertRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, insertRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, deleteRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, deleteRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, reloadRowsAtIndexPaths indexPaths: [NSIndexPath], withRowAnimation animation: UITableViewRowAnimation) {
interface?.source(source, reloadRowsAtIndexPaths: indexPaths, withRowAnimation: animation)
}
func source(source: TableViewSource, moveRowAtIndexPath indexPath: NSIndexPath, toIndexPath newIndexPath: NSIndexPath) {
interface?.source(source, moveRowAtIndexPath: indexPath, toIndexPath: newIndexPath)
}
var editing: Bool {
get {
return _interface.editing
}
set {
interface?.editing = newValue
}
}
func setEditing(editing: Bool, animated: Bool) {
interface?.setEditing(editing, animated: animated)
}
var allowsSelection: Bool {
get {
return _interface.allowsSelection
}
set {
interface?.allowsSelection = newValue
}
}
var allowsSelectionDuringEditing: Bool {
get {
return _interface.allowsSelectionDuringEditing
}
set {
interface?.allowsSelectionDuringEditing = newValue
}
}
var allowsMultipleSelection: Bool {
get {
return _interface.allowsMultipleSelection
}
set {
interface?.allowsMultipleSelection = newValue
}
}
var allowsMultipleSelectionDuringEditing: Bool {
get {
return _interface.allowsMultipleSelectionDuringEditing
}
set {
interface?.allowsMultipleSelectionDuringEditing = newValue
}
}
func indexPathForSelectedRowForSource(source: TableViewSource) -> NSIndexPath? {
return interface?.indexPathForSelectedRowForSource(source)
}
func indexPathsForSelectedRowsForSource(source: TableViewSource) -> [NSIndexPath]? {
return interface?.indexPathsForSelectedRowsForSource(source)
}
func source(source: TableViewSource, selectRowAtIndexPath indexPath: NSIndexPath?, animated: Bool, scrollPosition: UITableViewScrollPosition) {
interface?.source(source, selectRowAtIndexPath: indexPath, animated: animated, scrollPosition: scrollPosition)
}
func source(source: TableViewSource, deselectRowAtIndexPath indexPath: NSIndexPath, animated: Bool) {
interface?.source(source, deselectRowAtIndexPath: indexPath, animated: animated)
}
var sectionIndexMinimumDisplayRowCount: Int {
get {
return _interface.sectionIndexMinimumDisplayRowCount
}
set {
interface?.sectionIndexMinimumDisplayRowCount = newValue
}
}
var sectionIndexColor: UIColor? {
get {
return interface?.sectionIndexColor
}
set {
interface?.sectionIndexColor = newValue
}
}
var sectionIndexBackgroundColor: UIColor? {
get {
return interface?.sectionIndexBackgroundColor
}
set {
interface?.sectionIndexBackgroundColor = newValue
}
}
var sectionIndexTrackingBackgroundColor: UIColor? {
get {
return interface?.sectionIndexTrackingBackgroundColor
}
set {
interface?.sectionIndexTrackingBackgroundColor = newValue
}
}
var separatorStyle: UITableViewCellSeparatorStyle {
get {
return _interface.separatorStyle
}
set {
interface?.separatorStyle = newValue
}
}
var separatorColor: UIColor? {
get {
return interface?.separatorColor
}
set {
interface?.separatorColor = newValue
}
}
var separatorEffect: UIVisualEffect? {
get {
return interface?.separatorEffect
}
set {
interface?.separatorEffect = newValue
}
}
var tableHeaderView: UIView? {
get {
return interface?.tableHeaderView
}
set {
interface?.tableHeaderView = newValue
}
}
var tableFooterView: UIView? {
get {
return interface?.tableFooterView
}
set {
interface?.tableFooterView = newValue
}
}
func dequeueReusableCellWithIdentifier(identifier: String) -> UITableViewCell? {
return interface?.dequeueReusableCellWithIdentifier(identifier)
}
func source(source: TableViewSource, dequeueReusableCellWithIdentifier identifier: String, forIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return _interface.source(source, dequeueReusableCellWithIdentifier: identifier, forIndexPath: indexPath)
}
func dequeueReusableHeaderFooterViewWithIdentifier(identifier: String) -> UITableViewHeaderFooterView? {
return interface?.dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
func registerNib(nib: UINib?, forCellReuseIdentifier identifier: String) {
interface?.registerNib(nib, forCellReuseIdentifier: identifier)
}
func registerClass(cellClass: AnyClass?, forCellReuseIdentifier identifier: String) {
interface?.registerClass(cellClass, forCellReuseIdentifier: identifier)
}
func registerNib(nib: UINib?, forHeaderFooterViewReuseIdentifier identifier: String) {
interface?.registerNib(nib, forHeaderFooterViewReuseIdentifier: identifier)
}
func registerClass(aClass: AnyClass?, forHeaderFooterViewReuseIdentifier identifier: String) {
interface?.registerClass(aClass, forHeaderFooterViewReuseIdentifier: identifier)
}
}
| 59c544d20bf09b94850bedbbee37eace | 31.831099 | 165 | 0.662339 | false | false | false | false |
joseria/JADynamicTypeExampleInSwift | refs/heads/master | JADynamicTypeExample/ViewController.swift | mit | 1 | //
// ViewController.swift
// JADynamicTypeExample
//
// Created by Alvarez, Jose (MTV) on 10/21/14.
// Copyright (c) 2014 Jose Alvarez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class ViewController: UIViewController {
// Labels
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var caption1Label: UILabel!
@IBOutlet weak var caption2Label: UILabel!
@IBOutlet weak var footnoteLabel: UILabel!
@IBOutlet weak var headlineLabel: UILabel!
@IBOutlet weak var subheadlineLabel: UILabel!
// Buttons
@IBOutlet weak var bodyButton: UIButton!
@IBOutlet weak var caption1Button: UIButton!
@IBOutlet weak var caption2Button: UIButton!
@IBOutlet weak var footnoteButton: UIButton!
@IBOutlet weak var headlineButton: UIButton!
@IBOutlet weak var subheadlineButton: UIButton!
// Container view labels
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var bodyInView: UILabel!
@IBOutlet weak var caption1InView: UILabel!
@IBOutlet weak var caption2InView: UILabel!
@IBOutlet weak var footnoteInView: UILabel!
@IBOutlet weak var headlineInView: UILabel!
@IBOutlet weak var subheadlineInView: UITextView!
// Switchers
@IBOutlet weak var italicsLabel: UILabel!
@IBOutlet weak var boldLabel: UILabel!
@IBOutlet weak var italicsSwitch: UISwitch!
@IBOutlet weak var boldSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
containerView.layer.borderColor = UIColor.grayColor().CGColor
containerView.layer.borderWidth = 1.0
let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(UIFontTextStyleBody)
let italicsFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitItalic)
italicsLabel.font = UIFont(descriptor:italicsFontDescriptor, size:0)
let boldFontDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
boldLabel.font = UIFont(descriptor:boldFontDescriptor, size:0)
NSNotificationCenter.defaultCenter().addObserverForName(UIContentSizeCategoryDidChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (note:NSNotification) -> Void in
self.handleContentSizeCategoryDidChangeNotification()
}
}
func handleContentSizeCategoryDidChangeNotification () {
evaluateFonts()
}
func evaluateFonts () {
// Update labels
bodyLabel.font = evaluateFont(UIFontTextStyleBody)
caption1Label.font = evaluateFont(UIFontTextStyleCaption1)
caption2Label.font = evaluateFont(UIFontTextStyleCaption2)
footnoteLabel.font = evaluateFont(UIFontTextStyleFootnote)
headlineLabel.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineLabel.font = evaluateFont(UIFontTextStyleSubheadline)
// Update buttons
bodyButton.titleLabel?.font = evaluateFont(UIFontTextStyleBody)
caption1Button.titleLabel?.font = evaluateFont(UIFontTextStyleCaption1)
caption2Button.titleLabel?.font = evaluateFont(UIFontTextStyleCaption2)
footnoteButton.titleLabel?.font = evaluateFont(UIFontTextStyleFootnote)
headlineButton.titleLabel?.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineButton.titleLabel?.font = evaluateFont(UIFontTextStyleSubheadline)
// Update container view labels
bodyInView.font = evaluateFont(UIFontTextStyleBody)
caption1InView.font = evaluateFont(UIFontTextStyleCaption1)
caption2InView.font = evaluateFont(UIFontTextStyleCaption2)
footnoteInView.font = evaluateFont(UIFontTextStyleFootnote)
headlineInView.font = evaluateFont(UIFontTextStyleHeadline)
subheadlineInView.font = evaluateFont(UIFontTextStyleSubheadline)
}
// Helper function that handles displaying a font w/ italics and bold traits.
func evaluateFont(fontStyle:String)->UIFont {
let fontDescriptor = UIFontDescriptor.preferredFontDescriptorWithTextStyle(fontStyle)
var traitsDescriptor:UIFontDescriptor
if (italicsSwitch.on) {
traitsDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitItalic)
} else if (boldSwitch.on) {
traitsDescriptor = fontDescriptor.fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
} else {
traitsDescriptor = fontDescriptor
}
return UIFont(descriptor: traitsDescriptor, size: 0)
}
@IBAction func updateItalics(sender: UISwitch) {
// Reset bold since multiple trait support does not always work
boldSwitch.on = false
evaluateFonts()
}
@IBAction func updateBolds(sender: UISwitch) {
// Reset italics since multiple trait support does not always work
italicsSwitch.on = false
evaluateFonts()
}
}
| 1792eb143876968dc1ef8ec901fd48a2 | 43.536232 | 192 | 0.727302 | false | false | false | false |
RevenueCat/purchases-ios | refs/heads/main | Tests/UnitTests/TestHelpers/OSVersionEquivalent.swift | mit | 1 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// OSVersion.swift
//
// Created by Nacho Soto on 4/13/22.
import Foundation
import UIKit
/// The equivalent version for the current device running tests.
/// Examples:
/// - `tvOS 15.1` maps to `.iOS15`
/// - `iOS 14.3` maps to `.iOS14`
/// - `macCatalyst 15.2` maps to `.iOS15`
enum OSVersionEquivalent: Int {
case iOS12 = 12
case iOS13 = 13
case iOS14 = 14
case iOS15 = 15
case iOS16 = 16
}
extension OSVersionEquivalent {
static let current: Self = {
#if os(macOS)
// Not currently supported
// Must convert e.g.: macOS 10.15 to iOS 13
fatalError(Error.unknownOS().localizedDescription)
#else
// Note: this is either iOS/tvOS/macCatalyst
// They all share equivalent versions
let majorVersion = ProcessInfo().operatingSystemVersion.majorVersion
guard let equivalent = Self(rawValue: majorVersion) else {
fatalError(Error.unknownOS().localizedDescription)
}
return equivalent
#endif
}()
}
private extension OSVersionEquivalent {
private enum Error: Swift.Error {
case unknownOS(systemName: String, version: String)
static func unknownOS() -> Self {
let device = UIDevice.current
return .unknownOS(systemName: device.systemName, version: device.systemVersion)
}
}
}
| 52833467dd4d651aee9015c81a66bc5c | 23.101449 | 91 | 0.637402 | false | false | false | false |
OpenGenus/cosmos | refs/heads/master | code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.swift | gpl-3.0 | 5 | // Part of Cosmos by OpenGenus Foundation
public enum BinarySearchTree<T: Comparable> {
case empty
case leaf(T)
indirect case node(BinarySearchTree, T, BinarySearchTree)
public var count: Int {
switch self {
case .empty: return 0
case .leaf: return 1
case let .node(left, _, right): return left.count + 1 + right.count
}
}
public var height: Int {
switch self {
case .empty: return 0
case .leaf: return 1
case let .node(left, _, right): return 1 + max(left.height, right.height)
}
}
public func insert(newValue: T) -> BinarySearchTree {
switch self {
case .empty:
return .leaf(newValue)
case .leaf(let value):
if newValue < value {
return .node(.leaf(newValue), value, .empty)
} else {
return .node(.empty, value, .leaf(newValue))
}
case .node(let left, let value, let right):
if newValue < value {
return .node(left.insert(newValue), value, right)
} else {
return .node(left, value, right.insert(newValue))
}
}
}
public func search(x: T) -> BinarySearchTree? {
switch self {
case .empty:
return nil
case .leaf(let y):
return (x == y) ? self : nil
case let .node(left, y, right):
if x < y {
return left.search(x)
} else if y < x {
return right.search(x)
} else {
return self
}
}
}
public func contains(x: T) -> Bool {
return search(x) != nil
}
public func minimum() -> BinarySearchTree {
var node = self
var prev = node
while case let .node(next, _, _) = node {
prev = node
node = next
}
if case .leaf = node {
return node
}
return prev
}
public func maximum() -> BinarySearchTree {
var node = self
var prev = node
while case let .node(_, _, next) = node {
prev = node
node = next
}
if case .leaf = node {
return node
}
return prev
}
}
extension BinarySearchTree: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .empty: return "."
case .leaf(let value): return "\(value)"
case .node(let left, let value, let right):
return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))"
}
}
}
| 75a4668f7b9789c4e8b876c1ee12960b | 22.019802 | 82 | 0.577204 | false | false | false | false |
prebid/prebid-mobile-ios | refs/heads/master | InternalTestApp/PrebidMobileDemoRendering/ViewControllers/Adapters/Prebid/GAM/UnifiedNativeAdView.swift | apache-2.0 | 1 | /* Copyright 2018-2021 Prebid.org, 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 GoogleMobileAds
import PrebidMobile
class UnifiedNativeAdView: GADNativeAdView {
/// The height constraint applied to the ad view, where necessary.
private var heightConstraint: NSLayoutConstraint?
func renderUnifiedNativeAd(_ unifiedNativeAd: GADNativeAd) {
// Deactivate the height constraint that was set when the previous video ad loaded.
heightConstraint?.isActive = false
// Populate the native ad view with the native ad assets.
// The headline and mediaContent are guaranteed to be present in every native ad.
(headlineView as? UILabel)?.text = unifiedNativeAd.headline
mediaView?.mediaContent = unifiedNativeAd.mediaContent
// // Some native ads will include a video asset, while others do not. Apps can use the
// // GADVideoController's hasVideoContent property to determine if one is present, and adjust their
// // UI accordingly.
// let mediaContent = unifiedNativeAd.mediaContent
// if mediaContent.hasVideoContent {
// // By acting as the delegate to the GADVideoController, this ViewController receives messages
// // about events in the video lifecycle.
// mediaContent.videoController.delegate = self
// videoStatusLabel.text = "Ad contains a video asset."
// } else {
// videoStatusLabel.text = "Ad does not contain a video."
// }
// This app uses a fixed width for the GADMediaView and changes its height to match the aspect
// ratio of the media it displays.
if let mediaView = mediaView, unifiedNativeAd.mediaContent.aspectRatio > 0 {
heightConstraint = NSLayoutConstraint(
item: mediaView,
attribute: .height,
relatedBy: .equal,
toItem: mediaView,
attribute: .width,
multiplier: CGFloat(1 / unifiedNativeAd.mediaContent.aspectRatio),
constant: 0)
heightConstraint?.isActive = true
}
// These assets are not guaranteed to be present. Check that they are before
// showing or hiding them.
(bodyView as? UILabel)?.text = unifiedNativeAd.body
bodyView?.isHidden = unifiedNativeAd.body == nil
(callToActionView as? UIButton)?.setTitle(unifiedNativeAd.callToAction, for: .normal)
callToActionView?.isHidden = unifiedNativeAd.callToAction == nil
(iconView as? UIImageView)?.image = unifiedNativeAd.icon?.image
iconView?.isHidden = unifiedNativeAd.icon == nil
(starRatingView as? UIImageView)?.image = imageOfStars(from: unifiedNativeAd.starRating)
starRatingView?.isHidden = unifiedNativeAd.starRating == nil
(storeView as? UILabel)?.text = unifiedNativeAd.store
storeView?.isHidden = unifiedNativeAd.store == nil
(priceView as? UILabel)?.text = unifiedNativeAd.price
priceView?.isHidden = unifiedNativeAd.price == nil
(advertiserView as? UILabel)?.text = unifiedNativeAd.advertiser
advertiserView?.isHidden = unifiedNativeAd.advertiser == nil
// In order for the SDK to process touch events properly, user interaction should be disabled.
callToActionView?.isUserInteractionEnabled = false
// Associate the native ad view with the native ad object. This is
// required to make the ad clickable.
// Note: this should always be done after populating the ad views.
nativeAd = unifiedNativeAd
}
/// Returns a `UIImage` representing the number of stars from the given star rating; returns `nil`
/// if the star rating is less than 3.5 stars.
private func imageOfStars(from starRating: NSDecimalNumber?) -> UIImage? {
guard let rating = starRating?.doubleValue else {
return nil
}
if rating >= 5 {
return UIImage(named: "stars_5")
} else if rating >= 4.5 {
return UIImage(named: "stars_4_5")
} else if rating >= 4 {
return UIImage(named: "stars_4")
} else if rating >= 3.5 {
return UIImage(named: "stars_3_5")
} else {
return nil
}
}
}
| 6f49f04dc56e6cd0b34f30243ffc43ab | 43.681818 | 107 | 0.650865 | 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.