repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
UncleJoke/Spiral | Spiral/HelpMethods.swift | 1 | 1350 | //
// HelpFile.swift
// Spiral
//
// Created by 杨萧玉 on 15/6/9.
// Copyright (c) 2015年 杨萧玉. All rights reserved.
//
import SpriteKit
func * (left:CGFloat, right:Double) -> Double {
return Double(left) * right
}
func * (left:Int, right:CGFloat) -> CGFloat {
return CGFloat(left) * right
}
func * (left:CGSize, right:CGFloat) -> CGSize {
return CGSize(width: left.width * right, height: left.height * right)
}
private func imageWithView(view:UIView)->UIImage{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
view.drawViewHierarchyInRect(view.bounds,afterScreenUpdates:true)
let img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return img;
}
func imageFromNode(node:SKNode)->UIImage{
if let tex = ((UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController?.view as! SKView).textureFromNode(node) {
let view = SKView(frame: CGRectMake(0, 0, tex.size().width, tex.size().height))
let scene = SKScene(size: tex.size())
let sprite = SKSpriteNode(texture: tex)
sprite.position = CGPointMake( CGRectGetMidX(view.frame), CGRectGetMidY(view.frame) );
scene.addChild(sprite)
view.presentScene(scene)
return imageWithView(view)
}
return UIImage()
} | mit | c2e19c3bbd265b63a7e354ecc2dc5b59 | 30.093023 | 147 | 0.693114 | 3.952663 | false | false | false | false |
lrosa007/ghoul | gool/GPRSettings.swift | 2 | 946 | //
// GPRSettings.swift
// gool
//
// Holds information about measurement and analysis settings for a GPR session
import Foundation
class GPRSettings : NSObject {
var baseRdp : Double // Estimated relative dielectric permitivitty of soil measurements were taken in
var minTargetDepth, maxTargetDepth : Double // During analysis, only consider targets within this range (meters)
var 𝚫T : Double = 1e-10 // time elapsed between each consecutive sample, in seconds
init(rdp: Double, minDepth:Double = 0.0, maxDepth:Double = 2.0) {
baseRdp = rdp
minTargetDepth = minDepth
maxTargetDepth = maxDepth
}
convenience init(soilType: DSP.SoilType, minDepth:Double = 0.0, maxDepth:Double = 2.0) {
self.init(rdp: soilType.rawValue, minDepth: minDepth, maxDepth: maxDepth)
}
convenience override init() {
self.init(rdp: DSP.SoilType.Sandy_10_water.rawValue)
}
} | gpl-2.0 | 6acba52e0ebcd0e20a34487c531d1126 | 33.962963 | 116 | 0.69141 | 3.817814 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/PresentationLayer/Pin/Module/PinModule.swift | 1 | 751 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import UIKit
class PinModule {
class func create(app: Application, state: PinState) -> PinModuleInput {
let router = PinRouter()
let presenter = PinPresenter()
let interactor = PinInteractor()
let viewController = R.storyboard.pin.pinViewController()!
interactor.output = presenter
viewController.output = presenter
presenter.view = viewController
presenter.router = router
presenter.interactor = interactor
router.app = app
// MARK: Injection
let pinService = PinServiceFactory.create(with: state, delegate: presenter)
interactor.pinService = pinService
return presenter
}
}
| gpl-3.0 | 54879d983a628ca5fab4e0231e3bc880 | 23.193548 | 79 | 0.697333 | 4.807692 | false | false | false | false |
IcyButterfly/ListDataProvider | ListDataProvider/ListDataProvider/ImageTextArrowTableViewCell.swift | 1 | 1553 | //
// ImageTextArrowTableViewCell.swift
// ListDataProvider
//
// Created by ET|冰琳 on 2017/3/15.
// Copyright © 2017年 Ice Butterfly. All rights reserved.
//
import UIKit
class ImageTextArrowTableViewCell: LDPTableViewCell {
@IBInspectable var imageLeft: CGFloat = LDPTableViewCell.defaultLeftEdge
@IBInspectable var arrowRight: CGFloat = 15
@IBInspectable var textLeft: CGFloat = 10
var arrow = UIImageView(image: UIImage(named: "ListDataProvider.bundle/list_right_arrow"))
override func layoutSubviews() {
super.layoutSubviews()
var left = imageLeft
imageView?.sizeToFit()
if var frame = imageView?.frame, frame.width > 0.01{
frame.origin.x = left
imageView?.frame = frame
left += frame.width + self.textLeft
}else if self.textLeft < self.imageLeft{
left = self.imageLeft
}else {
left = self.textLeft
}
if var frame = textLabel?.frame {
frame.origin.x = left
textLabel?.frame = frame
}
arrow.sizeToFit()
var arrowframe = arrow.frame
arrowframe.origin.x = frame.width - arrowframe.width - arrowRight
arrowframe.origin.y = (frame.height - arrowframe.height)/2.0
arrow.frame = arrowframe
}
override func setup() {
self.contentView.addSubview(self.arrow)
self.imageView?.image = UIImage(named: "ListDataProvider.bundle/list_right_arrow")
}
}
| mit | d8bbd7dd4e18b085312879b40927fd2d | 28.730769 | 94 | 0.615136 | 4.417143 | false | false | false | false |
TongjiUAppleClub/WeCitizens | WeCitizens/ProposeTableViewController.swift | 1 | 13712 | //
// ProposeTableViewController.swift
// WeCitizens
//
// Created by Harold LIU on 2/11/16.
// Copyright © 2016 Tongji Apple Club. All rights reserved.
//
import UIKit
import MJRefresh
import CoreLocation
import MBProgressHUD
class ProposeTableViewController: UITableViewController,CLLocationManagerDelegate, NewLocationDelegate{
let tmpAvatar = UIImage(named: "avatar")
let testImages = [UIImage(named: "logo_1")!,UIImage(named: "logo_1")!]
let locationManager = CLLocationManager()
let locationLabel = UILabel(frame: (CGRectMake(0, 0, 110, 44)))
var currentLocal:String = "---- " {
didSet{
locationLabel.text = currentLocal
}
}
var voiceList = [Voice]()
let voiceModel = VoiceModel()
let userModel = UserModel()
let number = 10
var queryTimes = 0
//MARK:- Life cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
self.clearsSelectionOnViewWillAppear = true
initLocation()
tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
print("RefreshingHeader")
//上拉刷新,在获取数据后清空旧数据,并做缓存
self.queryTimes = 0
self.getVoiceFromRemote()
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.mj_header.endRefreshing()
}
})
tableView.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { () -> Void in
print("RefreshingFooter")
//1.下拉加载数据,将新数据append到数组中,不缓存
self.voiceModel.getVoice(self.number, queryTimes: self.queryTimes, cityName: "shanghai", needStore: false, resultHandler: { (results, error) -> Void in
if let _ = error {
//有错误,给用户提示
print("get voice fail with error:\(error!.userInfo)")
self.processError(error!.code)
} else {
if let voices = results {
voices.forEach({ (voice) -> () in
self.voiceList.append(voice)
})
self.tableView.reloadData()
self.queryTimes += 1
} else {
print("no data in refreshing footer")
}
}
})
dispatch_async(dispatch_get_main_queue()) { () -> Void in
self.tableView.mj_footer.endRefreshing()
}
})
tableView.mj_header.automaticallyChangeAlpha = true
//1.读缓存,如果有数据的话在tableView中填数据
self.voiceModel.getVoice("shanghai") { (results, error) -> Void in
if let _ = error {
//有错误,给用户提示
print("get voice from local fail with error:\(error!.userInfo)")
self.processError(error!.code)
} else {
if let voices = results {
self.voiceList = voices
self.tableView.reloadData()
} else {
//没取到数据
print("no data from local")
}
}
}
//2.向后台请求数据,返回数据时做缓存
getVoiceFromRemote()
}
func getVoiceFromRemote() {
self.voiceModel.getVoice(self.number, queryTimes: self.queryTimes, cityName: "shanghai", needStore: true, resultHandler: { (results, error) -> Void in
if let _ = error {
//有错误,给用户提示
print("get voice fail with error:\(error!.userInfo)")
self.processError(error!.code)
} else {
if let voices = results {
self.voiceList = voices
self.tableView.reloadData()
self.queryTimes += 1
} else {
//没取到数据
print("no data in refreshing header")
}
}
})
}
func processError(errorCode:Int) {
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = .Text
let errorMessage:(label:String, detail:String) = convertPFNSErrorToMssage(errorCode)
hud.labelText = errorMessage.label
hud.detailsLabelText = errorMessage.detail
hud.hide(true, afterDelay: 2.0)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
configureUI()
}
func setNewLocation(newLocation: String) {
print("locaiton:\(newLocation)")
}
// MARK:- Table view data source && delegate
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return voiceList.count
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 4
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("ShowDetail", sender: indexPath)
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: (CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 7)) )
view.backgroundColor = UIColor.clearColor()
return view
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CommentCell", forIndexPath: indexPath) as! CommentTableViewCell
dataBinder(cell, voice: self.voiceList[indexPath.section])
let images = self.voiceList[indexPath.section].images
imagesBinder(cell.ImgesContainer, images: images )
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "ShowDetail") {
let controller = segue.destinationViewController as! VoiceDetailTableViewController
let row = ( sender as! NSIndexPath ).section
controller.title = self.voiceList[row].title
controller.voice = self.voiceList[row]
} else if (segue.identifier == "PushVoice") {
let controller = segue.destinationViewController as! AddVoiceTableViewController
controller.currentLocation = self.currentLocal
} else if (segue.identifier == "ShowMap") {
let controller = segue.destinationViewController as! MapViewController
controller.voiceList = self.voiceList
}
}
//MARK:- UIConfigure
func configureUI() {
tableView.backgroundColor = UIColor(red: 216/255, green: 216/255, blue: 216/255, alpha: 1.0)
let titleView = UIView(frame: (CGRectMake(0, 0, 150, 44)))
let switchButton = UIButton(frame: CGRectMake(105, 0, 30, 44))
locationLabel.text = currentLocal
locationLabel.textColor = UIColor.lxd_MainBlueColor()
locationLabel.textAlignment = NSTextAlignment.Right
switchButton.setImage(UIImage(named: "switch"), forState: .Normal)
switchButton.addTarget(self, action: #selector(ProposeTableViewController.ChangeLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)
//如何获取到controller?
titleView.addSubview(locationLabel)
titleView.addSubview(switchButton)
self.navigationItem.titleView = titleView
}
func ChangeLocation(sender:UIButton) {
let controller = storyboard?.instantiateViewControllerWithIdentifier("LocationTable")
self.navigationController?.pushViewController(controller!, animated: true)
}
//MARK:- Location Init
func initLocation() {
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.distanceFilter = 1000
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let currentLocation = locations.last {
let long = currentLocation.coordinate.longitude
let lat = currentLocation.coordinate.latitude
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: lat, longitude:long)
geoCoder.reverseGeocodeLocation(location) { (placemark, error) -> Void in
if let validPlacemark = placemark?[0]{
let placemark = validPlacemark as CLPlacemark;
if let city = placemark.addressDictionary!["City"] as? NSString {
self.currentLocal = city as String
print("location:\(self.currentLocal)")
}
}
}
}
else
{
print("No location")
}
}
func dataBinder(cell:CommentTableViewCell,voice:Voice) {
cell.VoiceTitle.text = voice.title
if let image = voice.user?.avatar {
cell.Avatar.image = image
} else {
cell.Avatar.image = tmpAvatar
}
cell.Reputation.text = "\(voice.user!.resume)"
cell.CommentUser.text = "\(voice.user!.userName)"
cell.UpdateTime.text = voice.dateStr
cell.Abstract.text = voice.abstract
cell.Classify.text = voice.classify
}
func imagesBinder(containter:UIView,images:[UIImage]) {
let Xoffset = CGFloat(6)
let Yoffset = CGFloat(4)
for view in containter.subviews {
if view.tag == 1
{
view.removeFromSuperview()
}
}
switch images.count {
case 1:
let imgView = UIImageView(image: images.first)
imgView.frame = containter.frame
imgView.frame.origin = CGRectZero.origin
imgView.frame.size.width = tableView.frame.width - 40
containter.addSubview(imgView)
break;
case 2:
let img1 = UIImageView(image: images[1])
img1.frame = containter.frame
img1.frame.origin = CGRectZero.origin
img1.frame.size.width = tableView.frame.width - 30
img1.frame.size.width /= 2
containter.addSubview(img1)
let img2 = UIImageView(image: images[0])
img2.frame = img1.frame
img2.frame.origin.x += (img2.frame.size.width + Xoffset)
containter.addSubview(img2)
break;
case 3:
let img1 = UIImageView(image: images[0])
img1.frame = containter.frame
img1.frame.size.width = tableView.frame.width - 40
img1.frame.origin = CGRectZero.origin
img1.frame.size.width /= 2
img1.frame.size.height += Yoffset
containter.addSubview(img1)
let img2 = UIImageView(image: images[1])
img2.frame = img1.frame
img2.frame.origin.x += (img2.frame.size.width + Xoffset)
img2.frame.size.height /= 2
containter.addSubview(img2)
let img3 = UIImageView(image: images[2])
img3.frame = img2.frame
img3.frame.origin.y += img3.frame.size.height + Yoffset
containter.addSubview(img3)
break;
case 4:
let img1 = UIImageView(image: images[0])
img1.frame = containter.frame
img1.frame.size.width = tableView.frame.width - 40
img1.frame.origin = CGRectZero.origin
img1.frame.size.width /= 2
img1.frame.size.height /= 2
containter.addSubview(img1)
let img2 = UIImageView(image: images[1])
img2.frame = img1.frame
img2.frame.origin.x += (img2.frame.size.width + Xoffset)
containter.addSubview(img2)
let img3 = UIImageView(image: images[2])
img3.frame = img2.frame
img3.frame.origin.y += img3.frame.size.height + Yoffset
containter.addSubview(img3)
let img4 = UIImageView(image: images[3])
img4.frame = img3.frame
img4.frame.origin.x = img1.frame.origin.x
containter.addSubview(img4)
break;
default:
containter.removeFromSuperview()
break;
}
for view in containter.subviews
{
view.tag = 1
view.layer.masksToBounds = false
view.layer.cornerRadius = 5
view.clipsToBounds = true
}
}
}
| mit | 14bd3122ede198fb8727635b1537270d | 37.167139 | 163 | 0.56654 | 5.093762 | false | false | false | false |
xwu/swift | test/Inputs/polymorphic_builtins.swift | 20 | 11064 |
import Swift
// =============================================================================
// A `Never`-like type for default implementations and associated types
@frozen
public enum _SIMDNever {}
// A `Never`-like type for default implementations that provides a SIMDScalar
// based T for use in where requirements.
//
// This is necessary for the following code to properly compile:
//
// extension _SIMDGenericNever: _SIMDStorageWithOps {
// public typealias Scalar = T
// public typealias _InnerStorage = _SIMDGenericNever<T>
// ...
// }
//
// Given that we want _InnerStorage.Scalar to equal specific Scalar values to
// appease the type checker. If one does not need this functionality, just pass
// _SIMDNever as the generic parameter since it is a SIMDScalar.
@frozen
public enum _SIMDGenericNever<T : SIMDScalar> {}
// =============================================================================
public protocol SIMDStorage {
associatedtype Scalar: SIMDScalar
associatedtype _InnerStorage: _SIMDStorageWithOps = _SIMDGenericNever<_SIMDNever> where _InnerStorage.Scalar == Self.Scalar
static var _hasVectorRepresentation: Bool { get }
static var scalarCount: Int { get }
var _innerStorage: _InnerStorage { get set }
var scalarCount: Int { get }
init()
init(_storage: _InnerStorage)
subscript(index: Int) -> Scalar { get set }
}
extension SIMDStorage {
@_transparent
public static var _hasVectorRepresentation: Bool {
return false
}
public var _innerStorage: _InnerStorage {
@inline(never)
get {
// Will never be called unless `_hasVectorRepresentation == true`,
// in which case this implementation would be overriden in stdlib
fatalError("""
Error! Called default SIMDStorage._vector impl?! A SIMDStorage class
overrides _hasVectorRepresentation to return true, but did not provide
an implementation for this method as well!
""")
}
set {
fatalError("""
Error! Called default SIMDStorage._vector impl?! A SIMDStorage class
overrides _hasVectorRepresentation to return true, but did not provide
an implementation for this method as well!
""")
}
}
// Previously, the static `scalarCount` was defined in terms of this
// property; also I think this property should be deprecated altogether
public var scalarCount: Int {
@_transparent
get {
return Self.scalarCount
}
}
@inline(never)
public init(_storage: _InnerStorage) {
// Will never be called unless `_hasVectorRepresentation == true`, in
// which case this implementation would be overriden in stdlib
fatalError("""
Error! Called default SIMDStorage.init(_vector) impl?! A SIMDStorage class
overrides _hasVectorRepresentation to return true, but did not provide an
implementation for this method as well!
""")
}
}
public protocol _SIMDStorageWithOps : SIMDStorage {
static func add(_ lhs: Self, _ rhs: Self) -> Self
static func mul(_ lhs: Self, _ rhs: Self) -> Self
}
extension _SIMDStorageWithOps {
public static func add(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("In default SIMDStorageWithOps impl. Only here for never types?!")
}
public static func mul(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("In default SIMDStorageWithOps impl. Only here for never types?!")
}
}
extension _SIMDNever: _SIMDStorageWithOps {
public typealias Scalar = _SIMDNever
public typealias _InnerStorage = _SIMDNever
public static func add(_ lhs: Self, _ rhs: Self) -> Self {}
public static func mul(_ lhs: Self, _ rhs: Self) -> Self {}
public static var scalarCount: Int {
@inline(never)
get {
switch Self() {}
}
}
public var _innerStorage: _InnerStorage {
get {
switch Self() {}
}
set {
}
}
public subscript(index: Int) -> Scalar {
@inline(never)
get {
switch self {}
}
set {}
}
@inline(never)
public init() {
fatalError("\(Self.self) cannot be instantiated")
}
}
extension _SIMDGenericNever: _SIMDStorageWithOps {
public typealias Scalar = T
public typealias _InnerStorage = _SIMDGenericNever<T>
public static func add(_ lhs: Self, _ rhs: Self) -> Self {}
public static var scalarCount: Int {
@inline(never)
get {
switch Self() {}
}
}
public subscript(index: Int) -> Scalar {
@inline(never)
get {
switch self {}
}
set {}
}
@inline(never)
public init() {
fatalError("\(Self.self) cannot be instantiated")
}
public var _innerStorage: _InnerStorage {
get {
switch Self() {}
}
set {
}
}
}
// =============================================================================
public protocol SIMDScalar {
// ...
associatedtype SIMD4Storage: _SIMDStorageWithOps where SIMD4Storage.Scalar == Self
// ...
}
extension _SIMDNever: SIMDScalar {
// ...
public typealias SIMD4Storage = _SIMDNever
// ...
}
// =============================================================================
public protocol SIMD: SIMDStorage {
}
extension SIMD {
public var indices: Range<Int> {
@_transparent get {
return 0 ..< scalarCount
}
}
// ...
@_transparent
public init(_storage: _InnerStorage) {
self.init()
_innerStorage = _storage
}
}
extension SIMD where Scalar: FixedWidthInteger {
@_transparent
public static func &+(lhs: Self, rhs: Self) -> Self {
// In this case, we guard using _isConcrete to ensure that if we call this
// through a vtable, we go down the slow fallback path instead of hitting
// the assert inserted by IRgen when it lowers the unspecialized polymorphic
// builtin.
if _fastPath(Self._hasVectorRepresentation && _isConcrete(Self.self)) {
// Delegate to concrete operations on `Self._InnerStorage`
let lVec = lhs._innerStorage
let rVec = rhs._innerStorage
let result = Self._InnerStorage.add(lVec, rVec)
return Self(_storage: result)
}
// Slow fallback
var result = Self()
for i in result.indices { result[i] = lhs[i] &+ rhs[i] }
return result
}
@_transparent
public static func &*(lhs: Self, rhs: Self) -> Self {
// We'll almost always be calling this on stdlib SIMD types, so this
// branch is very likely in a generic context.
//
// This is purposely unguarded so in our test cases we can validate that
// without the guard an implementation like this asserts.
if _fastPath(Self._hasVectorRepresentation) {
// Delegate to concrete operations on `Self._Vector`
let lVec = lhs._innerStorage
let rVec = rhs._innerStorage
let result = Self._InnerStorage.mul(lVec, rVec)
return Self(_storage: result)
}
// Slow fallback
var result = Self()
for i in result.indices { result[i] = lhs[i] &* rhs[i] }
return result
}
}
// =============================================================================
@frozen
public struct SIMD4<Scalar: SIMDScalar>: SIMD {
public typealias _InnerStorage = Scalar.SIMD4Storage
public var _innerStorage: _InnerStorage {
@_transparent
get { return _storage }
@_transparent
set { _storage = newValue }
}
public static var _hasVectorRepresentation: Bool {
@_transparent get {
return Scalar.SIMD4Storage._hasVectorRepresentation
}
}
public static var scalarCount: Int {
@_transparent get {
return Scalar.SIMD4Storage.scalarCount
}
}
public var _storage: Scalar.SIMD4Storage
public subscript(index: Int) -> Scalar {
@_transparent get {
return self._storage[index]
}
@_transparent set {
self._storage[index] = newValue
}
}
@_transparent
public init() {
_storage = Scalar.SIMD4Storage()
}
public init(_ inputValues: [Scalar]) {
self.init()
assert(inputValues.count == Self.scalarCount)
for i in 0..<inputValues.count {
self[i] = inputValues[i]
}
}
// ...
public var asArray: [Scalar] {
return (0..<Self.scalarCount).map { self[$0] }
}
}
public protocol _SIMDVectorStorage : _SIMDStorageWithOps {
// Must be a builtin type eventually.
associatedtype _Vector
var _vector: _Vector { get }
init(_vector: _Vector)
static func add(_ lhs: Self, _ rhs: Self) -> Self
}
extension _SIMDVectorStorage {
@_transparent
public static func add(_ lhs: Self, _ rhs: Self) -> Self {
return Self(_vector: Builtin.generic_add(lhs._vector, rhs._vector))
}
@_transparent
public static func mul(_ lhs: Self, _ rhs: Self) -> Self {
return Self(_vector: Builtin.generic_mul(lhs._vector, rhs._vector))
}}
// =============================================================================
extension Int32: SIMDScalar {
@frozen
public struct SIMD4Storage: _SIMDVectorStorage {
public typealias Scalar = Int32
/// This specific struct does not have any inner storage.
public typealias _InnerStorage = _SIMDGenericNever<Scalar>
public typealias _Vector = Builtin.Vec4xInt32
public static var _hasVectorRepresentation: Bool {
@_transparent get {
return true
}
}
public static var scalarCount: Int {
@_transparent get {
return 4
}
}
public var _vector: _Vector
public subscript(index: Int) -> Scalar {
@_transparent get {
return Int32(Builtin.extractelement_Vec4xInt32_Int32(
_vector,
Int32(truncatingIfNeeded: index)._value
))
}
@_transparent set {
_vector = Builtin.insertelement_Vec4xInt32_Int32_Int32(
_vector,
newValue._value,
Int32(truncatingIfNeeded: index)._value
)
}
}
@_transparent
public init() {
_vector = Builtin.zeroInitializer()
}
@_transparent
public init(_vector: _Vector) {
self._vector = _vector
}
}
}
extension Int64: SIMDScalar {
@frozen
public struct SIMD4Storage: _SIMDStorageWithOps {
public typealias Scalar = Int64
public typealias _InnerStorage = _SIMDGenericNever<Scalar>
public typealias _Vector = Builtin.Vec4xInt64
public static var _hasVectorRepresentation: Bool {
@_transparent get {
return false
}
}
public static var scalarCount: Int {
@_transparent get {
return 4
}
}
public var _vector: _Vector
public subscript(index: Int) -> Scalar {
@_transparent get {
return Int64(Builtin.extractelement_Vec4xInt64_Int32(
_vector,
Int32(truncatingIfNeeded: index)._value
))
}
@_transparent set {
_vector = Builtin.insertelement_Vec4xInt64_Int64_Int32(
_vector,
newValue._value,
Int32(truncatingIfNeeded: index)._value
)
}
}
@_transparent
public init() {
_vector = Builtin.zeroInitializer()
}
@_transparent
public init(_vector: _Vector) {
self._vector = _vector
}
}
}
| apache-2.0 | 1e7578dc639f7643f0a71884c5fa4280 | 24.088435 | 125 | 0.617046 | 4.295031 | false | false | false | false |
theScud/Lunch | lunchPlanner/das-Quadart/Session.swift | 2 | 7086 | //
// FSSession.swift
// Quadrat
//
// Created by Constantine Fry on 26/10/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
/** A handler used for authorization. */
public typealias AuthorizationHandler = (Bool, NSError?) -> Void
/** A nandler used by all endpoints. */
public typealias ResponseClosure = (_ result: Result) -> Void
/** A nandler for image downloading. */
public typealias DownloadImageClosure = (_ imageData: Data?, _ error: NSError?) -> Void
/** Typealias for parameters dictionary. */
public typealias Parameters = [String:String]
/**
Posted when session have access token, but server returns response with 401 HTTP code.
Guaranteed to be posted an main thread.
*/
public let QuadratSessionDidBecomeUnauthorizedNotification = "QuadratSessionDidBecomeUnauthorizedNotification"
private var _sharedSession: Session?
open class Session {
/** The coniguration. */
let configuration: Configuration
/** The session which perform all network requests. */
let URLSession: Foundation.URLSession
/** The current authorizer. */
var authorizer: Authorizer?
/** Used as image cache for downloaded files. */
let dataCache: DataCache
/** The queue on which tasks have to call completion handlers. */
let completionQueue: OperationQueue
/** The keychain. */
let keychain: Keychain
/** Manages network activity indicator. */
var networkActivityController: NetworkActivityIndicatorController?
/**
One can create custom logger to process all errors and responses in one place.
Main purpose is to debug or to track all the errors accured in framework via some analytic tool.
*/
open var logger: Logger?
open lazy var users: Users = {
return Users(session: self)
}()
open lazy var venues: Venues = {
return Venues(session: self)
}()
open lazy var venueGroups: VenueGroups = {
return VenueGroups(session: self)
}()
open lazy var checkins: Checkins = {
return Checkins(session: self)
}()
open lazy var tips: Tips = {
return Tips(session: self)
}()
open lazy var lists: Lists = {
return Lists(session: self)
}()
open lazy var updates: Updates = {
return Updates(session: self)
}()
open lazy var photos: Photos = {
return Photos(session: self)
}()
open lazy var settings: Settings = {
return Settings(session: self)
}()
open lazy var specials: Specials = {
return Specials(session: self)
}()
open lazy var events: Events = {
return Events(session: self)
}()
open lazy var pages: Pages = {
return Pages(session: self)
}()
open lazy var pageUpdates: PageUpdates = {
return PageUpdates(session: self)
}()
open lazy var multi: Multi = {
return Multi(session: self)
}()
public init(configuration: Configuration, completionQueue: OperationQueue = OperationQueue.main) {
if configuration.shouldControllNetworkActivityIndicator {
self.networkActivityController = NetworkActivityIndicatorController()
}
self.configuration = configuration
self.completionQueue = completionQueue
let URLConfiguration = URLSessionConfiguration.default
URLConfiguration.timeoutIntervalForRequest = configuration.timeoutInterval
let delegateQueue = OperationQueue()
delegateQueue.maxConcurrentOperationCount = 1
self.URLSession = Foundation.URLSession(configuration: URLConfiguration,
delegate: nil, delegateQueue: delegateQueue)
self.dataCache = DataCache(name: configuration.userTag)
if configuration.debugEnabled {
self.logger = ConsoleLogger()
}
self.keychain = Keychain(configuration: self.configuration)
self.keychain.logger = self.logger
}
open class func setupSharedSessionWithConfiguration(_ configuration: Configuration,
completionQueue: OperationQueue = OperationQueue.main) {
if _sharedSession == nil {
_sharedSession = Session(configuration: configuration, completionQueue: completionQueue)
} else {
fatalError("You shouldn't call call setupSharedSessionWithConfiguration twice!")
}
}
open class func sharedSession() -> Session {
if _sharedSession == nil {
fatalError("You must call setupSharedInstanceWithConfiguration before!")
}
return _sharedSession!
}
/** Whether session is authorized or not. */
open func isAuthorized() -> Bool {
do {
let accessToken = try self.keychain.accessToken()
return accessToken != nil
} catch {
return false
}
}
open func accessToken() -> String? {
do {
return try self.keychain.accessToken()
} catch {
return nil
}
}
/**
Removes access token from keychain.
This method doesn't post `QuadratSessionDidBecomeUnauthorizedNotification`.
*/
open func deauthorize() {
do {
try self.keychain.deleteAccessToken()
self.dataCache.clearCache()
} catch {
}
}
/** Returns cached image data. */
open func cachedImageDataForURL(_ url: Foundation.URL) -> Data? {
return self.dataCache.dataForKey("\((url as NSURL).hash)")
}
/** Downloads image at URL and puts in cache. */
open func downloadImageAtURL(_ url: Foundation.URL, completionHandler: @escaping DownloadImageClosure) {
let request = URLRequest(url: url)
let identifier = networkActivityController?.beginNetworkActivity()
let task = self.URLSession.downloadTask(with: request, completionHandler: {
(fileURL, response, error) -> Void in
self.networkActivityController?.endNetworkActivity(identifier)
var data: Data?
if let fileURL = fileURL {
data = try? Data(contentsOf: fileURL)
self.dataCache.addFileAtURL(fileURL, withKey: "\((url as NSURL).hash)")
}
self.completionQueue.addOperation {
completionHandler(data, error as NSError?)
}
})
task.resume()
}
func processResult(_ result: Result) {
if result.HTTPSTatusCode == 401 && self.isAuthorized() {
self.deathorizeAndNotify()
}
self.logger?.session(self, didReceiveResult: result)
}
fileprivate func deathorizeAndNotify() {
self.deauthorize()
DispatchQueue.main.async {
let name = QuadratSessionDidBecomeUnauthorizedNotification
NotificationCenter.default.post(name: Notification.Name(rawValue: name), object: self)
}
}
}
| apache-2.0 | 0c174601859e4c763955c4ac3347f147 | 30.918919 | 110 | 0.627011 | 5.241124 | false | true | false | false |
xwu/swift | test/SILGen/implicitly_unwrapped_optional.swift | 1 | 4433 |
// RUN: %target-swift-emit-silgen -module-name implicitly_unwrapped_optional -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck %s
func foo(f f: (() -> ())!) {
var f: (() -> ())! = f
f?()
}
// CHECK: sil hidden [ossa] @{{.*}}foo{{.*}} : $@convention(thin) (@guaranteed Optional<@callee_guaranteed () -> ()>) -> () {
// CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> ()>):
// CHECK: [[F:%.*]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PF:%.*]] = project_box [[F]]
// CHECK: [[T0_COPY:%.*]] = copy_value [[T0]]
// CHECK: store [[T0_COPY]] to [init] [[PF]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PF]] : $*Optional<@callee_guaranteed () -> ()>
// CHECK: [[HASVALUE:%.*]] = select_enum_addr [[READ]]
// CHECK: cond_br [[HASVALUE]], bb1, bb3
//
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[READ]]
// CHECK-NEXT: [[FN0:%.*]] = load [copy] [[FN0_ADDR]]
// .... then call it
// CHECK: [[B:%.*]] = begin_borrow [[FN0]]
// CHECK: apply [[B]]() : $@callee_guaranteed () -> ()
// CHECK: end_borrow [[B]]
// CHECK: br bb2
// CHECK: bb2(
// CHECK: destroy_value [[F]]
// CHECK: return
// CHECK: bb3:
// CHECK: enum $Optional<()>, #Optional.none!enumelt
// CHECK: br bb2
// The rest of this is tested in optional.swift
// } // end sil function '{{.*}}foo{{.*}}'
func wrap<T>(x x: T) -> T! { return x }
// CHECK-LABEL: sil hidden [ossa] @$s29implicitly_unwrapped_optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F
func wrap_then_unwrap<T>(x x: T) -> T {
// CHECK: switch_enum_addr {{%.*}}, case #Optional.some!enumelt: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]]
// CHECK: [[FAIL]]:
// CHECK: unreachable
// CHECK: [[OK]]:
return wrap(x: x)!
}
// CHECK-LABEL: sil hidden [ossa] @$s29implicitly_unwrapped_optional10tuple_bind1xSSSgSi_SStSg_tF : $@convention(thin) (@guaranteed Optional<(Int, String)>) -> @owned Optional<String> {
func tuple_bind(x x: (Int, String)!) -> String? {
return x?.1
// CHECK: switch_enum {{%.*}}, case #Optional.some!enumelt: [[NONNULL:bb[0-9]+]], case #Optional.none!enumelt: [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]](
// CHECK: [[STRING:%.*]] = destructure_tuple {{%.*}} : $(Int, String)
// CHECK-NOT: destroy_value [[STRING]]
}
// CHECK-LABEL: sil hidden [ossa] @$s29implicitly_unwrapped_optional011tuple_bind_a1_B01xSSSi_SStSg_tF
func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String {
return x.1
}
func return_any() -> AnyObject! { return nil }
func bind_any() {
let object : AnyObject? = return_any()
}
// CHECK-LABEL: sil hidden [ossa] @$s29implicitly_unwrapped_optional6sr3758yyF
func sr3758() {
// Verify that there are no additional reabstractions introduced.
// CHECK: [[CLOSURE:%.+]] = function_ref @$s29implicitly_unwrapped_optional6sr3758yyFyypSgcfU_ : $@convention(thin) (@in_guaranteed Optional<Any>) -> ()
// CHECK: [[F:%.+]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) (@in_guaranteed Optional<Any>) -> () to $@callee_guaranteed (@in_guaranteed Optional<Any>) -> ()
// CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]]
// CHECK: = apply [[BORROWED_F]]({{%.+}}) : $@callee_guaranteed (@in_guaranteed Optional<Any>) -> ()
// CHECK: end_borrow [[BORROWED_F]]
let f: ((Any?) -> Void) = { (arg: Any!) in }
f(nil)
} // CHECK: end sil function '$s29implicitly_unwrapped_optional6sr3758yyF'
// SR-10492: Make sure we can SILGen all of the below without crashing:
class SR_10492_C1 {
init!() {}
}
class SR_10492_C2 {
init(_ foo: SR_10492_C1) {}
}
@objc class C {
@objc func foo() -> C! { nil }
}
struct S {
var i: Int!
func foo() -> Int! { nil }
subscript() -> Int! { 0 }
func testParend(_ anyObj: AnyObject) {
let _: Int? = (foo)()
let _: Int = (foo)()
let _: Int? = foo.self()
let _: Int = foo.self()
let _: Int? = (self.foo.self)()
let _: Int = (self.foo.self)()
// Not really paren'd, but a previous version of the compiler modeled it
// that way.
let _ = SR_10492_C2(SR_10492_C1())
let _: C = (anyObj.foo)!()
}
func testCurried() {
let _: Int? = S.foo(self)()
let _: Int = S.foo(self)()
let _: Int? = (S.foo(self).self)()
let _: Int = (S.foo(self).self)()
}
}
| apache-2.0 | f07da769017679d3c9ecd2aa91e5b6d9 | 36.567797 | 185 | 0.588766 | 3.087047 | false | false | false | false |
kalia-akkad/uSpy | ClarifaiApiDemo/ChallengerVC.swift | 1 | 5918 | //
// ChallengerVC.swift
// ClarifaiApiDemo
//
// Created by Kalia Akkad on 2015-11-14.
// Copyright © 2015 Clarifai, Inc. All rights reserved.
//
import UIKit
//import MobileCoreServices
/*
import AVFoundation
import CoreMedia
let CMYKHalftone = "CMYK Halftone"
let CMYKHalftoneFilter = CIFilter(name: "CICMYKHalftone", withInputParameters: ["inputWidth" : 20, "inputSharpness": 1])
let ComicEffect = "Comic Effect"
let ComicEffectFilter = CIFilter(name: "CIComicEffect")
let Crystallize = "Crystallize"
let CrystallizeFilter = CIFilter(name: "CICrystallize", withInputParameters: ["inputRadius" : 30])
let Edges = "Edges"
let EdgesEffectFilter = CIFilter(name: "CIEdges", withInputParameters: ["inputIntensity" : 10])
let HexagonalPixellate = "Hex Pixellate"
let HexagonalPixellateFilter = CIFilter(name: "CIHexagonalPixellate", withInputParameters: ["inputScale" : 40])
let Invert = "Invert"
let InvertFilter = CIFilter(name: "CIColorInvert")
let Pointillize = "Pointillize"
let PointillizeFilter = CIFilter(name: "CIPointillize", withInputParameters: ["inputRadius" : 30])
let LineOverlay = "Line Overlay"
let LineOverlayFilter = CIFilter(name: "CILineOverlay")
let Posterize = "Posterize"
let PosterizeFilter = CIFilter(name: "CIColorPosterize", withInputParameters: ["inputLevels" : 5])
let Filters = [
CMYKHalftone: CMYKHalftoneFilter,
ComicEffect: ComicEffectFilter,
Crystallize: CrystallizeFilter,
Edges: EdgesEffectFilter,
HexagonalPixellate: HexagonalPixellateFilter,
Invert: InvertFilter,
Pointillize: PointillizeFilter,
LineOverlay: LineOverlayFilter,
Posterize: PosterizeFilter
]
let FilterNames = [String](Filters.keys).sort()
*/
class ChallengerVC: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var tag1: UILabel!
@IBOutlet weak var tag2: UILabel!
/*
@IBOutlet weak var cameraImageView: UIImageView!
@IBOutlet weak var previewView: UIView!
@IBAction func cameraViewTapped(sender: AnyObject) {
}
*/
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://www.wolframcloud.com/objects/d5484999-7deb-421c-a7a7-8b74bb382fc3?x=2")!
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
// Will happen when task completes
if let urlContent = data {
let webContent = NSString(data: urlContent, encoding: NSUTF8StringEncoding)
let stringwithoutquotes = webContent!.stringByReplacingOccurrencesOfString("\"", withString: "")
let removeBracket1 = stringwithoutquotes.stringByReplacingOccurrencesOfString("{", withString: "")
let removeBracket2 = removeBracket1.stringByReplacingOccurrencesOfString("}", withString: "")
let removeSpace = removeBracket2.stringByReplacingOccurrencesOfString(" ", withString: "")
print (removeSpace)
let thisArray = removeSpace.characters.split{$0 == ","}.map(String.init)
self.tag1.text = thisArray[0]
self.tag2.text = thisArray[1]
} else {
// Show error message
}
}
task.resume()
}
/*
@IBAction func takePicture(sender: AnyObject) {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.mediaTypes = [String(kUTTypeImage)]
picker.allowsEditing = true
self.presentViewController(picker, animated: true, completion: nil)
}
else{
NSLog("No Camera.")
}
}
*/
/*
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: NSDictionary!) {
NSLog("Received image from camera")
let mediaType = info[UIImagePickerControllerMediaType] as String
var originalImage:UIImage?, editedImage:UIImage?, imageToSave:UIImage?
let compResult:CFComparisonResult = CFStringCompare(mediaType as NSString!, kUTTypeImage, CFStringCompareFlags.CompareCaseInsensitive)
if ( compResult == CFComparisonResult.CompareEqualTo ) {
editedImage = info[UIImagePickerControllerEditedImage] as UIImage?
originalImage = info[UIImagePickerControllerOriginalImage] as UIImage?
if ( editedImage != nil ) {
imageToSave = editedImage
} else {
imageToSave = originalImage
}
imgView.image = imageToSave
imgView.reloadInputViews()
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBarHidden = true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3a0ea2d56dcc8690f7fc6dd194b901c6 | 32.811429 | 142 | 0.642724 | 5.065925 | false | false | false | false |
C4Framework/C4iOS | C4/Core/Math.swift | 2 | 5943 | // Copyright © 2014 C4
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import Foundation
/// Clamp a value to the range [min, max].
///
/// If the value is less than min this function returns min, if the value is greater than max the function returns max,
/// otherwise it returns the value.
///
/// ````
/// clamp(10, 0, 5) = 5
/// clamp(10, 0, 20) = 10
/// clamp(10,20,30) = 20
/// ````
///
/// - parameter val: The value
/// - parameter min: The lower bound
/// - parameter max: The upper bound
///
/// - returns: The clamped value
public func clamp<T: Comparable>(_ val: T, min: T, max: T) -> T {
assert(min < max, "min has to be less than max")
if val < min { return min }
if val > max { return max }
return val
}
/// Linear interpolation. For any two values a and b return a linear interpolation with parameter `param`.
///
/// ````
/// lerp(0, 100, 0.5) = 50
/// lerp(100, 200, 0.5) = 150
/// lerp(500, 1000, 0.33) = 665
/// ````
///
/// - parameter a: first value
/// - parameter b: second value
/// - parameter param: parameter between 0 and 1 for interpolation
///
/// - returns: The interpolated value
public func lerp<T: FloatingPoint>(_ a: T, _ b: T, at: T) -> T {
return a + (b - a) * at
}
/// Linear mapping. Maps a value in the source range [min, max) to a value in the target range [toMin, toMax) using linear interpolation.
///
/// ````
/// map(10, 0..<20, 0..<200) = 100
/// map(10, 0..<100, 200..<300) = 210
/// map(10, 0..<20, 200..<300) = 250
/// ````
///
/// - parameter val: Source value
/// - parameter min: Source range lower bound
/// - parameter max: Source range upper bound
/// - parameter toMin: Target range lower bound
/// - parameter toMax: Target range upper bound
///
/// - returns: The mapped value.
public func map<T: FloatingPoint>(_ val: T, from: Range<T>, to: Range<T>) -> T {
let param = (val - from.lowerBound)/(from.upperBound - from.lowerBound)
return lerp(to.lowerBound, to.upperBound, at: param)
}
/// Linear mapping. Maps a value in the source range [min, max] to a value in the target range [toMin, toMax] using linear interpolation.
///
/// ````
/// map(10, 0...20, 0...200) = 100
/// map(10, 0...100, 200...300) = 210
/// map(10, 0...20, 200...300) = 250
/// ````
///
/// - parameter val: Source value
/// - parameter min: Source range lower bound
/// - parameter max: Source range upper bound
/// - parameter toMin: Target range lower bound
/// - parameter toMax: Target range upper bound
///
/// - returns: The mapped value.
public func map<T: FloatingPoint>(_ val: T, from: ClosedRange<T>, to: ClosedRange<T>) -> T {
let param = (val - from.lowerBound) / (from.upperBound - from.lowerBound)
return lerp(to.lowerBound, to.upperBound, at: param)
}
/// Returns a random `Int`.
///
/// ````
/// let x = random()
/// ````
///
/// - returns: Random `Int`.
public func random() -> Int {
var r = 0
withUnsafeMutableBytes(of: &r) { bufferPointer in
arc4random_buf(bufferPointer.baseAddress, MemoryLayout<Int>.size)
}
return r
}
/// Return a random integer below `below`
///
/// ````
/// let x = random(below: 20)
/// ````
///
/// - parameter below: The upper bound
///
/// - returns: A random value in the range `0 ..< below`
public func random(below: Int) -> Int {
return abs(random()) % below
}
/// Return a random integer in the given range.
///
/// ````
/// let x = random(in: 10..<20)
/// ````
///
/// - parameter range: range of values
///
/// - returns: A random value greater than or equal to min and less than max.
public func random(in range: Range<Int>) -> Int {
return range.lowerBound + random(below: range.upperBound - range.lowerBound)
}
/// Return a random Double in the given range.
///
/// ````
/// let x = random(in: 0..<1)
/// ````
///
/// - parameter range: range of values
/// - returns: A random Double uniformly distributed between 0 and 1
public func random(in range: Range<Double>) -> Double {
let intRange: Range<Double> = Double(-Int.max) ..< Double(Int.max) + 1
let r = Double(random())
return map(r, from: intRange, to: range)
}
/// Converts radian values to degrees.
///
/// Uses the following equation: value * 180.0 / PI
///
/// ````
/// radToDeg(Double.pi) = 180
/// radToDeg(Double.pi / 2.0) = 90
/// ````
///
/// - parameter val: The value in radians.
/// - returns: A double value representation of the radian value in degrees.
public func radToDeg(_ val: Double) -> Double {
return 180.0 * val / Double.pi
}
/// Converts degree values to radians.
///
/// Uses the following equation: value * PI / 180.0
///
/// ````
/// degToRad(270) = 3*Double.pi / 2.0 (4.712...)
/// degToRad(360) = 2*PI (6.283...)
/// ````
///
/// - parameter val: The value in degrees.
/// - returns: A double value representation of the degree value in radians.
public func degToRad(_ val: Double) -> Double {
return Double.pi * val / 180.0
}
| mit | b10dcd8bc91b26380af9ed4ef15c1245 | 31.118919 | 137 | 0.641367 | 3.564487 | false | false | false | false |
Sharelink/Bahamut | Bahamut/Persistents/Model/ModelExtension.swift | 1 | 7023 | //
// ModelExtension.swift
// iDiaries
//
// Created by AlexChow on 15/12/8.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import EVReflection
//MARK: Model Enity
extension BahamutObject
{
func saveModel()
{
PersistentManager.sharedInstance.saveModel(self)
}
static func saveObjectOfArray<T:BahamutObject>(_ arr:[T])
{
for item in arr
{
item.saveModel()
}
}
static func deleteObjectArray(_ arr:[BahamutObject])
{
PersistentManager.sharedInstance.removeModels(arr)
}
}
extension Array
{
func saveBahamutObjectModels(){
if self.count > 0 && (self.first! is BahamutObject){
self.forEach({ (element) -> () in
if let e = element as? BahamutObject{
e.saveModel()
}
})
}
}
}
class ModelExtensionConstant
{
static let coreDataModelId = "BahamutModel"
static let modelArrCacheName = "[Bahamut.AllModel]"
static let idFieldName = "id"
static let entityName = "ModelEntity"
}
class ModelExtension: PersistentExtensionProtocol
{
static var defaultInstance:ModelExtension!
fileprivate(set) var coreData = CoreDataManager()
func releaseExtension() {
coreData.deinitManager()
}
func destroyExtension() {
coreData.destroyDbFile()
}
func resetExtension() {
}
func storeImmediately() {
coreData.saveNow()
}
}
extension PersistentManager
{
func useModelExtension(_ dbFileUrl:URL,momdBundle:Bundle)
{
self.useExtension(ModelExtension()) { (ext) -> Void in
ModelExtension.defaultInstance = ext
ext.coreData.initManager(ModelExtensionConstant.coreDataModelId, dbFileUrl: dbFileUrl,momdBundle: momdBundle)
}
}
func saveModelChangesDelay()
{
ModelExtension.defaultInstance.coreData.saveContextDelay()
}
func saveModelChanges()
{
ModelExtension.defaultInstance.coreData.saveNow()
}
func clearAllModelData()
{
ModelExtension.defaultInstance.coreData.deleteAll(ModelExtensionConstant.entityName)
}
func getModel<T:BahamutObject>(_ type:T.Type,idValue:String) -> T?
{
if String.isNullOrWhiteSpace(idValue)
{
return nil
}
let typename = type.description()
//read from core data
let indexIdValue = "\(typename):\(idValue)"
if let cellModel = ModelExtension.defaultInstance.coreData.getCellById(ModelExtensionConstant.entityName, idFieldName: ModelExtensionConstant.idFieldName, idValue: indexIdValue) as? ModelEntity
{
let jsonString = cellModel.serializableValue
let model = T.fromJsonString(json: jsonString, T())
return model
}
return nil
}
func getModels<T:BahamutObject>(_ type:T.Type ,idValues:[String]) -> [T?]?
{
if let cells = ModelExtension.defaultInstance.coreData.getCellsByIds(ModelExtensionConstant.entityName, idFieldName: ModelExtensionConstant.idFieldName, idValues: idValues) as? [ModelEntity?]
{
var result = [T?]()
let t = T()
for entity in cells
{
if let et = entity{
let jsonString = et.serializableValue
let model = T.fromJsonString(json: jsonString, t)
result.append(model)
}else{
result.append(nil)
}
}
return result
}else{
return nil
}
}
@discardableResult
func getAllModel<T:BahamutObject>(_ type:T.Type) -> [T]
{
let typename = type.description()
let predicate = NSPredicate(format: "\(ModelExtensionConstant.idFieldName) LIKE %@", argumentArray: ["\(typename):*"])
let result = ModelExtension.defaultInstance.coreData.getCells(ModelExtensionConstant.entityName,predicate: predicate).map{ obj -> T in
let entity = obj as! ModelEntity
let model = T.fromJsonString(json: entity.serializableValue, T())
return model
}
return result
}
func getAllModelFromCache<T:BahamutObject>(_ type:T.Type) -> [T]
{
return getAllModel(type)
}
func removeAllModels<T:BahamutObject>(_ type:T.Type) -> [T]{
let arr = getAllModel(type)
removeModels(arr)
return arr
}
func refreshCache<T:BahamutObject>(_ type:T.Type)
{
getAllModel(type)
}
func clearArrCache<T:BahamutObject>(_ type:T.Type)
{
}
func removeModel<T:BahamutObject>(_ model:T)
{
removeModels([model])
}
func removeModels<T:BahamutObject>(_ m:T,idArray:[String]) {
if idArray.count == 0 {
return
}
let typeName = m.classForCoder.description()
let idValues = idArray.map { (id) -> String in
return "\(typeName):\(id)"
}
ModelExtension.defaultInstance.coreData.deleteCellByIds(ModelExtensionConstant.entityName, idFieldName: ModelExtensionConstant.idFieldName, idValues: idValues)
saveModelChanges()
clearArrCache(T.self)
}
func removeModels<T:BahamutObject>(_ models:[T])
{
if models.count == 0
{
return
}
let typeName = models.first!.classForCoder.description()
let idValues = models.map { (model) -> String in
let idValue = model.getObjectUniqueIdValue()
return "\(typeName):\(idValue)"
}
ModelExtension.defaultInstance.coreData.deleteCellByIds(ModelExtensionConstant.entityName, idFieldName: ModelExtensionConstant.idFieldName, idValues: idValues)
saveModelChanges()
clearArrCache(T.self)
}
func saveModel<T:BahamutObject>(_ model:T)
{
//save in cache
let typeName = model.classForCoder.description()
let idValue = model.getObjectUniqueIdValue()
let indexIdValue = "\(typeName):\(idValue)"
var jsonString = model.toJsonString()
jsonString = jsonString.split("\n").map{$0.trim()}.joined(separator: "")
if let cellModel = ModelExtension.defaultInstance.coreData.getCellById(ModelExtensionConstant.entityName, idFieldName: ModelExtensionConstant.idFieldName, idValue: indexIdValue) as? ModelEntity
{
cellModel.serializableValue = jsonString
}else
{
if let cellModel = ModelExtension.defaultInstance.coreData.insertNewCell(ModelExtensionConstant.entityName) as? ModelEntity{
cellModel.serializableValue = jsonString
cellModel.id = indexIdValue
cellModel.modelType = typeName
}
}
ModelExtension.defaultInstance.coreData.saveContextDelay()
}
}
| mit | 1ee70c6e588f1f64309628ae8d080ad7 | 29.258621 | 201 | 0.612536 | 4.594241 | false | false | false | false |
ericmarkmartin/Nightscouter2 | Common/Protocols/DictionaryRepresentable.swift | 1 | 1197 | //
// DictionaryRepresentable.swift
// Nightscouter
//
// Created by Peter Ina on 11/13/15.
// Copyright © 2015 Peter Ina. All rights reserved.
//
import Foundation
public protocol DictionaryConvertible {
var dictionary: [String: AnyObject] { get }
}
extension DictionaryConvertible {
public var dictionary: [String: AnyObject] {
var dict = [String :AnyObject] ()
let mirror = Mirror(reflecting: self)
for child in mirror.children {
guard let key = child.label else {
continue
}
let value = child.value
guard let result = self.unwrap(value) else {
continue
}
// print("\(key): \(result)")
dict[key] = result as? AnyObject
}
return dict
}
private func unwrap(subject: Any) -> Any? {
var value: Any?
let mirrored = Mirror(reflecting:subject)
if mirrored.displayStyle != .Optional {
value = subject
} else if let firstChild = mirrored.children.first {
value = firstChild.value
}
return value
}
}
| mit | 23b7299577b93f2e3a9655f3b96c1236 | 23.408163 | 60 | 0.545151 | 4.861789 | false | false | false | false |
shohei/firefox-ios | UITests/BookmarkingTests.swift | 9 | 4317 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
class BookmarkingTests: KIFTestCase, UITextFieldDelegate {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
/**
* Tests basic page navigation with the URL bar.
*/
func testBookmarkingUI() {
// Load a page
tester().tapViewWithAccessibilityIdentifier("url")
let url1 = "\(webRoot)/numberedPage.html?page=1"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
// Bookmark it using the bookmark button
tester().tapViewWithAccessibilityLabel("Bookmark")
let bookmarkButton = tester().waitForViewWithAccessibilityLabel("Bookmark") as! UIButton
XCTAssertTrue(bookmarkButton.selected, "Bookmark button is marked selected")
// Load a different page in a new tab
tester().tapViewWithAccessibilityLabel("Show Tabs")
tester().tapViewWithAccessibilityLabel("Add Tab")
tester().tapViewWithAccessibilityIdentifier("url")
let url2 = "\(webRoot)/numberedPage.html?page=2"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url2)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page 2")
// Check that the bookmark button is no longer selected
XCTAssertFalse(bookmarkButton.selected, "Bookmark button is not marked selected")
// Now switch back to the original tab
tester().tapViewWithAccessibilityLabel("Show Tabs")
tester().tapViewWithAccessibilityLabel("Page 1")
XCTAssertTrue(bookmarkButton.selected, "Bookmark button is marked selected")
// Check that it appears in the bookmarks home panel
tester().tapViewWithAccessibilityIdentifier("url")
tester().tapViewWithAccessibilityLabel("Bookmarks")
let bookmarkRow = tester().waitForViewWithAccessibilityLabel("Page 1") as! UITableViewCell
XCTAssertNotNil(bookmarkRow.imageView?.image)
// Tap to open it
tester().tapViewWithAccessibilityLabel("Page 1")
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
// Unbookmark it using the bookmark button
tester().tapViewWithAccessibilityLabel("Bookmark")
XCTAssertFalse(bookmarkButton.selected, "Bookmark button is not selected")
// Check that it no longer appears in the bookmarks home panel
tester().tapViewWithAccessibilityIdentifier("url")
tester().tapViewWithAccessibilityLabel("Bookmarks")
tester().waitForAbsenceOfViewWithAccessibilityLabel("Page 1")
tester().tapViewWithAccessibilityLabel("Cancel")
}
func testBookmarkNoTitle() {
// Load a page with no title
tester().tapViewWithAccessibilityIdentifier("url")
let url1 = "\(webRoot)/noTitle.html"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url1)\n")
tester().waitForWebViewElementWithAccessibilityLabel("This page has no title")
// Bookmark it using the bookmark button
tester().tapViewWithAccessibilityLabel("Bookmark")
var bookmarkButton = tester().waitForViewWithAccessibilityLabel("Bookmark") as! UIButton
XCTAssertTrue(bookmarkButton.selected, "Bookmark button is marked selected")
// Check that its row in the bookmarks panel has a url instead of a title
tester().tapViewWithAccessibilityIdentifier("url")
tester().tapViewWithAccessibilityLabel("Bookmarks")
tester().waitForAbsenceOfViewWithAccessibilityLabel("Page 1")
// XXX: Searching for the table cell directly here can result in finding the wrong view.
let cell = tester().waitForCellAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), inTableViewWithAccessibilityIdentifier: "SiteTable")
XCTAssertEqual(cell.textLabel!.text!, url1, "Cell shows url")
tester().tapViewWithAccessibilityLabel("Cancel")
}
override func tearDown() {
BrowserUtils.resetToAboutHome(tester())
}
}
| mpl-2.0 | c319db5dd0f3266f69a5ede406dc2758 | 44.925532 | 141 | 0.708826 | 6.037762 | false | true | false | false |
LeeShiYoung/DouYu | DouYuAPP/DouYuAPP/Classes/Home/View/Yo_RecommendContentView.swift | 1 | 2608 | //
// Yo_RecommendContentView.swift
// DouYuAPP
//
// Created by shying li on 2017/4/1.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
import FSPagerView
class Yo_RecommendContentView: Yo_BaseContentView {
override func configureView() {
super.configureView()
}
lazy var collectionView: UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
layout.headerReferenceSize = CGSize(width: kScreenW, height: 50)
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.contentInset = UIEdgeInsets(top:kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
return collectionView
}()
lazy var cycleView: Yo_HomeCycleView = {[weak self] in
let cycleView = Yo_HomeCycleView(frame: CGRect.zero)
cycleView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: cycleViewCellID)
cycleView.itemSize = .zero
cycleView.automaticSlidingInterval = 3.0
self?.collectionView.addSubview(cycleView)
return cycleView
}()
lazy var gameView: UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 10
layout.itemSize = CGSize(width: 80, height: kGameViewH)
layout.scrollDirection = .horizontal
let gameView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
gameView.backgroundColor = UIColor.white
gameView.showsHorizontalScrollIndicator = false
gameView.showsVerticalScrollIndicator = false
self?.collectionView.addSubview(gameView)
return gameView
}()
}
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
extension Yo_RecommendContentView {
public func setupUI() {
addSubview(collectionView)
collectionView.snp.makeConstraints { (maker) in
maker.top.bottom.left.right.equalTo(self)
}
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
addIndicatorView()
}
}
| apache-2.0 | 1dbada518155da30a5deeda5fde45a00 | 33.197368 | 110 | 0.667564 | 5.10609 | false | false | false | false |
Mobelux/ImageLoader | ImageLoader/Extensions/UIImageView+Animation.swift | 1 | 2398 | //
// UIImageView+Animation.swift
// ImageLoader
//
// MIT License
//
// Copyright (c) 2017 Mobelux
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public extension UIImageView {
/// Fades in a new image. It begins at the current state of the UIImageView, so if you want to fade from one image to the next, you should set the initial image via `imageView.image = initialImage` prior to calling this.
///
/// - Parameters:
/// - image: The new image that should be faded in, and shown fully when the animation is complete
/// - duration: How long should the fade take
/// - completion: Called when the animation is complete. It will be called on the same queue that called this `fadeTo()` function, which you should do from the main queue.
public func fadeTo(image: UIImage, duration: TimeInterval, completion: (() -> Void)?) {
guard self.image != image else { return }
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
let animation = CATransition()
animation.duration = duration
animation.type = kCATransitionFade
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
layer.add(animation, forKey: "imageTransition")
self.image = image
CATransaction.commit()
}
}
| mit | 74ff8f77641d116e4f70fc6f79fa0e16 | 44.245283 | 224 | 0.718098 | 4.585086 | false | false | false | false |
AshuMishra/BMSLocationFinder | BMSLocationFinder/BMSLocationFinder/Helper/ENSideMenuNavigationController.swift | 1 | 1721 | //
// RootNavigationViewController.swift
// SwiftSideMenu
//
// Created by Evgeny Nazarov on 29.09.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
public class ENSideMenuNavigationController: UINavigationController, ENSideMenuProtocol {
public var sideMenu : ENSideMenu?
public var sideMenuAnimationType : ENSideMenuAnimation = .Default
// MARK: - Life cycle
public override func viewDidLoad() {
super.viewDidLoad()
}
public init( menuTableViewController: UITableViewController, contentViewController: UIViewController?) {
super.init(nibName: nil, bundle: nil)
if (contentViewController != nil) {
self.viewControllers = [contentViewController!]
}
sideMenu = ENSideMenu(sourceView: self.view, menuTableViewController: menuTableViewController, menuPosition:.Left)
// view.bringSubviewToFront(navigationBar)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
public func setContentViewController(contentViewController: UIViewController) {
self.sideMenu?.toggleMenu()
switch sideMenuAnimationType {
case .None:
self.viewControllers = [contentViewController]
break
default:
contentViewController.navigationItem.hidesBackButton = true
self.setViewControllers([contentViewController], animated: true)
break
}
}
}
| mit | 78558b73e6044259b861f8be421a6e41 | 29.192982 | 122 | 0.667054 | 5.736667 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Async/WaitTask.swift | 1 | 2886 | //
// WaitTask.swift
//
//
// Created by Vladislav Fitc on 10.03.2020.
//
import Foundation
class WaitTask: AsyncOperation, ResultContainer {
typealias TaskStatusService = (RequestOptions?, @escaping ResultCallback<TaskInfo>) -> Void
let taskStatusService: TaskStatusService
let requestOptions: RequestOptions?
let timeout: TimeInterval?
private var launchDate: Date?
let completion: (ResultCallback<TaskStatus>)
var result: Result<TaskStatus, Swift.Error> = .failure(SyncOperationError.notFinished) {
didSet {
completion(result)
state = .finished
}
}
var isTimeout: Bool {
guard let timeout = timeout, let launchDate = launchDate else {
return false
}
return Date().timeIntervalSince(launchDate) >= timeout
}
init(taskStatusService: @escaping TaskStatusService,
timeout: TimeInterval? = nil,
requestOptions: RequestOptions?,
completion: @escaping ResultCallback<TaskStatus>) {
self.taskStatusService = taskStatusService
self.timeout = timeout
self.requestOptions = requestOptions
self.completion = completion
}
override func main() {
launchDate = Date()
checkStatus()
}
private func checkStatus() {
guard !isTimeout else {
result = .failure(Error.timeout)
return
}
taskStatusService(requestOptions) { [weak self] result in
guard let request = self else { return }
switch result {
case .success(let taskStatus):
switch taskStatus.status {
case .published:
request.result = .success(taskStatus.status)
default:
sleep(1)
request.checkStatus()
}
case .failure(let error):
request.result = .failure(error)
}
}
}
enum Error: Swift.Error {
case timeout
}
}
extension WaitTask {
convenience init(index: Index,
taskID: TaskID,
timeout: TimeInterval? = nil,
requestOptions: RequestOptions?,
completion: @escaping ResultCallback<TaskStatus>) {
self.init(taskStatusService: { requestOptions, completion in index.taskStatus(for: taskID, requestOptions: requestOptions, completion: completion) },
timeout: timeout,
requestOptions: requestOptions,
completion: completion)
}
convenience init(client: Client,
taskID: AppTaskID,
timeout: TimeInterval? = nil,
requestOptions: RequestOptions?,
completion: @escaping ResultCallback<TaskStatus>) {
self.init(taskStatusService: { requestOptions, completion in client.taskStatus(for: taskID, requestOptions: requestOptions, completion: completion) },
timeout: timeout,
requestOptions: requestOptions,
completion: completion)
}
}
| mit | 44da653fad6f686ed11b5a3da3878d0b | 25.722222 | 154 | 0.642758 | 4.826087 | false | false | false | false |
NijiDigital/NetworkStack | Example/MoyaComparison/Pods/JSONCodable/JSONCodable/JSONDecodable.swift | 1 | 13548 | //
// JSONDecodable.swift
// JSONCodable
//
// Created by Matthew Cheok on 17/7/15.
// Copyright © 2015 matthewcheok. All rights reserved.
//
// Decoding Errors
public enum JSONDecodableError: Error, CustomStringConvertible {
case missingTypeError(
key: String
)
case incompatibleTypeError(
key: String,
elementType: Any.Type,
expectedType: Any.Type
)
case arrayTypeExpectedError(
key: String,
elementType: Any.Type
)
case dictionaryTypeExpectedError(
key: String,
elementType: Any.Type
)
case transformerFailedError(
key: String
)
public var description: String {
switch self {
case let .missingTypeError(key: key):
return "JSONDecodableError: Missing value for key \(key)"
case let .incompatibleTypeError(key: key, elementType: elementType, expectedType: expectedType):
return "JSONDecodableError: Incompatible type for key \(key); Got \(elementType) instead of \(expectedType)"
case let .arrayTypeExpectedError(key: key, elementType: elementType):
return "JSONDecodableError: Got \(elementType) instead of an array for key \(key)"
case let .dictionaryTypeExpectedError(key: key, elementType: elementType):
return "JSONDecodableError: Got \(elementType) instead of a dictionary for key \(key)"
case let .transformerFailedError(key: key):
return "JSONDecodableError: Transformer failed for key \(key)"
}
}
}
// Dictionary -> Struct
public protocol JSONDecodable {
init(object: JSONObject) throws
init(object: [JSONObject]) throws
}
public extension JSONDecodable {
/// initialize with top-level Array JSON data
public init(object: [JSONObject]) throws {
// use empty string key
try self.init(object:["": object])
}
public init?(optional: JSONObject) {
do {
try self.init(object: optional)
} catch {
return nil
}
}
}
public extension Array where Element: JSONDecodable {
init(JSONArray: [Any]) throws {
self.init(try JSONArray.flatMap {
guard let json = $0 as? [String : Any] else {
throw JSONDecodableError.dictionaryTypeExpectedError(key: "n/a", elementType: type(of: $0))
}
return try Element(object: json)
})
}
}
// JSONDecoder - provides utility methods for decoding
public class JSONDecoder {
let object: JSONObject
public init(object: JSONObject) {
self.object = object
}
/// Get index from `"[0]"` formatted `String`
/// returns `nil` if invalid format (i.e. no brackets or contents not an `Int`)
internal func parseArrayIndex(_ key:String) -> Int? {
var chars = key.characters
let first = chars.popFirst()
let last = chars.popLast()
if first == "[" && last == "]" {
return Int(String(chars))
} else {
return nil
}
}
private func get(_ key: String) -> Any? {
let keys = key.replacingOccurrences(of: "[", with: ".[").components(separatedBy: ".")
let result = keys.reduce(object as Any?) {
value, key in
switch value {
case let dict as [String: Any]:
return dict[key]
case let arr as [Any]:
guard let index = parseArrayIndex(key) else {
return nil
}
guard (0..<arr.count) ~= index else {
return nil
}
return arr[index]
default:
return nil
}
}
return (result ?? object[key]).flatMap{$0 is NSNull ? nil : $0}
}
// JSONCompatible
public func decode<Compatible: JSONCompatible>(_ key: String) throws -> Compatible {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let compatible = value as? Compatible else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: Compatible.self)
}
return compatible
}
// JSONCompatible?
public func decode<Compatible: JSONCompatible>(_ key: String) throws -> Compatible? {
return (get(key) ?? object[key] as Any) as? Compatible
}
// JSONDecodable
public func decode<Decodable: JSONDecodable>(_ key: String) throws -> Decodable {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let object = value as? JSONObject else {
throw JSONDecodableError.dictionaryTypeExpectedError(key: key, elementType: type(of: value))
}
return try Decodable(object: object)
}
// JSONDecodable?
public func decode<Decodable: JSONDecodable>(_ key: String) throws -> Decodable? {
guard let value = get(key) else {
return nil
}
guard let object = value as? JSONObject else {
throw JSONDecodableError.dictionaryTypeExpectedError(key: key, elementType: type(of: value))
}
return try Decodable(object: object)
}
// Enum
public func decode<Enum: RawRepresentable>(_ key: String) throws -> Enum {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let raw = value as? Enum.RawValue else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: Enum.RawValue.self)
}
guard let result = Enum(rawValue: raw) else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: Enum.RawValue.self, expectedType: Enum.self)
}
return result
}
// Enum?
public func decode<Enum: RawRepresentable>(_ key: String) throws -> Enum? {
guard let value = get(key) else {
return nil
}
guard let raw = value as? Enum.RawValue else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: Enum.RawValue.self)
}
guard let result = Enum(rawValue: raw) else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: Enum.RawValue.self, expectedType: Enum.self)
}
return result
}
// [JSONCompatible]
public func decode<Element: JSONCompatible>(_ key: String) throws -> [Element] {
guard let value = get(key) else {
return []
}
guard let array = value as? [Element] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [Element].self)
}
return array
}
// [JSONCompatible]?
public func decode<Element: JSONCompatible>(_ key: String) throws -> [Element]? {
guard let value = get(key) else {
return nil
}
guard let array = value as? [Element] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [Element].self)
}
return array
}
// [JSONDecodable]
public func decode<Element: JSONDecodable>(_ key: String) throws -> [Element] {
guard let value = get(key) else {
return []
}
guard let array = value as? [JSONObject] else {
throw JSONDecodableError.arrayTypeExpectedError(key: key, elementType: type(of: value))
}
return try array.flatMap { try Element(object: $0)}
}
// [JSONDecodable]?
public func decode<Element: JSONDecodable>(_ key: String) throws -> [Element]? {
guard let value = get(key) else {
return nil
}
guard let array = value as? [JSONObject] else {
throw JSONDecodableError.arrayTypeExpectedError(key: key, elementType: type(of: value))
}
return try array.flatMap { try Element(object: $0)}
}
// [[JSONDecodable]]
public func decode<Element: JSONDecodable>(_ key: String) throws -> [[Element]] {
guard let value = get(key) else {
return []
}
guard let array = value as? [[JSONObject]] else {
throw JSONDecodableError.arrayTypeExpectedError(key: key, elementType: type(of: value))
}
var res:[[Element]] = []
for x in array {
let nested = try x.flatMap { try Element(object: $0)}
res.append(nested)
}
return res
}
// [[JSONCompatible]]
public func decode<Element: JSONCompatible>(_ key: String) throws -> [[Element]] {
guard let value = get(key) else {
return []
}
guard let array = value as? [[Element]] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [Element].self)
}
var res:[[Element]] = []
for x in array {
res.append(x)
}
return res
}
// [Enum]
public func decode<Enum: RawRepresentable>(_ key: String) throws -> [Enum] {
guard let value = get(key) else {
return []
}
guard let array = value as? [Enum.RawValue] else {
throw JSONDecodableError.arrayTypeExpectedError(key: key, elementType: type(of: value))
}
return array.flatMap { Enum(rawValue: $0) }
}
// [Enum]?
public func decode<Enum: RawRepresentable>(_ key: String) throws -> [Enum]? {
guard let value = get(key) else {
return nil
}
guard let array = value as? [Enum.RawValue] else {
throw JSONDecodableError.arrayTypeExpectedError(key: key, elementType: type(of: value))
}
return array.flatMap { Enum(rawValue: $0) }
}
// [String:JSONCompatible]
public func decode<Value: JSONCompatible>(_ key: String) throws -> [String: Value] {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let dictionary = value as? [String: Value] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [String: Value].self)
}
return dictionary
}
// [String:JSONCompatible]?
public func decode<Value: JSONCompatible>(_ key: String) throws -> [String: Value]? {
guard let value = get(key) else {
return nil
}
guard let dictionary = value as? [String: Value] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [String: Value].self)
}
return dictionary
}
// [String:JSONDecodable]
public func decode<Element: JSONDecodable>(_ key: String) throws -> [String: Element] {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let dictionary = value as? [String: JSONObject] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [String: Element].self)
}
var decoded = [String: Element]()
try dictionary.forEach {
decoded[$0] = try Element(object: $1)
}
return decoded
}
// [String:JSONDecodable]?
public func decode<Element: JSONDecodable>(_ key: String) throws -> [String: Element]? {
guard let value = get(key) else {
return nil
}
guard let dictionary = value as? [String: JSONObject] else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: [String: Element].self)
}
var decoded = [String: Element]()
try dictionary.forEach {
decoded[$0] = try Element(object: $1)
}
return decoded
}
// JSONTransformable
public func decode<EncodedType, DecodedType>(_ key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws -> DecodedType {
guard let value = get(key) else {
throw JSONDecodableError.missingTypeError(key: key)
}
guard let actual = value as? EncodedType else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: EncodedType.self)
}
guard let result = transformer.decoding(actual) else {
throw JSONDecodableError.transformerFailedError(key: key)
}
return result
}
// JSONTransformable?
public func decode<EncodedType, DecodedType>(_ key: String, transformer: JSONTransformer<EncodedType, DecodedType>) throws -> DecodedType? {
guard let value = get(key) else {
return nil
}
guard let actual = value as? EncodedType else {
throw JSONDecodableError.incompatibleTypeError(key: key, elementType: type(of: value), expectedType: EncodedType.self)
}
guard let result = transformer.decoding(actual) else {
throw JSONDecodableError.transformerFailedError(key: key)
}
return result
}
}
| apache-2.0 | 0f68cc936c636d2c292a4f0eedde7829 | 35.319035 | 144 | 0.596368 | 4.642563 | false | false | false | false |
git-hushuai/MOMO | MMHSMeterialProject/UINavigationController/BusinessFile/登录相关/HSUserProtocalController.swift | 1 | 1454 | //
// HSUserProtocalController.swift
// MMHSMeterialProject
//
// Created by hushuaike on 16/3/28.
// Copyright © 2016年 hushuaike. All rights reserved.
//
import UIKit
class HSUserProtocalController: UIViewController {
let webView : UIWebView = UIWebView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height-64));
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.init(red: 0xf3/255.0, green: 0xf3/255.0, blue: 0xf3/255.0, alpha: 1.0);
self.title = "用户许可协议";
self.webView.scalesPageToFit = true;
self.view.addSubview(self.webView);
let url = NSURL.init(string: "http://www.elitez.cn/html/user_agreement");
let request = NSURLRequest.init(URL: url!);
self.webView.loadRequest(request);
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 48957940b5378841b5bb55f61e689e1e | 30.282609 | 159 | 0.663655 | 4.135057 | false | false | false | false |
rnystrom/VectorKit | VectorKit/Distance.swift | 1 | 849 | //
// Distance.swift
// ATCSim
//
// Created by Ryan Nystrom on 3/15/15.
// Copyright (c) 2015 Ryan Nystrom. All rights reserved.
//
import Foundation
import Darwin
public func turnRadius(velocity: Double, bank: Double) -> Double {
// http://aviation.stackexchange.com/a/2872
let magicConstant = 11.26
return pow(velocity, 2.0) / (magicConstant * tan(bank))
}
public func distance(x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
return sqrt(pow(x2 - x1, 2.0) + pow(y2 - y1, 2.0))
}
public func distance(p1: Point, p2: Point, center: Point) -> Double {
let theta = thetaBetweenPoints(p1, center, p2)
let percent = theta / (2 * M_PI)
let r = distance(p1.x, p1.y, center.x, center.y)
let c = circumference(r)
return c * percent
}
public func circumference(radius: Double) -> Double {
return 2 * M_PI * radius
}
| mit | f4ff4269d63be7c76206dae8ca9b9c30 | 25.53125 | 80 | 0.667845 | 2.927586 | false | false | false | false |
iAugux/iBBS-Swift | iBBS/PasscodeLock/PasscodeLock/ChangePasscodeState.swift | 4 | 1064 | //
// ChangePasscodeState.swift
// PasscodeLock
//
// Created by Yanko Dimitrov on 8/28/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
struct ChangePasscodeState: PasscodeLockStateType {
let title: String
let description: String
let isCancellableAction = true
var isTouchIDAllowed = false
init() {
title = localizedStringFor("PasscodeLockChangeTitle", comment: "Change passcode title")
description = localizedStringFor("PasscodeLockChangeDescription", comment: "Change passcode description")
}
func acceptPasscode(passcode: [String], fromLock lock: PasscodeLockType) {
guard let currentPasscode = lock.repository.passcode else {
return
}
if passcode == currentPasscode {
let nextState = SetPasscodeState()
lock.changeStateTo(nextState)
} else {
lock.delegate?.passcodeLockDidFail(lock)
}
}
}
| mit | 148c4e68e25d6f94072cc6ef0964eedc | 24.926829 | 113 | 0.614299 | 5.479381 | false | false | false | false |
nessBautista/iOSBackup | RxSwift_01/RxSwift_01/ViewController.swift | 1 | 13113 | //
// ViewController.swift
// RxSwift_01
//
// Created by Nestor Javier Hernandez Bautista on 5/24/17.
// Copyright © 2017 Definity First. All rights reserved.
//
import UIKit
import Foundation
import RxSwift
import RxCocoa
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
//self.basics()
//self.mapExamples()
//self.filterExamples()
//self.combineExamples()
self.sideEffectsExample()
}
func sideEffectsExample()
{
exampleOf("doOnNext") {
let disposeBag = DisposeBag()
let farenheitTemps = [-40, 0, 32, 70, 212]
let source = Observable.from(farenheitTemps)
source.do(onNext: { $0 * $0},
onError: {error in},
onCompleted: nil,
onSubscribe: nil, onSubscribed: nil, onDispose: nil)
.do(onNext: { print("\($0)ºF = ", terminator: "")},
onError: {error in},
onCompleted: nil,
onSubscribe: nil, onSubscribed: nil, onDispose: nil)
.map {
Double($0 - 32) * 5 / 9.0
}
.subscribe(onNext: {print(String(format: "%.1fºC", $0))},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
}
}
func combineExamples()
{
exampleOf("StartWith") {
let disposeBag = DisposeBag()
Observable.of("1","2","3")
.startWith("A")
.startWith("B")
.startWith("C", "D")
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
}
exampleOf("Merge") {
let disposeBag = DisposeBag()
let subject1 = PublishSubject<String>()
let subject2 = PublishSubject<String>()
Observable.of(subject1, subject2)
.merge()
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
subject1.onNext("A")
subject1.onNext("B")
subject2.onNext("1")
subject2.onNext("2")
subject1.onNext("C")
subject2.onNext("3")
}
exampleOf("Zip") {
let disposeBag = DisposeBag()
let stringSubject = PublishSubject<String>()
let intSubject = PublishSubject<Int>()
Observable.zip(stringSubject, intSubject){ stringElement, intElement in
"\(stringElement) \(intElement)"
}
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
stringSubject.onNext("A")
stringSubject.onNext("B")
intSubject.onNext(1)
intSubject.onNext(2)
intSubject.onNext(3)
stringSubject.onNext("C")
}
}
func filterExamples()
{
exampleOf("filter") {
let disposeBag = DisposeBag()
//Generate numbers from 1 to 100
let numbers = Observable.generate(initialState: 1, condition: {$0 < 101}, iterate: {$0 + 1})
numbers.filter { number in
guard number > 1 else {return false}
var isPrime = true
(2..<number).forEach({
if number % $0 == 0
{
isPrime = false
}
})
return isPrime
}
.toArray()
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
}
exampleOf("DistinctUntilChanged") {
let disposeBag = DisposeBag()
let searchString = Variable("")
searchString.asObservable()
.map({$0.lowercased()})
.distinctUntilChanged()
.subscribe(onNext: {print($0)},
onError: {error in},
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
searchString.value = "APPLE"
searchString.value = "APPLE"
searchString.value = "banana"
searchString.value = "APPLE"
}
exampleOf("takeWhile") {
let disposeBag = DisposeBag()
let numbers = [1,2,3,4,3,2,1]
let source = Observable.from(numbers)
source.takeWhile{ $0 < 4}
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
}
}
func mapExamples()
{
exampleOf("map"){
Observable.of(1,2,3)
.map{$0 * $0}
.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: nil,
onDisposed: nil)
.dispose()
}
exampleOf("FlatMap") {
// Dispose bag
let disposeBag = DisposeBag()
//Example Struct
struct Player {
let score: Variable<Int>
}
let scott = Player(score: Variable(80))
let lori = Player(score: Variable(90))
//This is the variable which we will be subscribe to, it's kind of a placeholder
var player = Variable(scott)
player.asObservable()
.flatMap{$0.score.asObservable()}
.subscribe(onNext: {print($0)},
onError: {error in},
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
//Change the subscribed variable value
player.value.score.value = 85
//Change the current player value directly
scott.score.value = 88
//Assign a new value to the placeholder, this also be emitted
player.value = lori
//Check how flatmap is still listening the changes at the past value
scott.score.value = 95
}
exampleOf("FlatMapLatest") {
// Dispose bag
let disposeBag = DisposeBag()
//Example Struct
struct Player {
let score: Variable<Int>
}
let scott = Player(score: Variable(80))
let lori = Player(score: Variable(90))
//This is the variable which we will be subscribe to, it's kind of a placeholder
var player = Variable(scott)
player.asObservable()
.flatMapLatest{$0.score.asObservable()}
.subscribe(onNext: {print($0)},
onError: {error in},
onCompleted: nil,
onDisposed: nil)
.addDisposableTo(disposeBag)
//Change the subscribed variable value
player.value.score.value = 85
//Change the current player value directly
scott.score.value = 88
//Assign a new value to the placeholder, this also be emitted
player.value = lori
//Check how flatmaplatest won't listen the changes at the past value, only at the current value inside our placeholder
scott.score.value = 95
lori.score.value = 100
player.value.score.value = 105
}
}
func basics()
{
//MARK: Observable sequences
exampleOf("just"){
let observable = Observable.just("Que Pasa AKI")
observable.subscribe({ (event : Event<String>) in
print(event)
})
}
exampleOf("of") {
let observable = Observable.of(1,2,3)
observable.subscribe({ print($0) })
}
//Converting an array of elements to an observable sequence
exampleOf("toObservable"){
let numbers = [1,2,3,4,5]
let source = Observable.from(numbers)
let disposeBag = DisposeBag()
let subscription: Disposable = source.subscribe(onNext: { (event) in
print(event)
}, onError: { (error) in
}, onCompleted: {
}, onDisposed: {
})
subscription.addDisposableTo(disposeBag)
}
//MARK: Working with subjects
/*
Publish: publish subjects emits only new items to its subscriber , in other words, elements added to a publish subject before a subscription is creted will not be emitted.
*/
exampleOf("PublishSubject") {
let subject = PublishSubject<String>()
subject.subscribe({
print($0)
})
enum MyError: Error
{
case Test
}
subject.onNext("Hello")
//subject.onCompleted()
//subject.onError(MyError.Test)
subject.onNext("World")
let newSubscription = subject.subscribe(onNext: {print("New subscription:",$0)
},
onError: { (Error) in
},
onCompleted: {
},
onDisposed: {
})
subject.onNext("what's up")
//newSubscription.dispose()
subject.onNext("Still There?")
}
exampleOf("BehaviorObject") {
let subject = BehaviorSubject(value: "a")
let firstSubscription = subject.subscribe(onNext: {print(#line, $0)},
onError: {error in},
onCompleted: {},
onDisposed: {})
subject.onNext("b")
let secondSubscription = subject.subscribe(onNext: {print(#line, $0)},
onError: {error in},
onCompleted: {},
onDisposed: {})
}
exampleOf("ReplaySubject"){
let subject = ReplaySubject<Int>.create(bufferSize: 3)
subject.onNext(1)
subject.onNext(2)
subject.onNext(3)
subject.onNext(4)
subject.subscribe(onNext: {print($0)},
onError: {error in },
onCompleted: {},
onDisposed: {})
}
exampleOf("Variable"){
let disposeBag = DisposeBag()
let variable = Variable("A")
variable.asObservable().subscribe(onNext: {print($0)},
onError: {Error in },
onCompleted: {},
onDisposed: {}).addDisposableTo(disposeBag)
variable.value = "B"
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func exampleOf(_ description: String, action: (Void) -> Void)
{
print("\n--- Example of: ", description, "---")
action()
}
}
| cc0-1.0 | d5f09208324f335a9d1143c31d87a525 | 32.963731 | 180 | 0.429977 | 5.852679 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ApplePlatform/ImageIO/AVDepthData.swift | 1 | 2884 | //
// AVDepthData.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
#if canImport(CoreGraphics) && canImport(ImageIO) && canImport(AVFoundation) && !os(watchOS)
@available(macCatalyst 14.0, *)
extension AVDepthData {
public convenience init<T>(texture: StencilTexture<T>, metadata: CGImageMetadata? = nil) throws {
var description: [AnyHashable: Any] = [:]
description[kCGImagePropertyPixelFormat] = kCVPixelFormatType_DepthFloat32
description[kCGImagePropertyWidth] = texture.width
description[kCGImagePropertyHeight] = texture.height
description[kCGImagePropertyBytesPerRow] = 4 * texture.width
let pixels = texture.pixels as? MappedBuffer<Float> ?? texture.pixels.map(Float.init)
var dictionary: [AnyHashable: Any] = [
kCGImageAuxiliaryDataInfoData: pixels.data as CFData,
kCGImageAuxiliaryDataInfoDataDescription: description
]
if let metadata = metadata {
dictionary[kCGImageAuxiliaryDataInfoMetadata] = metadata
}
try self.init(fromDictionaryRepresentation: dictionary)
}
}
extension CGImageRep {
@available(macCatalyst 14.0, *)
public var disparityData: AVDepthData? {
guard let info = self.auxiliaryDataInfo(kCGImageAuxiliaryDataTypeDisparity as String) else { return nil }
return try? AVDepthData(fromDictionaryRepresentation: info)
}
@available(macCatalyst 14.0, *)
public var depthData: AVDepthData? {
guard let info = self.auxiliaryDataInfo(kCGImageAuxiliaryDataTypeDepth as String) else { return nil }
return try? AVDepthData(fromDictionaryRepresentation: info)
}
}
#endif
| mit | efa9cdac5c718c918755e952a253d721 | 40.2 | 113 | 0.709085 | 4.607029 | false | false | false | false |
kinetic-fit/sensors-swift-trainers | Sources/SwiftySensorsTrainers/KineticService.swift | 1 | 3733 | //
// KineticService.swift
// SwiftySensorsTrainers
//
// https://github.com/kinetic-fit/sensors-swift-trainers
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import CoreBluetooth
import SwiftySensors
open class KineticService: Service, ServiceProtocol {
public static var uuid: String { return "E9410300-B434-446B-B5CC-36592FC4C724" }
public static var characteristicTypes: Dictionary<String, Characteristic.Type> = [
Configuration.uuid: Configuration.self,
ControlPoint.uuid: ControlPoint.self,
Debug.uuid: Debug.self,
SystemWeight.uuid: SystemWeight.self
]
public var configuration: Configuration? { return characteristic() }
public var controlPoint: ControlPoint? { return characteristic() }
public var debug: Debug? { return characteristic() }
public var systemWeight: SystemWeight? { return characteristic() }
open class Configuration: Characteristic {
public static let uuid: String = "E9410301-B434-446B-B5CC-36592FC4C724"
public var config: KineticSerializer.KineticConfig?
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
config = KineticSerializer.readConfig(value)
}
super.valueUpdated()
}
}
open class ControlPoint: Characteristic {
public static let uuid: String = "E9410302-B434-446B-B5CC-36592FC4C724"
public var response: KineticSerializer.KineticControlPointResponse?
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
response = KineticSerializer.readControlPointResponse(value)
}
super.valueUpdated()
}
}
open class Debug: Characteristic {
public static let uuid: String = "E9410303-B434-446B-B5CC-36592FC4C724"
public var debugData: KineticSerializer.KineticDebugData?
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.notify(true)
}
override open func valueUpdated() {
if let value = cbCharacteristic.value {
debugData = KineticSerializer.readDebugData(value)
}
super.valueUpdated()
}
}
open class SystemWeight: Characteristic {
public static let uuid: String = "E9410304-B434-446B-B5CC-36592FC4C724"
required public init(service: Service, cbc: CBCharacteristic) {
super.init(service: service, cbc: cbc)
cbCharacteristic.read()
}
private(set) var weight: UInt8 = 0
override open func valueUpdated() {
if let value = cbCharacteristic.value?.first {
weight = value
}
super.valueUpdated()
}
}
public func writeSensorName(_ deviceName: String) {
if let controlPoint = controlPoint {
let bytes = KineticSerializer.setDeviceName(deviceName)
controlPoint.cbCharacteristic.write(Data(bytes), writeType: .withResponse)
}
}
}
| mit | 3f4e22db4b9c7662c6b1d56389af6e1d | 31.172414 | 86 | 0.602894 | 4.809278 | false | true | false | false |
dander521/ShareTest | Uhome/Classes/Module/ProjectHouses/View/HouseTableViewCell.swift | 1 | 1762 | //
// HouseTableViewCell.swift
// Uhome
//
// Created by 程荣刚 on 2017/9/7.
// Copyright © 2017年 menhao. All rights reserved.
//
import UIKit
import SDWebImage
class HouseTableViewCell: UITableViewCell {
@IBOutlet weak var houseImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var conditionLabel: UILabel!
@IBOutlet weak var giftImageView: UIImageView!
@IBOutlet weak var customerImpressionLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
open var model:HouseModel? {
didSet {
self.houseImageView.sd_setImage(with: URL(string: hostAddress + (model?.img_url)!), placeholderImage: UIImage.init(named: "ic_tab_home_default"), options: .retryFailed, completed: { (image, error, cacheType, imageURL) in
})
self.nameLabel.text = model?.title
self.conditionLabel.text = model?.mianji
self.customerImpressionLabel.text = model?.huxing
self.priceLabel.text = model?.rent
}
}
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
}
class func cellWithTableView(tableView: UITableView) -> HouseTableViewCell {
let cellId = "HouseTableViewCell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellId)
if cell == nil {
cell = Bundle.main.loadNibNamed("HouseTableViewCell", owner: self, options: nil)?.first as! HouseTableViewCell
}
return cell as! HouseTableViewCell
}
}
| mit | 3abc7fe9988fad3676450bee1909a25f | 32.075472 | 232 | 0.656589 | 4.637566 | false | false | false | false |
arvedviehweger/swift | benchmark/single-source/Prefix.swift | 1 | 5963 | //===--- Prefix.swift -----------------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to Prefix.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let prefixCount = sequenceCount - 1024
let sumCount = prefixCount * (prefixCount - 1) / 2
@inline(never)
public func run_PrefixCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixCountableRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixSequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySeqCntRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySeqCRangeIter: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnyCollection: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixArray: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixCountableRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixSequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySeqCntRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnySeqCRangeIterLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixAnyCollectionLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_PrefixArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.prefix(prefixCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in PrefixArrayLazy: \(result) != \(sumCount)")
}
}
| apache-2.0 | 1aa94c3ad676b886cd6359e72ba3f3e7 | 30.057292 | 91 | 0.615127 | 3.882161 | false | false | false | false |
Johennes/firefox-ios | Client/Frontend/Widgets/ActionOverlayTableViewCell.swift | 1 | 3386 | /* 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
struct ActionOverlayTableViewCellUX {
static let LabelColor = UIConstants.SystemBlueColor
static let BorderWidth: CGFloat = CGFloat(0.5)
static let CellSideOffset = 20
static let TitleLabelOffset = 10
static let CellTopBottomOffset = 12
static let StatusIconSize = 24
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let CornerRadius: CGFloat = 3
}
class ActionOverlayTableViewCell: UITableViewCell {
lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMedium
titleLabel.textColor = ActionOverlayTableViewCellUX.LabelColor
titleLabel.textAlignment = .Left
titleLabel.numberOfLines = 1
return titleLabel
}()
lazy var statusIcon: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.ScaleAspectFit
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = ActionOverlayTableViewCellUX.CornerRadius
return siteImageView
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = ActionOverlayTableViewCellUX.SelectedOverlayColor
selectedOverlay.hidden = true
return selectedOverlay
}()
override var selected: Bool {
didSet {
self.selectedOverlay.hidden = !selected
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
isAccessibilityElement = true
contentView.addSubview(selectedOverlay)
contentView.addSubview(titleLabel)
contentView.addSubview(statusIcon)
let separatorLineView = UIView(frame:CGRectMake(0, 0, contentView.frame.width, 0.25))
separatorLineView.backgroundColor = UIColor.grayColor()
contentView.addSubview(separatorLineView)
selectedOverlay.snp_remakeConstraints { make in
make.edges.equalTo(contentView)
}
titleLabel.snp_remakeConstraints { make in
make.leading.equalTo(contentView).offset(12)
make.trailing.equalTo(statusIcon.snp_leading)
make.centerY.equalTo(contentView)
}
statusIcon.snp_remakeConstraints { make in
make.size.equalTo(ActionOverlayTableViewCellUX.StatusIconSize)
make.trailing.equalTo(contentView).inset(12)
make.centerY.equalTo(contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureCell(label: String, imageString: String) {
titleLabel.text = label
if let uiImage = UIImage(named: imageString) {
let image = uiImage.imageWithRenderingMode(.AlwaysTemplate)
statusIcon.image = image
statusIcon.tintColor = UIConstants.SystemBlueColor
}
}
}
| mpl-2.0 | c42c02c6f5788d09c9803c4442015576 | 33.907216 | 93 | 0.689014 | 5.209231 | false | false | false | false |
googlemaps/maps-sdk-for-ios-samples | GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/TrafficMapViewController.swift | 1 | 990 | // Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GoogleMaps
import UIKit
class TrafficMapViewController: UIViewController {
private var mapView: GMSMapView = {
let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12)
let mapView = GMSMapView(frame: .zero, camera: camera)
mapView.isTrafficEnabled = true
return mapView
}()
override func loadView() {
view = mapView
}
}
| apache-2.0 | 6bf76887e24814587d27c17945c9e53d | 32 | 91 | 0.734343 | 4.323144 | false | false | false | false |
lucdion/aide-devoir | sources/AideDevoir/Classes/Domain/Services/DataService.swift | 1 | 89444 | //
// DataService.swift
// AideDevoir
//
// Created by Luc Dion on 2016-10-23.
// Copyright © 2016 Mirego. All rights reserved.
//
import Firebase
import RxSwift
class DataService: NSObject {
static let instance = DataService()
fileprivate let ref = Database.database().reference()
fileprivate var refHomeworks: DatabaseReference!
fileprivate var localHomeworks: [Homework] = []
// fileprivate let homeworksDirectoryURL: URL
var homeworks: Variable<[Homework]> = Variable([])
fileprivate override init() {
// let documentDirURL = try FileManager.default.url(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask, appropriateFor: nil, create: true)
// homeworksDirectoryURL = documentDirURL.appendingPathComponent("homeworks")
super.init()
initFirebase()
//initDirectories()
addHomeworks()
}
fileprivate func initFirebase() {
refHomeworks = ref.child("homeworks")
refHomeworks.observe(.value, with: { (snapshot) in
var newHomeworks: [Homework] = []
if snapshot.value != nil {
for snapshot in snapshot.children.allObjects as! [DataSnapshot] {
print("rest.key: \(snapshot.key)")
print(snapshot.value ?? "")
if let homework = Homework(snapshot: snapshot) {
newHomeworks.append(homework)
}
}
newHomeworks.append(contentsOf: self.localHomeworks)
self.homeworks.value = newHomeworks
}
})
}
// fileprivate func initDirectories() {
// if !FileManager.default.fileExists(atPath: homeworksDirectoryURL.path) {
// do {
// try FileManager.default.createDirectory(at: homeworksDirectoryURL, withIntermediateDirectories: true, attributes: nil)
// } catch let error as NSError {
// print("Failed writing to create directory: \(homeworksDirectoryURL), Error: " + error.localizedDescription)
// }
// }
// }
/*func loadHomeworks() {
do {
let files = try FileManager.default.contentsOfDirectory(at: homeworksDirectoryURL, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsSubdirectoryDescendants)
for fileURL in files {
do {
let jsonData = try Data(contentsOf: fileURL)
if let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : Any] {
let homework = try Homework(JSON: jsonResult)
localHomeworks.append(homework)
print("homework: \(homework)")
}
} catch let error as NSError {
print("Cannot read file URL: \(fileURL), Error: " + error.localizedDescription)
}
}
} catch let error as NSError {
print("Failed writing to URL: \(homeworksDirectoryURL), Error: " + error.localizedDescription)
}
}*/
func save(homework: Homework) -> Error? {
let refHomework = homework.ref ?? refHomeworks.childByAutoId()
refHomework.setValue(homework.toJSON()) { (error, _) in
if error != nil {
assert(false)
}
}
return nil
}
func deleteHomework(homework: Homework) {
guard let ref = homework.ref else { return }
ref.removeValue { (error, _) in
if error != nil {
assert(false)
}
}
}
// fileprivate func deleteHomeworkJSON(homework: Homework) {
// let fileURL = url(forHomework: homework)
//
// if FileManager.default.fileExists(atPath: fileURL.path) {
// do {
// try FileManager.default.removeItem(at: fileURL)
// } catch let exception {
// print("deleteHomeworkJSON exception: \(exception)")
// }
// }
// }
// fileprivate func url(forHomework homework: Homework) -> URL {
// return homeworksDirectoryURL.appendingPathComponent("\(homework.id).json")
// }
fileprivate func addLocal(homework: Homework) {
// _ = save(homework: homework)
localHomeworks.append(homework)
}
fileprivate func addHomeworks() {
/*addLocal(homework: Homework(id: "0", name: "Dictée 1", entries: [
WordEntry(word: "arriver", sentence: "arriver à l'infinitif"),
WordEntry(word: "aventure", sentence: "Il part à l'aventure"),
WordEntry(word: "capitale", sentence: "Québec est la capitale du Québec"),
WordEntry(word: "chez", sentence: "Il est chez lui"),
WordEntry(word: "drôle", sentence: "Il est drôle"),
WordEntry(word: "éclatent", sentence: "Les ballons éclatent"),
WordEntry(word: "en", sentence: "Il en mange beaucoup"),
WordEntry(word: "façon", sentence: "Il a de drôle de façon"),
WordEntry(word: "français", sentence: ""),
WordEntry(word: "France", sentence: ""),
WordEntry(word: "leur", sentence: "C'est leur ballon"),
WordEntry(word: "longtemps", sentence: "Il y a longtemps que je t'aime"),
WordEntry(word: "parle", sentence: "Il parle à son ami"),
WordEntry(word: "Québec", sentence: "La province de Québec", isCaseSensitive: true),
WordEntry(word: "raconter", sentence: "raconter à l'infinitif"),
WordEntry(word: "retrouve", sentence: "Il retrouve son meilleur ami"),
WordEntry(word: "souviendront", sentence: "Les enfants se souviendront de leur enfance"),
WordEntry(word: "soudain", sentence: ""),
WordEntry(word: "voyage", sentence: "")
]))*/
/*addLocal(homework: Homework(id: "1", name: "Dictée 6", entries: [
WordEntry(word: "admirer", sentence: "admirer à l'infinitif"),
WordEntry(word: "automne", sentence: ""),
WordEntry(word: "admirerons", sentence: "Nous admirerons les statuts"),
WordEntry(word: "charmante", sentence: "Cette fille est charmante"),
WordEntry(word: "chasse", sentence: "La chasse au lapin"),
WordEntry(word: "commencerons", sentence: "nous commencerons les premiers"),
WordEntry(word: "est", sentence: "Elle est belle"),
WordEntry(word: "feuille", sentence: "Une feuille d'automne"),
WordEntry(word: "fois", sentence: "Il était une fois"),
WordEntry(word: "fusil", sentence: "Un fusil de chasse"),
WordEntry(word: "grande", sentence: "La grande porte"),
WordEntry(word: "heureusement", sentence: ""),
WordEntry(word: "intéressante", sentence: ""),
WordEntry(word: "irons", sentence: "nous irons au bois"),
WordEntry(word: "jusqu'à", sentence: "Continue jusqu'-à ce que tu arrives au bois"),
WordEntry(word: "là-bas", sentence: "Regarde là-bas"),
WordEntry(word: "lentement", sentence: "Marche lentement."),
WordEntry(word: "marcherons", sentence: "nous marcherons dans le bois"),
WordEntry(word: "moi", sentence: ""),
WordEntry(word: "pas", sentence: "Ne pas faire cela"),
WordEntry(word: "notre", sentence: "C'est notre fusil de chasse"),
WordEntry(word: "petite", sentence: ""),
WordEntry(word: "pont", sentence: "Sur le pont d'Avignon"),
WordEntry(word: "près", sentence: "Il hâbite près du bois"),
WordEntry(word: "prix", sentence: "Le prix est très élevé"),
WordEntry(word: "saison", sentence: "C'est la saison de la chasse"),
WordEntry(word: "très", sentence: "Il est très beau ce camion"),
WordEntry(word: "verte", sentence: "Une belle pomme verte"),
WordEntry(word: "voisine", sentence: "La voisine est partie"),
WordEntry(word: "voulons", sentence: "Nous voulons manger du lapin")
]))
addLocal(homework: Homework(id: "2", name: "Dictée 7", entries: [
WordEntry(word: "quand", sentence: "Quand as-tu fait ce dessin?"),
WordEntry(word: "aimerais", sentence: "J'aimerais avoir des bonbons."),
WordEntry(word: "bête", sentence: "J'ai vu une bête dans les bois."),
WordEntry(word: "blanche", sentence: "Où est la maison blanche?"),
WordEntry(word: "bleue", sentence: "J'ai acheté une robe bleue."),
WordEntry(word: "campagne", sentence: "Je vais à la campagne."),
WordEntry(word: "canard", sentence: "J'aime le canard!"),
WordEntry(word: "certainement", sentence: "Je suis certainement le meilleur."),
WordEntry(word: "commencerais", sentence: "Je commencerais bien un dessin."),
WordEntry(word: "dangereux", sentence: "Ce monstre est dangereux."),
WordEntry(word: "distraite", sentence: "Je suis distraite."),
WordEntry(word: "seriez", sentence: "Vous seriez fiers de moi."),
WordEntry(word: "faudrait", sentence: "Il faudrait faire vite."),
WordEntry(word: "ferme", sentence: "Je vais à la ferme."),
WordEntry(word: "grand", sentence: "Je suis le plus grand."),
WordEntry(word: "grange", sentence: "Le foin est dans la grange."),
WordEntry(word: "laitière", sentence: "L'industrie laitière nous donne du lait."),
WordEntry(word: "loup", sentence: "Je n'ai pas peur du loup"),
WordEntry(word: "mare", sentence: "Les canards sont dans la mare."),
WordEntry(word: "nourrir", sentence: "Il faut bien se nourrir."),
WordEntry(word: "oie", sentence: "Une oie est une volaille"),
WordEntry(word: "parfois", sentence: "Parfois des outardes passent par là."),
WordEntry(word: "peur", sentence: "J'ai peur des clowns."),
WordEntry(word: "quelques", sentence: "J'ai écrit quelques phrases."),
WordEntry(word: "renard", sentence: "J'aime les renards."),
WordEntry(word: "roi", sentence: "Le roi est avec la reine."),
WordEntry(word: "sauvage", sentence: "Les loups sont sauvages."),
WordEntry(word: "surveiller", sentence: "Il faut toujours surveiller un chien."),
WordEntry(word: "toi", sentence: "J'aime jouer avec toi."),
WordEntry(word: "tôt", sentence: "Je me lève tôt."),
WordEntry(word: "veau", sentence: "J'aime les veaux."),
WordEntry(word: "vie", sentence: "La vie est précieuse."),
WordEntry(word: "", sentence: "")
]))
addLocal(homework: Homework(id: "3", name: "Dictée Isabelle", entries: [
WordEntry(word: "à côté", sentence: "Reste à côté de moi"),
WordEntry(word: "alors", sentence: "j'ai faim, alors je mange"),
WordEntry(word: "après", sentence: "je viendrai après l'école"),
WordEntry(word: "assez", sentence: " j'en ai assez!"),
WordEntry(word: "aucun", sentence: "il ne me reste aucun crayon"),
WordEntry(word: "aujourd'hui", sentence: "j'y vais aujourd'hui"),
WordEntry(word: "aussi", sentence: " tu viens toi aussi"),
WordEntry(word: "aussitôt", sentence: "je viendrai aussitôt que j'aurai terminé"),
WordEntry(word: "autour", sentence: "la lune tourne autour de la Terre"),
WordEntry(word: "avant", sentence: "ma fête est avant la tienne"),
WordEntry(word: "avec", sentence: "Veux-tu jouer avec moi"),
WordEntry(word: "beaucoup", sentence: "je t'aime beaucoup"),
WordEntry(word: "bientôt", sentence: "Mamie arrive bientôt"),
WordEntry(word: "chaque", sentence: "chaque joueur reçoit 5 cartes"),
WordEntry(word: "chez", sentence: "je dormirai chez toi"),
WordEntry(word: "combien", sentence: "combien as-tu d'argent?"),
WordEntry(word: "comme", sentence: "mon chandail est comme le tien"),
WordEntry(word: "dehors", sentence: "allons jouer dehors!"),
WordEntry(word: "déjà", sentence: "J'ai déjà vu ce film"),
WordEntry(word: "demain", sentence: "demain c'est la dictée"),
WordEntry(word: "depuis", sentence: "je viens ici depuis que je suis tout petit"),
WordEntry(word: "durant", sentence: "il est interdit de jouer durant les heures de classe"),
WordEntry(word: "encore", sentence: "j'ai encore échappé mon efface"),
WordEntry(word: "est-ce que", sentence: "est-ce que tu as vu mon frère?"),
WordEntry(word: "là", sentence: "Il est là"),
WordEntry(word: "lentement", sentence: "Avance lentement"),
WordEntry(word: "loin", sentence: "tu es rendu trop loin"),
WordEntry(word: "longtemps", sentence: "il y a longtemps que je t'aime"),
WordEntry(word: "lorsque", sentence: "regarde bien lorsque tu traverse"),
WordEntry(word: "maintenant", sentence: "j'ai maintenant 10 ans"),
WordEntry(word: "mais", sentence: "la soupe est bonne mais elle est trop froide"),
WordEntry(word: "même", sentence: "j'ai le même vélo que toi"),
WordEntry(word: "mes", sentence: "mes lacets sont détachés"),
WordEntry(word: "mieux", sentence: "écris mieux que ça!"),
WordEntry(word: "nos", sentence: "Nos poules ont pondu ce matin"),
WordEntry(word: "notre", sentence: "notre chien est parti"),
WordEntry(word: "parfois", sentence: "j'ai parfois peur la nuit"),
WordEntry(word: "partout", sentence: "il y a des pissenlits partout"),
WordEntry(word: "pendant", sentence: "j'y irai pendant les vacances"),
WordEntry(word: "peut-être", sentence: "J'y irai peut-être demain"),
WordEntry(word: "plein", sentence: "mon verre est trop plein"),
WordEntry(word: "plusieurs", sentence: "j'ai plusieurs jeux de cartes"),
WordEntry(word: "pourquoi", sentence: "pourquoi dis-tu cela?"),
WordEntry(word: "pourtant", sentence: "Je l'ai pourtant mis là"),
WordEntry(word: "près", sentence: "Viens plus près de moi"),
WordEntry(word: "presque", sentence: "J'ai presque terminé"),
WordEntry(word: "puis", sentence: "Et puis après?"),
WordEntry(word: "puisque", sentence: "Puisque tu ne viens pas, je pars sans toi."),
WordEntry(word: "qu'est-ce que", sentence: "qu'est-ce que tu manges?"),
WordEntry(word: "quand", sentence: "Quand as-tu fait ce dessin?"),
WordEntry(word: "quelqu'un", sentence: "Quelqu'un sonne à la porte"),
WordEntry(word: "quelque chose", sentence: "quelque chose vient de tomber"),
WordEntry(word: "sans", sentence: "Vas-y sans moi"),
WordEntry(word: "ses", sentence: "Il joue avec ses amis"),
WordEntry(word: "soudain", sentence: "Soudain, il lui vint une idée"),
WordEntry(word: "sous", sentence: "Cache-le sous ton lit"),
WordEntry(word: "dessous", sentence: "Mets un naperon dessous ton assiette"),
WordEntry(word: "souvent", sentence: "Je joue souvent à ce jeu"),
WordEntry(word: "sur", sentence: "Mets-le sur le comptoir"),
WordEntry(word: "tard", sentence: "Il est tard, vas te coucher."),
WordEntry(word: "tôt", sentence: "Je t'attendais plus tôt"),
WordEntry(word: "toujours", sentence: "Tu ris toujours de mes blagues"),
WordEntry(word: "tout à coup", sentence: "Tout à coup, il entendit un gros bruit"),
WordEntry(word: "très", sentence: "Je suis très fatigué"),
WordEntry(word: "trop", sentence: "J'ai trop froid!"),
WordEntry(word: "vers", sentence: "je regarde vers le ciel"),
WordEntry(word: "vite", sentence: "Marche moins vite"),
WordEntry(word: "voici", sentence: "Voici ma meilleure amie"),
WordEntry(word: "voilà", sentence: "Nous voilà arrivés"),
WordEntry(word: "vos", sentence: "Vos enfants sont magnifiques"),
WordEntry(word: "votre", sentence: "Votre chien m'a mordu"),
WordEntry(word: "année", sentence: "Bonne année"),
WordEntry(word: "autobus", sentence: "J'ai manqué l'autobus"),
WordEntry(word: "compter", sentence: "Je sans compter jusqu'à 100"),
WordEntry(word: "congé", sentence: "aujourd'hui, c'est congé!"),
WordEntry(word: "écouter", sentence: "J'aime écouter de la musique"),
WordEntry(word: "jeune", sentence: "tu es trop jeune pour apprendre à conduire"),
WordEntry(word: "nombre", sentence: "choisis un nombre entre 0 et 10"),
WordEntry(word: "photo", sentence: "Quelle belle photo!"),
WordEntry(word: "prix", sentence: "Quel est le prix de ce jouet"),
WordEntry(word: "souvenir", sentence: "j'en garde un bon souvenir"),
WordEntry(word: "stylo", sentence: "Écris avec un stylo bleu"),
WordEntry(word: "apprendre", sentence: "Il faut apprendre l'anglais"),
WordEntry(word: "balle", sentence: "Lance-moi la balle"),
WordEntry(word: "ballon", sentence: "où est mon ballon?"),
WordEntry(word: "commencer", sentence: "Je ne sais pas par où commencer"),
WordEntry(word: "cours", sentence: "J'ai pris un cours de natation"),
WordEntry(word: "dictée", sentence: "demain c'est la dictée"),
WordEntry(word: "faute", sentence: "Je n'ai pas fait de faute!"),
WordEntry(word: "genre", sentence: "À quel genre de jeu veux-tu jouer"),
WordEntry(word: "gens", sentence: "Où sont les gens que tu connais"),
WordEntry(word: "remettre", sentence: "Il faut remettre le travail demain"),
WordEntry(word: "réussir", sentence: "Il va réussir son cours."),
WordEntry(word: "rien", sentence: "je n'ai rien à faire"),
WordEntry(word: "septembre", sentence: "ma fête est le 7 septembre"),
WordEntry(word: "terminer", sentence: "Il doit terminer son repas."),
WordEntry(word: "alphabet", sentence: "je connais mon alphabet"),
WordEntry(word: "bureau", sentence: "mets-le sur mon bureau"),
WordEntry(word: "environ", sentence: "j'ai environ 30 billes dans mon sac"),
WordEntry(word: "épeler", sentence: "il faut épeler tous ces mots"),
WordEntry(word: "juste", sentence: "Ce n'est pas juste!"),
WordEntry(word: "marcher", sentence: "Il sont partis marcher"),
WordEntry(word: "ménage", sentence: "Je dois faire le ménage de ma chambre"),
WordEntry(word: "offrir", sentence: "J'ai offrir des fleurs à ma mère"),
WordEntry(word: "possible", sentence: "Ce n'est pas possible!"),
WordEntry(word: "professeur", sentence: "Qui est ton professeur"),
WordEntry(word: "quel", sentence: "À quel jeu veux-tu jouer?"),
WordEntry(word: "quels", sentence: "Avec quels crayons veux-tu dessiner?"),
WordEntry(word: "quelle", sentence: "Quelle tuque as-tu mis?"),
WordEntry(word: "quelles", sentence: "Quelles céréales préfères-tu?"),
WordEntry(word: "rencontré", sentence: "Je n'ai jamais rencontré tes parents"),
WordEntry(word: "robot", sentence: "Dessine-moi un robot"),
WordEntry(word: "sans que", sentence: "Je suis partie sans que tu t'en aperçoive"),
WordEntry(word: "timide", sentence: "Je suis tellement timide!"),
WordEntry(word: "articulation", sentence: "j'ai mal à cette articulation"),
WordEntry(word: "chaise", sentence: "cette chaise est trop haute"),
WordEntry(word: "chiffre", sentence: "choisis un chiffre entre 1 et 10"),
WordEntry(word: "comprends", sentence: "Je ne comprends pas"),
WordEntry(word: "enregistrer", sentence: "J'aimerais enregistrer cette émission"),
WordEntry(word: "facile", sentence: "C'est vraiment facile!"),
WordEntry(word: "futuriste", sentence: "Quelle voiture futuriste!"),
WordEntry(word: "laissé", sentence: "Il m'a laissé passer"),
WordEntry(word: "mauvais", sentence: "Ça sent mauvais!"),
WordEntry(word: "meilleur", sentence: "Je suis le meilleur!"),
WordEntry(word: "minute", sentence: "Attends une minute"),
WordEntry(word: "neuf", sentence: "J'ai un manteau neuf"),
WordEntry(word: "neuve", sentence: "J'ai une voiture neuve"),
WordEntry(word: "pièce", sentence: "as-tu vu ma pièce de cinq cents?"),
WordEntry(word: "prochaine", sentence: "À la prochaine!"),
WordEntry(word: "question", sentence: "J'ai une question à te poser"),
WordEntry(word: "abri", sentence: "Reste sous l'abri"),
WordEntry(word: "âge", sentence: "Tu as quel âge?"),
WordEntry(word: "allure", sentence: "Tout cela n'a pas d'allure!"),
WordEntry(word: "attention", sentence: "Fais très attention!"),
WordEntry(word: "bottes", sentence: "J'ai besoin de mes bottes de pluie"),
WordEntry(word: "corps", sentence: "J'ai des piqûres sur tout le corps"),
WordEntry(word: "cri", sentence: "J'ai entendu un grand cri"),
WordEntry(word: "enquête", sentence: "Les policiers mènent une enquête"),
WordEntry(word: "fraiche", sentence: "Quelle bonne eau fraiche"),
WordEntry(word: "frais", sentence: "Du bon pain frais"),
WordEntry(word: "méchant", sentence: "Le grand méchant loup"),
WordEntry(word: "mort", sentence: "Mon voisin est mort"),
WordEntry(word: "octobre", sentence: "L'Halloween est le 31 octobre"),
WordEntry(word: "aider", sentence: "Pourrais-tu m'aider?"),
WordEntry(word: "attrapé", sentence: "J'ai attrapé la balle!"),
WordEntry(word: "danger", sentence: "C'est un réel danger"),
WordEntry(word: "doigts", sentence: "J'ai mal à ces deux doigts"),
WordEntry(word: "désespérer", sentence: "Il ne faut jamais désespérer"),
WordEntry(word: "guerre", sentence: "Il y a de la guerre dans la monde"),
WordEntry(word: "horrible", sentence: "C'est vriment horrible!"),
WordEntry(word: "jambe", sentence: "Je me tiens sur une seule jambe"),
WordEntry(word: "joue", sentence: "je ne joue plus avec toi"),
WordEntry(word: "lancer", sentence: "J'ai du mal à lancer la balle"),
WordEntry(word: "métier", sentence: "Quel est ton métier?"),
WordEntry(word: "rejoindre", sentence: "J'irai te rejoindre plus tard"),
WordEntry(word: "transpirer", sentence: "Elle va beaucoup transpirer"),
WordEntry(word: "certain", sentence: "Es-tu certain?"),
WordEntry(word: "claire", sentence: "L'eau de ce lac est vraiment claire"),
WordEntry(word: "clair", sentence: "Quel beau clair de lune"),
WordEntry(word: "consoler", sentence: "Elle va me consoler"),
WordEntry(word: "courir", sentence: "J'aime beaucoup courir"),
WordEntry(word: "épais", sentence: "il y a un épais brouillard"),
WordEntry(word: "goutte", sentence: "Il n'y en a plus une seule goutte"),
WordEntry(word: "hauteur", sentence: "C'est la bonne hauteur"),
WordEntry(word: "lentement", sentence: "marche lentement"),
WordEntry(word: "lumière", sentence: "Allume la lumière"),
WordEntry(word: "spectaculaire", sentence: "C'était spectaculaire!"),
WordEntry(word: "clé", sentence: "Où as-tu mis la clé?"),
WordEntry(word: "d'abord", sentence: "Mange d'abord ton repas"),
WordEntry(word: "frapper", sentence: "Essaie de frapper la balle que je te lance"),
WordEntry(word: "habiter", sentence: "J'aime habiter à Montréal"),
WordEntry(word: "minuit", sentence: "Je me suis couché à minuit"),
WordEntry(word: "ombre", sentence: "Il est plus vite que son ombre"),
WordEntry(word: "réaction", sentence: "Ta réaction m'a étonné"),
WordEntry(word: "soigner", sentence: "Je me suis fait soigner"),
WordEntry(word: "terrifié", sentence: "Ce film m'a terrifié!"),
WordEntry(word: "amoureux", sentence: "Je suis amoureux de cette fille"),
WordEntry(word: "coins", sentence: "J'aime jouer au ballon 4 coins"),
WordEntry(word: "étonnant", sentence: "Quel fait étonnant!"),
WordEntry(word: "gorge", sentence: "J'ai mal à la gorge"),
WordEntry(word: "novembre", sentence: "En novembre, il fait froid"),
WordEntry(word: "or", sentence: "Un bague en or"),
WordEntry(word: "troisième", sentence: "Je suis en troisième année"),
WordEntry(word: "voyage", sentence: "Bon voyage!"),
WordEntry(word: "appartement", sentence: "Tu habites dans un appartement"),
WordEntry(word: "apporté", sentence: "J'ai apporté un cadeau"),
WordEntry(word: "cadeau", sentence: "J'ai apporté un cadeau"),
WordEntry(word: "rond", sentence: "Cesse de tourner en rond"),
WordEntry(word: "trésor", sentence: "C'est mon trésor"),
WordEntry(word: "collation", sentence: "As-tu amené une collation?"),
WordEntry(word: "genou", sentence: "J'ai un bobo sur le genou"),
WordEntry(word: "maladie", sentence: "Il a une maladie contagieuse"),
WordEntry(word: "mille", sentence: " J'ai gagné mille dollars "),
WordEntry(word: "millier", sentence: "Il y a un millier de fourmis"),
WordEntry(word: "millions", sentence: "Il y a 4 millions d'année"),
WordEntry(word: "oublié", sentence: "J'ai oublié son nom"),
WordEntry(word: "quelques-uns", sentence: "J'ai quelques-uns de ces jouets"),
WordEntry(word: "recevoir", sentence: "J'aime recevoir des amis à la maison"),
WordEntry(word: "rendre", sentence: "Veux-tu me rendre mon crayon"),
WordEntry(word: "saison", sentence: "J'aime la saison de l'été"),
WordEntry(word: "baigner", sentence: "On peut se baigner dans ce lac"),
WordEntry(word: "bonhomme", sentence: "Il manque un bonhomme dans ce jeu"),
WordEntry(word: "coquin", sentence: "Tu es vraiment coquin"),
WordEntry(word: "date", sentence: "Quelle date sommes-nous aujourd'hui? "),
WordEntry(word: "dattes", sentence: "J'aimes ces biscuits aux dattes"),
WordEntry(word: "décembre", sentence: "Jésus est né le 24 décembre"),
WordEntry(word: "hôpitaux", sentence: "On ne peut pas fumer dans les hôpitaux"),
WordEntry(word: "lèvre", sentence: "j'ai un bobo sur la lèvre"),
WordEntry(word: "après-midi", sentence: "C'est arrivé cet après-midi"),
WordEntry(word: "battre", sentence: "Il ne faut jamais se battre"),
WordEntry(word: "bonheur", sentence: "L'argent ne fait pas le bonheur"),
WordEntry(word: "buts", sentence: "J'ai compté plusieurs buts!"),
WordEntry(word: "château", sentence: "C'Est vrai château, ici!"),
WordEntry(word: "sac-à-dos", sentence: "Où est mon sac-à-dos?"),
WordEntry(word: "fil", sentence: "le funambule marche sur un fil"),
WordEntry(word: "Québec", sentence: "J'habite au Québec"),
WordEntry(word: "affaires", sentence: "Ce n'est pas de tes affaires!"),
WordEntry(word: "agneau", sentence: "La viande d'agneau est délicieuse"),
WordEntry(word: "bande", sentence: "vous êtes une bande de voyous!"),
WordEntry(word: "bête", sentence: "C'est une bête sauvage"),
WordEntry(word: "brutal", sentence: "Il a reçu un coup brutal"),
WordEntry(word: "dauphin", sentence: "Le chant du dauphin est magnifique"),
WordEntry(word: "fer", sentence: "Cet outil est en fer"),
WordEntry(word: "janvier", sentence: "Le premier mois de l'année est janvier"),
WordEntry(word: "lièvre", sentence: " le lièvre et la tortue"),
WordEntry(word: "lionne", sentence: "la femme du lion est la lionne"),
WordEntry(word: "manquer", sentence: "je vais manquer l'autobus"),
WordEntry(word: "pierres", sentence: "j'ai lancé toutes les pierres"),
WordEntry(word: "poil", sentence: "mon chat a un très beau poil"),
WordEntry(word: "ampoule", sentence: "il faut changer cette ampoule"),
WordEntry(word: "argent", sentence: "je n'ai pas assez d'argent"),
WordEntry(word: "chasseur", sentence: "je suis un chasseur de chevreuil"),
WordEntry(word: "courts", sentence: "j'ai les cheveux courts"),
WordEntry(word: "habileté", sentence: "C'est une habileté que j'aimerais avoir"),
WordEntry(word: "mètre", sentence: "je mesure plus d'un mètre"),
WordEntry(word: "poussin", sentence: "j'ai eu un poussin pour ma fête"),
WordEntry(word: "renard", sentence: "le renard roux est magnifique"),
WordEntry(word: "sabot", sentence: "le sabot du cheval"),
WordEntry(word: "approcher", sentence: "je l'ai entendu approcher"),
WordEntry(word: "bâton", sentence: "ne frappe personne avec ce bâton"),
WordEntry(word: "chant", sentence: "le chant de l'oiseau"),
WordEntry(word: "langue", sentence: "je ne parle pas cette langue"),
WordEntry(word: "mammifère", sentence: "l'homme est un mammifère"),
WordEntry(word: "moyen", sentence: "est-ce le bon moyen pour y arriver?"),
WordEntry(word: "occupé", sentence: "je suis occupé"),
WordEntry(word: "ours", sentence: "l'ours brun vit au Québec"),
WordEntry(word: "ourse", sentence: "La mère ourse a deux petits"),
WordEntry(word: "parc", sentence: "allons jouer au parc"),
WordEntry(word: "puissance", sentence: "la puissance de cette auto m'étonne"),
WordEntry(word: "service", sentence: "j'aime rendre service"),
WordEntry(word: "champ", sentence: "un beau champ de fleur"),
WordEntry(word: "malheur", sentence: "quel malheur!"),
WordEntry(word: "museau", sentence: "le museau du chien est froid"),
WordEntry(word: "nourriture", sentence: "il y a de la nourriture"),
WordEntry(word: "pâle", sentence: "tu es très pâle"),
WordEntry(word: "passage", sentence: "libérez le passage"),
WordEntry(word: "record", sentence: "je dois battre mon record"),
WordEntry(word: "remarqué", sentence: "je n'avais pas remarqué"),
WordEntry(word: "bain", sentence: "c'est l'heure du bain"),
WordEntry(word: "jouet", sentence: "où est mon jouet?"),
WordEntry(word: "magasin", sentence: "je dois aller au magasin"),
WordEntry(word: "nourrir", sentence: "je vais nourrir mees poules"),
WordEntry(word: "poids", sentence: "mon poids est le même que le tien"),
WordEntry(word: "restaurant", sentence: "allons au restaurant!"),
WordEntry(word: "vacances", sentence: "c'est les vacances!"),
WordEntry(word: "glisser", sentence: "Je vais glisser sur cette glissoire"),
WordEntry(word: "village", sentence: "c'est mon village"),
WordEntry(word: "rabais", sentence: "il est en rabais"),
WordEntry(word: "journaux", sentence: "on le dit dans les journaux"),
WordEntry(word: "jeter", sentence: "ne pas jeter de déchets ici"),
WordEntry(word: "jus", sentence: "du jus s'il vous plait"),
WordEntry(word: "marché", sentence: "allons au Marché Jean-Talon"),
WordEntry(word: "moitié", sentence: "J'en ai gardé la moitié"),
WordEntry(word: "nouveauté", sentence: "c'est une nouveauté"),
WordEntry(word: "rayon", sentence: "dans le rayon des fruits et légumes"),
WordEntry(word: "terrain", sentence: "le terrain de soccer"),
WordEntry(word: "vêtements", sentence: "range tes vêtements"),
WordEntry(word: "boire", sentence: "je vais boire de l'eau"),
WordEntry(word: "permettre", sentence: "dois-je te le permettre?"),
WordEntry(word: "plastique", sentence: "Un plat de plastique"),
WordEntry(word: "repas", sentence: "mon repas est bon"),
WordEntry(word: "santé", sentence: "je suis en santé"),
WordEntry(word: "schéma", sentence: "fais un schéma pour illustrer ce problème"),
WordEntry(word: "contexte", sentence: "dans quel contexte?"),
WordEntry(word: "bateau", sentence: "je regarde le bateau sur l'eau"),
WordEntry(word: "descendre", sentence: "il faut descendre la pente"),
WordEntry(word: "fixe", sentence: "je fixe un point au loin"),
WordEntry(word: "gentil", sentence: "mon ami est gentil"),
WordEntry(word: "haut", sentence: "c'est trop haut pour moi"),
WordEntry(word: "pile", sentence: "il est 10 heures pile"),
WordEntry(word: "ruisseau", sentence: "l'eau du ruisseau est froide"),
WordEntry(word: "semble", sentence: "il me semble que oui"),
WordEntry(word: "zoo", sentence: "j'aime aller au zoo"),
WordEntry(word: "bord", sentence: "au bord de la mer"),
WordEntry(word: "découvrir", sentence: "j'aime découvrir de nouvelles choses"),
WordEntry(word: "matelot", sentence: "j'ai déjà été matelot"),
WordEntry(word: "mer", sentence: "au bord de la mer"),
WordEntry(word: "mère", sentence: "ma mère ne veut pas"),
WordEntry(word: "mousse", sentence: "il y a de la mousse sur ces roches"),
WordEntry(word: "murmures", sentence: "j'entends des murmures"),
WordEntry(word: "surface", sentence: "la surface est lisse"),
WordEntry(word: "tour", sentence: "c'est à mon tour à jouer"),
WordEntry(word: "vue", sentence: "j'ai une très bonne vue"),
WordEntry(word: "mois", sentence: "nous sommes rendus quel mois"),
WordEntry(word: "protéger", sentence: "j'ai protéger mon livre de la pluie"),
WordEntry(word: "retard", sentence: "n'arrive pas en retard"),
WordEntry(word: "salut", sentence: "salut mon ami!"),
WordEntry(word: "son", sentence: "baisse le son de la radio"),
WordEntry(word: "vitesse", sentence: "il roule à grande vitesse"),
WordEntry(word: "algue", sentence: "cette plante est une algue"),
WordEntry(word: "danser", sentence: "j'aime danser"),
WordEntry(word: "penché", sentence: "je me suis penché pour le ramasser"),
WordEntry(word: "pin", sentence: "cet arbre est un pin"),
WordEntry(word: "pleuvoir", sentence: "il va bientôt pleuvoir"),
WordEntry(word: "rêvé", sentence: "j'ai rêvé que j'étais riche"),
WordEntry(word: "sec", sentence: "mon chandail est sec"),
WordEntry(word: "sèche", sentence: "ma robe est sèche"),
WordEntry(word: "soirée", sentence: "quelle belle soirée"),
WordEntry(word: "ventre", sentence: "j'ai mal au ventre"),
WordEntry(word: "cause", sentence: "qu'est-ce qui cause tout cela?"),
WordEntry(word: "conte", sentence: "j'ai lu ce conte plusieurs fois"),
WordEntry(word: "compte", sentence: "je compte sur mes doigts"),
WordEntry(word: "dès que", sentence: "dès que j'arrive, je t'appelle"),
WordEntry(word: "fiction", sentence: "ce film est une fiction"),
WordEntry(word: "important", sentence: "c'est important!"),
WordEntry(word: "coque", sentence: "des oeufs à la coque"),
WordEntry(word: "droit", sentence: "j'ai le droit d'y aller"),
WordEntry(word: "droit", sentence: "c'est du côté droit"),
WordEntry(word: "fleuve", sentence: "le fleuve Saint-Laurent"),
WordEntry(word: "fond", sentence: "je touche au fond"),
WordEntry(word: "mai", sentence: "ma fête est le 5 mai"),
WordEntry(word: "morceau", sentence: "il manque un morceau"),
WordEntry(word: "nid", sentence: "ma poule a pondu dans son nid"),
WordEntry(word: "pantalon", sentence: "c'est mon pantalon"),
WordEntry(word: "verser", sentence: "il faut verser tranquillement"),
WordEntry(word: "avancer", sentence: "tu dois avancer"),
WordEntry(word: "choix", sentence: "c'est ton choix"),
WordEntry(word: "couleur", sentence: "c'est ma couleur préférée"),
WordEntry(word: "exemple", sentence: "donne-moi un exemple"),
WordEntry(word: "herbe", sentence: "le lapin mange de l'herbe"),
WordEntry(word: "imprimé", sentence: "ce livre est imprimé au Québec"),
WordEntry(word: "juin", sentence: "l'école finit en juin"),
WordEntry(word: "mourir", sentence: "je souhaite mourir vieux"),
WordEntry(word: "part", sentence: "c'est ma part de gâteau"),
WordEntry(word: "point", sentence: "Mets un point à la fin de la phrase"),
WordEntry(word: "rappeler", sentence: "tu dois me rappeler plus tard"),
WordEntry(word: "salle", sentence: "la fête a lieu dans la grande salle"),
WordEntry(word: "scénario", sentence: "j'ai écrit le scénario de ce film"),
WordEntry(word: "sujet", sentence: "le sujet de ce livre m'intéresse"),
WordEntry(word: "tranquille", sentence: "reste tranquille"),
WordEntry(word: "juillet", sentence: "je pars en vacances en juillet"),
WordEntry(word: "naissance", sentence: "c'est ma date de naissance"),
WordEntry(word: "promettre", sentence: "tu dois me le promettre"),
WordEntry(word: "promets", sentence: "je promets d'être là"),
WordEntry(word: "réveillé", sentence: "je me suis réveillé tôt"),
WordEntry(word: "souhaites", sentence: "tu souhaites venir chez moi"),
WordEntry(word: "sourcils", sentence: "mes sourcils sont bruns"),
WordEntry(word: "spectacle", sentence: "quel beau spectacle"),
WordEntry(word: "pot", sentence: "le beau pot de fleur"),
WordEntry(word: "remplir", sentence: "je vais remplir ton verre d'eau"),
WordEntry(word: "retenir", sentence: "je dois me retenir"),
WordEntry(word: "trottoir", sentence: "il y a un nouveau trottoir"),
WordEntry(word: "août", sentence: "l'école commenc en août"),
WordEntry(word: "posséder", sentence: "j'aimerais posséder cette maison"),
WordEntry(word: "présente", sentence: "je vous présente mon amie Julie"),
WordEntry(word: "soie", sentence: "C'est doux comme de la soie"),
WordEntry(word: "téléphone", sentence: "Où est mon téléphone?"),
WordEntry(word: "verre", sentence: "veux tu un verre d'eau?"),
WordEntry(word: "vinaigre", sentence: "je mets du vinaigre dans ma poutine")
]))*/
/*addLocal(homework: Homework(id: "5", name: "Éloi", entries: [
WordEntry(word: "lune", sentence: "la lune"),
WordEntry(word: "ami", sentence: "ami au masculin"),
WordEntry(word: "papa", sentence: "mon papa"),
WordEntry(word: "rue", sentence: "la rue"),
WordEntry(word: "robe", sentence: "la robe"),
WordEntry(word: "livres", sentence: "les livres"),
WordEntry(word: "table", sentence: "la table"),
WordEntry(word: "lire", sentence: "lire"),
WordEntry(word: "vie", sentence: "ma vie"),
WordEntry(word: "dame", sentence: "les dames"),
WordEntry(word: "têtes", sentence: "les têtes"),
WordEntry(word: "père", sentence: "père"),
WordEntry(word: "mère", sentence: "mère"),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: ""),
WordEntry(word: "", sentence: "")
]))*/
addLocal(homework: Homework(id: "5", name: "Éloi Automne", entries: [
WordEntry(word: "ami", sentence: "Tu es mon ami"),
WordEntry(word: "amie", sentence: "Une amie que j'aime beaucoup"),
WordEntry(word: "papa", sentence: "Bonjour papa"),
WordEntry(word: "rue", sentence: "Je vais traverser la rue"),
WordEntry(word: "robe", sentence: "Ceci est ma robe"),
WordEntry(word: "livres", sentence: "Ce sont des livres de la bibliothèque"),
WordEntry(word: "table", sentence: "Je mange à la table"),
WordEntry(word: "lune", sentence: "Une pleine lune"),
WordEntry(word: "vie", sentence: "La vie est belle"),
WordEntry(word: "dame", sentence: "Regarde la dame sur le trottoir"),
WordEntry(word: "lire", sentence: "J'aime beaucoup lire des livres"),
WordEntry(word: "mère", sentence: "C'est ma mère"),
WordEntry(word: "père", sentence: "Mon père est au travail"),
WordEntry(word: "fête", sentence: "C'est ta fête aujourd'hui"),
WordEntry(word: "tête", sentence: "J'ai mal à la tête"),
WordEntry(word: "bonbons", sentence: "Je mange des bonbons"),
WordEntry(word: "monde", sentence: "Le monde est vraiment beau"),
WordEntry(word: "ballon", sentence: "J'ai un beau ballon"),
WordEntry(word: "poules", sentence: "Regarde les deux poules"),
WordEntry(word: "bouche", sentence: "J'ai l'eau à la bouche"),
WordEntry(word: "roi", sentence: "Le roi Saint-Éloi"),
WordEntry(word: "joie", sentence: "Il y a de la joie dans mon coeur"),
WordEntry(word: "fois", sentence: "Des fois je fais des cauchemards"),
WordEntry(word: "trois", sentence: "Les trois mousquetaires"),
WordEntry(word: "soir", sentence: "Le soir je lis des livres"),
WordEntry(word: "devoirs", sentence: "J'ai des devoirs ce soir"),
WordEntry(word: "voir", sentence: "Je vais voir un film au cinéma"),
WordEntry(word: "pouvoir", sentence: "Superman a le pouvoir de voler"),
WordEntry(word: "bleu", sentence: "Mon camion est bleu"),
WordEntry(word: "bleue", sentence: "Ma pelle est bleue"),
WordEntry(word: "jeu", sentence: "J'ai un jeu dans mon sac"),
WordEntry(word: "jeudi", sentence: "Jeudi je vais à la natation"),
WordEntry(word: "lundi", sentence: "Lundi c'est le premier jour de la semaine"),
WordEntry(word: "brun", sentence: "Mon camion est brun"),
WordEntry(word: "brune", sentence: "Mon automobile est brune"),
WordEntry(word: "pluie", sentence: "Il tombe de la pluie dehors"),
WordEntry(word: "nuit", sentence: "C'est déjà la nuit"),
WordEntry(word: "dans", sentence: "Il fait noir dans ma chambre"),
WordEntry(word: "maman", sentence: "J'aime ma maman"),
WordEntry(word: "chanter", sentence: "Je vais chanter ce soir"),
WordEntry(word: "dent", sentence: "J'ai perdu une dent aujourd'hui"),
WordEntry(word: "vent", sentence: "Mes cheveux vole au vent"),
WordEntry(word: "enfant", sentence: "Je suis encore un enfant"),
WordEntry(word: "chemin", sentence: "Pour aller à l'école je prends le chemin de l'église."),
WordEntry(word: "jardin", sentence: "Je suis dans le jardin"),
WordEntry(word: "matin", sentence: "Le matin je prends un déjeuner"),
WordEntry(word: "sapin", sentence: "Le beau sapin de noël"),
WordEntry(word: "lutin", sentence: "Mon lutin est parti ce matin"),
WordEntry(word: "main", sentence: "J'ai mal à la main"),
WordEntry(word: "pain", sentence: "Je mange du pain au raisin"),
WordEntry(word: "train", sentence: "Le train est très long"),
WordEntry(word: "plein", sentence: "J'ai eu plein de cadeau cette années."),
WordEntry(word: "pleine", sentence: "La bouteille est pleine d'eau"),
WordEntry(word: "étoiles", sentence: "Regarde les étoiles dans le ciel"),
WordEntry(word: "vélo", sentence: "Viens tu faire du vélo avec moi?"),
WordEntry(word: "bébé", sentence: "Je ne suis plus un bébé"),
WordEntry(word: "journée", sentence: "C'est la journée de noël aujourd'hui"),
WordEntry(word: "poupées", sentence: "J'aime joué avec des poupées"),
WordEntry(word: "année", sentence: "Je suis en première année")
]))
addLocal(homework: Homework(id: "6", name: "Éloi - Liste 17", entries: [
WordEntry(word: "aile", sentence: "Une aile de poulet."),
WordEntry(word: "air", sentence: "Je n'aime pas l'air climatisé."),
WordEntry(word: "plaisir", sentence: "J'ai beaucoup de plaisir à l'école."),
WordEntry(word: "maison", sentence: "Je m'en vais à la maison"),
WordEntry(word: "neige", sentence: "Il a tombé de la neige aujourd'hui."),
WordEntry(word: "reine", sentence: "La reine Victoria a eu 9 enfants."),
WordEntry(word: "mais", sentence: "J'aime les pommes, mais j'aime encore plus les bananes.")
]))
addLocal(homework: Homework(id: "6000", name: "Éloi - Liste 2.1", entries: [
WordEntry(word: "an", sentence: "j'habite ici depuis un an."),
WordEntry(word: "il y a", sentence: "il y a une souris dans la maison."),
WordEntry(word: "été", sentence: "nous avons passé un été magnifique."),
WordEntry(word: "non", sentence: "pourquoi dis-tu toujours non quand je te demande si tu veux jouer avec moi?."),
WordEntry(word: "nom", sentence: "quel est ton nom?"),
WordEntry(word: "pas", sentence: "ne fais pas un pas de plus."),
WordEntry(word: "par", sentence: "Je te l'ai envoyé par la poste."),
WordEntry(word: "pour", sentence: "ce cadeau est pour toi."),
WordEntry(word: "au", sentence: "nous allons au cinéma."),
WordEntry(word: "aux", sentence: "j'en ai donné aux amis de ma classe."),
WordEntry(word: "avec", sentence: "Veux-tu jouer avec moi?"),
WordEntry(word: "leur", sentence: "ils ont perdu leur chat."),
WordEntry(word: "peur", sentence: "je n'ai pas peur de ce chien."),
WordEntry(word: "enfin", sentence: "j'ai enfin terminé mon travail."),
WordEntry(word: "encore", sentence: "j'ai encore faim."),
WordEntry(word: "entre", sentence: "place toi entre moi et lui."),
WordEntry(word: "bananes", sentence: "je mange souvent des bananes en collation."),
WordEntry(word: "dire", sentence: "il faut toujours dire merci."),
WordEntry(word: "nature", sentence: "j'aime marcher dans la nature."),
WordEntry(word: "tante", sentence: "j'adore aller chez ma tante Nancy."),
WordEntry(word: "tente", sentence: "Nous allons dormir dans notre nouvelle tente."),
WordEntry(word: "élèves", sentence: "ces élèves sont vraiment bons en mathématique."),
WordEntry(word: "patates", sentence: "il y a des patates dans la fricassée."),
WordEntry(word: "vite", sentence: "j'ai couru très vite pour te rejoindre."),
WordEntry(word: "malade", sentence: "je ne suis plus malade."),
WordEntry(word: "lecture", sentence: "j'adore la lecture."),
WordEntry(word: "près", sentence: "Viens près de moi."),
WordEntry(word: "après", sentence: "Nous irons au parc après l'école."),
WordEntry(word: "très", sentence: "Je suis très fatiguée."),
WordEntry(word: "peut-être", sentence: "Je pourrai peut-être jouer avec toi plus tard."),
WordEntry(word: "prière", sentence: "Il a récité une prière à l'église."),
WordEntry(word: "même", sentence: "j'ai le même chandail que toi."),
WordEntry(word: "ces", sentence: "ces pantalons-là sont rendus trop petits ."),
WordEntry(word: "oncle", sentence: "mon oncle m'a aidé à faire ce château de sable."),
WordEntry(word: "monter", sentence: "il faut monter jusqu'en haut de cette montagne."),
WordEntry(word: "chanter", sentence: "je n'aime pas chanter devant des gens."),
WordEntry(word: "chanson", sentence: "j'ai déjà entendu cette chanson."),
WordEntry(word: "donc", sentence: "il pleut, donc nous n'irons pas jouer dehors."),
WordEntry(word: "monstre", sentence: "je me déguiserai en monstre à l'Halloween."),
WordEntry(word: "surtout", sentence: "j'aime surtout les autos qui roulent toute seule."),
WordEntry(word: "partout", sentence: "il y a des jouets qui trainent partout."),
WordEntry(word: "souvent", sentence: "je vais souvent voir ma Mamie."),
WordEntry(word: "sous", sentence: "il y a plein de miettes sous la table."),
WordEntry(word: "toujours", sentence: "je t'aimerai toujours."),
WordEntry(word: "alors", sentence: "ma mère m'attends, alors je dois me dépêcher."),
WordEntry(word: "devant", sentence: "Attends-moi devant la maison."),
WordEntry(word: "avant", sentence: "je dois aller au toilette avant de partir."),
WordEntry(word: "moi", sentence: "Veux-tu venir jouer chez moi?"),
WordEntry(word: "toi", sentence: "Est-ce que je peux venir avec toi?"),
WordEntry(word: "j'ai", sentence: "je pense que j'ai oublié mon agenda à l'école."),
WordEntry(word: "as", sentence: "est-ce que tu as bien barré la porte?"),
WordEntry(word: "à", sentence: "Gaston a offert des fleur à sa mère."),
WordEntry(word: "avons", sentence: "nous avons des poules."),
WordEntry(word: "avez", sentence: "vous avez une très garnde maison."),
WordEntry(word: "ont", sentence: "ils ont un chalet à Alma.")
]))
addLocal(homework: Homework(id: "7", name: "Dictée Isabelle (v2)", entries: [
WordEntry(word: "à côté", sentence: "Reste à côté de moi"),
WordEntry(word: "alors", sentence: "j'ai faim, alors je mange"),
WordEntry(word: "après", sentence: "je viendrai après l'école"),
WordEntry(word: "assez", sentence: " j'en ai assez!"),
WordEntry(word: "aucun", sentence: "il ne me reste aucun crayon"),
WordEntry(word: "aujourd'hui", sentence: "j'y vais aujourd'hui"),
WordEntry(word: "aussi", sentence: " tu viens toi aussi"),
WordEntry(word: "aussitôt", sentence: "je viendrai aussitôt que j'aurai terminé"),
WordEntry(word: "autour", sentence: "la lune tourne autour de la Terre"),
WordEntry(word: "avant", sentence: "ma fête est avant la tienne"),
WordEntry(word: "beaucoup", sentence: "je t'aime beaucoup"),
WordEntry(word: "bientôt", sentence: "Mamie arrive bientôt"),
WordEntry(word: "chaque", sentence: "chaque joueur reçoit 5 cartes"),
WordEntry(word: "chez", sentence: "je dormirai chez toi"),
WordEntry(word: "combien", sentence: "combien as-tu d'argent?"),
WordEntry(word: "comme", sentence: "mon chandail est comme le tien"),
WordEntry(word: "dehors", sentence: "allons jouer dehors!"),
WordEntry(word: "déjà", sentence: "J'ai déjà vu ce film"),
WordEntry(word: "depuis", sentence: "je viens ici depuis que je suis tout petit"),
WordEntry(word: "durant", sentence: "il est interdit de jouer durant les heures de classe"),
WordEntry(word: "est-ce que", sentence: "est-ce que tu as vu mon frère?"),
WordEntry(word: "là", sentence: "Il est là"),
WordEntry(word: "loin", sentence: "tu es rendu trop loin"),
WordEntry(word: "longtemps", sentence: "il y a longtemps que je t'aime"),
WordEntry(word: "lorsque", sentence: "regarde bien lorsque tu traverse"),
WordEntry(word: "maintenant", sentence: "j'ai maintenant 10 ans"),
WordEntry(word: "même", sentence: "j'ai le même vélo que toi"),
WordEntry(word: "mes", sentence: "mes lacets sont détachés"),
WordEntry(word: "mieux", sentence: "écris mieux que ça!"),
WordEntry(word: "nos", sentence: "Nos poules ont pondu ce matin"),
WordEntry(word: "notre", sentence: "notre chien est parti"),
WordEntry(word: "parfois", sentence: "j'ai parfois peur la nuit"),
WordEntry(word: "partout", sentence: "il y a des pissenlits partout"),
WordEntry(word: "peut-être", sentence: "J'y irai peut-être demain"),
WordEntry(word: "plein", sentence: "mon verre est trop plein"),
WordEntry(word: "plusieurs", sentence: "j'ai plusieurs jeux de cartes"),
WordEntry(word: "pourquoi", sentence: "pourquoi dis-tu cela?"),
WordEntry(word: "pourtant", sentence: "Je l'ai pourtant mis là"),
WordEntry(word: "presque", sentence: "J'ai presque terminé"),
WordEntry(word: "puis", sentence: "Et puis après?"),
WordEntry(word: "puisque", sentence: "Puisque tu ne viens pas, je pars sans toi."),
WordEntry(word: "qu'est-ce que", sentence: "qu'est-ce que tu manges?"),
WordEntry(word: "quand", sentence: "Quand as-tu fait ce dessin?"),
WordEntry(word: "quelqu'un", sentence: "Quelqu'un sonne à la porte"),
WordEntry(word: "quelque chose", sentence: "quelque chose vient de tomber"),
WordEntry(word: "sans", sentence: "Vas-y sans moi"),
WordEntry(word: "ses", sentence: "Il joue avec ses amis"),
WordEntry(word: "soudain", sentence: "Soudain, il lui vint une idée"),
WordEntry(word: "sous", sentence: "Cache-le sous ton lit"),
WordEntry(word: "dessous", sentence: "Mets un naperon dessous ton assiette"),
WordEntry(word: "sur", sentence: "Mets-le sur le comptoir"),
WordEntry(word: "tard", sentence: "Il est tard, vas te coucher."),
WordEntry(word: "toujours", sentence: "Tu ris toujours de mes blagues"),
WordEntry(word: "tout à coup", sentence: "Tout à coup, il entendit un gros bruit"),
WordEntry(word: "trop", sentence: "J'ai trop froid!"),
WordEntry(word: "vers", sentence: "je regarde vers le ciel"),
WordEntry(word: "vite", sentence: "Marche moins vite"),
WordEntry(word: "voici", sentence: "Voici ma meilleure amie"),
WordEntry(word: "voilà", sentence: "Nous voilà arrivés"),
WordEntry(word: "votre", sentence: "Votre chien m'a mordu"),
WordEntry(word: "année", sentence: "Bonne année"),
WordEntry(word: "autobus", sentence: "J'ai manqué l'autobus"),
WordEntry(word: "compter", sentence: "Je sans compter jusqu'à 100"),
WordEntry(word: "congé", sentence: "aujourd'hui, c'est congé!"),
WordEntry(word: "photo", sentence: "Quelle belle photo!"),
WordEntry(word: "prix", sentence: "Quel est le prix de ce jouet"),
WordEntry(word: "souvenir", sentence: "j'en garde un bon souvenir"),
WordEntry(word: "stylo", sentence: "Écris avec un stylo bleu"),
WordEntry(word: "apprendre", sentence: "Il faut apprendre l'anglais"),
WordEntry(word: "balle", sentence: "Lance-moi la balle"),
WordEntry(word: "ballon", sentence: "où est mon ballon?"),
WordEntry(word: "commencer", sentence: "Je ne sais pas par où commencer"),
WordEntry(word: "cours", sentence: "J'ai pris un cours de natation"),
WordEntry(word: "faute", sentence: "Je n'ai pas fait de faute!"),
WordEntry(word: "gens", sentence: "Où sont les gens que tu connais"),
WordEntry(word: "remettre", sentence: "Il faut remettre le travail demain"),
WordEntry(word: "réussir", sentence: "Il va réussir son cours."),
WordEntry(word: "rien", sentence: "je n'ai rien à faire"),
WordEntry(word: "septembre", sentence: "ma fête est le 7 septembre"),
WordEntry(word: "terminer", sentence: "Il doit terminer son repas."),
WordEntry(word: "alphabet", sentence: "je connais mon alphabet"),
WordEntry(word: "bureau", sentence: "mets-le sur mon bureau"),
WordEntry(word: "environ", sentence: "j'ai environ 30 billes dans mon sac"),
WordEntry(word: "épeler", sentence: "il faut épeler tous ces mots"),
WordEntry(word: "juste", sentence: "Ce n'est pas juste!"),
WordEntry(word: "marcher", sentence: "Il sont partis marcher"),
WordEntry(word: "ménage", sentence: "Je dois faire le ménage de ma chambre"),
WordEntry(word: "offrir", sentence: "J'ai offrir des fleurs à ma mère"),
WordEntry(word: "professeur", sentence: "Qui est ton professeur"),
WordEntry(word: "quel", sentence: "À quel jeu veux-tu jouer?"),
WordEntry(word: "quels", sentence: "Avec quels crayons veux-tu dessiner?"),
WordEntry(word: "quelle", sentence: "Quelle tuque as-tu mis?"),
WordEntry(word: "quelles", sentence: "Quelles céréales préfères-tu?"),
WordEntry(word: "rencontré", sentence: "Je n'ai jamais rencontré tes parents"),
WordEntry(word: "robot", sentence: "Dessine-moi un robot"),
WordEntry(word: "sans que", sentence: "Je suis partie sans que tu t'en aperçoive"),
WordEntry(word: "timide", sentence: "Je suis tellement timide!"),
WordEntry(word: "articulation", sentence: "j'ai mal à cette articulation"),
WordEntry(word: "chaise", sentence: "cette chaise est trop haute"),
WordEntry(word: "comprends", sentence: "Je ne comprends pas"),
WordEntry(word: "enregistrer", sentence: "J'aimerais enregistrer cette émission"),
WordEntry(word: "facile", sentence: "C'est vraiment facile!"),
WordEntry(word: "laissé", sentence: "Il m'a laissé passer"),
WordEntry(word: "mauvais", sentence: "Ça sent mauvais!"),
WordEntry(word: "meilleur", sentence: "Je suis le meilleur!"),
WordEntry(word: "neuf", sentence: "J'ai un manteau neuf"),
WordEntry(word: "neuve", sentence: "J'ai une voiture neuve"),
WordEntry(word: "pièce", sentence: "as-tu vu ma pièce de cinq cents?"),
WordEntry(word: "prochaine", sentence: "À la prochaine!"),
WordEntry(word: "question", sentence: "J'ai une question à te poser"),
WordEntry(word: "abri", sentence: "Reste sous l'abri"),
WordEntry(word: "âge", sentence: "Tu as quel âge?"),
WordEntry(word: "allure", sentence: "Tout cela n'a pas d'allure!"),
WordEntry(word: "attention", sentence: "Fais très attention!"),
WordEntry(word: "bottes", sentence: "J'ai besoin de mes bottes de pluie"),
WordEntry(word: "corps", sentence: "J'ai des piqûres sur tout le corps"),
WordEntry(word: "cri", sentence: "J'ai entendu un grand cri"),
WordEntry(word: "enquête", sentence: "Les policiers mènent une enquête"),
WordEntry(word: "fraiche", sentence: "Quelle bonne eau fraiche"),
WordEntry(word: "frais", sentence: "Du bon pain frais"),
WordEntry(word: "aider", sentence: "Pourrais-tu m'aider?"),
WordEntry(word: "attrapé", sentence: "J'ai attrapé la balle!"),
WordEntry(word: "danger", sentence: "C'est un réel danger"),
WordEntry(word: "doigts", sentence: "J'ai mal à ces deux doigts"),
WordEntry(word: "désespérer", sentence: "Il ne faut jamais désespérer"),
WordEntry(word: "guerre", sentence: "Il y a de la guerre dans la monde"),
WordEntry(word: "horrible", sentence: "C'est vriment horrible!"),
WordEntry(word: "jambe", sentence: "Je me tiens sur une seule jambe"),
WordEntry(word: "joue", sentence: "je ne joue plus avec toi"),
WordEntry(word: "lancer", sentence: "J'ai du mal à lancer la balle"),
WordEntry(word: "métier", sentence: "Quel est ton métier?"),
WordEntry(word: "rejoindre", sentence: "J'irai te rejoindre plus tard"),
WordEntry(word: "transpirer", sentence: "Elle va beaucoup transpirer"),
WordEntry(word: "certain", sentence: "Es-tu certain?"),
WordEntry(word: "claire", sentence: "L'eau de ce lac est vraiment claire"),
WordEntry(word: "clair", sentence: "Quel beau clair de lune"),
WordEntry(word: "consoler", sentence: "Elle va me consoler"),
WordEntry(word: "courir", sentence: "J'aime beaucoup courir"),
WordEntry(word: "épais", sentence: "il y a un épais brouillard"),
WordEntry(word: "goutte", sentence: "Il n'y en a plus une seule goutte"),
WordEntry(word: "lentement", sentence: "marche lentement"),
WordEntry(word: "lumière", sentence: "Allume la lumière"),
WordEntry(word: "spectaculaire", sentence: "C'était spectaculaire!"),
WordEntry(word: "clé", sentence: "Où as-tu mis la clé?"),
WordEntry(word: "d'abord", sentence: "Mange d'abord ton repas"),
WordEntry(word: "frapper", sentence: "Essaie de frapper la balle que je te lance"),
WordEntry(word: "habiter", sentence: "J'aime habiter à Montréal"),
WordEntry(word: "minuit", sentence: "Je me suis couché à minuit"),
WordEntry(word: "ombre", sentence: "Il est plus vite que son ombre"),
WordEntry(word: "réaction", sentence: "Ta réaction m'a étonné"),
WordEntry(word: "soigner", sentence: "Je me suis fait soigner"),
WordEntry(word: "terrifié", sentence: "Ce film m'a terrifié!"),
WordEntry(word: "coins", sentence: "J'aime jouer au ballon 4 coins"),
WordEntry(word: "étonnant", sentence: "Quel fait étonnant!"),
WordEntry(word: "gorge", sentence: "J'ai mal à la gorge"),
WordEntry(word: "novembre", sentence: "En novembre, il fait froid"),
WordEntry(word: "or", sentence: "Un bague en or"),
WordEntry(word: "troisième", sentence: "Je suis en troisième année"),
WordEntry(word: "voyage", sentence: "Bon voyage!"),
WordEntry(word: "appartement", sentence: "Tu habites dans un appartement"),
WordEntry(word: "apporté", sentence: "J'ai apporté un cadeau"),
WordEntry(word: "rond", sentence: "Cesse de tourner en rond"),
WordEntry(word: "trésor", sentence: "C'est mon trésor"),
WordEntry(word: "collation", sentence: "As-tu amené une collation?"),
WordEntry(word: "genou", sentence: "J'ai un bobo sur le genou"),
WordEntry(word: "maladie", sentence: "Il a une maladie contagieuse"),
WordEntry(word: "mille", sentence: " J'ai gagné mille dollars "),
WordEntry(word: "millier", sentence: "Il y a un millier de fourmis"),
WordEntry(word: "millions", sentence: "Il y a 4 millions d'année"),
WordEntry(word: "oublié", sentence: "J'ai oublié son nom"),
WordEntry(word: "quelques-uns", sentence: "J'ai quelques-uns de ces jouets"),
WordEntry(word: "rendre", sentence: "Veux-tu me rendre mon crayon"),
WordEntry(word: "baigner", sentence: "On peut se baigner dans ce lac"),
WordEntry(word: "bonhomme", sentence: "Il manque un bonhomme dans ce jeu"),
WordEntry(word: "coquin", sentence: "Tu es vraiment coquin"),
WordEntry(word: "date", sentence: "Quelle date sommes-nous aujourd'hui? "),
WordEntry(word: "dattes", sentence: "J'aimes ces biscuits aux dattes"),
WordEntry(word: "décembre", sentence: "Jésus est né le 24 décembre"),
WordEntry(word: "hôpitaux", sentence: "On ne peut pas fumer dans les hôpitaux"),
WordEntry(word: "lèvre", sentence: "j'ai un bobo sur la lèvre"),
WordEntry(word: "après-midi", sentence: "C'est arrivé cet après-midi"),
WordEntry(word: "battre", sentence: "Il ne faut jamais se battre"),
WordEntry(word: "bonheur", sentence: "L'argent ne fait pas le bonheur"),
WordEntry(word: "buts", sentence: "J'ai compté plusieurs buts!"),
WordEntry(word: "château", sentence: "C'Est vrai château, ici!"),
WordEntry(word: "sac-à-dos", sentence: "Où est mon sac-à-dos?"),
WordEntry(word: "fil", sentence: "le funambule marche sur un fil"),
WordEntry(word: "Québec", sentence: "J'habite au Québec"),
WordEntry(word: "affaires", sentence: "Ce n'est pas de tes affaires!"),
WordEntry(word: "agneau", sentence: "La viande d'agneau est délicieuse"),
WordEntry(word: "bande", sentence: "vous êtes une bande de voyous!"),
WordEntry(word: "brutal", sentence: "Il a reçu un coup brutal"),
WordEntry(word: "dauphin", sentence: "Le chant du dauphin est magnifique"),
WordEntry(word: "janvier", sentence: "Le premier mois de l'année est janvier"),
WordEntry(word: "lièvre", sentence: " le lièvre et la tortue"),
WordEntry(word: "manquer", sentence: "je vais manquer l'autobus"),
WordEntry(word: "pierres", sentence: "j'ai lancé toutes les pierres"),
WordEntry(word: "poil", sentence: "mon chat a un très beau poil"),
WordEntry(word: "ampoule", sentence: "il faut changer cette ampoule"),
WordEntry(word: "argent", sentence: "je n'ai pas assez d'argent"),
WordEntry(word: "chasseur", sentence: "je suis un chasseur de chevreuil"),
WordEntry(word: "courts", sentence: "j'ai les cheveux courts"),
WordEntry(word: "habileté", sentence: "C'est une habileté que j'aimerais avoir"),
WordEntry(word: "poussin", sentence: "j'ai eu un poussin pour ma fête"),
WordEntry(word: "renard", sentence: "le renard roux est magnifique"),
WordEntry(word: "sabot", sentence: "le sabot du cheval"),
WordEntry(word: "approcher", sentence: "je l'ai entendu approcher"),
WordEntry(word: "bâton", sentence: "ne frappe personne avec ce bâton"),
WordEntry(word: "langue", sentence: "je ne parle pas cette langue"),
WordEntry(word: "mammifère", sentence: "l'homme est un mammifère"),
WordEntry(word: "moyen", sentence: "est-ce le bon moyen pour y arriver?"),
WordEntry(word: "occupé", sentence: "je suis occupé"),
WordEntry(word: "ours", sentence: "l'ours brun vit au Québec"),
WordEntry(word: "ourse", sentence: "La mère ourse a deux petits"),
WordEntry(word: "parc", sentence: "allons jouer au parc"),
WordEntry(word: "puissance", sentence: "la puissance de cette auto m'étonne"),
WordEntry(word: "service", sentence: "j'aime rendre service"),
WordEntry(word: "champ", sentence: "un beau champ de fleur"),
WordEntry(word: "malheur", sentence: "quel malheur!"),
WordEntry(word: "museau", sentence: "le museau du chien est froid"),
WordEntry(word: "nourriture", sentence: "il y a de la nourriture"),
WordEntry(word: "pâle", sentence: "tu es très pâle"),
WordEntry(word: "passage", sentence: "libérez le passage"),
WordEntry(word: "record", sentence: "je dois battre mon record"),
WordEntry(word: "remarqué", sentence: "je n'avais pas remarqué"),
WordEntry(word: "magasin", sentence: "je dois aller au magasin"),
WordEntry(word: "poids", sentence: "mon poids est le même que le tien"),
WordEntry(word: "restaurant", sentence: "allons au restaurant!"),
WordEntry(word: "vacances", sentence: "c'est les vacances!"),
WordEntry(word: "glisser", sentence: "Je vais glisser sur cette glissoire"),
WordEntry(word: "village", sentence: "c'est mon village"),
WordEntry(word: "journaux", sentence: "on le dit dans les journaux"),
WordEntry(word: "jeter", sentence: "ne pas jeter de déchets ici"),
WordEntry(word: "jus", sentence: "du jus s'il vous plait"),
WordEntry(word: "moitié", sentence: "J'en ai gardé la moitié"),
WordEntry(word: "nouveauté", sentence: "c'est une nouveauté"),
WordEntry(word: "rayon", sentence: "dans le rayon des fruits et légumes"),
WordEntry(word: "vêtements", sentence: "range tes vêtements"),
WordEntry(word: "boire", sentence: "je vais boire de l'eau"),
WordEntry(word: "permettre", sentence: "dois-je te le permettre?"),
WordEntry(word: "plastique", sentence: "Un plat de plastique"),
WordEntry(word: "repas", sentence: "mon repas est bon"),
WordEntry(word: "santé", sentence: "je suis en santé"),
WordEntry(word: "schéma", sentence: "fais un schéma pour illustrer ce problème"),
WordEntry(word: "contexte", sentence: "dans quel contexte?"),
WordEntry(word: "bateau", sentence: "je regarde le bateau sur l'eau"),
WordEntry(word: "descendre", sentence: "il faut descendre la pente"),
WordEntry(word: "haut", sentence: "c'est trop haut pour moi"),
WordEntry(word: "pile", sentence: "il est 10 heures pile"),
WordEntry(word: "ruisseau", sentence: "l'eau du ruisseau est froide"),
WordEntry(word: "semble", sentence: "il me semble que oui"),
WordEntry(word: "zoo", sentence: "j'aime aller au zoo"),
WordEntry(word: "bord", sentence: "au bord de la mer"),
WordEntry(word: "découvrir", sentence: "j'aime découvrir de nouvelles choses"),
WordEntry(word: "mer", sentence: "au bord de la mer"),
WordEntry(word: "mère", sentence: "ma mère ne veut pas"),
WordEntry(word: "mousse", sentence: "il y a de la mousse sur ces roches"),
WordEntry(word: "murmures", sentence: "j'entends des murmures"),
WordEntry(word: "surface", sentence: "la surface est lisse"),
WordEntry(word: "tour", sentence: "c'est à mon tour à jouer"),
WordEntry(word: "vue", sentence: "j'ai une très bonne vue"),
WordEntry(word: "mois", sentence: "nous sommes rendus quel mois"),
WordEntry(word: "protéger", sentence: "j'ai protéger mon livre de la pluie"),
WordEntry(word: "retard", sentence: "n'arrive pas en retard"),
WordEntry(word: "salut", sentence: "salut mon ami!"),
WordEntry(word: "vitesse", sentence: "il roule à grande vitesse"),
WordEntry(word: "danser", sentence: "j'aime danser"),
WordEntry(word: "penché", sentence: "je me suis penché pour le ramasser"),
WordEntry(word: "pin", sentence: "cet arbre est un pin"),
WordEntry(word: "pleuvoir", sentence: "il va bientôt pleuvoir"),
WordEntry(word: "rêvé", sentence: "j'ai rêvé que j'étais riche"),
WordEntry(word: "sèche", sentence: "ma robe est sèche"),
WordEntry(word: "soirée", sentence: "quelle belle soirée"),
WordEntry(word: "ventre", sentence: "j'ai mal au ventre"),
WordEntry(word: "cause", sentence: "qu'est-ce qui cause tout cela?"),
WordEntry(word: "compte", sentence: "je compte sur mes doigts"),
WordEntry(word: "dès que", sentence: "dès que j'arrive, je t'appelle"),
WordEntry(word: "fiction", sentence: "ce film est une fiction"),
WordEntry(word: "important", sentence: "c'est important!"),
WordEntry(word: "coque", sentence: "des oeufs à la coque"),
WordEntry(word: "droit", sentence: "j'ai le droit d'y aller"),
WordEntry(word: "droit", sentence: "c'est du côté droit"),
WordEntry(word: "mai", sentence: "ma fête est le 5 mai"),
WordEntry(word: "nid", sentence: "ma poule a pondu dans son nid"),
WordEntry(word: "pantalon", sentence: "c'est mon pantalon"),
WordEntry(word: "verser", sentence: "il faut verser tranquillement"),
WordEntry(word: "avancer", sentence: "tu dois avancer"),
WordEntry(word: "choix", sentence: "c'est ton choix"),
WordEntry(word: "herbe", sentence: "le lapin mange de l'herbe"),
WordEntry(word: "imprimé", sentence: "ce livre est imprimé au Québec"),
WordEntry(word: "juin", sentence: "l'école finit en juin"),
WordEntry(word: "mourir", sentence: "je souhaite mourir vieux"),
WordEntry(word: "part", sentence: "c'est ma part de gâteau"),
WordEntry(word: "point", sentence: "Mets un point à la fin de la phrase"),
WordEntry(word: "rappeler", sentence: "tu dois me rappeler plus tard"),
WordEntry(word: "salle", sentence: "la fête a lieu dans la grande salle"),
WordEntry(word: "scénario", sentence: "j'ai écrit le scénario de ce film"),
WordEntry(word: "sujet", sentence: "le sujet de ce livre m'intéresse"),
WordEntry(word: "tranquille", sentence: "reste tranquille"),
WordEntry(word: "juillet", sentence: "je pars en vacances en juillet"),
WordEntry(word: "naissance", sentence: "c'est ma date de naissance"),
WordEntry(word: "promettre", sentence: "tu dois me le promettre"),
WordEntry(word: "promets", sentence: "je promets d'être là"),
WordEntry(word: "réveillé", sentence: "je me suis réveillé tôt"),
WordEntry(word: "souhaites", sentence: "tu souhaites venir chez moi"),
WordEntry(word: "sourcils", sentence: "mes sourcils sont bruns"),
WordEntry(word: "spectacle", sentence: "quel beau spectacle"),
WordEntry(word: "pot", sentence: "le beau pot de fleur"),
WordEntry(word: "remplir", sentence: "je vais remplir ton verre d'eau"),
WordEntry(word: "trottoir", sentence: "il y a un nouveau trottoir"),
WordEntry(word: "août", sentence: "l'école commenc en août"),
WordEntry(word: "posséder", sentence: "j'aimerais posséder cette maison"),
WordEntry(word: "présente", sentence: "je vous présente mon amie Julie"),
WordEntry(word: "soie", sentence: "C'est doux comme de la soie"),
WordEntry(word: "verre", sentence: "veux tu un verre d'eau?"),
WordEntry(word: "vinaigre", sentence: "je mets du vinaigre dans ma poutine")
]))
addLocal(homework: Homework(id: "8", name: "Émilien - 6.1", entries: [
WordEntry(word: "angle", sentence: "Je dois mesurer cet angle."),
WordEntry(word: "balance", sentence: "Tu devrais utiliser une balance."),
WordEntry(word: "banlieue", sentence: "Je n'aimerais pas habiter en banlieue"),
WordEntry(word: "banque", sentence: "Ils ont dévalisé la banque."),
WordEntry(word: "brillant", sentence: "Je suis un enfant brillant."),
WordEntry(word: "croyances", sentence: "On a tous droit à nos croyances."),
WordEntry(word: "déranger", sentence: "Veux-tu arrêter de me déranger."),
WordEntry(word: "divan", sentence: "Il a dormi sur le divan"),
WordEntry(word: "s'élancer", sentence: "Il aurait dû s'élancer avant de sauter"),
WordEntry(word: "franchir", sentence: "Il est interdit de franchir cette porte."),
WordEntry(word: "garantie", sentence: "Il y a une garantie."),
WordEntry(word: "grandir", sentence: "Je n'ai pas fini de grandir"),
WordEntry(word: "indépendance", sentence: "Plusieurs souhaite l'indépendance du Québec."),
WordEntry(word: "intéressant", sentence: "Je trouve ce sujet très intéressant."),
WordEntry(word: "mandat", sentence: "Il a reçu un mandat d'arrestation."),
WordEntry(word: "Marchandises", sentence: "c'est un train de marchandises"),
WordEntry(word: "pansement", sentence: "Je mettrais bien un pansement sur ma blessure."),
WordEntry(word: "planches", sentence: "Voici les planches que vous utiliserez."),
WordEntry(word: "sandwichs", sentence: "J'adore les sandwichs faits avec des croissants."),
WordEntry(word: "séance", sentence: "Nous verrons cela à la prochaine séance."),
WordEntry(word: "tranche", sentence: "J'en prendrais une tranche s'il te plait."),
WordEntry(word: "anglais", sentence: "J'apprends l'anglais."),
WordEntry(word: "bâtiment", sentence: "C'est un nouveau bâtiment."),
WordEntry(word: "bienvenu", sentence: "Tu es le bienvenu chez moi."),
WordEntry(word: "bienvenue", sentence: "Il m'a souhaité la bienvenue."),
WordEntry(word: "cahier", sentence: "J'ai oublié mon cahier."),
WordEntry(word: "cités", sentence: "J'ai écouté Les cités d'or."),
WordEntry(word: "composer", sentence: "J'aime composer des chansons"),
WordEntry(word: "correspondance", sentence: "Je fais de la correspondance avec un Français"),
WordEntry(word: "découvertes", sentence: "J'ai fait de belles découvertes dans ce musée."),
WordEntry(word: "demeure", sentence: "Bienvenue dans ma demeure."),
WordEntry(word: "devant", sentence: "Passe devant moi."),
WordEntry(word: "différence", sentence: "Je ne vois pas la différence entre les deux."),
WordEntry(word: "éducation", sentence: "J'aime le cours d'éducation physique"),
WordEntry(word: "français", sentence: "Ma mère enseigne le français"),
WordEntry(word: "manque", sentence: "Il t'en manque combien?"),
WordEntry(word: "méthode", sentence: "J'ai pourtant bien suivi la méthode."),
WordEntry(word: "noter", sentence: "Je préfère noter ton numéro."),
WordEntry(word: "orthographe", sentence: "Je m'améliore beaucoup en orthographe et ma mère est fière de moi."),
WordEntry(word: "pauvreté", sentence: "Il y a trop de pauvreté dans le monde."),
WordEntry(word: "prénom", sentence: "Rapelle-moi ton prénom."),
WordEntry(word: "rang", sentence: "Reste dans le rang."),
WordEntry(word: "récréation", sentence: "J'ai hâte à la récréation"),
WordEntry(word: "richesse", sentence: "L'eau est une richesse naturelle."),
WordEntry(word: "style", sentence: "J'ai ton style sportif."),
WordEntry(word: "tissé", sentence: "Ce sac a été tissé à la main"),
WordEntry(word: "vieillard", sentence: "Ce vieillard semble malade.")
]))
addLocal(homework: Homework(id: "9", name: "Émilien - 6.3", entries: [
WordEntry(word: "ambassadeur", sentence: "Cet homme a déjà été l'ambassadeur du Canada"),
WordEntry(word: "ambassadrice", sentence: "L'ambassadrice de France est en visite au Québec."),
WordEntry(word: "camp", sentence: "J'ai envie d'aller au camp à Dominic!"),
WordEntry(word: "combattre", sentence: "J'ai réussi à combattre ce rhume."),
WordEntry(word: "compliments", sentence: "Il m'a fait plein de compliments."),
WordEntry(word: "comportement", sentence: "Ce jeune a des troubles de comportement."),
WordEntry(word: "emploi", sentence: "J'ai décroché un nouvel emploi."),
WordEntry(word: "emprunt", sentence: "Tu pourrais faire un emprunt à la banque."),
WordEntry(word: "importation", sentence: "Ce vendeur fait de l'importation de meubles."),
WordEntry(word: "impôts", sentence: "As-tu payé tes impôts?"),
WordEntry(word: "jambon", sentence: "Ce jambon est trop salé."),
WordEntry(word: "membres", sentence: "Cet endroit est réservé aux membres du club."),
WordEntry(word: "pompières", sentence: "Il y a très peu de pompières."),
WordEntry(word: "rassemblement", sentence: "Il y a un rassemblement au coin de la rue."),
WordEntry(word: "récompense", sentence: "Tu auras une belle récompense!"),
WordEntry(word: "ressemblance", sentence: "Il y a une forte ressemblance entre toi et ton frère."),
WordEntry(word: "semblable", sentence: "Ce chandail est semblable au mien."),
WordEntry(word: "sympathies", sentence: "J'ai offert mes sympathies à la dame qui vient de perdre son mari."),
WordEntry(word: "sympathique", sentence: "Cet enfant est tellement sympathique!")
]))
addLocal(homework: Homework(id: "9", name: "Émilien - Mots invariables", entries: [
WordEntry(word: "selon", sentence: "selon moi, tu es le meilleur."),
WordEntry(word: "cela", sentence: "cela est inacceptable."),
WordEntry(word: "beaucoup", sentence: "Je t'aime beaucoup, mon garçon."),
WordEntry(word: "temps.", sentence: "il est temps de partir"),
WordEntry(word: "longtemps", sentence: "Est-ce que ça fait longtemps que tu attends?"),
WordEntry(word: "aussi", sentence: "moi aussi, je souhaite y aller!"),
WordEntry(word: "souvent", sentence: "Je pense très souvent à toi."),
WordEntry(word: "ainsi", sentence: "C'est ainsi que tout cela est arrivé."),
WordEntry(word: "ainsi que", sentence: "les poules, les chèvres ainsi que les cochons vivent sur la ferme."),
WordEntry(word: "déjà", sentence: "Tu es déjà prêt?"),
WordEntry(word: "chez", sentence: "Nous irons chez Mamie demain."),
WordEntry(word: "À côté", sentence: "Place toi à côté de lui."),
WordEntry(word: "devant", sentence: "Ne passe pas devant les autres."),
WordEntry(word: "encore", sentence: "C'est encore à tour de jouer."),
WordEntry(word: "ensuite", sentence: "Mange d'abord, tu joueras ensuite."),
WordEntry(word: "quand", sentence: "Quand penses-tu avoir terminé?"),
WordEntry(word: "toujours", sentence: "Tu pourras toujours compter sur moi."),
WordEntry(word: "voici", sentence: "Voici ma collection de timbres."),
WordEntry(word: "voilà", sentence: "voilà pourquoi je n'ai pas pu venir chez toi."),
WordEntry(word: "bientôt", sentence: "Ce sera bientôt ton tour."),
WordEntry(word: "alors", sentence: "Je suis alors partie en courant."),
WordEntry(word: "aujourd'hui", sentence: "C'est mon anniversaire aujourd'hui."),
WordEntry(word: "autour", sentence: "Il y a des enfants tout autour de moi."),
WordEntry(word: "assez", sentence: "Je n'ai pas assez d'argent sur moi."),
WordEntry(word: "aucun", sentence: "Il n'y a aucun problème."),
WordEntry(word: "demain", sentence: "Je dois remettre ce travail demain."),
WordEntry(word: "depuis", sentence: "Depuis quand as-tu mal à la tête?"),
WordEntry(word: "en dessous", sentence: "Place un naperon en dessous ton assiette"),
WordEntry(word: "au-dessus", sentence: "Place ce livre au-dessus de l'autre."),
WordEntry(word: "dessus", sentence: "Ne marche pas dessus!"),
WordEntry(word: "dehors", sentence: "Allons jouer dehors!"),
WordEntry(word: "dedans", sentence: "Il n'y a rien dedans."),
WordEntry(word: "est-ce que", sentence: "est-ce que tu veux venir jouer chez moi?"),
WordEntry(word: "eux", sentence: "Ce n'est pas eux qui ont fait ce mauvais coup."),
WordEntry(word: "hier", sentence: "Je croyais que ça se terminait hier."),
WordEntry(word: "il y a", sentence: "Il y a beaucoup de neige dehors."),
WordEntry(word: "lentement", sentence: "Vas-y plus lentement."),
WordEntry(word: "lorsque", sentence: "Tu viendras lorsque je t'appellerai."),
WordEntry(word: "maintenant", sentence: "Je n'ai pas le temps maintenant."),
WordEntry(word: "mieux", sentence: "Je sais que tu peux faire mieux."),
WordEntry(word: "parce que", sentence: "N'y vas pas parce que c'est dangereux."),
WordEntry(word: "parfois", sentence: "Parfois, j'oublie l'orthographe des mots."),
WordEntry(word: "pendant", sentence: "Nous y irons pendant les vacances."),
WordEntry(word: "plusieurs", sentence: "J'ai plusieurs amis."),
WordEntry(word: "Pourtant", sentence: "Je l'avais pourtant mis là."),
WordEntry(word: "presque", sentence: "C'est presque l'automne."),
WordEntry(word: "puisque", sentence: "je t'invite puisque tu es mon ami."),
WordEntry(word: "peut-être", sentence: "J'irai peut-être au cinéma ce soir."),
WordEntry(word: "qu'est-ce que", sentence: "qu'est-ce que tu fais ce soir?"),
WordEntry(word: "quelqu'un", sentence: "quelqu'un viendra chercher cette boite."),
WordEntry(word: "sans", sentence: "Je ne partirai pas sans toi"),
WordEntry(word: "tard", sentence: "Il est bien trop tard."),
WordEntry(word: "tôt", sentence: "Tu t'es vevé très tôt ce matin"),
WordEntry(word: "tout à coup", sentence: "Tout à coup, j'ai entendu un bruit."),
WordEntry(word: "trop", sentence: "Ne mets pas trop d'eau dans ton verre."),
WordEntry(word: "soudain", sentence: "Soudain, il partit à courir vers moi."),
WordEntry(word: "vraiment", sentence: "J'ai vraiment besoin de ton aide.")
]))
}
}
| apache-2.0 | dae38b29606e7853e41b914df7fffd1f | 71.113914 | 206 | 0.60253 | 3.314311 | false | false | false | false |
morizotter/xcmultilingual | DemoApp/DemoApp/Multilingual.swift | 1 | 3200 | //
// Multilingual.swift
// xcmultilingual
//
// Created by xcmultilingual.
//
//
import Foundation
struct Multilingual {
enum Animal: String {
case CAT = "CAT"
case DOG = "DOG"
case BEAR = "BEAR"
case DEER = "DEER"
case SQUIRREL = "SQUIRREL"
case ELEPHANT = "ELEPHANT"
case GIRAFFE = "GIRAFFE"
case TIGER = "TIGER"
case LION = "LION"
case RABBIT = "RABBIT"
case RHINOCEROS = "RHINOCEROS"
case GORILLA = "GORILLA"
case MONKEY = "MONKEY"
var value: String {
return NSLocalizedString(rawValue, tableName: Animal.name, bundle: Multilingual.bundle(nil), value: rawValue, comment: "")
}
static let name = "Animal"
static var keys: [String] {
return ["CAT", "DOG", "BEAR", "DEER", "SQUIRREL", "ELEPHANT", "GIRAFFE", "TIGER", "LION", "RABBIT", "RHINOCEROS", "GORILLA", "MONKEY"]
}
static var localizations: [String] {
return Animal.keys.map { Animal(rawValue: $0)!.value }
}
}
enum Localizable: String {
case HELLO = "HELLO"
case GOODMORNING = "GOODMORNING"
case GOODEVENING = "GOODEVENING"
var value: String {
return NSLocalizedString(rawValue, tableName: Localizable.name, bundle: Multilingual.bundle(nil), value: rawValue, comment: "")
}
static let name = "Localizable"
static var keys: [String] {
return ["HELLO", "GOODMORNING", "GOODEVENING"]
}
static var localizations: [String] {
return Localizable.keys.map { Localizable(rawValue: $0)!.value }
}
}
enum Sample2Sample_Localization: String {
case SAMPLE_2 = "SAMPLE 2"
var value: String {
return NSLocalizedString(rawValue, tableName: Sample2Sample_Localization.name, bundle: Multilingual.bundle("sample2.bundle"), value: rawValue, comment: "")
}
static let name = "Sample Localization"
static var keys: [String] {
return ["SAMPLE 2"]
}
static var localizations: [String] {
return Sample2Sample_Localization.keys.map { Sample2Sample_Localization(rawValue: $0)!.value }
}
}
enum SampleSample: String {
case SAMPLE = "SAMPLE"
var value: String {
return NSLocalizedString(rawValue, tableName: SampleSample.name, bundle: Multilingual.bundle("sample.bundle"), value: rawValue, comment: "")
}
static let name = "Sample"
static var keys: [String] {
return ["SAMPLE"]
}
static var localizations: [String] {
return SampleSample.keys.map { SampleSample(rawValue: $0)!.value }
}
}
}
extension Multilingual {
class ClassForBundle {}
private static func bundle(bundleFile: String?) -> NSBundle {
if let bundleFile = bundleFile {
let path = NSBundle(forClass: Multilingual.ClassForBundle.self).resourcePath!.stringByAppendingPathComponent(bundleFile)
return NSBundle(path: path)!
}
return NSBundle(forClass: ClassForBundle.self)
}
}
| mit | 28f5240a2d6a18ba845524af61257da1 | 27.828829 | 167 | 0.59125 | 3.945746 | false | false | false | false |
DasHutch/minecraft-castle-challenge | app/_src/RequirementTableViewCell.swift | 1 | 2889 | //
// RequirementTableViewCell.swift
// MC Castle Challenge
//
// Created by Gregory Hutchinson on 9/17/15.
// Copyright © 2015 Gregory Hutchinson. All rights reserved.
//
import UIKit
class RequirementTableViewCell: UITableViewCell {
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var quantityLabel: UILabel!
struct ViewData {
let requirement: Requirement
}
var viewData: ViewData? {
didSet {
updateItemLabel(viewData?.requirement.description)
updateQuantityLabel(viewData?.requirement.quantity)
accessoryTypeForCompleted(viewData?.requirement.completed ?? false)
updateLabelFontForDynamicTextStyles()
}
}
//MARK: - Lifecycle
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override func prepareForReuse() {
//NOTE: Clear Labels & Checkmarks
updateItemLabel(nil)
updateQuantityLabel(nil)
accessoryTypeForCompleted(false)
}
//MARK: - Public
func loadRequirement(req: NSDictionary) {
let quantity = req[CastleChallengeKeys.StageRequriementItemKeys.Quantity] as? NSNumber
let item = req[CastleChallengeKeys.StageRequriementItemKeys.Item] as? String ?? ""
let completed = req[CastleChallengeKeys.StageRequriementItemKeys.Completed] as? Bool ?? false
updateItemLabel(item)
updateQuantityLabel(quantity)
accessoryTypeForCompleted(completed)
}
//MARK: - Private
private func accessoryTypeForCompleted(completed: Bool) {
if completed {
accessoryType = UITableViewCellAccessoryType.Checkmark
}else {
accessoryType = UITableViewCellAccessoryType.None
}
}
private func updateItemLabel(itemName: String?) {
updateLabel(itemLabel, withText: itemName)
}
private func updateQuantityLabel(quantity: NSNumber?) {
guard let quantity = quantity as? Int else {
updateLabel(quantityLabel, withText: "")
return
}
if quantity > 0 {
let quantityString = "\(quantity)"
updateLabel(quantityLabel, withText: quantityString)
}else {
updateLabel(quantityLabel, withText: "")
}
}
private func updateLabel(label: UILabel?, withText text: String?) {
label?.text = text
}
private func updateLabelFontForDynamicTextStyles() {
quantityLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleHeadline)
itemLabel.font = UIFont.preferredAvenirFontForTextStyle(UIFontTextStyleBody)
}
}
extension RequirementTableViewCell.ViewData {
// init(requirement: Requirement) {
// self.requirement = requirement
// }
}
| gpl-2.0 | 8eacf3ee8e36fe88fd8f34b126c7ec90 | 29.4 | 101 | 0.654432 | 5.048951 | false | false | false | false |
kevinup7/S4HeaderExtensions | Sources/S4HeaderExtensions/RequestHeaders/Expect.swift | 1 | 1208 | import S4
extension Headers {
/**
The "Expect" header field in a request indicates a certain set of
behaviors (expectations) that need to be supported by the server in
order to properly handle this request. The only such expectation
defined by this specification is 100-continue.
## Example Headers
`Expect: 100-continue`
## Examples
var request = Request()
request.headers.expect = .Continue
- seealso: [RFC7231](https://tools.ietf.org/html/rfc7231#section-5.1.1)
*/
public var expect: Expect? {
get {
return headers["Expect"].flatMap({ Expect(headerValue: $0) })
}
set {
headers["Expect"] = newValue?.headerValue
}
}
}
public enum Expect: String {
case Continue = "100-continue"
}
extension Expect: HeaderValueInitializable {
public init?(headerValue: String) {
if headerValue.lowercased() == "100-continue" {
self = .Continue
} else {
return nil
}
}
}
extension Expect: HeaderValueRepresentable {
public var headerValue: String {
return self.headerValue
}
}
| mit | e0092a472cfe9846db6f3286feed0ab0 | 23.653061 | 79 | 0.595199 | 4.541353 | false | false | false | false |
a736220388/FinestFood | FinestFood/FinestFood/classes/common/MyDownloader.swift | 1 | 1884 | //
// MyDownloader.swift
// FinestFood
//
// Created by qianfeng on 16/8/15.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class MyDownloader: NSObject {
var didFailWithError:((NSError)->Void)?
var didFinishWithData:((NSData)->Void)?
func downloadWithUrlString(urlString:String){
let url = NSURL(string: urlString)
let request = NSURLRequest(URL: url!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
self.didFailWithError!(error!)
}else{
let httpRes = response as! NSHTTPURLResponse
if httpRes.statusCode == 200{
self.didFinishWithData!(data!)
}else{
let error = NSError(domain: "\(httpRes.statusCode)", code: 0, userInfo: nil)
self.didFailWithError?(error)
}
}
}
task.resume()
}
func downloadWithPostUrlString(urlString:String,paramString:String){
let url = NSURL(string: urlString)
let request = NSMutableURLRequest(URL: url!)
let data = paramString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = data
request.HTTPMethod = "POST"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { (data, response, error) in
if error != nil{
self.didFailWithError!(error!)
}else{
let httpRes = response as! NSHTTPURLResponse
if httpRes.statusCode == 200{
self.didFinishWithData!(data!)
}else{
self.didFinishWithData!(data!)
}
}
}
task.resume()
}
}
| mit | 6d02d87c3b63198b8298690d1f2003e6 | 33.833333 | 96 | 0.565125 | 4.97619 | false | false | false | false |
TotalDigital/People-iOS | People at Total/Reachability.swift | 1 | 1608 | //
// Reachability.swift
// Reachability
//
// Created by Florian Letellier on 31/01/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
/* Only Working for WIFI
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
*/
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
| apache-2.0 | de4cec860a6e6ff43e2b2a2e51bae3c6 | 33.191489 | 143 | 0.629123 | 4.884498 | false | false | false | false |
lukaskollmer/RuntimeKit | RuntimeKit/Sources/Protocols.swift | 1 | 3014 | //
// Protocols.swift
// RuntimeKit
//
// Created by Lukas Kollmer on 31.03.17.
// Copyright © 2017 Lukas Kollmer. All rights reserved.
//
import Foundation
import ObjectiveC
/// struct describing a method for a protocol
public struct ObjCMethodDescription {
/// The method's name
let name: Selector
/// The method's return type
let returnType: ObjCTypeEncoding
/// The method's argument types
let argumentTypes: [ObjCTypeEncoding]
/// `MethodType` case determining whether the method is an instance method or a class method
let methodType: MethodType
/// Boolean determining whether the method is required
var isRequired = false
/// The method's encoding
var encoding: [CChar] {
return TypeEncoding(returnType, argumentTypes)
}
/// Create a new `ObjCMethodDescription` instance
///
/// - Parameters:
/// - name: The method's name
/// - returnType: The method's return type
/// - argumentTypes: The method's argument types
/// - methodType: `MethodType` case determining whether the method is an instance method or a class method
/// - isRequired: Boolean determining whether the method is required
init(_ name: Selector, returnType: ObjCTypeEncoding = .void, argumentTypes: [ObjCTypeEncoding] = [.object, .selector], methodType: MethodType, isRequired: Bool = false) {
self.name = name
self.returnType = returnType
self.argumentTypes = argumentTypes
self.methodType = methodType
}
}
public extension Runtime {
/// Returns a specified protocol
///
/// - Parameter name: The name of a protocol.
/// - Returns: The protocol named `name`, or `nil` if no protocol named name could be found
public static func getProtocol(_ name: String) -> Protocol? {
return objc_getProtocol(name.cString(using: .utf8)!)
}
/// Creates a new protocol instance.
///
/// - Parameters:
/// - name: The name of the protocol you want to create.
/// - methods: The methods you want to add to the new protocol
/// - Returns: A new protocol instance
/// - Throws: `RuntimeKitError.protocolAlreadyExists` if a protocol with the same name already exists, `RuntimeKitError.unableToCreateProtocol` if there was an error creating the protocol
public static func createProtocol(_ name: String, methods: [ObjCMethodDescription]) throws -> Protocol {
guard Runtime.getProtocol(name) == nil else {
throw RuntimeKitError.protocolAlreadyExists
}
guard let newProtocol = objc_allocateProtocol(name.cString(using: .utf8)!) else {
throw RuntimeKitError.unableToCreateProtocol
}
methods.forEach {
protocol_addMethodDescription(newProtocol, $0.name, $0.encoding, $0.isRequired, $0.methodType == .instance)
}
objc_registerProtocol(newProtocol)
return newProtocol
}
}
| mit | 4ab91f50a95dba9f939adf1faf939925 | 35.301205 | 191 | 0.659476 | 4.707813 | false | false | false | false |
Marquis103/instagram-clone | ParseStarterProject/AppDelegate.swift | 1 | 7254 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
// If you want to use any of the UI components, uncomment this line
// import ParseUI
// If you want to use Crash Reporting - uncomment this line
// import ParseCrashReporting
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
//--------------------------------------
// MARK: - UIApplicationDelegate
//--------------------------------------
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// ParseCrashReporting.enable()
//
// Uncomment and fill in with your Parse credentials:
Parse.setApplicationId("fjTjWnbrB6HK9FoElfEKyGffrPdAXftV246RHYTc", clientKey: "5PTpZbzo1S87uvNqMxGFv2CBqdQYuN938Wfqu3Ci")
//
// If you are using Facebook, uncomment and add your FacebookAppID to your bundle's plist as
// described here: https://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
// Uncomment the line inside ParseStartProject-Bridging-Header and the following line here:
// PFFacebookUtils.initializeFacebook()
// ****************************************************************************
PFUser.enableAutomaticUser()
let defaultACL = PFACL();
// If you would like all objects to be private by default, remove this line.
defaultACL.setPublicReadAccess(true)
PFACL.setDefaultACL(defaultACL, withAccessForCurrentUser:true)
if application.applicationState != UIApplicationState.Background {
// Track an app open here if we launch with a push, unless
// "content_available" was used to trigger a background push (introduced in iOS 7).
// In that case, we skip tracking here to avoid double counting the app-open.
let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
var noPushPayload = false;
if let options = launchOptions {
noPushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil;
}
if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
}
}
//
// Swift 1.2
//
// if application.respondsToSelector("registerUserNotificationSettings:") {
// let userNotificationTypes = UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound
// let settings = UIUserNotificationSettings(forTypes: userNotificationTypes, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types = UIRemoteNotificationType.Badge | UIRemoteNotificationType.Alert | UIRemoteNotificationType.Sound
// application.registerForRemoteNotificationTypes(types)
// }
//
// Swift 2.0
//
// if #available(iOS 8.0, *) {
// let types: UIUserNotificationType = [.Alert, .Badge, .Sound]
// let settings = UIUserNotificationSettings(forTypes: types, categories: nil)
// application.registerUserNotificationSettings(settings)
// application.registerForRemoteNotifications()
// } else {
// let types: UIRemoteNotificationType = [.Alert, .Badge, .Sound]
// application.registerForRemoteNotificationTypes(types)
// }
return true
}
//--------------------------------------
// MARK: Push Notifications
//--------------------------------------
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation.saveInBackground()
PFPush.subscribeToChannelInBackground("") { (succeeded: Bool, error: NSError?) in
if succeeded {
print("ParseStarterProject successfully subscribed to push notifications on the broadcast channel.\n");
} else {
print("ParseStarterProject failed to subscribe to push notifications on the broadcast channel with error = %@.\n", error)
}
}
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
if error.code == 3010 {
print("Push notifications are not supported in the iOS Simulator.\n")
} else {
print("application:didFailToRegisterForRemoteNotificationsWithError: %@\n", error)
}
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
PFPush.handlePush(userInfo)
if application.applicationState == UIApplicationState.Inactive {
PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
}
}
///////////////////////////////////////////////////////////
// Uncomment this method if you want to use Push Notifications with Background App Refresh
///////////////////////////////////////////////////////////
// func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == UIApplicationState.Inactive {
// PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
// }
// }
//--------------------------------------
// MARK: Facebook SDK Integration
//--------------------------------------
///////////////////////////////////////////////////////////
// Uncomment this method if you are using Facebook
///////////////////////////////////////////////////////////
// func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool {
// return FBAppCall.handleOpenURL(url, sourceApplication:sourceApplication, session:PFFacebookUtils.session())
// }
}
| mit | 4e756df7af0f112e0a0fbcaa39efb59c | 46.411765 | 193 | 0.612903 | 5.907166 | false | false | false | false |
maxoly/PulsarKit | PulsarKitExample/PulsarKitExample/Controllers/Basic/Merge/MergeViewController.swift | 1 | 1138 | //
// MergeViewController.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 01/03/2021.
// Copyright © 2021 Nacoon. All rights reserved.
//
import UIKit
import PulsarKit
final class MergeViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "Merge"
populateSource()
}
}
extension MergeViewController {
func populateSource() {
let itemsMenuItem = MenuItem(icon: UIImage.itemsMove, title: "Simple merge", description: Constants.Lorem) {
let controller = SimpleMergeViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
let sectionsMenuItem = MenuItem(icon: UIImage.sectionsMove, title: "Search merge", description: Constants.Lorem) {
let controller = SearchMergeViewController()
self.navigationController?.pushViewController(controller, animated: true)
}
source.add(section: SourceSection(headerModel: Header(title: "Basic")))
source.add(models: [itemsMenuItem, sectionsMenuItem])
}
}
| mit | eee05c507ed2d1dfcc353bb92d336c0d | 31.485714 | 122 | 0.67898 | 4.659836 | false | false | false | false |
thebinaryarchitect/journal | Journal/Classes/EntryViewController.swift | 1 | 926 | //
// EntryViewController.swift
// Journal
//
// Copyright (C) 2015 Xiao Yao. All Rights Reserved.
// See LICENSE.txt for more information.
//
import Foundation
import UIKit
class EntryViewController : UIViewController {
// The text view
let textView: UITextView
// The entry
let entry: Entry
// Initialize with an entry
init(entry: Entry) {
self.entry = entry
self.textView = UITextView.init()
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.textView.bounds = self.view.bounds
self.textView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.textView.font = UIFont.systemFontOfSize(17.0)
self.textView.text = self.entry.text
}
} | mit | 9372a28a927c813cdc79b0994ffc848b | 23.394737 | 74 | 0.638229 | 4.367925 | false | false | false | false |
aipeople/PokeIV | Pods/PGoApi/PGoApi/Classes/GPSOAuth.swift | 1 | 3927 | //
// GPSOAuth.swift
// pgoapi
//
// Created by Rowell Heria on 02/08/2016.
// Copyright © 2016 Coadstal. All rights reserved.
//
import Foundation
import Alamofire
public class GPSOAuth: PGoAuth {
private let baseParams = [
"accountType": "HOSTED_OR_GOOGLE",
"has_permission": "1",
"add_account": "1",
"source": "android",
"androidId": "9774d56d682e549c",
"device_country": "us",
"operatorCountry": "us",
"lang": "en",
"sdk_version": "17"
]
private let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
public var email: String!
public var password: String!
public var token: String?
public var accessToken: String?
public var expires: Int?
public var loggedIn: Bool = false
public var delegate: PGoAuthDelegate?
public var authType: PGoAuthType = .Google
public var endpoint: String = PGoEndpoint.Rpc
public var authToken: Pogoprotos.Networking.Envelopes.AuthTicket?
public var manager: Manager
public init() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = Alamofire.Manager(configuration: configuration)
}
private func parseKeyValues(body:String) -> Dictionary<String, String> {
var obj = [String:String]()
let bodySplit = body.componentsSeparatedByString("\n")
for values in bodySplit {
var keysValues = values.componentsSeparatedByString("=")
if keysValues.count >= 2 {
obj[keysValues[0]] = keysValues[1]
}
}
return obj;
}
private func getTicket() {
var params = baseParams
params["Email"] = self.email
params["Passwd"] = self.password
params["service"] = "ac2dm"
Alamofire.request(.POST, PGoEndpoint.GoogleLogin, parameters: params, headers: headers, encoding: .URLEncodedInURL)
.responseJSON { (response) in
let responseString = NSString(data: response.data!, encoding: NSUTF8StringEncoding)
let googleDict = self.parseKeyValues(responseString! as String)
if googleDict["Token"] != nil {
self.loginOAuth(googleDict["Token"]!)
self.token = googleDict["Token"]
} else {
self.delegate?.didNotReceiveAuth()
}
}
}
private func loginOAuth(token: String) {
var params = baseParams
params["Email"] = self.email
params["EncryptedPasswd"] = token
params["service"] = "audience:server:client_id:848232511240-7so421jotr2609rmqakceuu1luuq0ptb.apps.googleusercontent.com"
params["app"] = "com.nianticlabs.pokemongo"
params["client_sig"] = "321187995bc7cdc2b5fc91b11a96e2baa8602c62"
Alamofire.request(.POST, PGoEndpoint.GoogleLogin, parameters: params, headers: headers, encoding: .URLEncodedInURL)
.responseJSON { (response) in
let responseString = NSString(data: response.data!, encoding: NSUTF8StringEncoding)
let googleDict = self.parseKeyValues(responseString! as String)
if googleDict["Auth"] != nil {
self.accessToken = googleDict["Auth"]!
self.expires = Int(googleDict["Expiry"]!)!
self.loggedIn = true
self.delegate?.didReceiveAuth()
} else {
self.delegate?.didNotReceiveAuth()
}
}
}
public func login(withUsername username: String, withPassword password: String) {
self.email = username.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
self.password = password
self.getTicket()
}
} | gpl-3.0 | d0e8935781ff36584eb28b7ecd83e674 | 35.027523 | 128 | 0.598319 | 4.554524 | false | false | false | false |
kgn/KGNUserInterface | Source/UIView+Snapshot.swift | 1 | 1781 | //
// UIView+Snapshot.swift
// KGNUserInterface
//
// Created by David Keegan on 11/7/15.
// Copyright © 2015 David Keegan. All rights reserved.
//
import UIKit
extension UIView {
/**
Snapshot a view into an image object.
- parameter opaque: A Boolean flag indicating whether the bitmap is opaque.
If you know the bitmap is fully opaque, specify true to ignore the alpha
channel and optimize the bitmap’s storage. Specifying false means that the
bitmap must include an alpha channel to handle any partially transparent pixels.
Defautls to `false`.
- parameter scale: The scale factor to apply to the bitmap. If you specify a value
of 0.0, the scale factor is set to the scale factor of the device’s main screen.
Defaults to `0`.
- parameter afterUpdates: A Boolean value that indicates whether the snapshot should
be rendered after recent changes have been incorporated. Specify the value false if
you want to render a snapshot in the view hierarchy’s current state, which might not
include recent changes. Defaults to `false`.
- returns: The image object for the snapshot.
*/
public func snapshot(opaque: Bool = false, scale: CGFloat = 0, afterScreenUpdates: Bool = false) -> UIImage? {
if self.bounds == CGRect.zero {
return nil
}
defer {
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(self.bounds.size, opaque, scale)
if !self.drawHierarchy(in: self.bounds, afterScreenUpdates: afterScreenUpdates) {
return nil
}
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
return image
}
}
| mit | 3c960a4b405b9b28b14c3ca4d5a9672a | 34.48 | 114 | 0.674183 | 4.887052 | false | false | false | false |
a2/Simon | Simon WatchKit App Extension/MainMenuInterfaceController.swift | 1 | 2495 | import Foundation
import SimonKit
import WatchKit
let HighScoresKey = "HighScores"
let MaxHighScoresCount = 10
class MainMenuInterfaceController: WKInterfaceController {
let userDefaults = NSUserDefaults(suiteName: "group.us.pandamonia.Simon")!
var highScores: [HighScore] {
get {
let rawValues = userDefaults.arrayForKey(HighScoresKey) as? [[String : AnyObject]]
return rawValues?.flatMap(HighScore.init).sort() ?? []
}
set {
let object = newValue.map { $0.rawValue }
userDefaults.setObject(object, forKey: HighScoresKey)
}
}
// MARK: - IBOutlets
@IBOutlet weak var gameOverGroup: WKInterfaceGroup!
@IBOutlet weak var gameOverText: WKInterfaceLabel!
@IBOutlet weak var highScoreLabel: WKInterfaceLabel!
// MARK: - Actions
@IBAction func play() {
WKInterfaceController.reloadRootControllersWithNames(["game"], contexts: nil)
}
@IBAction func showHighScores() {
let segueName = highScores.count > 0 ? "highScores" : "emptyHighScores"
pushControllerWithName(segueName, context: Box(highScores))
}
// MARK: - Life Cycle
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
if userDefaults.objectForKey(GameHistoryKey) != nil {
play()
return
}
if let score = context as? Int {
var newHighScores = highScores
newHighScores.append(HighScore(score: score, date: NSDate()))
newHighScores.sortInPlace()
if newHighScores.count > MaxHighScoresCount {
newHighScores.removeRange(MaxHighScoresCount..<newHighScores.count)
}
highScores = newHighScores
gameOverText.setText(String.localizedStringWithFormat(NSLocalizedString("You survived for %d rounds! Better luck next time.", comment: "Game over text; {count} is replaced with the number of rounds completed"), score))
gameOverGroup.setHidden(false)
} else {
gameOverGroup.setHidden(true)
}
if let highScore = highScores.first {
highScoreLabel.setHidden(false)
highScoreLabel.setText(String.localizedStringWithFormat(NSLocalizedString("High Score: %d", comment: "High score label; {score} is replaced with the high score"), highScore.score))
} else {
highScoreLabel.setHidden(true)
}
}
}
| mit | cc62566ee050d2ce074637635ca9cd3c | 34.642857 | 230 | 0.651303 | 4.873047 | false | false | false | false |
zesming/RandomMenu | RandomMenu/RMMenuTableViewController.swift | 1 | 3119 | //
// RMMenuTableViewController.swift
// RandomMenu
//
// Created by 赵恩生 on 16/7/10.
// Copyright © 2016年 Ming. All rights reserved.
//
import UIKit
class RMMenuTableViewController: 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 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "menuCell", for: indexPath)
cell.textLabel?.text = "Test"
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: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 6bd5b01da869f833ce1ac6b61b555af6 | 33.175824 | 136 | 0.674277 | 5.253378 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothGATT/GATTModelNumber.swift | 1 | 1731 | //
// GATTModelNumber.swift
// Bluetooth
//
// Created by Carlos Duclos on 6/21/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/**
Model Number String
[Model Number String](https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.model_number_string.xml)
The value of this characteristic is a UTF-8 string representing the model number assigned by the device vendor.
*/
@frozen
public struct GATTModelNumber: RawRepresentable, GATTCharacteristic {
public static var uuid: BluetoothUUID { return .modelNumberString }
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
public init?(data: Data) {
guard let rawValue = String(data: data, encoding: .utf8)
else { return nil }
self.init(rawValue: rawValue)
}
public var data: Data {
return Data(rawValue.utf8)
}
}
extension GATTModelNumber: Equatable {
public static func == (lhs: GATTModelNumber, rhs: GATTModelNumber) -> Bool {
return lhs.rawValue == rhs.rawValue
}
}
extension GATTModelNumber: CustomStringConvertible {
public var description: String {
return rawValue
}
}
extension GATTModelNumber: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(rawValue: value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self.init(rawValue: value)
}
public init(unicodeScalarLiteral value: String) {
self.init(rawValue: value)
}
}
| mit | f1473f69c65087e950b1c0ec83d0e347 | 21.763158 | 146 | 0.642775 | 4.663073 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/Control/FullScreenImage/ImageViewer.swift | 1 | 13119 | //
// ImageViewer.swift
// Pods
//
// Created by MacMini-2 on 31/08/17.
//
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
open class ImageViewer: UIViewController {
// MARK: - Properties
fileprivate let kMinMaskViewAlpha: CGFloat = 0.3
fileprivate let kMaxImageScale: CGFloat = 2.5
fileprivate let kMinImageScale: CGFloat = 1.0
fileprivate let senderView: UIImageView
fileprivate var originalFrameRelativeToScreen: CGRect!
fileprivate var rootViewController: UIViewController!
fileprivate let imageView = UIImageView()
fileprivate var panGesture: UIPanGestureRecognizer!
fileprivate var panOrigin: CGPoint!
fileprivate var isAnimating = false
fileprivate var isLoaded = false
fileprivate var closeButton = UIButton()
fileprivate let windowBounds = UIScreen.main.bounds
fileprivate let scrollView = UIScrollView()
fileprivate let maskView = UIView()
// MARK: - Lifecycle methods
init(senderView: UIImageView, backgroundColor: UIColor) {
self.senderView = senderView
rootViewController = UIApplication.shared.keyWindow!.rootViewController!
maskView.backgroundColor = backgroundColor
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
configureView()
configureMaskView()
configureScrollView()
configureCloseButton()
configureImageView()
configureConstraints()
}
// MARK: - View configuration
fileprivate func configureScrollView() {
scrollView.frame = windowBounds
scrollView.delegate = self
scrollView.minimumZoomScale = kMinImageScale
scrollView.maximumZoomScale = kMaxImageScale
scrollView.zoomScale = 1
view.addSubview(scrollView)
}
fileprivate func configureMaskView() {
maskView.frame = windowBounds
maskView.alpha = 0.0
view.insertSubview(maskView, at: 0)
}
fileprivate func configureCloseButton() {
closeButton.alpha = 0.0
closeButton.setTitle("x", for: UIControl.State())
closeButton.setTitleColor(UIColor.black, for: UIControl.State())
closeButton.translatesAutoresizingMaskIntoConstraints = false
closeButton.addTarget(self, action: #selector(ImageViewer.closeButtonTapped(_:)), for: UIControl.Event.touchUpInside)
view.addSubview(closeButton)
view.setNeedsUpdateConstraints()
}
fileprivate func configureView() {
var originalFrame = senderView.convert(windowBounds, to: nil)
originalFrame.origin = CGPoint(x: originalFrame.origin.x, y: originalFrame.origin.y)
originalFrame.size = senderView.frame.size
originalFrameRelativeToScreen = originalFrame
}
fileprivate func configureImageView() {
senderView.alpha = 0.0
imageView.frame = originalFrameRelativeToScreen
imageView.isUserInteractionEnabled = true
imageView.contentMode = senderView.contentMode
imageView.image = senderView.image
scrollView.addSubview(imageView)
animateEntry()
addPanGestureToView()
addGestures()
centerScrollViewContents()
}
fileprivate func configureConstraints() {
var constraints: [NSLayoutConstraint] = []
let views: [String: UIView] = [
"closeButton": closeButton
]
constraints.append(NSLayoutConstraint(item: closeButton, attribute: .centerX, relatedBy: .equal, toItem: closeButton.superview, attribute: .centerX, multiplier: 1.0, constant: 0))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:[closeButton(==64)]-40-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views))
constraints.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:[closeButton(==64)]", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: nil, views: views))
NSLayoutConstraint.activate(constraints)
}
// MARK: - Gestures
fileprivate func addPanGestureToView() {
panGesture = UIPanGestureRecognizer(target: self, action: #selector(ImageViewer.gestureRecognizerDidPan(_:)))
panGesture.cancelsTouchesInView = false
panGesture.delegate = self
imageView.addGestureRecognizer(panGesture)
}
fileprivate func addGestures() {
let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didSingleTap(_:)))
singleTapRecognizer.numberOfTapsRequired = 1
singleTapRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(singleTapRecognizer)
let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ImageViewer.didDoubleTap(_:)))
doubleTapRecognizer.numberOfTapsRequired = 2
doubleTapRecognizer.numberOfTouchesRequired = 1
scrollView.addGestureRecognizer(doubleTapRecognizer)
singleTapRecognizer.require(toFail: doubleTapRecognizer)
}
fileprivate func zoomInZoomOut(_ point: CGPoint) {
let newZoomScale = scrollView.zoomScale > (scrollView.maximumZoomScale / 2) ? scrollView.minimumZoomScale : scrollView.maximumZoomScale
let scrollViewSize = scrollView.bounds.size
let w = scrollViewSize.width / newZoomScale
let h = scrollViewSize.height / newZoomScale
let x = point.x - (w / 2.0)
let y = point.y - (h / 2.0)
let rectToZoomTo = CGRect(x: x, y: y, width: w, height: h)
scrollView.zoom(to: rectToZoomTo, animated: true)
}
// MARK: - Animation
fileprivate func animateEntry() {
guard let image = imageView.image else {
return
}
self.imageView.frame = self.originalFrameRelativeToScreen
UIView.animate(withDuration: 0.4, delay: 0.0, options: UIView.AnimationOptions(rawValue: 0), animations: {
self.imageView.frame = self.centerFrameFromImage(image)
self.closeButton.alpha = 1.0
self.maskView.alpha = 1.0
self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.1, y: 1.1)
self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 0.97, y: 0.95)
}) { (finished) in
}
}
fileprivate func centerFrameFromImage(_ image: UIImage) -> CGRect {
var newImageSize = imageResizeBaseOnWidth(windowBounds.size.width, oldWidth: image.size.width, oldHeight: image.size.height)
newImageSize.height = min(windowBounds.size.height, newImageSize.height)
return CGRect(x: 0, y: windowBounds.size.height / 2 - newImageSize.height / 2, width: newImageSize.width, height: newImageSize.height)
}
fileprivate func imageResizeBaseOnWidth(_ newWidth: CGFloat, oldWidth: CGFloat, oldHeight: CGFloat) -> CGSize {
let scaleFactor = newWidth / oldWidth
let newHeight = oldHeight * scaleFactor
return CGSize(width: newWidth, height: newHeight)
}
// MARK: - Actions
@objc func gestureRecognizerDidPan(_ recognizer: UIPanGestureRecognizer) {
if scrollView.zoomScale != 1.0 || isAnimating {
return
}
senderView.alpha = 0.0
scrollView.bounces = false
let windowSize = maskView.bounds.size
let currentPoint = panGesture.translation(in: scrollView)
let y = currentPoint.y + panOrigin.y
imageView.frame.origin = CGPoint(x: currentPoint.x + panOrigin.x, y: y)
let yDiff = abs((y + imageView.frame.size.height / 2) - windowSize.height / 2)
maskView.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha)
closeButton.alpha = max(1 - yDiff / (windowSize.height / 0.95), kMinMaskViewAlpha) / 2
if (panGesture.state == UIGestureRecognizer.State.ended || panGesture.state == UIGestureRecognizer.State.cancelled)
&& scrollView.zoomScale == 1.0 {
maskView.alpha < 0.85 ? dismissViewController() : rollbackViewController()
}
}
@objc func didSingleTap(_ recognizer: UITapGestureRecognizer) {
scrollView.zoomScale == 1.0 ? dismissViewController() : scrollView.setZoomScale(1.0, animated: true)
}
@objc func didDoubleTap(_ recognizer: UITapGestureRecognizer) {
let pointInView = recognizer.location(in: imageView)
zoomInZoomOut(pointInView)
}
@objc func closeButtonTapped(_ sender: UIButton) {
if scrollView.zoomScale != 1.0 {
scrollView.setZoomScale(1.0, animated: true)
}
dismissViewController()
}
// MARK: - Misc.
fileprivate func centerScrollViewContents() {
let boundsSize = rootViewController.view.bounds.size
var contentsFrame = imageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
imageView.frame = contentsFrame
}
fileprivate func rollbackViewController() {
guard let image = imageView.image else {
fatalError("no image provided")
}
isAnimating = true
UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: UIView.AnimationOptions.beginFromCurrentState, animations: { () in
self.imageView.frame = self.centerFrameFromImage(image)
self.maskView.alpha = 1.0
self.closeButton.alpha = 1.0
}, completion: { (finished) in
self.isAnimating = false
})
}
fileprivate func dismissViewController() {
isAnimating = true
DispatchQueue.main.async(execute: {
self.imageView.clipsToBounds = true
UIView.animate(withDuration: 0.2, animations: { () in
self.closeButton.alpha = 0.0
})
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.6, options: [UIView.AnimationOptions.beginFromCurrentState, UIView.AnimationOptions.curveEaseInOut], animations: { () in
self.imageView.frame = self.originalFrameRelativeToScreen
self.rootViewController.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0)
self.view.transform = CGAffineTransform.identity.scaledBy(x: 1.0, y: 1.0)
self.maskView.alpha = 0.0
}, completion: { (finished) in
self.willMove(toParent: nil)
self.view.removeFromSuperview()
self.removeFromParent()
self.senderView.alpha = 1.0
self.isAnimating = false
})
})
}
func presentFromRootViewController() {
willMove(toParent: rootViewController)
rootViewController.view.addSubview(view)
rootViewController.addChild(self)
didMove(toParent: rootViewController)
}
}
// MARK: - GestureRecognizer delegate
extension ImageViewer: UIGestureRecognizerDelegate {
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
panOrigin = imageView.frame.origin
gestureRecognizer.isEnabled = true
return !isAnimating
}
}
// MARK: - ScrollView delegate
extension ImageViewer: UIScrollViewDelegate {
public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(_ scrollView: UIScrollView) {
isAnimating = true
centerScrollViewContents()
}
public func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
isAnimating = false
}
}
public extension UIImageView {
func setupForImageViewer(_ backgroundColor: UIColor = UIColor.white) {
isUserInteractionEnabled = true
let gestureRecognizer = ImageViewerTapGestureRecognizer(target: self, action: #selector(UIImageView.didTap(_:)), backgroundColor: backgroundColor)
addGestureRecognizer(gestureRecognizer)
}
@objc internal func didTap(_ recognizer: ImageViewerTapGestureRecognizer) {
let imageViewer = ImageViewer(senderView: self, backgroundColor: recognizer.backgroundColor)
imageViewer.presentFromRootViewController()
}
}
class ImageViewerTapGestureRecognizer: UITapGestureRecognizer {
let backgroundColor: UIColor
init(target: AnyObject, action: Selector, backgroundColor: UIColor) {
self.backgroundColor = backgroundColor
super.init(target: target, action: action)
}
}
| mit | 696fea6b82b896c8cc358cb1045e5958 | 35.441667 | 230 | 0.676957 | 5.175148 | false | false | false | false |
ello/ello-ios | Sources/Extensions/CGRectExtensions.swift | 1 | 5798 | ////
/// CGRectExtensions.swift
//
extension CGRect {
static var `default`: CGRect = CGRect(origin: .zero, size: CGSize(width: 600, height: 600))
// MARK: debug
func tap(_ name: String = "frame") -> CGRect {
print("\(name): \(self)")
return self
}
// MARK: convenience
init(x: CGFloat, y: CGFloat, right: CGFloat, bottom: CGFloat) {
self.init(x: x, y: y, width: right - x, height: bottom - y)
}
init(x: CGFloat, y: CGFloat) {
self.init(x: x, y: y, width: 0, height: 0)
}
init(origin: CGPoint) {
self.init(origin: origin, size: .zero)
}
init(width: CGFloat, height: CGFloat) {
self.init(origin: .zero, size: CGSize(width: width, height: height))
}
init(size: CGSize) {
self.init(origin: .zero, size: size)
}
// MARK: helpers
var x: CGFloat { return origin.x }
var y: CGFloat { return origin.y }
var center: CGPoint {
get { return CGPoint(x: self.midX, y: self.midY) }
set { origin = CGPoint(x: newValue.x - width / 2, y: newValue.y - height / 2) }
}
// MARK: dimension setters
func at(origin amt: CGPoint) -> CGRect {
var f = self
f.origin = amt
return f
}
func with(size amt: CGSize) -> CGRect {
var f = self
f.size = amt
return f
}
func at(x amt: CGFloat) -> CGRect {
var f = self
f.origin.x = amt
return f
}
func at(y amt: CGFloat) -> CGRect {
var f = self
f.origin.y = amt
return f
}
func with(width amt: CGFloat) -> CGRect {
var f = self
f.size.width = amt
return f
}
func with(height amt: CGFloat) -> CGRect {
var f = self
f.size.height = amt
return f
}
// MARK: inset(xxx:)
func inset(all: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: all, left: all, bottom: all, right: all))
}
func inset(topBottom: CGFloat, sides: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: topBottom, left: sides, bottom: topBottom, right: sides))
}
func inset(topBottom: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: topBottom, left: 0, bottom: topBottom, right: 0))
}
func inset(sides: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: sides, bottom: 0, right: sides))
}
func inset(top: CGFloat, sides: CGFloat, bottom: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: top, left: sides, bottom: bottom, right: sides))
}
func inset(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: top, left: left, bottom: bottom, right: right))
}
func inset(_ insets: UIEdgeInsets) -> CGRect {
return inset(by: insets)
}
// MARK: shrink(xxx:)
func shrink(left amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: amt))
}
func shrink(right amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: amt, bottom: 0, right: 0))
}
func shrink(down amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: amt, left: 0, bottom: 0, right: 0))
}
func shrink(up amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: 0, bottom: amt, right: 0))
}
// MARK: grow(xxx:)
func grow(_ margins: UIEdgeInsets) -> CGRect {
return inset(
by: UIEdgeInsets(
top: -margins.top,
left: -margins.left,
bottom: -margins.bottom,
right: -margins.right
)
)
}
func grow(all: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: -all, left: -all, bottom: -all, right: -all))
}
func grow(topBottom: CGFloat, sides: CGFloat) -> CGRect {
return inset(
by: UIEdgeInsets(top: -topBottom, left: -sides, bottom: -topBottom, right: -sides)
)
}
func grow(top: CGFloat, sides: CGFloat, bottom: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: -top, left: -sides, bottom: -bottom, right: -sides))
}
func grow(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: -top, left: -left, bottom: -bottom, right: -right))
}
func grow(left amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: -amt, bottom: 0, right: 0))
}
func grow(right amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -amt))
}
func grow(up amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: -amt, left: 0, bottom: 0, right: 0))
}
func grow(down amt: CGFloat) -> CGRect {
return inset(by: UIEdgeInsets(top: 0, left: 0, bottom: -amt, right: 0))
}
// MARK: from(xxx:)
func fromTop() -> CGRect {
return CGRect(x: minX, y: minY, width: width, height: 0)
}
func fromBottom() -> CGRect {
return CGRect(x: minX, y: maxY, width: width, height: 0)
}
func fromLeft() -> CGRect {
return CGRect(x: minX, y: minY, width: 0, height: height)
}
func fromRight() -> CGRect {
return CGRect(x: maxX, y: minY, width: 0, height: height)
}
// MARK: shift(xxx:)
func shift(up amt: CGFloat) -> CGRect {
return at(y: self.y - amt)
}
func shift(down amt: CGFloat) -> CGRect {
return at(y: self.y + amt)
}
func shift(left amt: CGFloat) -> CGRect {
return at(x: self.x - amt)
}
func shift(right amt: CGFloat) -> CGRect {
return at(x: self.x + amt)
}
}
| mit | 8da941101beeadaaa00434cdbca6d1cb | 27.145631 | 100 | 0.56209 | 3.552696 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceClipLogic/Tests/EurofurenceClipLogicTests/MockClipFallbackContent.swift | 1 | 784 | import EurofurenceClipLogic
import XCTest
class MockClipFallbackContent: ClipContentScene {
enum Content: Equatable {
case unset
case events
case dealers
}
private(set) var displayedContent: Content = .unset
func prepareForShowingEvents() {
displayedContent = .events
}
func prepareForShowingDealers() {
displayedContent = .dealers
}
func assertNotDisplayingAnything(file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(displayedContent, .unset, file: file, line: line)
}
func assertDisplaying(_ expected: Content, file: StaticString = #file, line: UInt = #line) {
XCTAssertEqual(displayedContent, expected, file: file, line: line)
}
}
| mit | 467fb0843a956ed9e6c65ff9f551b16e | 25.133333 | 96 | 0.647959 | 4.722892 | false | false | false | false |
manavgabhawala/swift | test/SILGen/expressions.swift | 1 | 17320 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-stdlib -emit-silgen %s -I%t -disable-access-control | %FileCheck %s
import Swift
import FooBar
struct SillyString : _ExpressibleByBuiltinStringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {}
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
}
init(stringLiteral value: SillyString) { }
}
struct SillyUTF16String : _ExpressibleByBuiltinUTF16StringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { }
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) { }
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
}
init(stringLiteral value: SillyUTF16String) { }
}
func literals() {
var a = 1
var b = 1.25
var d = "foö"
var e:SillyString = "foo"
}
// CHECK-LABEL: sil hidden @_T011expressions8literalsyyF
// CHECK: integer_literal $Builtin.Int2048, 1
// CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}}
// CHECK: string_literal utf16 "foö"
// CHECK: string_literal utf8 "foo"
func bar(_ x: Int) {}
func bar(_ x: Int, _ y: Int) {}
func call_one() {
bar(42);
}
// CHECK-LABEL: sil hidden @_T011expressions8call_oneyyF
// CHECK: [[BAR:%[0-9]+]] = function_ref @_T011expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int) -> ()
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]])
func call_two() {
bar(42, 219)
}
// CHECK-LABEL: sil hidden @_T011expressions8call_twoyyF
// CHECK: [[BAR:%[0-9]+]] = function_ref @_T011expressions3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (Int, Int) -> ()
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219
// CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}})
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]])
func tuples() {
bar((4, 5).1)
var T1 : (a: Int16, b: Int) = (b : 42, a : 777)
}
// CHECK-LABEL: sil hidden @_T011expressions6tuplesyyF
class C {
var chi:Int
init() {
chi = 219
}
init(x:Int) {
chi = x
}
}
// CHECK-LABEL: sil hidden @_T011expressions7classesyyF
func classes() {
// CHECK: function_ref @_T011expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
var a = C()
// CHECK: function_ref @_T011expressions1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thick C.Type) -> @owned C
var b = C(x: 0)
}
struct S {
var x:Int
init() {
x = 219
}
init(x: Int) {
self.x = x
}
}
// CHECK-LABEL: sil hidden @_T011expressions7structsyyF
func structs() {
// CHECK: function_ref @_T011expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> S
var a = S()
// CHECK: function_ref @_T011expressions1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (Int, @thin S.Type) -> S
var b = S(x: 0)
}
func inoutcallee(_ x: inout Int) {}
func address_of_expr() {
var x: Int = 4
inoutcallee(&x)
}
func identity<T>(_ x: T) -> T {}
struct SomeStruct {
mutating
func a() {}
}
// CHECK-LABEL: sil hidden @_T011expressions5callsyyF
// CHECK: [[METHOD:%[0-9]+]] = function_ref @_T011expressions10SomeStructV1a{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout SomeStruct) -> ()
// CHECK: apply [[METHOD]]({{.*}})
func calls() {
var a : SomeStruct
a.a()
}
// CHECK-LABEL: sil hidden @_T011expressions11module_path{{[_0-9a-zA-Z]*}}F
func module_path() -> Int {
return FooBar.x
// CHECK: [[x_GET:%[0-9]+]] = function_ref @_T06FooBar1xSifau
// CHECK-NEXT: apply [[x_GET]]()
}
func default_args(_ x: Int, y: Int = 219, z: Int = 20721) {}
// CHECK-LABEL: sil hidden @_T011expressions19call_default_args_1{{[_0-9a-zA-Z]*}}F
func call_default_args_1(_ x: Int) {
default_args(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}F
// CHECK: [[YFUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A0_
// CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]()
// CHECK: [[ZFUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A1_
// CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]()
// CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]])
}
// CHECK-LABEL: sil hidden @_T011expressions19call_default_args_2{{[_0-9a-zA-Z]*}}F
func call_default_args_2(_ x: Int, z: Int) {
default_args(x, z:z)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}F
// CHECK: [[DEFFN:%[0-9]+]] = function_ref @_T011expressions12default_args{{[_0-9a-zA-Z]*}}A0_
// CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]()
// CHECK: apply [[FUNC]]({{.*}}, [[C219]], {{.*}})
}
struct Generic<T> {
var mono_member:Int
var typevar_member:T
// CHECK-LABEL: sil hidden @_T011expressions7GenericV13type_variable{{[_0-9a-zA-Z]*}}F
mutating
func type_variable() -> T.Type {
return T.self
// CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type
// CHECK: return [[METATYPE]]
}
// CHECK-LABEL: sil hidden @_T011expressions7GenericV19copy_typevar_member{{[_0-9a-zA-Z]*}}F
mutating
func copy_typevar_member(_ x: Generic<T>) {
typevar_member = x.typevar_member
}
// CHECK-LABEL: sil hidden @_T011expressions7GenericV12class_method{{[_0-9a-zA-Z]*}}FZ
static func class_method() {}
}
// CHECK-LABEL: sil hidden @_T011expressions18generic_member_ref{{[_0-9a-zA-Z]*}}F
func generic_member_ref<T>(_ x: Generic<T>) -> Int {
// CHECK: bb0([[XADDR:%[0-9]+]] : $*Generic<T>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @_T011expressions24bound_generic_member_ref{{[_0-9a-zA-Z]*}}F
func bound_generic_member_ref(_ x: Generic<UnicodeScalar>) -> Int {
var x = x
// CHECK: bb0([[XADDR:%[0-9]+]] : $Generic<UnicodeScalar>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @_T011expressions6coerce{{[_0-9a-zA-Z]*}}F
func coerce(_ x: Int32) -> Int64 {
return 0
}
class B {
}
class D : B {
}
// CHECK-LABEL: sil hidden @_T011expressions8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ x: B) -> D {
return x as! D
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D
}
// CHECK-LABEL: sil hidden @_T011expressions6upcast{{[_0-9a-zA-Z]*}}F
func upcast(_ x: D) -> B {
return x
// CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B
}
// CHECK-LABEL: sil hidden @_T011expressions14generic_upcast{{[_0-9a-zA-Z]*}}F
func generic_upcast<T : B>(_ x: T) -> B {
return x
// CHECK: upcast %{{.*}} to $B
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T011expressions16generic_downcast{{[_0-9a-zA-Z]*}}F
func generic_downcast<T : B>(_ x: T, y: B) -> T {
return y as! T
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T
// CHECK: return
}
// TODO: generic_downcast
// CHECK-LABEL: sil hidden @_T011expressions15metatype_upcast{{[_0-9a-zA-Z]*}}F
func metatype_upcast() -> B.Type {
return D.self
// CHECK: metatype $@thick D
// CHECK-NEXT: upcast
}
// CHECK-LABEL: sil hidden @_T011expressions19interpolated_string{{[_0-9a-zA-Z]*}}F
func interpolated_string(_ x: Int, y: String) -> String {
return "The \(x) Million Dollar \(y)"
}
protocol Runcible {
associatedtype U
var free:Int { get }
var associated:U { get }
func free_method() -> Int
mutating func associated_method() -> U.Type
static func static_method()
}
protocol Mincible {
var free:Int { get }
func free_method() -> Int
static func static_method()
}
protocol Bendable { }
protocol Wibbleable { }
// CHECK-LABEL: sil hidden @_T011expressions20archetype_member_ref{{[_0-9a-zA-Z]*}}F
func archetype_member_ref<T : Runcible>(_ x: T) {
var x = x
x.free_method()
// CHECK: witness_method $T, #Runcible.free_method!1
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[X:%.*]] to [initialization] [[TEMP]]
// CHECK-NEXT: apply
// CHECK-NEXT: destroy_addr [[TEMP]]
var u = x.associated_method()
// CHECK: witness_method $T, #Runcible.associated_method!1
// CHECK-NEXT: apply
T.static_method()
// CHECK: witness_method $T, #Runcible.static_method!1
// CHECK-NEXT: metatype $@thick T.Type
// CHECK-NEXT: apply
}
// CHECK-LABEL: sil hidden @_T011expressions22existential_member_ref{{[_0-9a-zA-Z]*}}F
func existential_member_ref(_ x: Mincible) {
x.free_method()
// CHECK: open_existential_addr
// CHECK-NEXT: witness_method
// CHECK-NEXT: apply
}
/*TODO archetype and existential properties and subscripts
func archetype_property_ref<T : Runcible>(_ x: T) -> (Int, T.U) {
x.free = x.free_method()
x.associated = x.associated_method()
return (x.free, x.associated)
}
func existential_property_ref<T : Runcible>(_ x: T) -> Int {
x.free = x.free_method()
return x.free
}
also archetype/existential subscripts
*/
struct Spoon : Runcible, Mincible {
typealias U = Float
var free: Int { return 4 }
var associated: Float { return 12 }
func free_method() -> Int {}
func associated_method() -> Float.Type {}
static func static_method() {}
}
struct Hat<T> : Runcible {
typealias U = [T]
var free: Int { return 1 }
var associated: U { get {} }
func free_method() -> Int {}
// CHECK-LABEL: sil hidden @_T011expressions3HatV17associated_method{{[_0-9a-zA-Z]*}}F
mutating
func associated_method() -> U.Type {
return U.self
// CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type
// CHECK: return [[META]]
}
static func static_method() {}
}
// CHECK-LABEL: sil hidden @_T011expressions7erasure{{[_0-9a-zA-Z]*}}F
func erasure(_ x: Spoon) -> Mincible {
return x
// CHECK: init_existential_addr
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T011expressions19declref_to_metatypeAA5SpoonVmyF
func declref_to_metatype() -> Spoon.Type {
return Spoon.self
// CHECK: metatype $@thin Spoon.Type
}
// CHECK-LABEL: sil hidden @_T011expressions27declref_to_generic_metatype{{[_0-9a-zA-Z]*}}F
func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type {
// FIXME parsing of T<U> in expression context
typealias GenericChar = Generic<UnicodeScalar>
return GenericChar.self
// CHECK: metatype $@thin Generic<UnicodeScalar>.Type
}
func int(_ x: Int) {}
func float(_ x: Float) {}
func tuple() -> (Int, Float) { return (1, 1.0) }
// CHECK-LABEL: sil hidden @_T011expressions13tuple_element{{[_0-9a-zA-Z]*}}F
func tuple_element(_ x: (Int, Float)) {
var x = x
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Float) }
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
int(x.0)
// CHECK: tuple_element_addr [[PB]] : {{.*}}, 0
// CHECK: apply
float(x.1)
// CHECK: tuple_element_addr [[PB]] : {{.*}}, 1
// CHECK: apply
int(tuple().0)
// CHECK: [[ZERO:%.*]] = tuple_extract {{%.*}} : {{.*}}, 0
// CHECK: apply {{.*}}([[ZERO]])
float(tuple().1)
// CHECK: [[ONE:%.*]] = tuple_extract {{%.*}} : {{.*}}, 1
// CHECK: apply {{.*}}([[ONE]])
}
// CHECK-LABEL: sil hidden @_T011expressions10containers{{[_0-9a-zA-Z]*}}F
func containers() -> ([Int], Dictionary<String, Int>) {
return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3])
}
// CHECK-LABEL: sil hidden @_T011expressions7if_expr{{[_0-9a-zA-Z]*}}F
func if_expr(_ a: Bool, b: Bool, x: Int, y: Int, z: Int) -> Int {
var a = a
var b = b
var x = x
var y = y
var z = z
// CHECK: bb0({{.*}}):
// CHECK: [[AB:%[0-9]+]] = alloc_box ${ var Bool }
// CHECK: [[PBA:%.*]] = project_box [[AB]]
// CHECK: [[BB:%[0-9]+]] = alloc_box ${ var Bool }
// CHECK: [[PBB:%.*]] = project_box [[BB]]
// CHECK: [[XB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBX:%.*]] = project_box [[XB]]
// CHECK: [[YB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBY:%.*]] = project_box [[YB]]
// CHECK: [[ZB:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBZ:%.*]] = project_box [[ZB]]
return a
? x
: b
? y
: z
// CHECK: [[A:%[0-9]+]] = load [trivial] [[PBA]]
// CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]])
// CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]]
// CHECK: [[IF_A]]:
// CHECK: [[XVAL:%[0-9]+]] = load [trivial] [[PBX]]
// CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int)
// CHECK: [[ELSE_A]]:
// CHECK: [[B:%[0-9]+]] = load [trivial] [[PBB]]
// CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]])
// CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]]
// CHECK: [[IF_B]]:
// CHECK: [[YVAL:%[0-9]+]] = load [trivial] [[PBY]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int)
// CHECK: [[ELSE_B]]:
// CHECK: [[ZVAL:%[0-9]+]] = load [trivial] [[PBZ]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int)
// CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : $Int):
// CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int)
// CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : $Int):
// CHECK: return [[A_RES]]
}
// Test that magic identifiers expand properly. We test #column here because
// it isn't affected as this testcase slides up and down the file over time.
func magic_identifier_expansion(_ a: Int = #column) {
// CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion
// This should expand to the column number of the first _.
var tmp = #column
// CHECK: integer_literal $Builtin.Int2048, 13
// This should expand to the column number of the (, not to the column number
// of #column in the default argument list of this function.
// rdar://14315674
magic_identifier_expansion()
// CHECK: integer_literal $Builtin.Int2048, 29
}
func print_string() {
// CHECK-LABEL: print_string
var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}"
// CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}"
}
// Test that we can silgen superclass calls that go farther than the immediate
// superclass.
class Super1 {
func funge() {}
}
class Super2 : Super1 {}
class Super3 : Super2 {
override func funge() {
super.funge()
}
}
// <rdar://problem/16880240> SILGen crash assigning to _
func testDiscardLValue() {
var a = 42
_ = a
}
func dynamicTypePlusZero(_ a : Super1) -> Super1.Type {
return type(of: a)
}
// CHECK-LABEL: dynamicTypePlusZero
// CHECK: bb0([[ARG:%.*]] : $Super1):
// CHECK-NOT: copy_value
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NOT: copy_value
// CHECK: value_metatype $@thick Super1.Type, [[BORROWED_ARG]] : $Super1
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
struct NonTrivialStruct { var c : Super1 }
func dontEmitIgnoredLoadExpr(_ a : NonTrivialStruct) -> NonTrivialStruct.Type {
return type(of: a)
}
// CHECK-LABEL: dontEmitIgnoredLoadExpr
// CHECK: bb0(%0 : $NonTrivialStruct):
// CHECK-NEXT: debug_value
// CHECK-NEXT: begin_borrow
// CHECK-NEXT: end_borrow
// CHECK-NEXT: %4 = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: destroy_value %0
// CHECK-NEXT: return %4 : $@thin NonTrivialStruct.Type
// <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding
// CHECK-LABEL: sil hidden @_T011expressions21implodeRecursiveTupleySi_Sit_SitSgF
// CHECK: bb0(%0 : $Optional<((Int, Int), Int)>):
func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) {
// CHECK: bb2([[WHOLE:%.*]] : $((Int, Int), Int)):
// CHECK-NEXT: [[X:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 0
// CHECK-NEXT: [[X0:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 0
// CHECK-NEXT: [[X1:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 1
// CHECK-NEXT: [[Y:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 1
// CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[X0]] : $Int, [[X1]] : $Int)
// CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x"
// CHECK-NEXT: debug_value [[Y]] : $Int, let, name "y"
let (x, y) = expr!
}
func test20087517() {
class Color {
static func greenColor() -> Color { return Color() }
}
let x: (Color?, Int) = (.greenColor(), 1)
}
func test20596042() {
enum E {
case thing1
case thing2
}
func f() -> (E?, Int)? {
return (.thing1, 1)
}
}
func test21886435() {
() = ()
}
| apache-2.0 | c0a9dca36952f4f791c4c2a5f20f19db | 28.701544 | 143 | 0.610765 | 3.071847 | false | false | false | false |
everald/JetPack | Sources/UI/ImageView.swift | 1 | 17542 | import UIKit
@objc(JetPack_ImageView)
open class ImageView: View {
public typealias Session = _ImageViewSession
public typealias SessionListener = _ImageViewSessionListener
public typealias Source = _ImageViewSource
fileprivate var activityIndicatorIsVisible = false
fileprivate var imageLayer = ImageLayer()
fileprivate var isLayouting = false
fileprivate var isSettingImage = false
fileprivate var isSettingImageFromSource = false
fileprivate var isSettingSource = false
fileprivate var isSettingSourceFromImage = false
fileprivate var lastAppliedTintColor: UIColor?
fileprivate var lastLayoutedSize = CGSize()
fileprivate var sourceImageRetrievalCompleted = false
fileprivate var sourceSession: Session?
fileprivate var sourceSessionConfigurationIsValid = true
fileprivate var tintedImage: UIImage?
public var imageChanged: Closure?
public var sourceTransitionDuration = TimeInterval(0)
public override init() {
super.init()
isUserInteractionEnabled = false
layer.addSublayer(imageLayer)
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
deinit {
sourceSession?.stopRetrievingImage()
}
fileprivate var _activityIndicator: UIActivityIndicatorView?
public final var activityIndicator: UIActivityIndicatorView {
return _activityIndicator ?? {
let child = UIActivityIndicatorView(style: .gray)
child.hidesWhenStopped = false
child.alpha = 0
child.startAnimating()
_activityIndicator = child
return child
}()
}
fileprivate var activityIndicatorShouldBeVisible: Bool {
guard showsActivityIndicatorWhileLoading else {
return false
}
guard source != nil && !sourceImageRetrievalCompleted else {
return false
}
return true
}
fileprivate func computeImageLayerFrame() -> CGRect {
guard let image = image else {
return .zero
}
let imageSize = image.size
let maximumImageLayerFrame = CGRect(size: bounds.size).insetBy(padding)
guard imageSize.isPositive && maximumImageLayerFrame.size.isPositive else {
return .zero
}
let gravity = self.gravity
let scaling = self.scaling
var imageLayerFrame = CGRect()
switch scaling {
case .fitIgnoringAspectRatio:
imageLayerFrame.size = maximumImageLayerFrame.size
case .fitInside, .fitOutside:
let horizontalScale = maximumImageLayerFrame.width / imageSize.width
let verticalScale = maximumImageLayerFrame.height / imageSize.height
let scale = (scaling == .fitInside ? min : max)(horizontalScale, verticalScale)
imageLayerFrame.size = imageSize.scaleBy(scale)
case .fitHorizontally:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height * (imageLayerFrame.width / imageSize.width)
case .fitHorizontallyIgnoringAspectRatio:
imageLayerFrame.width = maximumImageLayerFrame.width
imageLayerFrame.height = imageSize.height
case .fitVertically:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width * (imageLayerFrame.height / imageSize.height)
case .fitVerticallyIgnoringAspectRatio:
imageLayerFrame.height = maximumImageLayerFrame.height
imageLayerFrame.width = imageSize.width
case .none:
imageLayerFrame.size = imageSize
}
switch gravity.horizontal {
case .left:
imageLayerFrame.left = maximumImageLayerFrame.left
case .center:
imageLayerFrame.horizontalCenter = maximumImageLayerFrame.horizontalCenter
case .right:
imageLayerFrame.right = maximumImageLayerFrame.right
}
switch gravity.vertical {
case .top:
imageLayerFrame.top = maximumImageLayerFrame.top
case .center:
imageLayerFrame.verticalCenter = maximumImageLayerFrame.verticalCenter
case .bottom:
imageLayerFrame.bottom = maximumImageLayerFrame.bottom
}
switch image.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
let center = imageLayerFrame.center
let imageLayerFrameWidth = imageLayerFrame.width
let imageLayerFrameHeight = imageLayerFrame.height
imageLayerFrame.width = imageLayerFrameHeight
imageLayerFrame.height = imageLayerFrameWidth
imageLayerFrame.center = center
case .down, .downMirrored, .up, .upMirrored:
break
}
imageLayerFrame = alignToGrid(imageLayerFrame)
return imageLayerFrame
}
fileprivate func computeImageLayerTransform() -> CGAffineTransform {
guard let image = image else {
return CGAffineTransform.identity
}
// TODO support mirrored variants
let transform: CGAffineTransform
switch image.imageOrientation {
case .down: transform = CGAffineTransform(rotationAngle: .pi)
case .downMirrored: transform = CGAffineTransform(rotationAngle: .pi)
case .left: transform = CGAffineTransform(rotationAngle: -.pi / 2)
case .leftMirrored: transform = CGAffineTransform(rotationAngle: -.pi / 2)
case .right: transform = CGAffineTransform(rotationAngle: .pi / 2)
case .rightMirrored: transform = CGAffineTransform(rotationAngle: .pi / 2)
case .up: transform = CGAffineTransform.identity
case .upMirrored: transform = CGAffineTransform.identity
}
return transform
}
@available(*, unavailable, message: "Use .gravity and .scaling instead.")
public final override var contentMode: UIView.ContentMode {
get { return super.contentMode }
set { super.contentMode = newValue }
}
open override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
setNeedsLayout()
}
}
open var gravity = Gravity.center {
didSet {
guard gravity != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
open var image: UIImage? {
didSet {
precondition(!isSettingImage, "Cannot recursively set ImageView's 'image'.")
precondition(!isSettingSource || isSettingImageFromSource, "Cannot recursively set ImageView's 'image' and 'source'.")
isSettingImage = true
defer { isSettingImage = false }
guard image != oldValue || (oldValue == nil && source != nil) else { // TODO what if the current image is set again manually? source should be unset?
return
}
if !isSettingImageFromSource {
isSettingSourceFromImage = true
source = nil
isSettingSourceFromImage = false
}
lastAppliedTintColor = nil
setNeedsLayout()
if (image?.size ?? .zero) != (oldValue?.size ?? .zero) {
invalidateIntrinsicContentSize()
}
updateActivityIndicatorAnimated(true)
}
}
open override var intrinsicContentSize: CGSize {
return sizeThatFits()
}
fileprivate func invalidateConfiguration() {
guard sourceSessionConfigurationIsValid else {
return
}
sourceSessionConfigurationIsValid = false
setNeedsLayout()
}
open override func layoutSubviews() {
isLayouting = true
defer { isLayouting = false }
super.layoutSubviews()
let bounds = self.bounds
if bounds.size != lastLayoutedSize {
lastLayoutedSize = bounds.size
sourceSessionConfigurationIsValid = false
}
if let activityIndicator = _activityIndicator {
activityIndicator.center = bounds.insetBy(padding).center
}
let imageLayerFrame = computeImageLayerFrame()
imageLayer.bounds = CGRect(size: imageLayerFrame.size)
imageLayer.position = imageLayerFrame.center
if let image = image, image.renderingMode == .alwaysTemplate {
if tintColor != lastAppliedTintColor {
lastAppliedTintColor = tintColor
tintedImage = image.imageWithColor(tintColor)
}
}
else {
tintedImage = nil
}
if let contentImage = tintedImage ?? image {
imageLayer.contents = contentImage.cgImage
imageLayer.contentsScale = contentImage.scale
imageLayer.transform = CATransform3DMakeAffineTransform(computeImageLayerTransform())
let capInsets = contentImage.capInsets
let imageSize = contentImage.size
if capInsets.isEmpty || !imageSize.isPositive {
imageLayer.contentsCenter = CGRect(width: 1, height: 1)
}
else {
imageLayer.contentsCenter = CGRect(
left: capInsets.left / imageSize.width,
top: capInsets.top / imageSize.height,
width: (imageSize.width - capInsets.right - capInsets.left) / imageSize.width,
height: (imageSize.height - capInsets.top - capInsets.bottom) / imageSize.height
)
}
}
else {
imageLayer.contents = nil
imageLayer.transform = CATransform3DIdentity
}
startOrUpdateSourceSession()
}
open override func measureOptimalSize(forAvailableSize availableSize: CGSize) -> CGSize {
let fittingSize: CGSize
let availableSize = availableSize.insetBy(padding)
if availableSize.isPositive, let imageSize = image?.size, imageSize.isPositive {
let imageRatio = imageSize.width / imageSize.height
switch scaling {
case .fitHorizontally,
.fitHorizontallyIgnoringAspectRatio:
fittingSize = CGSize(
width: availableSize.width,
height: availableSize.width / imageRatio
)
case .fitVertically,
.fitVerticallyIgnoringAspectRatio:
fittingSize = CGSize(
width: availableSize.height * imageRatio,
height: availableSize.height
)
case .fitIgnoringAspectRatio,
.fitInside,
.fitOutside,
.none:
fittingSize = imageSize
}
}
else {
fittingSize = .zero
}
return CGSize(
width: fittingSize.width + padding.left + padding.right,
height: fittingSize.height + padding.top + padding.bottom
)
}
public var optimalImageScale: CGFloat {
return gridScaleFactor
}
public var optimalImageSize: CGSize {
let size = bounds.size.insetBy(padding)
guard size.width > 0 && size.height > 0 else {
return .zero
}
return size
}
open var padding = UIEdgeInsets() {
didSet {
if padding == oldValue {
return
}
setNeedsLayout()
invalidateConfiguration()
invalidateIntrinsicContentSize()
}
}
open override var preferredSize: PartialSize {
didSet {
guard preferredSize != oldValue else {
return
}
invalidateConfiguration()
}
}
open var scaling = Scaling.fitInside {
didSet {
guard scaling != oldValue else {
return
}
setNeedsLayout()
invalidateConfiguration()
}
}
open var showsActivityIndicatorWhileLoading = true {
didSet {
guard showsActivityIndicatorWhileLoading != oldValue else {
return
}
updateActivityIndicatorAnimated(true)
}
}
open var source: Source? {
didSet {
precondition(!isSettingSource, "Cannot recursively set ImageView's 'source'.")
precondition(!isSettingSource || isSettingSourceFromImage, "Cannot recursively set ImageView's 'source' and 'image'.")
if let source = source, let oldSource = oldValue, source.equals(oldSource) {
if sourceImageRetrievalCompleted && image == nil {
stopSourceSession()
startOrUpdateSourceSession()
updateActivityIndicatorAnimated(true)
}
return
}
if source == nil && oldValue == nil {
return
}
isSettingSource = true
defer {
isSettingSource = false
}
stopSourceSession()
if !isSettingSourceFromImage {
isSettingImageFromSource = true
image = nil
isSettingImageFromSource = false
}
if source != nil {
sourceSessionConfigurationIsValid = false
startOrUpdateSourceSession()
}
updateActivityIndicatorAnimated(true)
}
}
fileprivate func startOrUpdateSourceSession() {
guard !sourceSessionConfigurationIsValid && window != nil && (isLayouting || !needsLayout), let source = source else {
return
}
let optimalImageSize = self.optimalImageSize
guard !optimalImageSize.isEmpty else {
return
}
sourceSessionConfigurationIsValid = true
if let sourceSession = sourceSession {
sourceSession.imageViewDidChangeConfiguration(self)
}
else {
if let sourceSession = source.createSession() {
let listener = ClosureSessionListener { [weak self] image in
precondition(Thread.isMainThread, "ImageView.SessionListener.sessionDidRetrieveImage(_:) must be called on the main thread.")
guard let imageView = self else {
return
}
if sourceSession !== imageView.sourceSession {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called after session was stopped. The call will be ignored.")
return
}
if imageView.isSettingImageFromSource {
log("ImageView.SessionListener.sessionDidRetrieveImage(_:) was called from within an 'image' property observer. The call will be ignored.")
return
}
imageView.sourceImageRetrievalCompleted = true
imageView.isSettingImageFromSource = true
imageView.image = image
imageView.isSettingImageFromSource = false
imageView.updateActivityIndicatorAnimated(true)
let transitionDuration = imageView.sourceTransitionDuration
if transitionDuration > 0 {
let transition = CATransition()
transition.duration = transitionDuration
imageView.imageLayer.add(transition, forKey: kCATransition)
}
imageView.imageChanged?()
}
self.sourceSession = sourceSession
sourceSession.startRetrievingImageForImageView(self, listener: listener)
}
else if let image = source.staticImage {
sourceImageRetrievalCompleted = true
isSettingImageFromSource = true
self.image = image
isSettingImageFromSource = false
updateActivityIndicatorAnimated(true)
}
}
}
fileprivate func stopSourceSession() {
guard let sourceSession = sourceSession else {
return
}
sourceImageRetrievalCompleted = false
self.sourceSession = nil
sourceSession.stopRetrievingImage()
}
open override func tintColorDidChange() {
super.tintColorDidChange()
setNeedsLayout()
}
fileprivate func updateActivityIndicatorAnimated(_ animated: Bool) {
let animation = animated ? Animation() : nil
if activityIndicatorShouldBeVisible {
guard !activityIndicatorIsVisible else {
return
}
let activityIndicator = self.activityIndicator
activityIndicatorIsVisible = true
addSubview(activityIndicator)
animation.runAlways {
activityIndicator.alpha = 1
}
}
else {
guard activityIndicatorIsVisible, let activityIndicator = _activityIndicator else {
return
}
activityIndicatorIsVisible = false
animation.runAlwaysWithCompletion { complete in
activityIndicator.alpha = 0
complete { _ in
if !self.activityIndicatorIsVisible {
activityIndicator.removeFromSuperview()
}
}
}
}
}
public enum Gravity {
case bottomCenter
case bottomLeft
case bottomRight
case center
case centerLeft
case centerRight
case topCenter
case topLeft
case topRight
public init(horizontal: Horizontal, vertical: Vertical) {
switch vertical {
case .bottom:
switch horizontal {
case .left: self = .bottomLeft
case .center: self = .bottomCenter
case .right: self = .bottomRight
}
case .center:
switch horizontal {
case .left: self = .centerLeft
case .center: self = .center
case .right: self = .centerRight
}
case .top:
switch horizontal {
case .left: self = .topLeft
case .center: self = .topCenter
case .right: self = .topRight
}
}
}
public var horizontal: Horizontal {
switch self {
case .bottomLeft, .centerLeft, .topLeft:
return .left
case .bottomCenter, .center, .topCenter:
return .center
case .bottomRight, .centerRight, .topRight:
return .right
}
}
public var vertical: Vertical {
switch self {
case .bottomCenter, .bottomLeft, .bottomRight:
return .bottom
case .center, .centerLeft, .centerRight:
return .center
case .topCenter, .topLeft, .topRight:
return .top
}
}
public enum Horizontal {
case center
case left
case right
}
public enum Vertical {
case bottom
case center
case top
}
}
public enum Scaling {
case fitHorizontally
case fitHorizontallyIgnoringAspectRatio
case fitIgnoringAspectRatio
case fitInside
case fitOutside
case fitVertically
case fitVerticallyIgnoringAspectRatio
case none
}
}
public protocol _ImageViewSession: class {
func imageViewDidChangeConfiguration (_ imageView: ImageView)
func startRetrievingImageForImageView (_ imageView: ImageView, listener: ImageView.SessionListener)
func stopRetrievingImage ()
}
public protocol _ImageViewSessionListener {
func sessionDidFailToRetrieveImageWithFailure (_ failure: Failure)
func sessionDidRetrieveImage (_ image: UIImage)
}
public protocol _ImageViewSource {
var staticImage: UIImage? { get }
func createSession () -> ImageView.Session?
func equals (_ source: ImageView.Source) -> Bool
}
extension _ImageViewSource {
public var staticImage: UIImage? {
return nil
}
}
extension _ImageViewSource where Self: Equatable {
public func equals(_ source: ImageView.Source) -> Bool {
guard let source = source as? Self else {
return false
}
return self == source
}
}
private struct ClosureSessionListener: ImageView.SessionListener {
fileprivate let didRetrieveImage: (UIImage) -> Void
fileprivate init(didRetrieveImage: @escaping (UIImage) -> Void) {
self.didRetrieveImage = didRetrieveImage
}
fileprivate func sessionDidFailToRetrieveImageWithFailure(_ failure: Failure) {
// TODO support this case
}
fileprivate func sessionDidRetrieveImage(_ image: UIImage) {
didRetrieveImage(image)
}
}
private final class ImageLayer: Layer {
fileprivate override func action(forKey event: String) -> CAAction? {
return nil
}
}
| mit | 6dbafd5a68e4c949161ef1940ee497af | 21.930719 | 152 | 0.724832 | 4.179652 | false | false | false | false |
pebble8888/PBKit | PBKit/AudioStreamBasicDescription+PBExtension.swift | 1 | 1729 | //
// PBAudioTool.swift
//
// Created by pebble8888 on 2017/01/08.
// Copyright © 2017年 pebble8888. All rights reserved.
//
import Foundation
import AVFoundation
extension AudioStreamBasicDescription {
// 16bit mono wav
init?(monoWAV sampleRate: UInt32){
#if os(iOS)
guard let fmt = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16,
sampleRate: Double(sampleRate),
channels: 1,
interleaved: true) else { return nil }
self = fmt.streamDescription.pointee
#else
let fmt = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16,
sampleRate: Double(sampleRate),
channels: 1,
interleaved: true)
self = fmt.streamDescription.pointee
#endif
}
// 16bit stereo wav
init?(stereoWAV sampleRate: UInt32) {
#if os(iOS)
guard let fmt = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16,
sampleRate: Double(sampleRate),
channels: 2,
interleaved: true) else { return nil }
self = fmt.streamDescription.pointee
#else
let fmt = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16,
sampleRate: Double(sampleRate),
channels: 2,
interleaved: true)
self = fmt.streamDescription.pointee
#endif
}
}
| mit | 84bfb47f7aed9e43d7ac4f8b8d8972a3 | 38.227273 | 91 | 0.513326 | 5.734219 | false | false | false | false |
laszlokorte/reform-swift | ReformCore/ReformCore/StaticPointAnchor.swift | 1 | 882 | //
// StaticPointAnchor.swift
// ReformCore
//
// Created by Laszlo Korte on 13.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformMath
struct StaticPointAnchor : Anchor {
fileprivate let point : WriteableRuntimePoint
let name : String
init(point : WriteableRuntimePoint, name: String) {
self.point = point
self.name = name
}
func getPositionFor<R:Runtime>(_ runtime: R) -> Vec2d? {
return point.getPositionFor(runtime)
}
func translate<R:Runtime>(_ runtime: R, delta: Vec2d) {
if let oldPos = point.getPositionFor(runtime) {
point.setPositionFor(runtime, position: oldPos + delta)
}
}
}
extension StaticPointAnchor : Equatable {
}
func ==(lhs: StaticPointAnchor, rhs: StaticPointAnchor) -> Bool {
return lhs.point.isEqualTo(rhs.point)
}
| mit | 6a791578578a819aff58e58fbd607e3f | 22.810811 | 67 | 0.648127 | 3.864035 | false | false | false | false |
iHunterX/SocketIODemo | DemoSocketIO/Utils/Colors/MyColor.swift | 1 | 6291 | //
// MyColor.swift
// DemoSocketIO
//
// Created by Loc.dx-KeizuDev on 11/3/16.
// Copyright © 2016 Loc Dinh Xuan. All rights reserved.
//
import UIKit
extension UIColor {
public convenience init(hex: Int, alpha: CGFloat = 1.0) {
let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let g = CGFloat((hex & 0x00FF00) >> 08) / 255.0
let b = CGFloat((hex & 0x0000FF) >> 00) / 255.0
self.init(red:r, green:g, blue:b, alpha:alpha)
}
class func crayons_cantaloupeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFCC66, alpha: alpha) }
class func crayons_honeydewColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xCCFF66, alpha: alpha) }
class func crayons_spindriftColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FFCC, alpha: alpha) }
class func crayons_skyColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66CCFF, alpha: alpha) }
class func crayons_lavenderColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xCC66FF, alpha: alpha) }
class func crayons_carnationColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFF6FCF, alpha: alpha) }
class func crayons_licoriceColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x000000, alpha: alpha) }
class func crayons_snowColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFFFFF, alpha: alpha) }
class func crayons_salmonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFF6666, alpha: alpha) }
class func crayons_bananaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xFFFF66, alpha: alpha) }
class func crayons_floraColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FF66, alpha: alpha) }
class func crayons_iceColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x66FFFF, alpha: alpha) }
class func crayons_orchidColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x6666FF, alpha: alpha) }
class func crayons_bubblegumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff66ff, alpha: alpha) }
class func crayons_leadColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x191919, alpha: alpha) }
class func crayons_mercuryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xe6e6e6, alpha: alpha) }
class func crayons_tangerineColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff8000, alpha: alpha) }
class func crayons_limeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x80ff00, alpha: alpha) }
class func crayons_seaFoamColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ff80, alpha: alpha) }
class func crayons_aquaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x0080ff, alpha: alpha) }
class func crayons_grapeColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x8000ff, alpha: alpha) }
class func crayons_strawberryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff0080, alpha: alpha) }
class func crayons_tungstenColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x333333, alpha: alpha) }
class func crayons_silverColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xcccccc, alpha: alpha) }
class func crayons_maraschinoColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff0000, alpha: alpha) }
class func crayons_lemonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xffff00, alpha: alpha) }
class func crayons_springColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ff00, alpha: alpha) }
class func crayons_turquoiseColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x00ffff, alpha: alpha) }
class func crayons_blueberryColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x0000ff, alpha: alpha) }
class func crayons_magentaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xff00ff, alpha: alpha) }
class func crayons_ironColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x4c4c4c, alpha: alpha) }
class func crayons_magnesiumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0xb3b3b3, alpha: alpha) }
class func crayons_mochaColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x804000, alpha: alpha) }
class func crayons_fernColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x408000, alpha: alpha) }
class func crayons_mossColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008040, alpha: alpha) }
class func crayons_oceanColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x004080, alpha: alpha) }
class func crayons_eggplantColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x400080, alpha: alpha) }
class func crayons_maroonColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800040, alpha: alpha) }
class func crayons_steelColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x666666, alpha: alpha) }
class func crayons_aluminumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x999999, alpha: alpha) }
class func crayons_cayenneColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800000, alpha: alpha) }
class func crayons_asparagusColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x808000, alpha: alpha) }
class func crayons_cloverColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008000, alpha: alpha) }
class func crayons_tealColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x008080, alpha: alpha) }
class func crayons_midnightColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x000080, alpha: alpha) }
class func crayons_plumColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x800080, alpha: alpha) }
class func crayons_tinColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x7f7f7f, alpha: alpha) }
class func crayons_nickelColor (alpha: CGFloat = 1.0) -> UIColor { return UIColor(hex: 0x808080, alpha: alpha) }
}
| gpl-3.0 | bd1123604daed4c232f36c542284f641 | 91.5 | 120 | 0.67345 | 3.159216 | false | false | false | false |
filestack/filestack-ios | Sources/Filestack/UI/Internal/PhotoEditor/SelectionList/SelectableElement.swift | 1 | 4511 | //
// SelectableElement.swift
// Filestack
//
// Created by Ruben Nine on 7/11/19.
// Copyright © 2019 Filestack. All rights reserved.
//
import Photos
import UIKit
protocol SelectableElementDelegate: AnyObject {
func selectableElementThumbnailChanged(selectableElement: SelectableElement)
}
class SelectableElement {
let isEditable: Bool
let asset: PHAsset
weak var delegate: SelectableElementDelegate?
private(set) var additionalInfo: String?
private(set) var localURL: URL?
var mediaTypeImage: UIImage? {
switch asset.mediaType {
case .image:
return UIImage.fromFilestackBundle("icon-image").withRenderingMode(.alwaysTemplate)
case .video:
return UIImage.fromFilestackBundle("icon-video").withRenderingMode(.alwaysTemplate)
default:
return nil
}
}
var thumbnail: UIImage? {
didSet {
DispatchQueue.main.async {
self.delegate?.selectableElementThumbnailChanged(selectableElement: self)
}
}
}
var thumbnailSize: CGSize = CGSize(width: 512, height: 512)
var imageExportQuality: Float = 100
var imageExportPreset: ImageURLExportPreset = .current
var videoExportPreset: String = AVAssetExportPresetHEVCHighestQuality
private var requestIDs: [PHImageRequestID] = []
// MARK: - Lifecycle Functions
init(asset: PHAsset) {
self.asset = asset
switch asset.mediaType {
case .image:
isEditable = true
default:
isEditable = false
}
setup()
}
deinit {
for requestID in requestIDs {
PHImageManager.default().cancelImageRequest(requestID)
}
requestIDs.removeAll()
}
// MARK: - Public Functions
// Return editable image (backed with CIImage)
var editableImage: UIImage? {
guard isEditable else { return nil }
guard let localURL = localURL else { return nil }
guard let ciImage = CIImage(contentsOf: localURL, options: [.applyOrientationProperty: true]) else { return nil }
return UIImage(ciImage: ciImage)
}
// Update image
func update(image: UIImage) {
guard isEditable else { return }
guard let localURL = localURL, let cgBackedImage = image.cgImageBackedCopy() else { return }
if export(image: cgBackedImage, to: localURL) {
let ratio = max(thumbnailSize.width, thumbnailSize.height) / max(image.size.width, image.size.height)
let newSize = cgBackedImage.size.applying(CGAffineTransform(scaleX: ratio, y: ratio))
self.thumbnail = cgBackedImage.resized(for: newSize)
}
}
// MARK: - Private Functions
private func setup() {
// Get localURL & additionalInfo
asset.requestContentEditingInput(with: nil) { editingInput, _ in
if let editingInput = editingInput {
if let fullSizeImageURL = editingInput.fullSizeImageURL {
self.localURL = fullSizeImageURL.copyIntoTemporaryLocation()
} else if let audiovisualAsset = editingInput.audiovisualAsset,
let session = audiovisualAsset.videoExportSession(using: self.videoExportPreset) {
self.additionalInfo = audiovisualAsset.additionalInfo
session.exportAsynchronously {
self.localURL = session.outputURL
}
}
}
}
// Get original thumbnail
requestIDs.append(asset.fetchImage(forSize: thumbnailSize) { image, requestID in
self.requestIDs.removeAll { $0 == requestID }
self.thumbnail = image
})
}
}
// MARK: - Export Functions
extension SelectableElement {
private func export(image: UIImage, to destinationURL: URL) -> Bool {
switch imageExportPreset {
case .compatible:
return image.exportJPGImage(to: destinationURL, quality: imageExportQuality)
case .current:
// Use HEIC, and fallback to JPEG if it fails, since HEIC is not available in all devices
// (see https://support.apple.com/en-us/HT207022)
if image.exportHEICImage(to: destinationURL, quality: imageExportQuality) {
return true
} else {
return image.exportJPGImage(to: destinationURL, quality: imageExportQuality)
}
}
}
}
| mit | 9c15c020d1e456d556887a2fddcdc322 | 30.985816 | 121 | 0.629047 | 4.902174 | false | false | false | false |
DimensionSrl/Desman | Desman/Core/Managers/CoreDataSerializerManager.swift | 1 | 7402 | //
// CoreDataSerializerManager.swift
// Desman
//
// Created by Matteo Gavagnin on 18/11/15.
// Copyright © 2015 DIMENSION S.r.l. All rights reserved.
//
// Heaviliy based on https://github.com/mdelamata/CoreDataManager-Swift
import Foundation
import CoreData
class CoreDataSerializerManager: NSObject {
let kStoreName = "Desman.sqlite"
let kModmName = "Desman"
var _managedObjectContext: NSManagedObjectContext? = nil
var _managedObjectModel: NSManagedObjectModel? = nil
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
static let sharedInstance = CoreDataSerializerManager()
// #pragma mark - Core Data stack
func event(_ uuidString: String) -> CDEvent {
let request : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()
request.entity = NSEntityDescription.entity(forEntityName: "CDEvent", in: self.managedObjectContext)
request.predicate = NSPredicate(format: "uuid = %@", uuidString)
if let events = executeFetchRequest(request) as? [CDEvent], let event = events.last {
return event
} else {
return NSEntityDescription.insertNewObject(forEntityName: "CDEvent", into: self.managedObjectContext) as! CDEvent
}
}
var managedObjectContext: NSManagedObjectContext{
if Thread.isMainThread {
if (_managedObjectContext == nil) {
let coordinator = self.persistentStoreCoordinator
_managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
_managedObjectContext!.persistentStoreCoordinator = coordinator
return _managedObjectContext!
}
} else {
var threadContext : NSManagedObjectContext? = Thread.current.threadDictionary["NSManagedObjectContext"] as? NSManagedObjectContext;
if threadContext == nil {
if (_managedObjectContext == nil) {
let coordinator = self.persistentStoreCoordinator
_managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
threadContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
threadContext!.parent = _managedObjectContext
if #available(iOS 8.0, *) {
threadContext!.name = Thread.current.description
} else {
// Fallback on earlier versions
}
Thread.current.threadDictionary["NSManagedObjectContext"] = threadContext
NotificationCenter.default.addObserver(self, selector:#selector(CoreDataSerializerManager.contextWillSave(_:)) , name: NSNotification.Name.NSManagedObjectContextWillSave, object: threadContext)
}
return threadContext!;
}
return _managedObjectContext!
}
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if (_managedObjectModel == nil) {
let modelURL = Bundle(for: CoreDataSerializerManager.self).url(forResource: kModmName, withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOf: modelURL!)
}
return _managedObjectModel!
}
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if (_persistentStoreCoordinator == nil) {
let storeURL = applicationLibraryDirectory.appendingPathComponent(kStoreName)
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do {
try _persistentStoreCoordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: self.databaseOptions())
} catch let error {
print("Desman: cannot add CoreData persistent store \(error)")
}
}
return _persistentStoreCoordinator!
}
// #pragma mark - fetches
func executeFetchRequest(_ request:NSFetchRequest<NSFetchRequestResult>)-> Array<AnyObject>?{
var results:Array<AnyObject>?
self.managedObjectContext.performAndWait {
do {
results = try self.managedObjectContext.fetch(request)
} catch let error {
print("Desman: warning cannot fetch from Core Data \(error)")
}
}
return results
}
func executeFetchRequest(_ request:NSFetchRequest<NSFetchRequestResult>, completionHandler:@escaping (_ results: Array<NSFetchRequestResult>?) -> Void)-> (){
self.managedObjectContext.perform{
var results:Array<AnyObject>?
do {
results = try self.managedObjectContext.fetch(request)
} catch let error {
print("Desman: warning cannot fetch from Core Data \(error)")
}
completionHandler(results as? Array<NSFetchRequestResult>)
}
}
// #pragma mark - save methods
func save() {
let context:NSManagedObjectContext = self.managedObjectContext;
if context.hasChanges {
context.performAndWait{
do {
try context.save()
} catch _ {
print("Desman: warning cannot save to Core Data")
}
if let parentContext = context.parent {
parentContext.performAndWait {
do {
try parentContext.save()
} catch let error {
print("Desman: warning cannot save to Core Data \(error)")
}
}
}
}
}
}
func contextWillSave(_ notification:Foundation.Notification){
let context : NSManagedObjectContext! = notification.object as! NSManagedObjectContext
let insertedObjects = context.insertedObjects
if insertedObjects.count != 0 {
do {
try context.obtainPermanentIDs(for: Array(insertedObjects))
} catch let error {
print("Desman: warning cannot obtain ids from Core Data \(error)")
}
}
}
// #pragma mark - Utilities
func databaseOptions() -> Dictionary <String,Bool> {
var options = Dictionary<String,Bool>()
options[NSMigratePersistentStoresAutomaticallyOption] = true
options[NSInferMappingModelAutomaticallyOption] = true
return options
}
var applicationLibraryDirectory: URL {
let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)
return urls[urls.endIndex-1] as URL
}
}
| mit | 2d90ddb096fb23cb50a7534effe33693 | 39.222826 | 209 | 0.612215 | 6.131732 | false | false | false | false |
AntonTheDev/XCode-DI-Templates | Source/ProjectTemplates/tvOS/XCode-DI.xctemplate/Source/Extensions/UIColor+Hex.swift | 2 | 852 | //
// UIColor+Hex.swift
// Xcode Flight
//
// Copyright © 2017 Anton Doudarev. All rights reserved.
import Foundation
import UIKit
var colorCache = [Int : UIColor]()
extension UIColor {
static public func color(forHex hex: Int, withAlpha alpha : CGFloat = 1.0) -> UIColor {
if let color = colorCache[hex] {
return color
}
colorCache[hex] = UIColor(hex : hex, withAlpha : alpha)
return colorCache[hex]!
}
convenience init(hex: Int, withAlpha alpha : CGFloat = 1.0) {
let components = (
R: CGFloat((hex >> 16) & 0xff) / 255,
G: CGFloat((hex >> 08) & 0xff) / 255,
B: CGFloat((hex >> 00) & 0xff) / 255
)
self.init(red: components.R, green: components.G, blue: components.B, alpha: alpha)
}
}
| mit | cb9208c3542ca1b1b2bab4b12988bc7f | 24.787879 | 91 | 0.553467 | 3.799107 | false | false | false | false |
edx/edx-app-ios | Source/ContentInsetsController.swift | 1 | 3600 | //
// ContentInsetsController.swift
// edX
//
// Created by Akiva Leffert on 5/18/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public protocol ContentInsetsSourceDelegate : AnyObject {
func contentInsetsSourceChanged(source : ContentInsetsSource)
}
public protocol ContentInsetsSource : AnyObject {
var currentInsets: UIEdgeInsets { get }
var insetsDelegate: ContentInsetsSourceDelegate? { get set }
var affectsScrollIndicators: Bool { get }
}
public class ConstantInsetsSource : ContentInsetsSource {
public var currentInsets : UIEdgeInsets {
didSet {
self.insetsDelegate?.contentInsetsSourceChanged(source: self)
}
}
public let affectsScrollIndicators : Bool
public weak var insetsDelegate : ContentInsetsSourceDelegate?
public init(insets : UIEdgeInsets, affectsScrollIndicators : Bool) {
self.currentInsets = insets
self.affectsScrollIndicators = affectsScrollIndicators
}
}
/// General solution to the problem of edge insets that can change and need to
/// match a scroll view. When we drop iOS 7 support there may be a way to simplify this
/// by using the new layout margins API.
///
/// Other things like pull to refresh can be supported by creating a class that implements `ContentInsetsSource`
/// and providing a way to add it to the `insetsSources` list.
///
/// To use:
/// #. Call `setupInController:scrollView:` in the `viewDidLoad` method of your controller
/// #. Call `updateInsets` in the `viewDidLayoutSubviews` method of your controller
public class ContentInsetsController: NSObject, ContentInsetsSourceDelegate {
private var scrollView : UIScrollView?
private weak var owner : UIViewController?
private var insetSources : [ContentInsetsSource] = []
// Keyboard is separated out since it isn't a simple sum, but instead overrides other
// insets when present
private var keyboardSource : ContentInsetsSource?
public func setupInController(owner : UIViewController, scrollView : UIScrollView) {
self.owner = owner
self.scrollView = scrollView
keyboardSource = KeyboardInsetsSource(scrollView: scrollView)
keyboardSource?.insetsDelegate = self
}
private var controllerInsets : UIEdgeInsets {
let topGuideHeight = self.owner?.view.safeAreaInsets.top ?? 0
let bottomGuideHeight = self.owner?.view.safeAreaInsets.bottom ?? 0
return UIEdgeInsets(top : topGuideHeight, left : 0, bottom : bottomGuideHeight, right : 0)
}
public func contentInsetsSourceChanged(source: ContentInsetsSource) {
updateInsets()
}
public func addSource(source : ContentInsetsSource) {
source.insetsDelegate = self
insetSources.append(source)
updateInsets()
}
public func updateInsets() {
var regularInsets = insetSources
.map { $0.currentInsets }
.reduce(controllerInsets, +)
let indicatorSources = insetSources
.filter { $0.affectsScrollIndicators }
.map { $0.currentInsets }
var indicatorInsets = indicatorSources.reduce(controllerInsets, +)
if let keyboardHeight = keyboardSource?.currentInsets.bottom {
regularInsets.bottom = max(keyboardHeight, regularInsets.bottom)
indicatorInsets.bottom = max(keyboardHeight, indicatorInsets.bottom)
}
self.scrollView?.contentInset = regularInsets
self.scrollView?.scrollIndicatorInsets = indicatorInsets
}
}
| apache-2.0 | 02e498ea8fd42210a9c0d1851959d01a | 35.363636 | 112 | 0.699444 | 5.027933 | false | false | false | false |
u10int/Cartography | Cartography/Distribute.swift | 1 | 2677 | //
// Distribute.swift
// Cartography
//
// Created by Robert Böhnke on 17/02/15.
// Copyright (c) 2015 Robert Böhnke. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
typealias Accumulator = ([NSLayoutConstraint], LayoutProxy)
private func reduce(first: LayoutProxy, rest: [LayoutProxy], combine: (LayoutProxy, LayoutProxy) -> NSLayoutConstraint) -> [NSLayoutConstraint] {
rest.last?.view.car_translatesAutoresizingMaskIntoConstraints = false
return rest.reduce(([], first)) { (acc, current) -> Accumulator in
let (constraints, previous) = acc
return (constraints + [ combine(previous, current) ], current)
}.0
}
/// Distributes multiple views horizontally.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, horizontally first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.trailing == $1.leading - amount }
}
/// Distributes multiple views horizontally from left to right.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, leftToRight first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.right == $1.left - amount }
}
/// Distributes multiple views vertically.
///
/// All views passed to this function will have
/// their `translatesAutoresizingMaskIntoConstraints` properties set to `false`.
///
/// - parameter amount: The distance between the views.
/// - parameter views: The views to distribute.
///
/// - returns: An array of `NSLayoutConstraint` instances.
///
public func distribute(by amount: CGFloat, vertically first: LayoutProxy, _ rest: LayoutProxy...) -> [NSLayoutConstraint] {
return reduce(first, rest: rest) { $0.bottom == $1.top - amount }
}
/// Adds support for passing an array of views to distribute
/// https://github.com/robb/Cartography/issues/193
public func distribute(by amount: CGFloat, horizontally array: [LayoutProxy]) -> [NSLayoutConstraint] {
return reduce(array.first!, rest: Array(array.dropFirst())) { $0.trailing == $1.leading - amount }
}
| mit | 797a8e12dabd2c4c151e45bedb2c52ec | 35.643836 | 145 | 0.715514 | 4.134467 | false | false | false | false |
gregomni/swift | test/type/parameterized_existential.swift | 1 | 1727 | // RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on -requirement-machine-inferred-signatures=on -disable-availability-checking -enable-parameterized-existential-types
protocol Sequence<Element> {
associatedtype Element
}
struct ConcreteSequence<Element> : Sequence {}
extension Sequence {
func map<Other>(_ transform: (Self.Element) -> Other) -> ConcreteSequence<Other> {
return ConcreteSequence<Other>()
}
}
protocol DoubleWide<X, Y> {
associatedtype X
associatedtype Y
var x: X { get }
var y: Y { get }
}
extension Int: DoubleWide {
typealias X = Int
typealias Y = Int
var x: X { 0 }
var y: X { 0 }
}
struct Collapse<T: DoubleWide>: DoubleWide {
typealias X = T
typealias Y = T
var x: X
var y: X { self.x }
}
func test() -> any DoubleWide<some DoubleWide<Int, Int>, some DoubleWide<Int, Int>> { return Collapse<Int>(x: 42) }
func diagonalizeAny(_ x: any Sequence<Int>) -> any Sequence<(Int, Int)> {
return x.map { ($0, $0) }
}
func erase<T>(_ x: ConcreteSequence<T>) -> any Sequence<T> {
return x as any Sequence<T>
}
protocol Sponge<A, B> {
associatedtype A
associatedtype B
}
func saturation(_ dry: any Sponge, _ wet: any Sponge<Int, Int>) {
_ = dry as any Sponge<Int, Int>
// expected-error@-1 {{'any Sponge' is not convertible to 'any Sponge<Int, Int>'}}
// expected-note@-2 {{did you mean to use 'as!' to force downcast?}}
_ = dry as any Sponge
_ = wet as any Sponge<Int, Int> // Ok
_ = wet as any Sponge // Ok
_ = wet as any Sponge<String, String> // expected-error {{'any Sponge<Int, Int>' is not convertible to 'any Sponge<String, String>'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}}
}
| apache-2.0 | d5ea8af520b3f340323cf555f3528ea7 | 25.984375 | 197 | 0.667632 | 3.24015 | false | false | false | false |
solinor/paymenthighway-ios-framework | PaymentHighway/String+Extensions.swift | 1 | 2107 | //
// String+Extension.swift
// PaymentHighway
//
// Copyright © 2018 Payment Highway Oy. All rights reserved.
//
import Foundation
extension String {
/// Return only decimal digits
var decimalDigits: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
}
/// Get a given substring of a string
/// - parameter r: The range of the substring wanted
/// - returns: The found substring
subscript (range: Range<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
let endIndex = self.index(startIndex, offsetBy: range.upperBound - range.lowerBound)
return String(self[(startIndex ..< endIndex)])
}
/// Returns matches for given regexp
/// - parameter regex: The pattern to evaluate
/// - returns: Found matches as an array
func matchesForRegex(_ regex: String) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
let nsString = self as NSString
let results = regex.matches(in: nsString as String,
options: [],
range: NSRange(location: 0, length: nsString.length))
var strings = [String]()
for result in results {
for index in 1 ..< result.numberOfRanges {
let range = result.range(at: index)
if range.location != NSNotFound {
strings.append(nsString.substring(with: range))
}
}
}
return strings
}
/// Truncates the string to length number of characters and
/// appends optional trailing string if longer
/// Source: https://gist.github.com/budidino/8585eecd55fd4284afaaef762450f98e
func truncate(length: Int, trailing: String? = nil) -> String {
return (self.count > length) ? self.prefix(length) + (trailing ?? "") : self
}
var isNotEmpty: Bool {
return !isEmpty
}
}
| mit | b4d56e97bd1e9c575f0edfd89818215a | 32.967742 | 98 | 0.589744 | 4.797267 | false | false | false | false |
bradhilton/SwiftKVC | Pods/Reflection/Sources/Reflection/Construct.swift | 1 | 2812 | /// Create a struct with a constructor method. Return a value of `property.type` for each property.
public func construct<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T {
return try constructGenericType(constructor: constructor)
}
func constructGenericType<T>(_ type: T.Type = T.self, constructor: (Property.Description) throws -> Any) throws -> T {
if Metadata(type: T.self)?.kind == .struct {
return try constructValueType(constructor)
} else {
throw ReflectionError.notStruct(type: T.self)
}
}
/// Create a struct with a constructor method. Return a value of `property.type` for each property.
public func construct(_ type: Any.Type, constructor: (Property.Description) throws -> Any) throws -> Any {
return try extensions(of: type).construct(constructor: constructor)
}
private func constructValueType<T>(_ constructor: (Property.Description) throws -> Any) throws -> T {
guard Metadata(type: T.self)?.kind == .struct else { throw ReflectionError.notStruct(type: T.self) }
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
defer { pointer.deallocate(capacity: 1) }
var values: [Any] = []
try constructType(storage: UnsafeMutableRawPointer(pointer), values: &values, properties: properties(T.self), constructor: constructor)
return pointer.move()
}
private func constructType(storage: UnsafeMutableRawPointer, values: inout [Any], properties: [Property.Description], constructor: (Property.Description) throws -> Any) throws {
var errors = [Error]()
for property in properties {
do {
let value = try constructor(property)
values.append(value)
try property.write(value, to: storage)
} catch {
errors.append(error)
}
}
if errors.count > 0 {
throw ConstructionErrors(errors: errors)
}
}
/// Create a struct from a dictionary.
public func construct<T>(_ type: T.Type = T.self, dictionary: [String: Any]) throws -> T {
return try constructGenericType(constructor: constructorForDictionary(dictionary))
}
/// Create a struct from a dictionary.
public func construct(_ type: Any.Type, dictionary: [String: Any]) throws -> Any {
return try construct(type, constructor: constructorForDictionary(dictionary))
}
private func constructorForDictionary(_ dictionary: [String: Any]) -> (Property.Description) throws -> Any {
return { property in
if let value = dictionary[property.key] {
return value
} else if let expressibleByNilLiteral = property.type as? ExpressibleByNilLiteral.Type {
return expressibleByNilLiteral.init(nilLiteral: ())
} else {
throw ReflectionError.requiredValueMissing(key: property.key)
}
}
}
| mit | b9bb6ab5c88dcfa8bbd2ad682dcc9e8d | 42.9375 | 177 | 0.689545 | 4.286585 | false | false | false | false |
sleekbyte/tailor | src/test/swift/com/sleekbyte/tailor/grammar/Subscripts.swift | 1 | 1911 | struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")
var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
struct Celsius {
var temperatureInCelsius: Double = 4
var temperatureInKelvin: Double = 5
func doSomething() {
self[temperatureInCelsius, temperatureInKelvin]
}
subscript(celsius: Double, farenheit: Double) -> Int {
get {
return 2
}
set(newValue) {
// perform a suitable setting action here
}
}
}
extension SystemError {
public static func description(for errorNumber: Int32) -> String {
return String(cString: strerror(errorNumber))
}
}
extension SystemError: CustomStringConvertible {
public var description: String {
return SystemError.description(for: errorNumber)
}
}
| mit | 990dd7db55ce624abd2668c1be5813b1 | 25.915493 | 81 | 0.601779 | 4.083333 | false | false | false | false |
frootloops/swift | test/SILGen/class_resilience.swift | 1 | 6313 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
import resilient_class
// Accessing final property of resilient class from different resilience domain
// through accessor
// CHECK-LABEL: sil @_T016class_resilience20finalPropertyOfOthery010resilient_A022ResilientOutsideParentCF
// CHECK: function_ref @_T015resilient_class22ResilientOutsideParentC13finalPropertySSvg
public func finalPropertyOfOther(_ other: ResilientOutsideParent) {
_ = other.finalProperty
}
public class MyResilientClass {
public final var finalProperty: String = "MyResilientClass.finalProperty"
// CHECK-LABEL: sil [thunk] @_T016class_resilience16MyResilientClassC17publicMethodFirstSiSgyFTj : $@convention(method) (@guaranteed MyResilientClass) -> Optional<Int>
// CHECK: class_method %0 : $MyResilientClass, #MyResilientClass.publicMethodFirst!1 : (MyResilientClass) -> () -> Int?, $@convention(method) (@guaranteed MyResilientClass) -> Optional<Int>
// CHECK: return
public func publicMethodFirst() -> Int? { return nil }
// CHECK-LABEL: sil [thunk] @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
// CHECK: class_method %1 : $MyResilientClass, #MyResilientClass.publicMethodSecond!1 : (MyResilientClass) -> (AnyObject) -> (), $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
// CHECK: return
public func publicMethodSecond(_ a: AnyObject) {}
}
public class MyResilientSubclass : MyResilientClass {
// This override changes ABI so it gets its own dispatch thunk
// CHECK-LABEL: sil [thunk] @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTj : $@convention(method) (@guaranteed MyResilientSubclass) -> Int
// CHECK: class_method %0 : $MyResilientSubclass, #MyResilientSubclass.publicMethodFirst!1 : (MyResilientSubclass) -> () -> Int, $@convention(method) (@guaranteed MyResilientSubclass) -> Int
// CHECK: return
public override func publicMethodFirst() -> Int { return 0 }
public override func publicMethodSecond(_ a: AnyObject?) {}
}
// Accessing final property of resilient class from my resilience domain
// directly
// CHECK-LABEL: sil @_T016class_resilience19finalPropertyOfMineyAA16MyResilientClassCF
// CHECK: bb0([[ARG:%.*]] : @owned $MyResilientClass):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: ref_element_addr [[BORROWED_ARG]] : $MyResilientClass, #MyResilientClass.finalProperty
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
public func finalPropertyOfMine(_ other: MyResilientClass) {
_ = other.finalProperty
}
class SubclassOfOutsideChild : ResilientOutsideChild {
override func method() {}
func newMethod() {}
}
// CHECK-LABEL: sil @_T016class_resilience19callResilientMethodyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
public func callResilientMethod(_ s: MyResilientSubclass) {
// CHECK: class_method {{.*}} : $MyResilientSubclass, #MyResilientSubclass.publicMethodFirst!1
_ = s.publicMethodFirst()
// CHECK: class_method {{.*}} : $MyResilientSubclass, #MyResilientSubclass.publicMethodSecond!1
s.publicMethodSecond(nil)
// CHECK: return
}
// CHECK-LABEL: sil [serialized] @_T016class_resilience29callResilientMethodInlineableyAA02MyD8SubclassCF : $@convention(thin) (@owned MyResilientSubclass) -> ()
@_inlineable public func callResilientMethodInlineable(_ s: MyResilientSubclass) {
// CHECK: [[FN:%.*]] = function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTj : $@convention(method) (@guaranteed MyResilientSubclass) -> Int
_ = s.publicMethodFirst()
// CHECK: [[FN:%.*]] = function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
// CHECK: [[CONVERTED:%.*]] = convert_function [[FN]] : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> () to $@convention(method) (@owned Optional<AnyObject>, @guaranteed MyResilientSubclass) -> ()
s.publicMethodSecond(nil)
// CHECK: function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTc
_ = s.publicMethodFirst
// CHECK: function_ref @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyXlSgFTc
_ = s.publicMethodSecond
// CHECK: return
}
// CHECK-LABEL: sil shared [serializable] [thunk] @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTc : $@convention(thin) (@owned MyResilientSubclass) -> @owned @callee_guaranteed () -> Int
// CHECK: function_ref @_T016class_resilience19MyResilientSubclassC17publicMethodFirstSiyFTj
// CHECK: return
// CHECK-LABEL: sil shared [serializable] [thunk] @_T016class_resilience19MyResilientSubclassC18publicMethodSecondyyXlSgFTc : $@convention(thin) (@owned MyResilientSubclass) -> @owned @callee_guaranteed (@owned Optional<AnyObject>) -> ()
// CHECK: function_ref @_T016class_resilience16MyResilientClassC18publicMethodSecondyyXlFTj : $@convention(method) (@owned AnyObject, @guaranteed MyResilientClass) -> ()
// CHECK: return
// Note: no entries for [inherited] methods
// CHECK-LABEL: sil_vtable SubclassOfOutsideChild {
// CHECK-NEXT: #ResilientOutsideParent.init!initializer.1: (ResilientOutsideParent.Type) -> () -> ResilientOutsideParent : _T016class_resilience22SubclassOfOutsideChildCACycfc [override]
// CHECK-NEXT: #ResilientOutsideParent.method!1: (ResilientOutsideParent) -> () -> () : _T016class_resilience22SubclassOfOutsideChildC6methodyyF [override]
// CHECK-NEXT: #SubclassOfOutsideChild.newMethod!1: (SubclassOfOutsideChild) -> () -> () : _T016class_resilience22SubclassOfOutsideChildC9newMethodyyF
// CHECK-NEXT: #SubclassOfOutsideChild.deinit!deallocator: _T016class_resilience22SubclassOfOutsideChildCfD
// CHECK-NEXT: }
| apache-2.0 | bf15471d6998030f13d544b51a2f2ae5 | 61.50495 | 237 | 0.762078 | 4.158762 | false | false | false | false |
Jakintosh/WWDC-2015-Application | Jak-Tiano/Jak-Tiano/Entities/MenuOptionButton.swift | 1 | 4452 | //
// MenuOptionButton.swift
// Jak-Tiano
//
// Created by Jak Tiano on 4/26/15.
// Copyright (c) 2015 jaktiano. All rights reserved.
//
import Foundation
import SpriteKit
enum MenuDirection {
case Left, Right
}
class MenuOptionButton: Button {
// MARK: - Properties
let direction: MenuDirection
let offScreenAnchor: CGFloat
var wasSelected: Bool = false
var presentClosure: ((dir: MenuDirection, name: String) -> Void)?
var buttonName: String? {
didSet {
if let text = buttonName {
labelNode.text = text
self.name = text
menuContents.texture = SKTexture(imageNamed: text)
}
}
}
// MARK: - Nodes
let labelNode: SKLabelNode = SKLabelNode()
let background: SKSpriteNode
let menuNode: SKSpriteNode
let menuContents: SKSpriteNode = SKSpriteNode(imageNamed: "COMPANY")
init (dir: MenuDirection, sceneWidth: CGFloat, sceneHeight: CGFloat) {
direction = dir
// setup the size
let width = sceneWidth
let height = sceneHeight / 4
background = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(width, height))
menuNode = SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(sceneWidth, sceneHeight))
// set the anchor point off screen
switch (direction)
{
case .Left:
offScreenAnchor = -sceneWidth
case .Right:
offScreenAnchor = sceneWidth
}
// init superclass
super.init()
switch (direction)
{
case .Left:
menuNode.color = SKColor(white: 0.85, alpha: 1.0)
menuNode.position = CGPointMake(-sceneWidth, 0.0)
background.color = SKColor(white: 0.85, alpha: 1.0)
labelNode.fontColor = SKColor(white: 0.15, alpha: 1.0)
labelNode.position = CGPointMake(50, 0)
case .Right:
menuNode.color = SKColor(white: 0.15, alpha: 1.0)
menuNode.position = CGPointMake(sceneWidth, 0.0)
background.color = SKColor(white: 0.15, alpha: 1.0)
labelNode.fontColor = SKColor(white: 0.85, alpha: 1.0)
labelNode.position = CGPointMake(-50, 0)
}
background.anchorPoint = CGPointMake(0.5, 0.5)
labelNode.verticalAlignmentMode = .Center
labelNode.fontSize = 28
labelNode.zPosition = 1
menuNode.addChild(menuContents)
addChild(menuNode)
addChild(background)
addChild(labelNode)
}
required init?(coder aDecoder: NSCoder) {
fatalError("shouldn't use init(coder:)")
}
override func completionAction() {
if activated {
if let u_present = presentClosure {
wasSelected = true
u_present(dir: self.direction, name: self.buttonName!)
}
}
}
func setButtonPosition(pos: CGPoint) {
position = pos
menuNode.position.y = -pos.y
}
func present(delay: NSTimeInterval) {
activated = true
var xDelta: CGFloat = 0
if direction == .Left { xDelta = -60 }
else { xDelta = 60 }
let move = SKAction.moveToX(xDelta, duration: 0.5)
move.timingMode = .EaseOut
self.runAction(SKAction.sequence([SKAction.waitForDuration(delay),move]))
}
func dismiss(delay: NSTimeInterval) {
if !wasSelected {
activated = false
let move = SKAction.moveToX(offScreenAnchor, duration: 0.33)
move.timingMode = .EaseOut
self.runAction(SKAction.sequence([SKAction.waitForDuration(delay),move]))
}
}
func reset() {
wasSelected = false
var xDelta: CGFloat = 0
if direction == .Left { xDelta = -60 }
else { xDelta = 60 }
let move = SKAction.moveToX(xDelta, duration: 0.5)
move.timingMode = .EaseOut
self.runAction(move)
}
func select() {
let move = SKAction.moveToX(-offScreenAnchor, duration: 0.5)
move.timingMode = .EaseOut
self.runAction(SKAction.sequence([SKAction.waitForDuration(1.0),move]))
}
}
| mit | de8eb98d95b48c7b749c1681e4ea8f0d | 28.098039 | 101 | 0.559524 | 4.538226 | false | false | false | false |
kongtomorrow/ProjectEuler-Swift | ProjectEuler/p45.swift | 1 | 850 | //
// p45.swift
// ProjectEuler
//
// Created by Ken Ferry on 8/14/14.
// Copyright (c) 2014 Understudy. All rights reserved.
//
import Foundation
extension Problems {
func p45() -> Int {
/*
Triangular, pentagonal, and hexagonal
Problem 45
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
Triangle Tn=n(n+1)/2 1, 3, 6, 10, 15, ...
Pentagonal Pn=n(3n−1)/2 1, 5, 12, 22, 35, ...
Hexagonal Hn=n(2n−1) 1, 6, 15, 28, 45, ...
It can be verified that T285 = P165 = H143 = 40755.
Find the next triangle number that is also pentagonal and hexagonal.
*/
return ints.skip(143)?.map(hexagonalNum).filter(isPentagonalNum)?.filter(isTriangleNum)?.car ?? 0
}
}
| mit | 76981533e866db69bdedaa03a7e23d6e | 26.290323 | 105 | 0.565012 | 3.317647 | false | false | false | false |
larcus94/ImagePickerSheetController | ImagePickerSheetController/ImagePickerSheetController/Sheet/Preview/PreviewSupplementaryView.swift | 2 | 2494 | //
// PreviewSupplementaryView.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 06/09/14.
// Copyright (c) 2014 Laurin Brandner. All rights reserved.
//
import UIKit
class PreviewSupplementaryView: UICollectionReusableView {
fileprivate let button: UIButton = {
let button = UIButton()
button.tintColor = .white
button.isUserInteractionEnabled = false
button.setImage(PreviewSupplementaryView.checkmarkImage, for: UIControl.State())
button.setImage(PreviewSupplementaryView.selectedCheckmarkImage, for: .selected)
return button
}()
var buttonInset = UIEdgeInsets.zero
var selected: Bool = false {
didSet {
button.isSelected = selected
reloadButtonBackgroundColor()
}
}
class var checkmarkImage: UIImage? {
let bundle = Bundle(for: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark", in: bundle, compatibleWith: nil)
return image?.withRenderingMode(.alwaysTemplate)
}
class var selectedCheckmarkImage: UIImage? {
let bundle = Bundle(for: ImagePickerSheetController.self)
let image = UIImage(named: "PreviewSupplementaryView-Checkmark-Selected", in: bundle, compatibleWith: nil)
return image?.withRenderingMode(.alwaysTemplate)
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
fileprivate func initialize() {
addSubview(button)
}
// MARK: - Other Methods
override func prepareForReuse() {
super.prepareForReuse()
selected = false
}
override func tintColorDidChange() {
super.tintColorDidChange()
reloadButtonBackgroundColor()
}
fileprivate func reloadButtonBackgroundColor() {
button.backgroundColor = (selected) ? tintColor : nil
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
button.sizeToFit()
button.frame.origin = CGPoint(x: buttonInset.left, y: bounds.height-button.frame.height-buttonInset.bottom)
button.layer.cornerRadius = button.frame.height / 2.0
}
}
| mit | 6d278bc95ce78f88c373b046b53fc04f | 26.108696 | 115 | 0.628308 | 5.272727 | false | false | false | false |
Gitliming/Demoes | Demoes/Demoes/Sliding door type switch/NCViewController.swift | 1 | 6021 | //
// NCViewController.swift
// text
//
// Created by xpming on 16/4/21.
// Copyright © 2016年 xpming. All rights reserved.
//
import UIKit
class NCViewController: BaseViewController, UIGestureRecognizerDelegate {
@IBOutlet var NEwView: UIView!
var name:String?
var xib:UIView?
var pan:UIPanGestureRecognizer?
var startPan:CGPoint?
var index = 0
var previousView:UIView?
let rect = UIScreen.main.bounds
let width = UIScreen.main.bounds.width
let preRect = CGRect(x: -UIScreen.main.bounds.width, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
override func viewDidLoad() {
super.viewDidLoad()
name = "zhangsan"
view!.layer.contents = UIImage(named: "f")?.cgImage
setUp()
}
func setUp () {
let button = UIButton()
button.addTarget(self, action: #selector(NCViewController.share), for: .touchUpInside)
navigationItem.setRightButton(bgImgName: "share_btn", button:button)
// let vs = NSBundle.mainBundle().loadNibNamed("textXIb", owner: nil, options: nil)
//
// xib = vs[0] as? UIView
//
// xib?.frame = self.view.bounds
//
//
// self.view.addSubview(xib!)
//2.手势添加
pan = UIPanGestureRecognizer(target:self, action:#selector(NCViewController.panAction(_:)))
pan?.delegate = self
view.addGestureRecognizer(pan!)
addPages()
}
func share() {
if self.childViewControllers.count < 1{
let shareVc = shareViewController(nibName: "shareViewController", bundle: nil)
// shareVc.view.frame = view.frame
UIViewController.showViewController(self, VC: shareVc)
}
}
// 添加需要切换的页面
func addPages(){
xib = textXIb(frame: self.view.bounds)
let view1 = UIView(frame: rect)
let imageView1 = UIImageView(frame: rect)
imageView1.image = UIImage(named: "e")
view1.addSubview(imageView1)
view1.backgroundColor = UIColor.lightGray
let view2 = UIView(frame: rect)
view2.backgroundColor = UIColor.brown
let imageView2 = UIImageView(frame: rect)
imageView2.image = UIImage(named: "d")
view2.addSubview(imageView2)
let view3 = UIView(frame: rect)
view3.backgroundColor = UIColor.yellow
let imageView3 = UIImageView(frame: rect)
imageView3.image = UIImage(named: "c")
view3.addSubview(imageView3)
view.insertSubview(view1, at: 0)
view.insertSubview(view2, at: 1)
view.insertSubview(view3, at: 2)
view.insertSubview(xib!, at: 3)
index = view.subviews.count - 1
}
// 手势实现切换逻辑
func panAction(_ panGestu:UIPanGestureRecognizer){
let point = panGestu.location(in: view)
let move = point.x - (startPan?.x)!
let panMove = move / width
let targetView = view.subviews[index]
if panMove > 0 {
if index < 3{
previousView = view.subviews[index + 1]
previousView!.frame = preRect.offsetBy(dx: move, dy: 0)
}
}else{
targetView.frame = rect.offsetBy(dx: move, dy: 0)
}
if panGestu.state == UIGestureRecognizerState.ended {
if panMove < -0.5 {
if index == 0{
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect
})
}else{
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect.offsetBy(dx: -self.width, dy: 0)
})
}
if index > 0 {
index -= 1
}
}else if panMove < 0 && panMove >= -0.5 {
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect
})
}else if panMove < 0.5 && panMove >= 0 {
guard let pre = previousView else {
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect
})
return
}
UIView.animate(withDuration: 0.5, animations: {
pre.frame = self.preRect
})
if index == view.subviews.count - 1 {
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect
})
}
} else {
if index == view.subviews.count - 1 {
guard let pre = previousView else {
UIView.animate(withDuration: 0.5, animations: {
targetView.frame = self.rect
})
return
}
UIView.animate(withDuration: 0.5, animations: {
pre.frame = self.preRect
targetView.frame = self.rect
})
}else {
guard let pre = previousView else {return}
UIView.animate(withDuration: 0.5, animations: {
pre.frame = self.rect
})
}
if index < 3{
index += 1
}
}
}
}
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
startPan = gestureRecognizer.location(in: view)
return true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 9f7029a31b999eb10b825c9290efbc7e | 32.2 | 134 | 0.51573 | 4.698113 | false | false | false | false |
Azoy/Sword | Sources/Sword/Rest/RateLimit.swift | 1 | 1107 | //
// RateLimit.swift
// Sword
//
// Created by Alejandro Alonso
// Copyright © 2019 Alejandro Alonso. All rights reserved.
//
import Foundation
extension Sword {
/// Handles what to do when a request is complete (rate limiting)
///
/// - parameter response: The http response from the Discord
func handleRateLimit(_ response: HTTPURLResponse, _ route: String) {
/*
let headers = response.allHeaderFields
let _limit = headers["x-ratelimit-limit"] as? Int
let _remaining = headers["x-ratelimit-remaining"] as? Int
let _reset = headers["x-ratelimit-reset"] as? Int
let _date = headers["date"] as? String
guard let limit = _limit,
let remaining = _remaining,
let reset = _reset,
let date = _date else {
Sword.log(.error, "monkaS")
return
}
guard let bucket = buckets[route] else {
buckets[route] = Bucket(name: "sword.bucket.\(route)", limit: limit, interval: <#T##Int#>)
}
*/
}
/*
func haltRequests() {
for bucket in buckets.values {
bucket.worker.suspend()
}
}
*/
}
| mit | ccb7a29f78f8548b76cd6091e9dc6d4f | 24.136364 | 96 | 0.613924 | 3.908127 | false | false | false | false |
felipeflorencio/AdjustViewWhenHitTextField_Swift | AdjustViewWhenHitUITextField/ViewController.swift | 1 | 2853 | //
// ViewController.swift
// AdjustViewWhenHitUITextField
//
// Created by Felipe Florencio Garcia on 1/10/16.
// Copyright © 2016 Felipe Florencio Garcia. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var likeButton: UIButton!
@IBOutlet var txtFirstField: UITextField!
@IBOutlet var txtSecondTextField: UITextField!
@IBOutlet var btnNext: UIButton!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var viewInsideScroll: UIView!;
var selectedField:UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Set observer for receive keyboard notifications
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWasShown(_:)), name:NSNotification.Name(rawValue: "UIKeyboardDidShowNotification"), object:nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyboardWillBeHidden(_:)), name:NSNotification.Name(rawValue: "UIKeyboardWillHideNotification"), object:nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.userTappedOnField(_:)), name:NSNotification.Name(rawValue: "UITextFieldTextDidBeginEditingNotification"), object:nil)
let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer.init(target:self, action:#selector(ViewController.hideKeyBoard))
viewInsideScroll?.addGestureRecognizer(tapGesture)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func hideKeyBoard(){
self.view.endEditing(true)
}
func userTappedOnField(_ txtSelected: Notification){
if txtSelected.object is UITextField {
selectedField = txtSelected.object as? UITextField
}
}
// View readjust actions
func keyboardWasShown(_ notification: Notification) {
let info:NSDictionary = notification.userInfo! as NSDictionary
let keyboardSize:CGSize = ((info.object(forKey: UIKeyboardFrameBeginUserInfoKey) as AnyObject).cgRectValue.size)
let txtFieldView:CGPoint = selectedField!.frame.origin;
let txtFieldViewHeight:CGFloat = selectedField!.frame.size.height;
var visibleRect:CGRect = viewInsideScroll!.frame;
visibleRect.size.height -= keyboardSize.height;
if !visibleRect.contains(txtFieldView) {
let scrollPoint:CGPoint = CGPoint(x: 0.0, y: txtFieldView.y - visibleRect.size.height + (txtFieldViewHeight * 1.5))
scrollView?.setContentOffset(scrollPoint, animated: true)
}
}
func keyboardWillBeHidden(_ notification: Notification) {
scrollView?.setContentOffset(CGPoint.zero, animated: true)
}
}
| gpl-2.0 | ba9a01d1e0a6f03f21a9848fc1ebe3b9 | 33.361446 | 204 | 0.696353 | 5.310987 | false | false | false | false |
cemolcay/YSCards | YSCards/YSCards/Helpers/YSCards+UView.swift | 1 | 5058 | //
// YSCards+UView.swift
// YSCards
//
// Created by Cem Olcay on 30/10/15.
// Copyright © 2015 prototapp. All rights reserved.
//
import UIKit
// MARK: - Frame Extensions
extension UIView {
var x: CGFloat {
get {
return self.frame.origin.x
} set {
self.frame = CGRect (x: newValue, y: self.y, width: self.w, height: self.h)
}
}
var y: CGFloat {
get {
return self.frame.origin.y
} set {
self.frame = CGRect (x: self.x, y: newValue, width: self.w, height: self.h)
}
}
var w: CGFloat {
get {
return self.frame.size.width
} set {
self.frame = CGRect (x: self.x, y: self.y, width: newValue, height: self.h)
}
}
var h: CGFloat {
get {
return self.frame.size.height
} set {
self.frame = CGRect (x: self.x, y: self.y, width: self.w, height: newValue)
}
}
var left: CGFloat {
get {
return self.x
} set {
self.x = newValue
}
}
var right: CGFloat {
get {
return self.x + self.w
} set {
self.x = newValue - self.w
}
}
var top: CGFloat {
get {
return self.y
} set {
self.y = newValue
}
}
var bottom: CGFloat {
get {
return self.y + self.h
} set {
self.y = newValue - self.h
}
}
var position: CGPoint {
get {
return self.frame.origin
} set {
self.frame = CGRect (origin: newValue, size: self.frame.size)
}
}
var size: CGSize {
get {
return self.frame.size
} set {
self.frame = CGRect (origin: self.frame.origin, size: newValue)
}
}
var selfCenter: CGPoint {
return CGPoint(x: w/2, y: h/2)
}
func leftWithOffset (offset: CGFloat) -> CGFloat {
return self.left - offset
}
func rightWithOffset (offset: CGFloat) -> CGFloat {
return self.right + offset
}
func topWithOffset (offset: CGFloat) -> CGFloat {
return self.top - offset
}
func bottomWithOffset (offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
func leftWithInset (inset: CGFloat) -> CGFloat {
return self.left + inset
}
func rightWithInset (inset: CGFloat) -> CGFloat {
return self.right - inset
}
func topWithInset (inset: CGFloat) -> CGFloat {
return self.top - inset
}
func bottomWithInset (inset: CGFloat) -> CGFloat {
return self.bottom - inset
}
}
// MARK: - Border Extensions
extension UIView {
func addBorder (
width: CGFloat,
color: UIColor) {
self.layer.borderWidth = width
self.layer.borderColor = color.CGColor
self.layer.masksToBounds = true
}
func addTopBorder (
inset: UIEdgeInsets = UIEdgeInsetsZero,
lineWidth: CGFloat,
color: UIColor) {
let border = CALayer(
x: inset.left,
y: inset.top,
w: w - inset.left - inset.right,
h: lineWidth)
border.backgroundColor = color.CGColor
layer.addSublayer(border)
}
func addBottomBorder (
inset: UIEdgeInsets = UIEdgeInsetsZero,
lineWidth: CGFloat,
color: UIColor) {
let border = CALayer(
x: inset.left, y:
h - inset.bottom,
w: w - inset.left - inset.right,
h: lineWidth)
border.backgroundColor = color.CGColor
layer.addSublayer(border)
}
func addLeftBorder (
inset: UIEdgeInsets = UIEdgeInsetsZero,
lineWidth: CGFloat,
color: UIColor) {
let border = CALayer(
x: inset.left,
y: inset.top,
w: lineWidth,
h: h - inset.top - inset.bottom)
border.backgroundColor = color.CGColor
layer.addSublayer(border)
}
func addRightBorder (
inset: UIEdgeInsets = UIEdgeInsetsZero,
lineWidth: CGFloat,
color: UIColor) {
let border = CALayer(
x: inset.left,
y: inset.top,
w: lineWidth,
h: h - inset.top - inset.bottom)
border.backgroundColor = color.CGColor
layer.addSublayer(border)
}
}
// MARK: - Shadow Extensions
extension UIView {
func addShadow (
offset: CGSize,
radius: CGFloat,
color: UIColor,
opacity: Float,
cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.CGColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(
roundedRect: bounds,
cornerRadius: r).CGPath
}
}
}
| mit | 57074b5477fac5d0cd47e365c0e62591 | 21.779279 | 87 | 0.523631 | 4.274725 | false | false | false | false |
jpsim/Commandant | Sources/Commandant/ArgumentParser.swift | 3 | 4953 | //
// ArgumentParser.swift
// Commandant
//
// Created by Justin Spahr-Summers on 2014-11-21.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import Foundation
import Result
/// Represents an argument passed on the command line.
private enum RawArgument: Equatable {
/// A key corresponding to an option (e.g., `verbose` for `--verbose`).
case key(String)
/// A value, either associated with an option or passed as a positional
/// argument.
case value(String)
/// One or more flag arguments (e.g 'r' and 'f' for `-rf`)
case flag(Set<Character>)
}
private func ==(lhs: RawArgument, rhs: RawArgument) -> Bool {
switch (lhs, rhs) {
case let (.key(left), .key(right)):
return left == right
case let (.value(left), .value(right)):
return left == right
case let (.flag(left), .flag(right)):
return left == right
default:
return false
}
}
extension RawArgument: CustomStringConvertible {
fileprivate var description: String {
switch self {
case let .key(key):
return "--\(key)"
case let .value(value):
return "\"\(value)\""
case let .flag(flags):
return "-\(String(flags))"
}
}
}
/// Destructively parses a list of command-line arguments.
public final class ArgumentParser {
/// The remaining arguments to be extracted, in their raw form.
private var rawArguments: [RawArgument] = []
/// Initializes the generator from a simple list of command-line arguments.
public init(_ arguments: [String]) {
// The first instance of `--` terminates the option list.
let params = arguments.split(maxSplits: 1, omittingEmptySubsequences: false) { $0 == "--" }
// Parse out the keyed and flag options.
let options = params.first!
rawArguments.append(contentsOf: options.map { arg in
if arg.hasPrefix("-") {
// Do we have `--{key}` or `-{flags}`.
let opt = arg.characters.dropFirst()
if opt.first == "-" {
return .key(String(opt.dropFirst()))
} else {
return .flag(Set(opt))
}
} else {
return .value(arg)
}
})
// Remaining arguments are all positional parameters.
if params.count == 2 {
let positional = params.last!
rawArguments.append(contentsOf: positional.map(RawArgument.value))
}
}
/// Returns the remaining arguments.
internal var remainingArguments: [String]? {
return rawArguments.isEmpty ? nil : rawArguments.map { $0.description }
}
/// Returns whether the given key was enabled or disabled, or nil if it
/// was not given at all.
///
/// If the key is found, it is then removed from the list of arguments
/// remaining to be parsed.
internal func consumeBoolean(forKey key: String) -> Bool? {
let oldArguments = rawArguments
rawArguments.removeAll()
var result: Bool?
for arg in oldArguments {
if arg == .key(key) {
result = true
} else if arg == .key("no-\(key)") {
result = false
} else {
rawArguments.append(arg)
}
}
return result
}
/// Returns the value associated with the given flag, or nil if the flag was
/// not specified. If the key is presented, but no value was given, an error
/// is returned.
///
/// If a value is found, the key and the value are both removed from the
/// list of arguments remaining to be parsed.
internal func consumeValue(forKey key: String) -> Result<String?, CommandantError<NoError>> {
let oldArguments = rawArguments
rawArguments.removeAll()
var foundValue: String?
var index = 0
while index < oldArguments.count {
defer { index += 1 }
let arg = oldArguments[index]
guard arg == .key(key) else {
rawArguments.append(arg)
continue
}
index += 1
guard index < oldArguments.count, case let .value(value) = oldArguments[index] else {
return .failure(missingArgumentError("--\(key)"))
}
foundValue = value
}
return .success(foundValue)
}
/// Returns the next positional argument that hasn't yet been returned, or
/// nil if there are no more positional arguments.
internal func consumePositionalArgument() -> String? {
for (index, arg) in rawArguments.enumerated() {
if case let .value(value) = arg {
rawArguments.remove(at: index)
return value
}
}
return nil
}
/// Returns whether the given key was specified and removes it from the
/// list of arguments remaining.
internal func consume(key: String) -> Bool {
let oldArguments = rawArguments
rawArguments = oldArguments.filter { $0 != .key(key) }
return rawArguments.count < oldArguments.count
}
/// Returns whether the given flag was specified and removes it from the
/// list of arguments remaining.
internal func consumeBoolean(flag: Character) -> Bool {
for (index, arg) in rawArguments.enumerated() {
if case let .flag(flags) = arg, flags.contains(flag) {
var flags = flags
flags.remove(flag)
if flags.isEmpty {
rawArguments.remove(at: index)
} else {
rawArguments[index] = .flag(flags)
}
return true
}
}
return false
}
}
| mit | a9c98f967db0c53ebef838097e9dca53 | 24.796875 | 94 | 0.671108 | 3.530292 | false | false | false | false |
darkerk/v2ex | V2EX/Extensions/UITableViewController.swift | 1 | 1398 | //
// UITableViewController.swift
// V2EX
//
// Created by wgh on 2017/4/27.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
protocol ThemeUpdating {
func updateTheme()
}
extension UIViewController: ThemeUpdating {
@objc func updateTheme() {
}
func showLoginAlert(isPopBack: Bool = false) {
let alert = UIAlertController(title: "需要您登录V2EX", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: {_ in
if isPopBack {
self.navigationController?.popViewController(animated: true)
}
}))
alert.addAction(UIAlertAction(title: "登录", style: .default, handler: {_ in
self.drawerViewController?.performSegue(withIdentifier: LoginViewController.segueId, sender: nil)
}))
present(alert, animated: true, completion: nil)
}
}
extension UITableViewController {
override func updateTheme() {
switch tableView.style {
case .plain:
tableView?.backgroundColor = AppStyle.shared.theme.tableBackgroundColor
case .grouped:
tableView?.backgroundColor = AppStyle.shared.theme.tableGroupBackgroundColor
default:
break
}
tableView?.separatorColor = AppStyle.shared.theme.separatorColor
}
}
| mit | 1011b52ba7f46cc097f180498e1aaf2f | 28.297872 | 109 | 0.641249 | 4.667797 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications | lab-2/lab-2/lab-2/SecondViewController.swift | 1 | 3190 | /*
* @author Tyler Brockett
* @project CSE 394 Lab 2
* @version February 2, 2016
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tyler Brockett
*
* 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 SecondViewController: UIViewController {
@IBOutlet weak var secondMessage: UITextField!
@IBOutlet weak var labelFirstMessage: UILabel!
var default_height: CGFloat = 0.0
var firstMessage:String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.default_height = self.view.frame.origin.y
labelFirstMessage.text = firstMessage
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toThirdViewController"
{
if let thirdViewController: ThirdViewController = segue.destinationViewController as? ThirdViewController {
if let message: String = secondMessage.text!{
thirdViewController.secondMessage = message
thirdViewController.firstMessage = firstMessage
}
}
}
}
func keyboardWillShow(sender: NSNotification) {
self.view.frame.origin.y = self.default_height - 100
}
func keyboardWillHide(sender: NSNotification) {
self.view.frame.origin.y = self.default_height
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent:event)
view.endEditing(true)
self.secondMessage.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.secondMessage.resignFirstResponder()
return true
}
} | mit | 43aa5e92a056f2e94954291805bf35a6 | 37.914634 | 153 | 0.702194 | 5.039494 | false | false | false | false |
coderMONSTER/iosstar | iOSStar/Scenes/Market/CustomView/MenuItemCell.swift | 1 | 1302 | //
// MenuItemCell.swift
// iOSStar
//
// Created by J-bb on 17/4/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SnapKit
class MenuItemCell: UICollectionViewCell {
lazy var titleLabel:UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 16)
label.text = "明星"
label.textAlignment = .center
label.textColor = UIColor(hexString: "C2CFD8")
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSubViews()
}
func addSubViews() {
backgroundColor = UIColor.clear
addSubview(titleLabel)
titleLabel.snp.makeConstraints { (make) in
make.center.equalTo(self)
}
}
func setTitle(title:String?, colorString:String?, isZoom:Bool) {
var fontSize:CGFloat = 14.0
var string = colorString
if isZoom {
fontSize = 16.0
string = "333333"
}
titleLabel.font = UIFont.systemFont(ofSize: fontSize)
titleLabel.text = title
titleLabel.textColor = UIColor(hexString: string)
}
}
| gpl-3.0 | 14b143e97a83779c89a958a7f6635168 | 22.545455 | 68 | 0.584556 | 4.360269 | false | false | false | false |
alirsamar/BiOS | ios-nd-pirate-fleet-2/Pirate Fleet/GridView.swift | 1 | 8037 | //
// GridView.swift
// Pirate Fleet
//
// Created by Jarrod Parkes on 8/14/15.
// Copyright © 2015 Udacity, Inc. All rights reserved.
//
import UIKit
// MARK: - GridViewDelegate
protocol GridViewDelegate {
func didTapCell(location: GridLocation)
}
// MARK: - GridView
class GridView: UIView {
// MARK: Properties
var grid: [[GridCell]]!
var delegate: GridViewDelegate? = nil
var isInteractive = false {
willSet {
if newValue {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapCell))
addGestureRecognizer(tapGesture)
} else {
if let gestureRecognizers = gestureRecognizers {
for gestureRecognizer in gestureRecognizers {
if gestureRecognizer is UITapGestureRecognizer {
removeGestureRecognizer(gestureRecognizer)
}
}
}
}
}
}
let cellBackgroundImage = UIImage(named: Settings.Images.Water)
// MARK: Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
grid = [[GridCell]]()
let center = self.center
let sideLength = getSideLength()
self.frame = CGRect(x: 0, y: 0, width: sideLength * CGFloat(Settings.DefaultGridSize.width), height: sideLength * CGFloat(Settings.DefaultGridSize.height))
self.center = center
for x in 0..<Settings.DefaultGridSize.width {
var cells = [GridCell]()
for y in 0..<Settings.DefaultGridSize.height {
let view = UIView()
view.frame = CGRect(x: CGFloat(x) * sideLength, y: CGFloat(y) * sideLength, width: sideLength, height: sideLength)
addBackgroundToView(view, backgroundImage: cellBackgroundImage)
let gridCell = GridCell(location: GridLocation(x: x, y: y), view: view, containsObject: false, mine: nil, ship: nil, seamonster: nil)
cells.append(gridCell)
self.addSubview(view)
}
grid.append(cells)
}
}
// MARK: Reset
func reset() {
for x in 0..<Settings.DefaultGridSize.width {
for y in 0..<Settings.DefaultGridSize.height {
for view in grid[x][y].view.subviews {
view.removeFromSuperview()
}
grid[x][y].containsObject = false
grid[x][y].mine = nil
grid[x][y].seamonster = nil
if let _ = grid[x][y].ship {
grid[x][y].ship = nil
}
addBackgroundToView(grid[x][y].view, backgroundImage: cellBackgroundImage)
}
}
}
// MARK: Side Length
private func getSideLength() -> CGFloat {
let widthwiseSide = frame.size.width / CGFloat(Settings.DefaultGridSize.width)
let lengthwiseSide = frame.size.height / CGFloat(Settings.DefaultGridSize.height)
return (widthwiseSide > lengthwiseSide) ? lengthwiseSide : widthwiseSide
}
// MARK: Add Background To View
private func addBackgroundToView(view: UIView, backgroundImage: UIImage?) {
let imageView = UIImageView(frame: view.bounds)
imageView.image = backgroundImage
view.addSubview(imageView)
view.sendSubviewToBack(imageView)
}
// MARK: UIView
override func layoutSubviews() {
super.layoutSubviews()
guard let grid = grid else { return }
let size = Settings.DefaultGridSize
let sideLength = getSideLength()
let center = self.center
self.frame = CGRect(x: 0, y: 0, width: sideLength * CGFloat(size.width), height: sideLength * CGFloat(size.height))
self.center = center
for x in 0..<size.width {
for y in 0..<size.height {
grid[x][y].view.frame = CGRect(x: CGFloat(x) * sideLength, y: CGFloat(y) * sideLength, width: sideLength, height: sideLength)
for subview in grid[x][y].view.subviews {
subview.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: grid[x][y].view.frame.size)
}
}
}
}
}
// MARK: - GridViewDelegate
extension GridView {
func didTapCell(tapGestureRecognizer: UITapGestureRecognizer) {
guard let delegate = delegate else { return }
guard isInteractive else { return }
let tapLocation = tapGestureRecognizer.locationInView(self)
let width = self.frame.size.width / CGFloat(grid.count)
let height = self.frame.size.height / CGFloat(grid[0].count)
let location = GridLocation(x: Int(tapLocation.x / width), y: Int(tapLocation.y / height))
delegate.didTapCell(location)
}
}
// MARK: - Add Images to Grid
extension GridView {
func markImageAtLocation(location: GridLocation, image: String, hidden: Bool = false) {
addImageAtLocation(location, image: image, hidden: hidden)
}
func markShipPieceAtLocation(location: GridLocation, orientation: ShipPieceOrientation, playerType: PlayerType, isWooden: Bool) {
// if placing a computer piece, then hide it by default
let hidden = (playerType == .Computer) ? true : false
switch orientation {
case .EndUp:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipHeadUpWithFlag, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipEndUp, hidden: hidden)
}
case .EndDown:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipHeadDown, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipEndDown, hidden: hidden)
}
case .EndLeft:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipHeadLeft, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipEndLeft, hidden: hidden)
}
case .EndRight:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipHeadRightWithFlag, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipEndRight, hidden: hidden)
}
case .BodyHorz:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipBodyHorz, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipBodyHorz, hidden: hidden)
}
case .BodyVert:
if isWooden {
addImageAtLocation(location, image: Settings.Images.WoodenShipBodyVert, hidden: hidden)
} else {
addImageAtLocation(location, image: Settings.Images.ShipBodyVert, hidden: hidden)
}
}
}
func revealLocations(locations: [GridLocation]) {
for location in locations {
for views in grid[location.x][location.y].view.subviews {
views.hidden = false
}
}
}
private func addImageAtLocation(location: GridLocation, image: String, hidden: Bool = false) {
let imageView = UIImageView(image: UIImage(named: image))
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: self.grid[location.x][location.y].view.frame.size)
imageView.hidden = hidden
self.grid[location.x][location.y].view.addSubview(imageView)
}
} | mit | 39a051d62bebf86a03cee9343def0d2e | 35.366516 | 163 | 0.582628 | 4.704918 | false | false | false | false |
kzaher/RxSwift | Tests/RxSwiftTests/Observable+ShareReplayScopeTests.swift | 6 | 19238 | //
// Observable+ShareReplayScopeTests.swift
// Tests
//
// Created by Krunoslav Zaher on 5/28/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
class ObservableShareReplayScopeTests : RxTest {
}
extension ObservableShareReplayScopeTests {
func test_testDefaultArguments() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.next(550, 7)
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share() }
scheduler.scheduleAt(200) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(300) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6)
])
let replayedEvents2 = (0 ..< 0).map { Recorded.next(300, 6 - 0 + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6)])
XCTAssertEqual(res3.events, [.next(550, 7)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400),
Subscription(500, 600)
])
}
func test_forever_receivesCorrectElements() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.next(550, 7)
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .forever) }
scheduler.scheduleAt(200) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(300) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6)
])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
let replayedEvents3 = (0 ..< i).map { Recorded.next(500, 7 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6)])
XCTAssertEqual(res3.events, replayedEvents3 + [.next(550, 7)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400),
Subscription(500, 600)
])
}
}
func test_whileConnected_receivesCorrectElements() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.next(550, 7)
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .whileConnected) }
scheduler.scheduleAt(200) { subscription1 = ys.subscribe(res1) }
scheduler.scheduleAt(300) { subscription2 = ys.subscribe(res2) }
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6)
])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6)])
XCTAssertEqual(res3.events, [.next(550, 7)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 400),
Subscription(500, 600)
])
}
}
func test_forever_error() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.error(330, testError),
.next(340, -1),
.next(550, 7),
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res1_ = scheduler.createObserver(Int.self)
let res2_ = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .forever) }
scheduler.scheduleAt(200) {
subscription1 = ys.subscribe { event in
res1.on(event)
switch event {
case .error: subscription1 = ys.subscribe(res1_)
case .completed: subscription1 = ys.subscribe(res1_)
case .next: break
}
}
}
scheduler.scheduleAt(300) {
subscription2 = ys.subscribe { event in
res2.on(event)
switch event {
case .error: subscription2 = ys.subscribe(res2_)
case .completed: subscription2 = ys.subscribe(res2_)
case .next: break
}
}
}
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.error(330, testError)
])
let replayedEvents1 = (0 ..< i).map { Recorded.next(330, 7 - i + $0) }
XCTAssertEqual(res1_.events, replayedEvents1 + [.error(330, testError)])
XCTAssertEqual(res2_.events, replayedEvents1 + [.error(330, testError)])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6), .error(330, testError)])
let replayedEvents3 = (0 ..< i).map { Recorded.next(500, 7 - i + $0) }
XCTAssertEqual(res3.events, replayedEvents3 + [.error(500, testError)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330),
])
}
}
func test_whileConnected_error() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.error(330, testError),
.next(340, -1),
.next(550, 7),
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res1_ = scheduler.createObserver(Int.self)
let res2_ = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .whileConnected) }
scheduler.scheduleAt(200) {
subscription1 = ys.subscribe { event in
res1.on(event)
switch event {
case .error: subscription1 = ys.subscribe(res1_)
case .completed: subscription1 = ys.subscribe(res1_)
case .next: break
}
}
}
scheduler.scheduleAt(300) {
subscription2 = ys.subscribe { event in
res2.on(event)
switch event {
case .error: subscription2 = ys.subscribe(res2_)
case .completed: subscription2 = ys.subscribe(res2_)
case .next: break
}
}
}
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.error(330, testError)
])
XCTAssertEqual(res1_.events, [.next(340, -1)])
XCTAssertEqual(res2_.events, [.next(340, -1)])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6), .error(330, testError)])
XCTAssertEqual(res3.events, [.next(550, 7)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330),
Subscription(330, 400),
Subscription(500, 600)
])
}
}
func test_forever_completed() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.completed(330),
.next(340, -1),
.next(550, 7),
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res1_ = scheduler.createObserver(Int.self)
let res2_ = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .forever) }
scheduler.scheduleAt(200) {
subscription1 = ys.subscribe { event in
res1.on(event)
switch event {
case .error: subscription1 = ys.subscribe(res1_)
case .completed: subscription1 = ys.subscribe(res1_)
case .next: break
}
}
}
scheduler.scheduleAt(300) {
subscription2 = ys.subscribe { event in
res2.on(event)
switch event {
case .error: subscription2 = ys.subscribe(res2_)
case .completed: subscription2 = ys.subscribe(res2_)
case .next: break
}
}
}
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.completed(330)
])
let replayedEvents1 = (0 ..< i).map { Recorded.next(330, 7 - i + $0) }
XCTAssertEqual(res1_.events, replayedEvents1 + [.completed(330)])
XCTAssertEqual(res2_.events, replayedEvents1 + [.completed(330)])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6), .completed(330)])
let replayedEvents3 = (0 ..< i).map { Recorded.next(500, 7 - i + $0) }
XCTAssertEqual(res3.events, replayedEvents3 + [.completed(500)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330),
])
}
}
func test_whileConnected_completed() {
for i in 0 ..< 5 {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.completed(330),
.next(340, -1),
.next(550, 7),
])
var subscription1: Disposable! = nil
var subscription2: Disposable! = nil
var subscription3: Disposable! = nil
let res1 = scheduler.createObserver(Int.self)
let res2 = scheduler.createObserver(Int.self)
let res1_ = scheduler.createObserver(Int.self)
let res2_ = scheduler.createObserver(Int.self)
let res3 = scheduler.createObserver(Int.self)
var ys: Observable<Int>! = nil
scheduler.scheduleAt(Defaults.created) { ys = xs.share(replay: i, scope: .whileConnected) }
scheduler.scheduleAt(200) {
subscription1 = ys.subscribe { event in
res1.on(event)
switch event {
case .error: subscription1 = ys.subscribe(res1_)
case .completed: subscription1 = ys.subscribe(res1_)
case .next: break
}
}
}
scheduler.scheduleAt(300) {
subscription2 = ys.subscribe { event in
res2.on(event)
switch event {
case .error: subscription2 = ys.subscribe(res2_)
case .completed: subscription2 = ys.subscribe(res2_)
case .next: break
}
}
}
scheduler.scheduleAt(350) { subscription1.dispose() }
scheduler.scheduleAt(400) { subscription2.dispose() }
scheduler.scheduleAt(500) { subscription3 = ys.subscribe(res3) }
scheduler.scheduleAt(600) { subscription3.dispose() }
scheduler.start()
XCTAssertEqual(res1.events, [
.next(210, 1),
.next(220, 2),
.next(230, 3),
.next(240, 4),
.next(250, 5),
.next(320, 6),
.completed(330)
])
XCTAssertEqual(res1_.events, [.next(340, -1)])
XCTAssertEqual(res2_.events, [.next(340, -1)])
let replayedEvents2 = (0 ..< i).map { Recorded.next(300, 6 - i + $0) }
XCTAssertEqual(res2.events, replayedEvents2 + [.next(320, 6), .completed(330)])
XCTAssertEqual(res3.events, [.next(550, 7)])
XCTAssertEqual(xs.subscriptions, [
Subscription(200, 330),
Subscription(330, 400),
Subscription(500, 600)
])
}
}
#if TRACE_RESOURCES
func testReleasesResourcesOnComplete() {
for i in 0 ..< 5 {
_ = Observable<Int>.just(1).share(replay: i, scope: .forever).subscribe()
_ = Observable<Int>.just(1).share(replay: i, scope: .whileConnected).subscribe()
}
}
func testReleasesResourcesOnError() {
for i in 0 ..< 5 {
_ = Observable<Int>.error(testError).share(replay: i, scope: .forever).subscribe()
_ = Observable<Int>.error(testError).share(replay: i, scope: .whileConnected).subscribe()
}
}
#endif
}
| mit | a0a6ce17b437c06b25a5267a7ef3926e | 33.849638 | 105 | 0.496803 | 4.505152 | false | true | false | false |
yanagiba/swift-lint | Sources/Lint/Rule/NoForcedTryRule.swift | 2 | 1804 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import AST
class NoForcedTryRule: RuleBase, ASTVisitorRule {
let name = "No Forced Try"
var description: String? {
return """
Forced-try expression `try!` should be avoided, because it could crash the program
at the runtime when the expression throws an error.
We recommend using a `do-catch` statement with `try` operator and handle the errors
in `catch` blocks accordingly; or a `try?` operator with `nil`-checking.
"""
}
var examples: [String]? {
return [
"""
let result = try! getResult()
// do {
// let result = try getResult()
// } catch {
// print("Failed in getting result with error: \\(error).")
// }
//
// or
//
// guard let result = try? getResult() else {
// print("Failed in getting result.")
// }
""",
]
}
let category = Issue.Category.badPractice
func visit(_ tryOpExpr: TryOperatorExpression) throws -> Bool {
if case .forced = tryOpExpr.kind {
emitIssue(
tryOpExpr.sourceRange,
description: "having forced-try expression is dangerous")
}
return true
}
}
| apache-2.0 | 978c6796c160a3b6da8621fa625588ed | 28.096774 | 87 | 0.656319 | 4.432432 | false | false | false | false |
borglab/SwiftFusion | Sources/SwiftFusion/Inference/RawPixelTrackingFactor.swift | 1 | 5290 | // TODO: Deduplicate this with AppearanceTrackingFactor. This is equivalent to an
// AppearanceTrackingFactor with a constant generative model. It's not completely trivial to
// express it that way because AppearanceTrackingFactor assumes that there is a latent code that
// influences the result, and if we ignore the latent code then we get zero derivatives that
// confuse our optimizers.
import PenguinParallel
import PenguinStructures
import TensorFlow
/// A factor that measures the difference between a `target` image patch and the actual image
/// patch at a given pose.
public struct RawPixelTrackingFactor: LinearizableFactor1 {
/// The adjacent variable, the pose of the target in the image.
///
/// This explicitly specifies `LinearizableFactor2`'s `associatedtype V0`.
public typealias V0 = Pose2
/// The IDs of the variables adjacent to this factor.
public let edges: Variables.Indices
/// The image containing the target.
public let measurement: ArrayImage
/// The pixels of the target.
public let target: Tensor<Double>
/// Creates an instance.
///
/// - Parameters:
/// - poseId: the id of the adjacent pose variable.
/// - measurement: the image containing the target.
/// - target: the pixels of the target.
public init(_ poseID: TypedID<Pose2>, measurement: Tensor<Float>, target: Tensor<Double>) {
self.edges = Tuple1(poseID)
self.measurement = ArrayImage(measurement)
self.target = target
}
/// Returns the difference between `target` and the region of `measurement` at `pose`.
@differentiable
public func errorVector(_ pose: Pose2) -> TensorVector {
let patch = measurement.patch(
at: OrientedBoundingBox(center: pose, rows: target.shape[0], cols: target.shape[1]))
return TensorVector(Tensor<Double>(patch.tensor) - target)
}
/// Returns a linear approximation to `self` at `x`.
public func linearized(at x: Variables) -> LinearizedRawPixelTrackingFactor {
let pose = x.head
let region = OrientedBoundingBox(center: pose, rows: target.shape[0], cols: target.shape[1])
let (actualAppearance, actualAppearance_H_pose) = measurement.patchWithJacobian(at: region)
let actualAppearance_H_pose_tensor = Tensor<Double>(Tensor(stacking: [
actualAppearance_H_pose.dtheta.tensor,
actualAppearance_H_pose.du.tensor,
actualAppearance_H_pose.dv.tensor,
], alongAxis: -1))
return LinearizedRawPixelTrackingFactor(
error: TensorVector(-(Tensor<Double>(actualAppearance.tensor) - target)),
errorVector_H_pose: actualAppearance_H_pose_tensor,
edges: Variables.linearized(edges))
}
/// Returns the linearizations of `factors` at `x`.
///
/// Note: This causes factor graph linearization to use our custom linearization,
/// `LinearizedPPCATrackingFactor` instead of the default AD-generated linearization.
public static func linearized<C: Collection>(_ factors: C, at x: VariableAssignments)
-> AnyGaussianFactorArrayBuffer where C.Element == Self
{
Variables.withBufferBaseAddresses(x) { varsBufs in
.init(ArrayBuffer<LinearizedRawPixelTrackingFactor>(
count: factors.count, minimumCapacity: factors.count) { b in
ComputeThreadPools.local.parallelFor(n: factors.count) { (i, _) in
let f = factors[factors.index(factors.startIndex, offsetBy: i)]
(b + i).initialize(to: f.linearized(at: Variables(at: f.edges, in: varsBufs)))
}
})
}
}
}
/// A linear approximation to `RawPixelTrackingFactor`, at a certain linearization point.
public struct LinearizedRawPixelTrackingFactor: GaussianFactor {
/// The tangent vector of the `RawPixelTrackingFactor`'s "pose" variable.
public typealias Variables = Tuple1<Pose2.TangentVector>
/// The error vector at the linearization point.
public let error: TensorVector
/// The Jacobian with respect to the `RawPixelTrackingFactor`'s "pose" variable.
public let errorVector_H_pose: Tensor<Double>
/// The ID of the variable adjacent to this factor.
public let edges: Variables.Indices
/// Creates an instance with the given arguments.
public init(
error: TensorVector,
errorVector_H_pose: Tensor<Double>,
edges: Variables.Indices
) {
precondition(
errorVector_H_pose.shape == error.shape + [Pose2.TangentVector.dimension],
"\(errorVector_H_pose.shape) \(error.shape) \(Pose2.TangentVector.dimension)")
self.error = error
self.errorVector_H_pose = errorVector_H_pose
self.edges = edges
}
public func error(at x: Variables) -> Double {
return 0.5 * errorVector(at: x).squaredNorm
}
@differentiable
public func errorVector(at x: Variables) -> TensorVector {
errorVector_linearComponent(x) - error
}
public func errorVector_linearComponent(_ x: Variables) -> TensorVector {
let pose = x.head
return TensorVector(
matmul(errorVector_H_pose, pose.flatTensor.expandingShape(at: 1)).squeezingShape(at: 3))
}
public func errorVector_linearComponent_adjoint(_ y: TensorVector) -> Variables {
let t = y.tensor.reshaped(to: [error.dimension, 1])
let pose = matmul(
errorVector_H_pose.reshaped(to: [error.dimension, 3]),
transposed: true,
t)
return Tuple1(Vector3(flatTensor: pose))
}
}
| apache-2.0 | e596043610b51119efa3d08bbbcfce4b | 38.477612 | 96 | 0.716068 | 4.211783 | false | false | false | false |
Smartvoxx/ios | Step07/Start/SmartvoxxOnWrist Extension/DevoxxCache.swift | 2 | 25533 | //
// DevoxxCache.swift
// Smartvoxx
//
// Created by Sebastien Arbogast on 26/10/2015.
// Copyright © 2015 Epseelon. All rights reserved.
//
import CoreData
class DevoxxCache: NSObject {
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count - 1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("Smartvoxx", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Smartvoxx.sqlite")
do {
print(url)
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
print(error)
}
return coordinator
}()
lazy var mainObjectContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext
}()
lazy var privateObjectContext: NSManagedObjectContext = {
var privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = self.mainObjectContext
return privateContext
}()
override init() {
}
func saveContext(context: NSManagedObjectContext) {
do {
try context.save()
if let parentContext = context.parentContext {
try parentContext.save()
}
} catch {
print(error)
abort()
}
}
func getSchedules() -> [Schedule] {
return self.getSchedules(fromContext: self.mainObjectContext)
}
func saveSchedulesFromData(data: NSData) {
self.saveSchedulesFromData(data, inContext: self.privateObjectContext)
}
private func getSchedules(fromContext context: NSManagedObjectContext) -> [Schedule] {
var schedules = [Schedule]()
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Conference")
request.predicate = NSPredicate(format: "eventCode=%@", "DV15")
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
guard let devoxx15 = results[0] as? Conference, scheduleSet = devoxx15.schedules, scheduleArray = scheduleSet.array as? [Schedule] else {
schedules = [Schedule]()
return
}
schedules = scheduleArray
}
} catch let error as NSError {
print(error)
}
}
return schedules
}
private func getOrCreateDevoxx15(inContext context: NSManagedObjectContext) -> Conference? {
let request = NSFetchRequest(entityName: "Conference")
request.predicate = NSPredicate(format: "eventCode=%@", "DV15")
var devoxx15: Conference?
context.performBlockAndWait {
() -> Void in
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
devoxx15 = results[0] as? Conference
} else {
devoxx15 = NSEntityDescription.insertNewObjectForEntityForName("Conference", inManagedObjectContext: context) as? Conference
devoxx15!.eventCode = "DV15"
devoxx15!.label = "Devoxx 2015"
devoxx15!.localisation = "Antwerp, Belgium"
self.saveContext(context)
}
} catch let error as NSError {
print(error)
}
}
return devoxx15
}
private func getOrCreateScheduleForHref(href: String, inContext context: NSManagedObjectContext) -> Schedule? {
var schedule: Schedule?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Schedule")
request.predicate = NSPredicate(format: "href=%@", href)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
schedule = results[0] as? Schedule
} else {
schedule = NSEntityDescription.insertNewObjectForEntityForName("Schedule", inManagedObjectContext: context) as? Schedule
schedule!.href = href
self.saveContext(context)
}
} catch let error as NSError {
print(error)
}
}
return schedule
}
private func saveSchedulesFromData(data: NSData, inContext context: NSManagedObjectContext) {
context.performBlockAndWait {
() -> Void in
if data.length > 0 {
do {
let schedulesDict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let schedulesDict = schedulesDict as? NSDictionary, schedulesArray = schedulesDict["links"] as? NSArray {
guard let devoxx15 = self.getOrCreateDevoxx15(inContext: context) else {
print("Could not retrieve Devoxx15 conference")
return
}
var schedules = [Schedule]()
for scheduleDict in schedulesArray {
if let scheduleDict = scheduleDict as? NSDictionary {
guard let schedule = self.getOrCreateScheduleForHref(scheduleDict["href"] as! String, inContext: context) else {
print("Could not retrieve or create schedule")
return
}
schedule.title = scheduleDict["title"] as? String
schedule.href = scheduleDict["href"] as? String
schedule.conference = devoxx15
self.saveContext(context)
schedules.append(schedule)
}
}
devoxx15.schedules = NSOrderedSet(array: schedules)
self.saveContext(context)
}
} catch let jsonError as NSError {
print(jsonError)
}
}
}
}
func getSlotsForScheduleWithHref(href: String) -> [Slot] {
return self.getSlotsForScheduleWithHref(href, fromContext: self.mainObjectContext)
}
private func getSlotsForScheduleWithHref(href: String, fromContext context: NSManagedObjectContext) -> [Slot] {
var slots = [Slot]()
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Schedule")
request.predicate = NSPredicate(format: "href=%@", href)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let schedule = results[0] as? Schedule {
slots = schedule.slots!.array as! [Slot]
}
}
} catch {
print(error)
}
}
return slots
}
func saveSlotsFromData(data: NSData, forScheduleWithHref href: String) {
self.saveSlotsFromData(data, forScheduleWithHref: href, inContext: self.privateObjectContext)
}
private func configureSlot(slot: Slot, withData slotDict: NSDictionary, inSchedule schedule: Schedule) {
slot.slotId = slotDict["slotId"] as? String
slot.roomId = slotDict["roomId"] as? String
slot.roomName = slotDict["roomName"] as? String
slot.day = slotDict["day"] as? String
slot.fromTime = slotDict["fromTime"] as? String
slot.toTime = slotDict["toTime"] as? String
slot.fromTimeMillis = slotDict["fromTimeMillis"] as? NSNumber
slot.toTimeMillis = slotDict["toTimeMillis"] as? NSNumber
slot.schedule = schedule
}
private func getOrCreateBreakSlotWithBreakId(breakId: String, inContext context: NSManagedObjectContext) -> BreakSlot? {
var breakSlot: BreakSlot?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "BreakSlot")
request.predicate = NSPredicate(format: "breakId=%@", breakId)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let slot = results[0] as? BreakSlot {
breakSlot = slot
}
} else {
breakSlot = NSEntityDescription.insertNewObjectForEntityForName("BreakSlot", inManagedObjectContext: context) as? BreakSlot
breakSlot?.breakId = breakId
self.saveContext(context)
}
} catch {
print(error)
}
}
return breakSlot
}
private func getOrCreateTalkSlotWithTalkId(talkId: String, inContext context: NSManagedObjectContext) -> TalkSlot? {
var talkSlot: TalkSlot?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "TalkSlot")
request.predicate = NSPredicate(format: "talkId=%@", talkId)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let slot = results[0] as? TalkSlot {
talkSlot = slot
}
} else {
talkSlot = NSEntityDescription.insertNewObjectForEntityForName("TalkSlot", inManagedObjectContext: context) as? TalkSlot
talkSlot?.talkId = talkId
self.saveContext(context)
}
} catch {
print(error)
}
}
return talkSlot
}
private func getOrCreateSlotWithSlotId(slotId: String, inContext context: NSManagedObjectContext) -> Slot? {
var slot: Slot?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Slot")
request.predicate = NSPredicate(format: "slotId=%@", slotId)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let result = results[0] as? Slot {
slot = result
}
} else {
slot = NSEntityDescription.insertNewObjectForEntityForName("Slot", inManagedObjectContext: context) as? Slot
slot?.slotId = slotId
self.saveContext(context)
}
} catch {
print(error)
}
}
return slot
}
private func getOrCreateTrackWithName(name: String, inContext context: NSManagedObjectContext) -> Track? {
var track: Track?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Track")
request.predicate = NSPredicate(format: "name=%@", name)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let result = results[0] as? Track {
track = result
}
} else {
var error: NSError?
request.predicate = nil
let count = context.countForFetchRequest(request, error: &error)
track = NSEntityDescription.insertNewObjectForEntityForName("Track", inManagedObjectContext: context) as? Track
track?.name = name
track?.color = DataController.flatUiColors[count % DataController.flatUiColors.count]
self.saveContext(context)
}
} catch {
print(error)
}
}
return track
}
private func getOrCreateSpeakerWithHref(href: String, inContext context: NSManagedObjectContext) -> Speaker? {
var speaker: Speaker?
context.performBlockAndWait {
() -> Void in
let request = NSFetchRequest(entityName: "Speaker")
request.predicate = NSPredicate(format: "href=%@", href)
do {
let results = try context.executeFetchRequest(request)
if results.count > 0 {
if let result = results[0] as? Speaker {
speaker = result
}
} else {
speaker = NSEntityDescription.insertNewObjectForEntityForName("Speaker", inManagedObjectContext: context) as? Speaker
speaker?.href = href
self.saveContext(context)
}
} catch {
print(error)
}
}
return speaker
}
private func saveSlotsFromData(data: NSData, forScheduleWithHref href: String, inContext context: NSManagedObjectContext) {
context.performBlockAndWait {
() -> Void in
if data.length > 0 {
guard let schedule = self.getOrCreateScheduleForHref(href, inContext: context) else {
return
}
do {
let scheduleDict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let scheduleDict = scheduleDict as? NSDictionary {
if let slotsArray = scheduleDict["slots"] as? NSArray {
var slots = [Slot]()
for slotDict in slotsArray {
if let slotDict = slotDict as? NSDictionary {
if let breakSlotDict = slotDict["break"] as? NSDictionary {
let slot = self.getOrCreateBreakSlotWithBreakId(breakSlotDict["id"] as! String, inContext: context)
self.configureSlot(slot!, withData: slotDict, inSchedule: schedule)
slot!.breakId = breakSlotDict["id"] as? String
slot!.nameEN = breakSlotDict["nameEN"] as? String
slot!.nameFR = breakSlotDict["nameFR"] as? String
slots.append(slot!)
} else if let talkSlotDict = slotDict["talk"] as? NSDictionary {
let slot = self.getOrCreateTalkSlotWithTalkId(talkSlotDict["id"] as! String, inContext: context)
self.configureSlot(slot!, withData: slotDict, inSchedule: schedule)
slot!.talkId = talkSlotDict["id"] as? String
slot!.talkType = talkSlotDict["talkType"] as? String
if let track = talkSlotDict["track"] as? String {
slot!.track = self.getOrCreateTrackWithName(track, inContext: context)
}
slot!.summary = talkSlotDict["summary"] as? String
slot!.summaryAsHtml = talkSlotDict["summaryAsHtml"] as? String
slot!.title = talkSlotDict["title"] as? String
slot!.lang = talkSlotDict["lang"] as? String
for speaker in NSArray(array: slot!.speakers!.allObjects) {
if let speaker = speaker as? Speaker {
speaker.mutableSetValueForKey("talks").removeObject(slot!)
}
}
slot!.setValue(nil, forKey: "speakers")
if let speakersArray = talkSlotDict["speakers"] as? NSArray {
for speakerDict in speakersArray {
if let speakerDict = speakerDict as? NSDictionary {
if let linkDict = speakerDict["link"] as? NSDictionary {
if let href = linkDict["href"] as? String {
if let speaker = self.getOrCreateSpeakerWithHref(href, inContext: context) {
speaker.name = speakerDict["name"] as? String
speaker.href = href
speaker.mutableSetValueForKey("talks").addObject(slot!)
slot!.mutableSetValueForKey("speakers").addObject(speaker)
}
}
}
}
}
}
slots.append(slot!)
} else {
let slot = self.getOrCreateSlotWithSlotId(slotDict["slotId"] as! String, inContext: context)
self.configureSlot(slot!, withData: slotDict, inSchedule: schedule)
slots.append(slot!)
}
}
}
schedule.slots = NSOrderedSet(array: slots)
self.saveContext(context)
}
}
} catch let error as NSError {
print(error)
}
}
}
}
func swapFavoriteStatusForTalkSlotWithTalkId(talkId:String) {
self.swapFavoriteStatusForTalkSlotWithTalkId(talkId, inContext:self.privateObjectContext)
}
private func swapFavoriteStatusForTalkSlotWithTalkId(talkId:String, inContext context:NSManagedObjectContext) {
context.performBlockAndWait { () -> Void in
if let talkSlot = self.getOrCreateTalkSlotWithTalkId(talkId, inContext: context) {
talkSlot.favorite = NSNumber(bool: !(talkSlot.favorite!.boolValue))
self.saveContext(context)
}
}
}
func getTalkSlotWithTalkId(talkId:String) -> TalkSlot? {
return self.getOrCreateTalkSlotWithTalkId(talkId, inContext: self.mainObjectContext)
}
func getSpeakerWithHref(href:String) -> Speaker? {
return self.getOrCreateSpeakerWithHref(href, inContext: self.mainObjectContext)
}
func saveSpeakerFromData(data:NSData, forSpeakerWithHref href:String){
self.saveSpeakerFromData(data, forSpeakerWithHref:href, inContext:self.privateObjectContext)
}
private func saveSpeakerFromData(data:NSData, forSpeakerWithHref href:String, inContext context:NSManagedObjectContext) {
context.performBlockAndWait { () -> Void in
if data.length > 0 {
do {
let speakerDict = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
if let speakerDict = speakerDict as? NSDictionary {
if let speaker = self.getOrCreateSpeakerWithHref(href, inContext: context) {
speaker.uuid = speakerDict["uuid"] as? String
speaker.bioAsHtml = speakerDict["bioAsHtml"] as? String
speaker.company = speakerDict["company"] as? String
speaker.bio = speakerDict["bio"] as? String
speaker.firstName = speakerDict["firstName"] as? String
speaker.lastName = speakerDict["lastName"] as? String
speaker.avatarURL = speakerDict["avatarURL"] as? String
self.saveContext(context)
}
}
} catch let error as NSError {
print(error)
}
}
}
}
func saveAvatarFromData(data:NSData, forSpeakerWithHref href:String) {
self.saveAvatarFromData(data, forSpeakerWithHref: href, inContext:self.privateObjectContext)
}
private func saveAvatarFromData(data:NSData, forSpeakerWithHref href:String, inContext context:NSManagedObjectContext) {
context.performBlockAndWait { () -> Void in
if let speaker = self.getOrCreateSpeakerWithHref(href, inContext: context) {
speaker.avatar = data
self.saveContext(context)
}
}
}
func getAvatarForSpeakerWithHref(href:String) -> NSData? {
if let speaker = self.getSpeakerWithHref(href) {
return speaker.avatar
} else {
return nil
}
}
func getFavoriteTalksAfterDate(date:NSDate) -> [TalkSlot] {
var favoriteTalks = [TalkSlot]()
self.mainObjectContext.performBlockAndWait { () -> Void in
let request = NSFetchRequest(entityName: "TalkSlot")
request.predicate = NSPredicate(format: "favorite==1 and fromTimeMillis>%i", date.timeIntervalSince1970 * 1000)
request.sortDescriptors = [NSSortDescriptor(key: "fromTimeMillis", ascending: true)]
do {
let results = try self.mainObjectContext.executeFetchRequest(request)
favoriteTalks = results as! [TalkSlot]
} catch let error as NSError {
print(error)
}
}
return favoriteTalks
}
func getFavoriteTalksBeforeDate(date:NSDate) -> [TalkSlot] {
var favoriteTalks = [TalkSlot]()
self.mainObjectContext.performBlockAndWait { () -> Void in
let request = NSFetchRequest(entityName: "TalkSlot")
request.predicate = NSPredicate(format: "favorite==1 and fromTimeMillis<%i", date.timeIntervalSince1970 * 1000)
request.sortDescriptors = [NSSortDescriptor(key: "fromTimeMillis", ascending: true)]
do {
let results = try self.mainObjectContext.executeFetchRequest(request)
favoriteTalks = results as! [TalkSlot]
} catch let error as NSError {
print(error)
}
}
return favoriteTalks
}
func getFirstTalk() -> TalkSlot? {
var firstTalk:TalkSlot?
self.mainObjectContext.performBlockAndWait { () -> Void in
let request = NSFetchRequest(entityName: "TalkSlot")
request.sortDescriptors = [NSSortDescriptor(key: "fromTimeMillis", ascending: true)]
do {
let results = try self.mainObjectContext.executeFetchRequest(request)
if results.count > 0 {
firstTalk = results[0] as? TalkSlot
}
} catch {
print(error)
}
}
return firstTalk
}
func getLastTalk() -> TalkSlot? {
var lastTalk:TalkSlot?
self.mainObjectContext.performBlockAndWait { () -> Void in
let request = NSFetchRequest(entityName: "TalkSlot")
request.sortDescriptors = [NSSortDescriptor(key: "toTimeMillis", ascending: false)]
do {
let results = try self.mainObjectContext.executeFetchRequest(request)
if results.count > 0 {
lastTalk = results[0] as? TalkSlot
}
} catch {
print(error)
}
}
return lastTalk
}
}
| gpl-2.0 | 672d706e7b776c4f497b1b2fa05ae383 | 44.430605 | 157 | 0.519505 | 5.881594 | false | false | false | false |
cubixlabs/GIST-Framework | GISTFramework/Classes/Controls/AnimatedTextInput/AnimatedLine.swift | 1 | 2588 | import UIKit
class AnimatedLine: UIView {
enum FillType {
case leftToRight
case rightToLeft
}
fileprivate let lineLayer = CAShapeLayer()
var animationDuration: Double = 0.4
var defaultColor = UIColor.gray.withAlphaComponent(0.6) {
didSet {
backgroundColor = defaultColor
}
}
var fillType = FillType.leftToRight {
didSet {
updatePath()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
backgroundColor = defaultColor
addLine()
}
override open func layoutSubviews() {
super.layoutSubviews()
lineLayer.frame = bounds
lineLayer.lineWidth = bounds.height
updatePath()
}
fileprivate func addLine() {
lineLayer.frame = bounds
let clearColor = UIColor.clear.cgColor
lineLayer.backgroundColor = clearColor
lineLayer.fillColor = clearColor
lineLayer.strokeColor = defaultColor.cgColor
lineLayer.lineWidth = bounds.height
updatePath()
lineLayer.strokeEnd = 0
layer.addSublayer(lineLayer)
}
fileprivate func updatePath() {
lineLayer.path = linePath()
}
fileprivate func linePath() -> CGPath {
let path = UIBezierPath()
let initialPoint = CGPoint(x: 0, y: bounds.midY)
let finalPoint = CGPoint(x: bounds.maxX, y: bounds.midY)
switch fillType {
case .leftToRight:
path.move(to: initialPoint)
path.addLine(to: finalPoint)
case .rightToLeft:
path.move(to: finalPoint)
path.addLine(to: initialPoint)
}
return path.cgPath
}
func fillLine(with color: UIColor) {
if lineLayer.strokeEnd == 1 {
backgroundColor = UIColor(cgColor: lineLayer.strokeColor ?? defaultColor.cgColor)
}
lineLayer.strokeColor = color.cgColor
lineLayer.strokeEnd = 0
animateLine(to: 1.0)
}
func animateToInitialState() {
backgroundColor = defaultColor
animateLine(to: 0.0)
}
fileprivate func animateLine(to value: CGFloat) {
let function = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
transactionAnimation(with: animationDuration, timingFuncion: function) {
self.lineLayer.strokeEnd = value
}
}
}
| agpl-3.0 | a53565ac06c7a19f73f3a368af699fee | 23.884615 | 93 | 0.607419 | 5.054688 | false | false | false | false |
daaavid/TIY-Assignments | 37--Venue-Menu/Venue-Menu/Venue-Menu/Venue2.swift | 1 | 3986 | //
// Venue.swift
// Venue-Menu
//
// Created by david on 11/27/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
/*
class Venue
{
let name: String
let phone: String
let formattedPhone: String
let address: String
let lat: Double
let lng: Double
let distance: Int
let city: String
let state: String
let icon: String
// let rating: Double
let type: String
init(
name: String,
phone: String,
formattedPhone: String,
address: String,
lat: Double,
lng: Double,
distance: Int,
city: String,
state: String,
icon: String,
type: String
)
{
self.name = name
self.phone = phone
self.formattedPhone = formattedPhone
self.address = address
self.lat = lat
self.lng = lng
self.distance = distance
self.city = city
self.state = state
self.icon = icon
self.type = type
}
static func venueDictWithJSON(venueDict: NSDictionary) -> Venue?
{
var venue: Venue
var name = ""
if let tryName = venueDict["name"] as? String
{
name = tryName
}
var contact = NSDictionary()
if let tryContact = venueDict["contact"] as? NSDictionary
{
contact = tryContact
}
var phone = ""
if let tryPhone = contact["phone"] as? String
{
phone = tryPhone
}
var formattedPhone = ""
if let tryFormattedPhone = contact["formattedPhone"] as? String
{
formattedPhone = tryFormattedPhone
}
var location = NSDictionary()
if let tryLocation = venueDict["location"] as? NSDictionary
{
location = tryLocation
}
var address = ""
if let tryAddress = location["address"] as? String
{
address = tryAddress
}
var lat = 0.0 ; var lng = 0.0
if let tryLat = location["lat"] as? Double
{
if let tryLng = location["lng"] as? Double
{
lat = tryLat
lng = tryLng
}
}
var distance = 0
if let tryDistance = location["distance"] as? Int
{
distance = tryDistance
}
var city = ""
if let tryCity = location["city"] as? String
{
city = tryCity
}
var state = ""
if let tryState = location["state"] as? String
{
state = tryState
}
var categories = [NSDictionary]()
if let tryCategories = venueDict["categories"] as? [NSDictionary]
{
categories = tryCategories
}
var type: String = ""
var icon: String = ""
if let category = categories.first
{
if let shortName = category["shortName"] as? String
{
type = shortName
}
if let iconDict = category["icon"] as? NSDictionary
{
var prefix = iconDict["prefix"] as! String
prefix = prefix.stringByReplacingOccurrencesOfString("\\", withString: "")
let suffix = iconDict["suffix"] as! String
icon = prefix + "64" + suffix
}
}
venue = Venue(
name: name,
phone: phone,
formattedPhone: formattedPhone,
address: address,
lat: lat,
lng: lng,
distance: distance,
city: city,
state: state,
icon: icon,
type: type
)
return venue
}
}
*/ | cc0-1.0 | 067a65039d1106dcdd422588eefc2880 | 22.309942 | 90 | 0.470263 | 5.063532 | false | false | false | false |
dunkelstern/twohundred | TwoHundred/server.swift | 1 | 6106 | //
// server.swift
// twohundred
//
// Created by Johannes Schriewer on 01/11/15.
// Copyright © 2015 Johannes Schriewer. All rights reserved.
//
#if os(Linux)
import BlocksRuntime
#endif
import UnchainedIPAddress
import UnchainedLogger
import UnchainedSocket
import UnchainedString
/// HTTP Server baseclass, subclass to get useful behaviour
public class TwoHundredServer {
typealias ResponseHandlerBlock = @convention(block) (connection: UnsafeMutablePointer<Connection>, data: UnsafePointer<CChar>, size: Int) -> Bool
private var serverResponseHandlerBlock: ResponseHandlerBlock?
private var serverHandle: COpaquePointer = nil
private var requestHeaderData = [Int32:String]()
private var requestHeader = [Int32:RequestHeader]()
private var requestBody = [Int32:[UInt8]]()
/// Listening address
public let listeningAddress: IPAddress
/// Listening port
public let listeningPort: UInt16
// TODO: SSL/TLS config
// TODO: receive and send buffer sizes
// TODO: temporary file storage for big transfers
/// initialize with minimum settings needed
///
/// - Parameter listenAddress: address to listen on, use 0.0.0.0 for all interfaces
/// - Parameter port: the port to listen on, must be root to listen to ports below 1024
public init(listenAddress: IPAddress, port: UInt16) {
self.listeningAddress = listenAddress
self.listeningPort = port
}
/// initialize for localhost
///
/// - Parameter listenPort: port to listen on, must be root to listen to ports below 1024
public convenience init(listenPort: UInt16) {
self.init(listenAddress: .Wildcard, port:listenPort)
}
/// simplest possible initializer (localhost on port 8000)
public convenience init() {
self.init(listenAddress: .Wildcard, port: 8000)
}
/// run the server
public func start(timeout: Int32 = 10, numThreads: Int32 = 30) {
self.serverHandle = server_init(self.listeningAddress.description, "\(self.listeningPort)", false, timeout)
if self.serverHandle == nil {
Log.fatal("Could not initialize server!")
return
}
self.serverResponseHandlerBlock = { (connection: UnsafeMutablePointer<Connection>, data: UnsafePointer<CChar>, size: Int) -> Bool in
let connectionID = connection.memory.id
let remote = IPAddress(fromString: String.fromCString(connection.memory.remoteIP)!)
let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer<UInt8>(data), count: size)
for char in buffer {
if self.requestHeaderData[connectionID] == nil {
self.requestHeaderData[connectionID] = ""
}
if self.requestBody[connectionID] == nil {
// we're in header phase, append data to header
self.requestHeaderData[connectionID]!.append(UnicodeScalar(char))
if self.requestHeaderData[connectionID]!.isSuffixed("\r\n\r\n") {
if let header = RequestHeader(data: self.requestHeaderData[connectionID]!) {
self.requestHeader[connectionID] = header
self.requestHeaderData[connectionID] = ""
if let hdr = self.requestHeader[connectionID]!["Content-Length"] {
if let contentLength = Int(hdr) where contentLength == 0 {
self.prepareRequest(connection, remote: remote)
return false
} else {
self.requestBody[connectionID] = [UInt8]()
}
} else {
self.prepareRequest(connection, remote: remote)
return false
}
} else {
return false
}
}
} else {
// ok body phase, append to body
guard let hdr = self.requestHeader[connectionID]!["Content-Length"],
let contentLength = Int(hdr) else {
return false
}
self.requestBody[connectionID]!.append(char)
if (self.requestBody[connectionID]!.count == contentLength) {
self.prepareRequest(connection, remote: remote)
return false
}
}
}
return true
}
server_start(self.serverHandle, { (connection, instance, data, size) -> Bool in
let handler = unsafeBitCast(instance, ResponseHandlerBlock.self)
return handler(connection: connection, data: data, size: size)
}, unsafeBitCast(self.serverResponseHandlerBlock, UnsafeMutablePointer<Void>.self), numThreads)
}
public func stop() {
server_stop(self.serverHandle)
}
/// Override this function in your own TwoHundred subclass to handle requests
///
/// - parameter request: the request to handle
/// - returns: HTTPResponse to send
public func handleRequest(request: HTTPRequest) -> HTTPResponseBase {
Log.debug("Request from \(request.remoteIP): \(request.header.method) \(request.header.url)")
return HTTPResponseBase()
}
// MARK: - Private
private func prepareRequest(connection: UnsafeMutablePointer<Connection>, remote: IPAddress?) {
let connectionID = connection.memory.id
let body = self.requestBody[connectionID]
let header = self.requestHeader[connectionID]!
let request = HTTPRequest(remoteIP: remote, header: header, data: body)
let response = self.handleRequest(request)
let data = response.makeSocketData()
if case .StringData(let data) = data {
server_send_data(connection, data, data.utf8.count)
}
//self.socket!.send(response.makeSocketData(), connectionID: connectionID, successCallback: nil)
if header.method != .HEAD {
for result in response.body {
switch result {
case .StringData(let data):
server_send_data(connection, data, data.utf8.count)
case .Data(let data):
server_send_data(connection, UnsafePointer<CChar>(data), data.count)
case .File(let filename):
server_send_file(connection, filename)
}
//self.socket!.send(result, connectionID: connectionID, successCallback: nil)
}
}
self.requestBody.removeValueForKey(connectionID)
self.requestHeader.removeValueForKey(connectionID)
self.requestHeaderData.removeValueForKey(connectionID)
}
}
| bsd-3-clause | db6f5a9dbd2ff10a6b3422ba48238857 | 34.911765 | 149 | 0.680426 | 4.239583 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Post/PostEditor+MoreOptions.swift | 1 | 5619 | import Foundation
import WordPressFlux
extension PostEditor where Self: UIViewController {
func displayPostSettings() {
let settingsViewController: PostSettingsViewController
if post is Page {
settingsViewController = PageSettingsViewController(post: post)
} else {
settingsViewController = PostSettingsViewController(post: post)
}
settingsViewController.featuredImageDelegate = self as? FeaturedImageDelegate
settingsViewController.hidesBottomBarWhenPushed = true
self.navigationController?.pushViewController(settingsViewController, animated: true)
}
private func createPostRevisionBeforePreview(completion: @escaping (() -> Void)) {
let context = ContextManager.sharedInstance().mainContext
context.performAndWait {
post = self.post.createRevision()
ContextManager.sharedInstance().save(context)
completion()
}
}
private func savePostBeforePreview(completion: @escaping ((String?, Error?) -> Void)) {
let context = ContextManager.sharedInstance().mainContext
let postService = PostService(managedObjectContext: context)
if !post.hasUnsavedChanges() {
completion(nil, nil)
return
}
navigationBarManager.reloadTitleView(navigationBarManager.generatingPreviewTitleView)
postService.autoSave(post, success: { [weak self] savedPost, previewURL in
guard let self = self else {
return
}
self.post = savedPost
if self.post.isRevision() {
ContextManager.sharedInstance().save(context)
completion(previewURL, nil)
} else {
self.createPostRevisionBeforePreview() {
completion(previewURL, nil)
}
}
}) { error in
//When failing to save a published post will result in "preview not available"
DDLogError("Error while trying to save post before preview: \(String(describing: error))")
completion(nil, error)
}
}
private func displayPreviewNotAvailable(title: String, subtitle: String? = nil) {
let noResultsController = NoResultsViewController.controllerWith(title: title, subtitle: subtitle)
noResultsController.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(noResultsController, animated: true)
}
func displayPreview() {
guard !isUploadingMedia else {
displayMediaIsUploadingAlert()
return
}
guard post.remoteStatus != .pushing else {
displayPostIsUploadingAlert()
return
}
savePostBeforePreview() { [weak self] previewURLString, error in
guard let self = self else {
return
}
let navigationBarManager = self.navigationBarManager
navigationBarManager.reloadTitleView(navigationBarManager.blogTitleViewLabel)
if error != nil {
let title = NSLocalizedString("Preview Unavailable", comment: "Title on display preview error" )
self.displayPreviewNotAvailable(title: title)
return
}
let previewController: PreviewWebKitViewController
if let previewURLString = previewURLString, let previewURL = URL(string: previewURLString) {
previewController = PreviewWebKitViewController(post: self.post, previewURL: previewURL)
} else {
if self.post.permaLink == nil {
DDLogError("displayPreview: Post permalink is unexpectedly nil")
self.displayPreviewNotAvailable(title: NSLocalizedString("Preview Unavailable", comment: "Title on display preview error" ))
return
}
previewController = PreviewWebKitViewController(post: self.post)
}
previewController.trackOpenEvent()
let navWrapper = LightNavigationController(rootViewController: previewController)
if self.navigationController?.traitCollection.userInterfaceIdiom == .pad {
navWrapper.modalPresentationStyle = .fullScreen
}
self.navigationController?.present(navWrapper, animated: true)
}
}
func displayHistory() {
let revisionsViewController = RevisionsTableViewController(post: post) { [weak self] revision in
guard let post = self?.post.update(from: revision) else {
return
}
// show the notice with undo button
let notice = Notice(title: "Revision loaded", message: nil, feedbackType: .success, notificationInfo: nil, actionTitle: "Undo", cancelTitle: nil) { (happened) in
guard happened else {
return
}
DispatchQueue.main.async {
guard let original = self?.post.original,
let clone = self?.post.clone(from: original) else {
return
}
self?.post = clone
WPAnalytics.track(.postRevisionsLoadUndone)
}
}
ActionDispatcher.dispatch(NoticeAction.post(notice))
DispatchQueue.main.async {
self?.post = post
}
}
navigationController?.pushViewController(revisionsViewController, animated: true)
}
}
| gpl-2.0 | cfad89f191a4cccfe631de659f898aa2 | 38.570423 | 173 | 0.612565 | 5.952331 | false | false | false | false |
mikekavouras/project-euler | ProjectEuler.playground/Pages/Smallest Multiple.xcplaygroundpage/Contents.swift | 1 | 787 | //: [Largest Palindrome Product](@previous)
/*:
# Smallest Multiple
https://projecteuler.net/problem=5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
**What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20**
*/
import Foundation
//: First attempt
func smallestMultiple(range: Range<Int>) -> Int {
var result: Int = -1
for var i = 1;;i++ {
var found = 0
for j in range {
guard i % j == 0 else { break }
found++
result = i
}
if found == range.count {
return result
}
}
}
// uncomment the line below to execute
// smallestMultiple(1...20)
//: run time: 35.59s
//: [Next](@next)
| mit | 758b9da52ef570886ede64b890813a35 | 20.861111 | 106 | 0.599746 | 3.857843 | false | false | false | false |
djwbrown/swift | test/Misc/target-cpu.swift | 2 | 2312 | // RUN: not %swift -typecheck -target arm64-apple-ios7 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=TARGETCPU1 %s
// TARGETCPU1: "-target-cpu" "cyclone"
// RUN: not %swift -typecheck -target arm64-apple-tvos9 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=APPLETVTARGETCPU1 %s
// APPLETVTARGETCPU1: "-target-cpu" "cyclone"
// RUN: not %swift -typecheck -target armv7s-apple-tvos9 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=APPLETVTARGETCPU2 %s
// APPLETVTARGETCPU2: "-target-cpu" "swift"
// RUN: not %swift -typecheck -target armv7-apple-tvos9 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=APPLETVTARGETCPU3 %s
// APPLETVTARGETCPU3: "-target-cpu" "cortex-a8"
// RUN: not %swift -typecheck -target armv7k-apple-watchos2 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=WATCHTARGETCPU1 %s
// WATCHTARGETCPU1: "-target-cpu" "cortex-a7"
// RUN: not %swift -typecheck -target arm64-apple-watchos2 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=WATCHTARGETCPU2 %s
// WATCHTARGETCPU2: "-target-cpu" "cyclone"
// RUN: not %swift -typecheck -target armv7s-apple-ios7 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=TARGETCPU2 %s
// TARGETCPU2: "-target-cpu" "swift"
// RUN: not %swift -typecheck -target armv7-apple-ios7 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=TARGETCPU3 %s
// TARGETCPU3: "-target-cpu" "cortex-a8"
// RUN: not %swift -typecheck -target i386-apple-ios7 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=SIMULATOR_CPU %s
// SIMULATOR_CPU: "-target-cpu" "yonah"
// RUN: not %swift -typecheck -target i386-apple-watchos2 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=WATCHSIMULATOR_CPU %s
// WATCHSIMULATOR_CPU: "-target-cpu" "yonah"
// RUN: not %swift -typecheck -target x86_64-apple-ios7 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=SIMULATOR64_CPU %s
// SIMULATOR64_CPU: "-target-cpu" "core2"
// RUN: not %swift -typecheck -target x86_64-apple-tvos9 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=APPLETVSIMULATOR64_CPU %s
// APPLETVSIMULATOR64_CPU: "-target-cpu" "core2"
// RUN: not %swift -typecheck -target x86_64-apple-watchos2 -Xcc -### %s 2>&1 | %FileCheck -check-prefix=WATCHSIMULATOR64_CPU %s
// WATCHSIMULATOR64_CPU: "-target-cpu" "core2"
// RUN: not %swift -typecheck -target s390x-unknown-linux-gnu -Xcc -### %s 2>&1 | %FileCheck -check-prefix=S390X_CPU %s
// S390X_CPU: "-target-cpu" "z196"
| apache-2.0 | 7c1c62a7830539feb75eeb6a31855052 | 54.047619 | 128 | 0.682958 | 2.875622 | false | false | true | false |
roambotics/swift | test/SILOptimizer/diagnostic_constant_propagation_floats.swift | 2 | 10118 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
// RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
//
// These are tests for diagnostics produced by constant propagation pass
// on floating-point operations.
import StdlibUnittest
func testFPToIntConversion() {
_blackHole(Int8(-1.28E2))
_blackHole(Int8(-128.5)) // the result is -128 and is not an overflow
_blackHole(Int8(1.27E2))
_blackHole(Int8(-0))
_blackHole(Int8(3.33333))
_blackHole(Int8(-2E2)) // expected-error {{invalid conversion: '-2E2' overflows 'Int8'}}
_blackHole(UInt8(2E2))
_blackHole(UInt8(3E2)) // expected-error {{invalid conversion: '3E2' overflows 'UInt8'}}
_blackHole(UInt8(-0E0))
_blackHole(UInt8(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt8'}}
_blackHole(Int8(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'Int8'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(UInt8(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'UInt8'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Int16(3.2767E4))
_blackHole(Int16(3.2768E4)) // expected-error {{invalid conversion: '3.2768E4' overflows 'Int16'}}
_blackHole(Int16(-4E4)) // expected-error {{invalid conversion: '-4E4' overflows 'Int16'}}
_blackHole(UInt16(6.5535E4))
_blackHole(UInt16(6.5536E4)) // expected-error {{invalid conversion: '6.5536E4' overflows 'UInt16'}}
_blackHole(UInt16(7E4)) // expected-error {{invalid conversion: '7E4' overflows 'UInt16'}}
_blackHole(UInt16(-0E0))
_blackHole(UInt16(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt16'}}
_blackHole(Int32(-2.147483648E9))
_blackHole(Int32(-2.147483649E9)) // expected-error {{invalid conversion: '-2.147483649E9' overflows 'Int32'}}
_blackHole(Int32(3E9)) // expected-error {{invalid conversion: '3E9' overflows 'Int32'}}
_blackHole(UInt32(4.294967295E9))
_blackHole(UInt32(4.294967296E9)) // expected-error {{invalid conversion: '4.294967296E9' overflows 'UInt32'}}
_blackHole(UInt32(5E9)) // expected-error {{invalid conversion: '5E9' overflows 'UInt32'}}
_blackHole(UInt32(-0E0))
_blackHole(UInt32(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt32'}}
_blackHole(Int64(9.223372036854775E18))
// A case where the imprecision due to the implicit conversion of
// float literals to 'Double' results in an overflow.
_blackHole(Int64(9.223372036854775807E18)) // expected-error {{invalid conversion: '9.223372036854775807E18' overflows 'Int64'}}
// A case where implicit conversion of the float literal to 'Double'
// elides an overflow that one would expect during conversion to 'Int64'.
_blackHole(Int64(-9.223372036854775809E18))
// Cases of definite overflow.
_blackHole(Int64(9.223372036854775808E18)) // expected-error {{invalid conversion: '9.223372036854775808E18' overflows 'Int64'}}
_blackHole(Int64(1E19)) // expected-error {{invalid conversion: '1E19' overflows 'Int64'}}
// A case where implicit conversion of the float literal to 'Double'
// results in an overflow during conversion to 'UInt64''.
_blackHole(UInt64(1.844674407370955E19))
_blackHole(UInt64(1.8446744073709551615E19)) // expected-error {{invalid conversion: '1.8446744073709551615E19' overflows 'UInt64'}}
_blackHole(UInt64(2E19)) // expected-error {{invalid conversion: '2E19' overflows 'UInt64'}}
_blackHole(UInt64(-0E0))
_blackHole(UInt64(-2E2)) // expected-error {{negative literal '-2E2' cannot be converted to 'UInt64'}}
_blackHole(Int64(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'Int64'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(UInt64(1E6000)) // expected-error {{invalid conversion: '1E6000' overflows 'UInt64'}}
// expected-warning@-1 {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
}
func testFloatConvertOverflow() {
let f1: Float = 1E38
_blackHole(f1)
let f2: Float = 1E39 // expected-warning {{'1E39' overflows to inf during conversion to 'Float'}}
_blackHole(f2)
let f3: Float = 1234567891012345678912345671234561234512.0 // expected-warning {{'1234567891012345678912345671234561234512.0' overflows to inf during conversion to 'Float'}}
_blackHole(f3)
let f4: Float = 0.1234567891012345678912345671234561234512
_blackHole(f4)
let f5: Float32 = -3.4028236E+38 // expected-warning {{'-3.4028236E+38' overflows to -inf during conversion to 'Float32' (aka 'Float')}}
_blackHole(f5)
// Diagnostics for Double truncations have architecture dependent
// messages. See _nonx86 and _x86 test files.
let d1: Double = 1E308
_blackHole(d1)
let d2: Double = 1234567891012345678912345671234561234512.0
_blackHole(d2)
// All warnings are disabled during explicit conversions.
// Except when the number is so large that it wouldn't even fit into largest
// FP type available.
_blackHole(Float(1E38))
_blackHole(Float(1E39))
_blackHole(Float(100000000000000000000000000000000000000000000000.0))
_blackHole(Double(1E308))
_blackHole(Float(1E6000)) // expected-warning {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Float(-1E6000)) // expected-warning {{'-1E6000' overflows to -inf because its magnitude exceeds the limits of a float literal}}
_blackHole(Double(1E6000)) // expected-warning {{'1E6000' overflows to inf because its magnitude exceeds the limits of a float literal}}
}
func testFloatConvertUnderflow() {
let f0: Float = 0.500000006364665322827
_blackHole(f0)
let f1: Float = 1E-37
_blackHole(f1)
let f2: Float = 1E-39 // expected-warning {{'1E-39' underflows and loses precision during conversion to 'Float'}}
_blackHole(f2)
let f3: Float = 1E-45 // expected-warning {{'1E-45' underflows and loses precision during conversion to 'Float'}}
_blackHole(f3)
// A number close to 2^-150 (smaller than least non-zero float: 2^-149)
let f6: Float = 7.0064923E-46 // expected-warning {{'7.0064923E-46' underflows and loses precision during conversion to 'Float'}}
_blackHole(f6)
// Some cases where tininess doesn't cause extra imprecision.
// A number so close to 2^-130 that 2^-130 is its best approximation
// even in Float80.
let f4: Float = 7.3468396926392969248E-40
_blackHole(f4)
// A number very close to 2^-149.
let f5: Float = 1.4012984821624085566E-45
_blackHole(f5)
let f7: Float = 1.1754943E-38 // expected-warning {{'1.1754943E-38' underflows and loses precision during conversion to 'Float'}}
_blackHole(f7)
let f8: Float = 1.17549428E-38 // expected-warning {{'1.17549428E-38' underflows and loses precision during conversion to 'Float'}}
_blackHole(f8)
let d1: Double = 1E-307
_blackHole(d1)
// All warnings are disabled during explicit conversions.
_blackHole(Float(1E-37))
_blackHole(Float(1E-39))
_blackHole(Float(1E-45))
_blackHole(Double(1E-307))
}
func testHexFloatImprecision() {
let f1: Float = 0x0.800000p-126
_blackHole(f1)
// Smallest Float subnormal number.
let f2: Float = 0x0.000002p-126
_blackHole(f2)
let f3: Float = 0x1.000002p-127 // expected-warning {{'0x1.000002p-127' loses precision during conversion to 'Float'}}
_blackHole(f3)
let f4: Float = 0x1.000001p-127 // expected-warning {{'0x1.000001p-127' loses precision during conversion to 'Float'}}
_blackHole(f4)
let f5: Float = 0x1.0000002p-126 // expected-warning {{'0x1.0000002p-126' loses precision during conversion to 'Float'}}
_blackHole(f5)
// In the following cases, the literal is truncated to a Float through a
// (lossless) conversion to Double. There should be no warnings here.
let t1: Double = 0x1.0000002p-126
_blackHole(Float(t1))
let t2: Double = 0x1.000001p-126
_blackHole(Float(t2))
let t3 = 0x1.000000fp25
_blackHole(Float(t3))
let d1: Double = 0x0.8p-1022
_blackHole(d1)
// Smallest non-zero number representable in Double.
let d2: Double = 0x0.0000000000001p-1022
_blackHole(d2)
let d3: Double = 0x1p-1074
_blackHole(d3)
// Test the case where conversion results in subnormality in the destination.
let d4: Float = 0x1p-149
_blackHole(d4)
let d5: Float = 0x1.8p-149 // expected-warning {{'0x1.8p-149' loses precision during conversion to 'Float}}
_blackHole(d5)
// All warnings are disabled during explicit conversions.
_blackHole(Float(0x1.000002p-126))
_blackHole(Float(0x1.0000002p-126))
_blackHole(Float(0x1.000002p-127))
_blackHole(Float(0x1.000001p-127))
_blackHole(Float(Double(0x1.000000fp25)))
_blackHole(Double(0x1p-1074))
}
func testFloatArithmetic() {
// Ignore inf and Nan during arithmetic operations.
// This may become a warning in the future.
let infV: Float = 3.0 / 0.0
_blackHole(infV)
let a: Float = 1E38
let b: Float = 10.0
_blackHole(a * b)
}
func testIntToFloatConversion() {
let f1: Float = 16777216
_blackHole(f1)
let f2: Float = 1_000_000_000_000 // expected-warning {{'1000000000000' is not exactly representable as 'Float'; it becomes '999999995904'}}
_blackHole(f2)
// First positive integer that cannot be precisely represented in Float: 2^24 + 1
let f3: Float = 16777217 // expected-warning {{'16777217' is not exactly representable as 'Float'; it becomes '16777216'}}
_blackHole(f3)
let d1: Double = 9_007_199_254_740_992 // This value is 2^53
_blackHole(d1)
let d2: Double = 9_007_199_254_740_993 // expected-warning {{'9007199254740993' is not exactly representable as 'Double'; it becomes '9007199254740992'}}
_blackHole(d2)
// No warnings are emitted for conversion through explicit constructor calls.
_blackHole(Float(16777217))
_blackHole(Double(2_147_483_647))
}
| apache-2.0 | 330161147e90fa9a180985b58814fd38 | 44.169643 | 175 | 0.71358 | 3.314117 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK | OpenTimeSDK/Classes/OTSigninResponse.swift | 1 | 724 | //
// OTSigninResponse.swift
// OpenTime
//
// Created by Josh Woodcock on 10/23/15.
// Copyright © 2015 Connecting Open Time, LLC. All rights reserved.
//
public class OTSigninResponse : OTAPIResponse {
private var _person: OTDeserializedPerson!;
public init(success: Bool, message: String, rawData: AnyObject?) {
if(success == true && rawData != nil) {
let personDict = rawData!.object(forKey: "person") as! NSDictionary;
self._person = OTDeserializedPerson(dictionary: personDict);
}
super.init(success: success, message: message);
}
public func getPerson() -> OTDeserializedPerson {
return _person;
}
}
| mit | 4760c767095883cb51562c19433e9965 | 26.807692 | 80 | 0.61964 | 4.252941 | false | false | false | false |
Under100/ABOnboarding | Example/ABOnboarding/ViewController.swift | 1 | 2966 | //
// ViewController.swift
// ABOnboarding
//
// Created by Adam Boyd on 04/02/2016.
// Copyright (c) 2016 Adam Boyd. All rights reserved.
//
import UIKit
import ABOnboarding
class ViewController: UIViewController, ShowsABOnboardingItem {
var onboardingToShow: [ABOnboardingItem] = []
var onboardingIndex: Int = 0
var currentBlurViews: [UIView] = []
var onboardingSection: Int = 0
@IBOutlet weak var awesomeButton: UIButton!
@IBOutlet weak var anotherButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
if self.shouldShowOnboardingOnThisVC() && self.onboardingToShow.count == 0 {
self.onboardingToShow = [
ABOnboardingItem(message: "This is pointing at a pretty awesome button", placement: .Below(self.awesomeButton), blurredBackground: true),
ABOnboardingItem(message: "This is another button, but this time below", placement: .Above(self.anotherButton), blurredBackground: true),
ABOnboardingItem(message: "It doesn't have to point at anything!", placement: .RelativeToTop(100), blurredBackground: true),
ABOnboardingItem(message: "It doesn't have to have a blurred background", placement: .RelativeToTop(100), blurredBackground: false),
ABOnboardingItem(message: "You can delay the next item showing until a user completes an action (press the awesome button)", placement: .RelativeToTop(100), blurredBackground: true, nextItemAutomaticallyShows: false),
ABOnboardingItem(message: "This one is delayed. That's pretty cool right?", placement: .Below(self.awesomeButton), blurredBackground: true)
]
//Note: if you get an error about constraints here, the onboarding is being shown before the window is ready.
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
self.startOnboarding()
}
}
}
@IBAction func awesomeButtonAction(sender: AnyObject) {
if self.shouldShowOnboardingOnThisVC() {
self.showNextOnboardingItem()
}
}
// MARK: - ShowsABOnboardingItem
func userSkippedOnboarding() {
print("User hit the skip onboarding button, save the status in this method")
}
func userCompletedOnboarding() {
print("User completed all the onboarding, save the status in this method")
}
/**
If pod ABOnboarding should be showing items on this view controller
- returns: true if should show, false if not
*/
func shouldShowOnboardingOnThisVC() -> Bool {
return true
}
func skipOnboardingForwarder() {
self.skipOnboarding()
}
func showNextOnboardingItemForwarder() {
self.showNextOnboardingItem()
}
}
| mit | 6c8cd61e17070d41e4a16ce7eacb3161 | 37.025641 | 233 | 0.655428 | 4.738019 | false | false | false | false |
maxadamski/SwiftyHTTP | SwiftyServer/AppDelegate.swift | 1 | 3310 | //
// AppDelegate.swift
// SwiftyServer
//
// Created by Helge Heß on 6/25/14.
// Copyright (c) 2014 Always Right Institute. All rights reserved.
//
import Cocoa
import SwiftyHTTP
class AppDelegate: NSObject, NSApplicationDelegate {
/* our server */
var httpd : Connect!
var requestCounter = 1 // FIXME: not threadsafe, use sync_dispatch
func startServer() {
httpd = Connect()
.onLog {
[unowned self] in
self.log($0)
}
.useQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
/* request counter middleware */
httpd.use { _, _, _, next in
self.requestCounter++
next()
}
/* primary request handler */
httpd.use { rq, res, con, next in
var content = "<h3>Swifty request number #\(self.requestCounter)</h3>"
content += "<pre>"
content += "\r\n"
content += " /----------------------------------------------------\\\r\n"
content += " | Welcome to the Always Right Institute! |\r\n"
content += " | I am a twisted HTTP echo server |\r\n"
content += " \\----------------------------------------------------/\r\n"
content += "\r\n"
content += "</pre>"
content += "<pre>Request: \(rq.method) \(rq.url)\n"
for ( key, value ) in rq.headers {
content += " \(key): \(value)\n"
}
content += "</pre>"
res.bodyAsString = content
con.sendResponse(res)
next()
}
/* logger middleware */
httpd.use { rq, res, _, _ in
print("\(rq.method) \(rq.url) \(res.status)")
}
httpd.listen(1337)
}
/* Cocoa app boilerplate */
@IBOutlet var window : NSWindow!
@IBOutlet var logViewParent : NSScrollView!
@IBOutlet var label : NSTextField!
var logView : NSTextView {
// NSTextView doesn't work with weak?
return logViewParent.contentView.documentView as! NSTextView
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
startServer()
label.allowsEditingTextAttributes = true
label.selectable = true
if let address = httpd.socket.boundAddress {
let url = "http://127.0.0.1:\(address.port)"
let s = "<pre>Connect in your browser via " +
"'<a href='\(url)'>\(url)</a>'</pre>"
let utf8 = s.dataUsingEncoding(NSUTF8StringEncoding)!
let aS = NSAttributedString(HTML: utf8, documentAttributes: nil)
label.attributedStringValue = aS!
}
}
func applicationWillTerminate(aNotification: NSNotification) {
httpd?.stop()
httpd = nil
}
func log(string: String) {
// log to shell
print(string)
// log to view. Careful, must run in main thread!
dispatch_async(dispatch_get_main_queue()) {
self.logView.appendString(string + "\n")
}
}
}
extension NSTextView {
func appendString(string: String) {
if let ts = textStorage {
let ls = NSAttributedString(string: string)
ts.appendAttributedString(ls)
}
if let s = self.string {
let charCount = (s as NSString).length
self.scrollRangeToVisible(NSMakeRange(charCount, 0))
}
needsDisplay = true
}
}
| mit | fd6eff305753f321cdbca3e72b7c452a | 24.651163 | 80 | 0.559686 | 4.172762 | false | false | false | false |
yangdongzheng/DZRootViewController | DZRootViewController/DZRootViewController.swift | 1 | 1190 | //
// DZRootViewController.swift
// DZTopLine
//
// Created by mac on 2017/6/11.
// Copyright © 2017年 MarkYang. All rights reserved.
//
import UIKit
class DZRootViewController: UITabBarController {
override func loadView() {
super.loadView()
addChildViewController(ViewController(), title: "首页", imageName: "tabbar_home")
addChildViewController(ViewController(), title: "热门", imageName: "tabbar_gift")
addChildViewController(ViewController(), title: "分类", imageName: "tabbar_category")
addChildViewController(ViewController(), title: "我的", imageName: "tabbar_me")
}
override func viewDidLoad() {
super.viewDidLoad()
}
fileprivate func addChildViewController(_ controller: UIViewController, title: String, imageName: String) {
controller.tabBarItem.image = UIImage(named: imageName)
controller.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")
controller.tabBarItem.title = title;
controller.title = title;
let nav = DZNavigationViewController(rootViewController: controller)
addChildViewController(nav);
}
}
| mit | ae6e225bfa5fe2efc8a531e979e0700f | 33.441176 | 111 | 0.684885 | 4.982979 | false | false | false | false |
bryzinski/skype-ios-app-sdk-samples | BankingAppSwift/BankingAppSwift/ChatViewController.swift | 1 | 8031 | //+----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Module name: ChatViewController.swift
//----------------------------------------------------------------
import UIKit
class ChatViewController: UIViewController,ChatHandlerDelegate ,SfBAlertDelegate{
/** Called when new alert appears in the context where this delegate is attached.
*
* Each alert is passed to a delegate once and dismissed unconditionally.
* If no delegate is attached, alerts are accumulated and reported as soon
* as delegate is set. Accumulated alerts of the same category and type
* are coalesced, only the last one will be reported.
*/
let DisplayNameInfo: String = "displayName"
var conversation:SfBConversation?
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var endButton: UIBarButtonItem!
@IBOutlet weak var spaceConstraint: NSLayoutConstraint!
@IBOutlet weak var messageTextField: UITextField!
var chatTableViewController:ChatTableViewController? = nil
var chatHandler:ChatHandler? = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.registerForNotifications()
}
override func viewDidLoad() {
super.viewDidLoad()
self.joinMeeting()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit{
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationItem.setHidesBackButton(true, animated: true)
self.navigationController?.setNavigationBarHidden(false, animated: false)
}
//MARK: Keyboard Handling
func registerForNotifications() {
NotificationCenter.default.addObserver(self, selector:#selector(ChatViewController.leaveMeetingWhenAppTerminates(_:)), name:NSNotification.Name.UIApplicationWillTerminate, object:nil)
NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ChatViewController.keyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func leaveMeetingWhenAppTerminates(_ aNotification:Notification) {
if let conversation = self.chatHandler?.conversation{
leaveMeetingWithSuccess(conversation)
}
}
func keyboardWillShow(_ aNotification:Notification) {
let info:NSDictionary = aNotification.userInfo! as NSDictionary
let keyboardFrame: CGRect = ((info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue)!
self.spaceConstraint.constant = keyboardFrame.size.height
self.view.layoutIfNeeded()
// To scroll table up
//let newOffSet: CGPoint = CGPointMake(0, (self.chatTableViewController?.tableView.contentOffset.y)! + keyboardFrame.size.height)
// self.chatTableViewController?.tableView.setContentOffset(newOffSet, animated: true)
}
func keyboardWillBeHidden(_ aNotification:Notification) {
self.spaceConstraint.constant = 0
self.view.layoutIfNeeded()
}
//MARK: - Button actions
@IBAction func sendMessage(_ sender: AnyObject) {
self.messageTextField.resignFirstResponder()
self.sendChatMessage(self.messageTextField.text!)
}
@IBAction func endChat(_ sender: AnyObject) {
self.endMeeting()
}
func endMeeting() {
if let conversation = self.chatHandler?.conversation{
if(!leaveMeetingWithSuccess(conversation)){
showErrorAlert("Could Not Leave Meeting", viewController: self)
}
self.chatHandler?.conversation.removeObserver(self, forKeyPath: "canLeave")
}
var presentedFromOnlineMeetingViewController = false
let allViewControllers = self.navigationController?.viewControllers
for viewController in allViewControllers!{
if(viewController.isKind(of: OnlineMainViewController.self)){
presentedFromOnlineMeetingViewController = true
self.navigationController?.popToViewController(viewController, animated: true)
break;
}
}
if(!presentedFromOnlineMeetingViewController){
self.navigationController?.popViewController(animated: true)
}
}
func sendChatMessage(_ message: String) {
var error: NSError? = nil
if let chatHandler = self.chatHandler{
chatHandler.sendMessage(message, error: &error)
if (error != nil) {
self.navigationController!.popViewController(animated: true)
}
else {
self.messageTextField.text = ""
self.chatTableViewController?.addMessage(message, from: (chatHandler.userInfo as! Dictionary)[DisplayNameInfo]!, origin: .mySelf)
}
}
}
//MARK: Joins a Skype Meeting
//Joins a Skype meeting.
func joinMeeting() {
conversation?.alertDelegate = self
self.chatHandler = ChatHandler(conversation: self.conversation!,
delegate: self,
userInfo: [DisplayNameInfo:"Jake"])
conversation!.addObserver(self, forKeyPath: "canLeave", options: [.initial, .new] , context: nil)
}
func didReceive(_ alert: SfBAlert){
alert.showSfBAlertInController(self)
}
//MARK - Skype ChatHandlerDelegate Functions
// Notify the user when connection is established and message can be sent.
func chatHandler(_ chatHandler: ChatHandler, chatService: SfBChatService, didChangeCanSendMessage canSendMessage: Bool) {
if (canSendMessage) {
self.sendButton.isEnabled = true
self.sendButton.alpha = 1
self.chatTableViewController?.addStatus("now you can send a message")
}
else{
self.sendButton.isEnabled = false
}
}
//Handle message received from other meeting participant.
func chatHandler(_ chatHandler: ChatHandler, didReceiveMessage message: SfBMessageActivityItem) {
self.chatTableViewController?.addMessage(message.text,
from: (message.sender?.displayName)!, origin:.participant)
}
//MARK: - Additional KVO
// Monitor canLeave property of a conversation to prevent leaving prematurely
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if (keyPath == "canLeave") {
self.endButton.isEnabled = (self.chatHandler?.conversation.canLeave)!
}
}
//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?) {
if (segue.identifier == "chatTable") {
self.chatTableViewController = segue.destination as? ChatTableViewController
}
}
//MARK: - Helper UI
func handleError(_ readableErrorDescription:String) {
let alertController:UIAlertController = UIAlertController(title: "ERROR!", message: readableErrorDescription, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil))
present(alertController, animated: true, completion:nil)
}
}
| mit | 53f5b26362e65bce0f83d41d6e88e7e9 | 35.339367 | 190 | 0.642759 | 5.573213 | false | false | false | false |
pkadams67/PKA-Project---Advent-16 | Controllers/DayCollectionCell.swift | 1 | 1327 | //
// DayCollectionCell.swift
// Advent '16
//
// Created by Paul Kirk Adams on 11/15/16.
// Copyright © 2016 Paul Kirk Adams. All rights reserved.
//
import UIKit
class DayCollectionCell: UICollectionViewCell {
@IBOutlet var label: UILabel!
@IBOutlet var markedView: UIView!
@IBOutlet var markedViewWidth: NSLayoutConstraint!
@IBOutlet var markedViewHeight: NSLayoutConstraint!
var date: Date? {
didSet {
if date != nil {
label.text = "\(date!.day)"
} else {
label.text = ""
}
}
}
var disabled: Bool = false {
didSet {
if disabled {
alpha = 0.25
} else {
alpha = 1
}
}
}
var mark: Bool = false {
didSet {
if mark {
markedView!.hidden = false
} else {
markedView!.hidden = true
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
markedViewWidth!.constant = min(self.frame.width, self.frame.height)
markedViewHeight!.constant = min(self.frame.width, self.frame.height)
markedView!.layer.cornerRadius = min(self.frame.width, self.frame.height) / 2.0
}
}
| mit | e8972fb64bb8e9e5276af1f85edea40f | 23.555556 | 87 | 0.523379 | 4.541096 | false | false | false | false |
nestlabs/connectedhomeip | examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissioningView.swift | 1 | 3944 | /**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* 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 SwiftUI
struct CommissioningView: View {
var selectedCommissioner: DiscoveredNodeData?
@StateObject var viewModel = CommissioningViewModel();
init(_selectedCommissioner: DiscoveredNodeData?) {
self.selectedCommissioner = _selectedCommissioner
}
var body: some View {
VStack(alignment: .leading) {
if(viewModel.commisisoningWindowOpened == true) {
Text("Commissioning window opened.").padding()
Text("Onboarding PIN: " + String((CastingServerBridge.getSharedInstance()?.getOnboardingPaylod().setupPasscode)!))
.border(Color.blue, width: 1)
.padding()
Text("Discriminator: " + String((CastingServerBridge.getSharedInstance()?.getOnboardingPaylod().setupDiscriminator)!))
.border(Color.blue, width: 1)
.padding()
if(self.selectedCommissioner != nil)
{
if(viewModel.udcRequestSent == true)
{
Text("Complete commissioning on " + (selectedCommissioner?.deviceName)!)
.padding()
}
else if(viewModel.udcRequestSent == false) {
Text("Could not send user directed commissioning request to " + (selectedCommissioner?.deviceName)! + "! Complete commissioning manually!")
.foregroundColor(Color.red)
.padding()
}
}
else{
Text("Complete commissioning with a commissioner manually!").padding()
}
}
else if(viewModel.commisisoningWindowOpened == false) {
Text("Failed to open Commissioning window!")
.foregroundColor(Color.red)
.padding()
}
if(viewModel.commisisoningComplete == true)
{
Text("Commissioning finished!").padding()
NavigationLink(
destination: ContentLauncherView(),
label: {
Text("Next")
.frame(width: 100, height: 30, alignment: .center)
.border(Color.black, width: 1)
}
).background(Color.blue)
.foregroundColor(Color.white)
.frame(maxHeight: .infinity, alignment: .bottom)
.padding()
}
else if(viewModel.commisisoningComplete == false)
{
Text("Commissioning failure!")
.foregroundColor(Color.red)
.padding()
}
}
.navigationTitle("Commissioning...")
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .top)
.onAppear(perform: {
viewModel.prepareForCommissioning(selectedCommissioner: self.selectedCommissioner)
})
}
}
struct CommissioningView_Previews: PreviewProvider {
static var previews: some View {
CommissioningView(_selectedCommissioner: nil)
}
}
| apache-2.0 | 3f5134c4607e540d98e034afadd99954 | 38.838384 | 163 | 0.545385 | 5.251664 | false | false | false | false |
airspeedswift/swift | test/IRGen/prespecialized-metadata/enum-extradata-run.swift | 2 | 3173 | // RUN: %empty-directory(%t)
// RUN: %clang -c -v %target-cc-options -g -O0 -isysroot %sdk %S/Inputs/extraDataFields.cpp -o %t/extraDataFields.o -I %clang-include-dir -I %swift_src_root/include/ -I %swift_src_root/../llvm-project/llvm/include -I %clang-include-dir/../../llvm-macosx-x86_64/include -L %clang-include-dir/../lib/swift/macosx
// RUN: %target-build-swift -c %S/Inputs/enum-extra-data-fields.swift -emit-library -emit-module -enable-library-evolution -module-name ExtraDataFieldsNoTrailingFlags -target %module-target-future -Xfrontend -disable-generic-metadata-prespecialization -emit-module-path %t/ExtraDataFieldsNoTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsNoTrailingFlags)
// RUN: %target-build-swift -c %S/Inputs/enum-extra-data-fields.swift -emit-library -emit-module -enable-library-evolution -module-name ExtraDataFieldsTrailingFlags -target %module-target-future -Xfrontend -prespecialize-generic-metadata -emit-module-path %t/ExtraDataFieldsTrailingFlags.swiftmodule -o %t/%target-library-name(ExtraDataFieldsTrailingFlags)
// RUN: %target-build-swift -v %mcp_opt %s %t/extraDataFields.o -import-objc-header %S/Inputs/extraDataFields.h -Xfrontend -disable-generic-metadata-prespecialization -target %module-target-future -lc++ -L %clang-include-dir/../lib/swift/macosx -sdk %sdk -o %t/main -I %t -L %t -lExtraDataFieldsTrailingFlags -lExtraDataFieldsNoTrailingFlags -module-name main
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: OS=macosx
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: swift_test_mode_optimize
// UNSUPPORTED: swift_test_mode_optimize_size
func ptr<T>(to ty: T.Type) -> UnsafeMutableRawPointer {
UnsafeMutableRawPointer(mutating: unsafePointerToMetadata(of: ty))!
}
func unsafePointerToMetadata<T>(of ty: T.Type) -> UnsafePointer<T.Type> {
unsafeBitCast(ty, to: UnsafePointer<T.Type>.self)
}
import ExtraDataFieldsNoTrailingFlags
let one = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.FixedPayloadSize<Void>.self
)
)
// CHECK: nil
print(
trailingFlagsForEnumMetadata(
one
)
)
let onePayloadSize = payloadSizeForEnumMetadata(one)
// CHECK-NEXT: 8
print(onePayloadSize!.pointee)
let two = completeMetadata(
ptr(
to: ExtraDataFieldsNoTrailingFlags.DynamicPayloadSize<Int32>.self
)
)
// CHECK-NEXT: nil
print(
trailingFlagsForEnumMetadata(
two
)
)
let twoPayloadSize = payloadSizeForEnumMetadata(two)
// CHECK-NEXT: nil
print(twoPayloadSize)
import ExtraDataFieldsTrailingFlags
let three = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.FixedPayloadSize<Void>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForEnumMetadata(
three
)!.pointee
)
let threePayloadSize = payloadSizeForEnumMetadata(three)
// CHECK-NEXT: 8
print(threePayloadSize!.pointee)
let four = completeMetadata(
ptr(
to: ExtraDataFieldsTrailingFlags.DynamicPayloadSize<Int32>.self
)
)
// CHECK-NEXT: 0
print(
trailingFlagsForEnumMetadata(
four
)!.pointee
)
let fourPayloadSize = payloadSizeForEnumMetadata(four)
// CHECK-NEXT: nil
print(fourPayloadSize)
| apache-2.0 | c050595f75716ab1f1270a7bb076e2b5 | 29.805825 | 374 | 0.76174 | 3.541295 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/Keyboard/Keyboards/MKeyboardLandscape.swift | 1 | 2573 | import Foundation
class MKeyboardLandscape:MKeyboard
{
init(states:[MKeyboardState]?, initial:String)
{
let item0:MKeyboardRowItem0 = MKeyboardRowItem0()
let item1:MKeyboardRowItem1 = MKeyboardRowItem1()
let item2:MKeyboardRowItem2 = MKeyboardRowItem2()
let item3:MKeyboardRowItem3 = MKeyboardRowItem3()
let item4:MKeyboardRowItem4 = MKeyboardRowItem4()
let item5:MKeyboardRowItem5 = MKeyboardRowItem5()
let item6:MKeyboardRowItem6 = MKeyboardRowItem6()
let item7:MKeyboardRowItem7 = MKeyboardRowItem7()
let item8:MKeyboardRowItem8 = MKeyboardRowItem8()
let item9:MKeyboardRowItem9 = MKeyboardRowItem9()
let itemDot:MKeyboardRowItemDot = MKeyboardRowItemDot()
let itemSign:MKeyboardRowItemSign = MKeyboardRowItemSign()
let itemClear:MKeyboardRowItemClear = MKeyboardRowItemClear()
let itemBackspace:MKeyboardRowItemBackspace = MKeyboardRowItemBackspace()
let itemPercent:MKeyboardRowItemPercent = MKeyboardRowItemPercent()
let itemDivide:MKeyboardRowItemDivide = MKeyboardRowItemDivide()
let itemMultiply:MKeyboardRowItemMultiply = MKeyboardRowItemMultiply()
let itemSubtract:MKeyboardRowItemSubtract = MKeyboardRowItemSubtract()
let itemAdd:MKeyboardRowItemAdd = MKeyboardRowItemAdd()
let itemEquals:MKeyboardRowItemEquals = MKeyboardRowItemEquals()
let itemHide:MKeyboardRowItemHide = MKeyboardRowItemHide()
let itemsFirstRow:[MKeyboardRowItem] = [
itemClear,
item7,
item8,
item9,
itemSign,
itemDivide,
itemMultiply]
let itemsSecondRow:[MKeyboardRowItem] = [
itemBackspace,
item4,
item5,
item6,
itemPercent,
itemSubtract,
itemAdd]
let itemsThirdRow:[MKeyboardRowItem] = [
item0,
item1,
item2,
item3,
itemDot,
itemEquals,
itemHide]
let firstRow:MKeyboardRow = MKeyboardRow(
items:itemsFirstRow)
let secondRow:MKeyboardRow = MKeyboardRow(
items:itemsSecondRow)
let thirdRow:MKeyboardRow = MKeyboardRow(
items:itemsThirdRow)
let rows:[MKeyboardRow] = [
firstRow,
secondRow,
thirdRow]
super.init(rows:rows, states:states, initial:initial)
}
}
| mit | bc687849e3b7fc99ed6512e29a22f067 | 35.239437 | 81 | 0.631558 | 4.553982 | false | false | false | false |
MrZoidberg/metapp | metapp/Pods/RxSwift/RxSwift/Observables/Observable+Creation.swift | 43 | 8824 | //
// Observable+Creation.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
extension Observable {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(_ subscribe: @escaping (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> Observable<E> {
return Error(error: error)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
public static func of(_ elements: E ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: elements, scheduler: scheduler)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
public static func generate(initialState: E, condition: @escaping (E) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (E) throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
public static func repeatElement(_ element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<R: Disposable>(_ resourceFactory: @escaping () throws -> R, observableFactory: @escaping (R) throws -> Observable<E>) -> Observable<E> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
extension Observable where Element : SignedInteger {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
public static func range(start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
extension Observable {
/**
Converts an array to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from(_ array: [E], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return ObservableSequence(elements: array, scheduler: scheduler)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
public static func from<S: Sequence>(_ sequence: S, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> where S.Iterator.Element == E {
return ObservableSequence(elements: sequence, scheduler: scheduler)
}
}
| mpl-2.0 | a4b0e4bffb8063443586876fa8e72db1 | 42.463054 | 213 | 0.724357 | 4.973506 | false | false | false | false |
yfujiki/ios-charts | Charts/Classes/Charts/MultiplePieChartView.swift | 1 | 2087 | //
// MultiplePieChartView.swift
// Charts
//
// Created by Yuichi Fujiki on 8/21/15.
// Copyright (c) 2015 dcg. All rights reserved.
//
import UIKit
public class MultiplePieChartView: PieChartView {
internal var _drawAnglesPerDataSet: [[CGFloat]]?
internal var _absoluteAnglesPerDataSet: [[CGFloat]]?
public var drawAnglesPerDataSet: [[CGFloat]] {
return _drawAnglesPerDataSet ?? [[CGFloat]]()
}
public var absoluteAnglesPerDataSet: [[CGFloat]] {
return _absoluteAnglesPerDataSet ?? [[CGFloat]]()
}
internal override func initialize()
{
super.initialize()
renderer = MultiplePieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double, dataSet: ChartDataSet) -> CGFloat
{
return CGFloat(value) / CGFloat(dataSet.yValueSum) * 360.0
}
override internal func calcAngles()
{
_drawAnglesPerDataSet = [[CGFloat]]()
_absoluteAnglesPerDataSet = [[CGFloat]]()
var dataSets = _data.dataSets
for (var i = 0; i < _data.dataSetCount; i++)
{
var drawAngles = [CGFloat]()
var absoluteAngles = [CGFloat]()
drawAngles.reserveCapacity(_data.yValCount)
absoluteAngles.reserveCapacity(_data.yValCount)
var cnt = 0
let set = dataSets[i]
var entries = set.yVals
for (var j = 0; j < entries.count; j++)
{
drawAngles.append(calcAngle(abs(entries[j].value), dataSet: set))
if (cnt == 0)
{
absoluteAngles.append(drawAngles[cnt])
}
else
{
absoluteAngles.append(absoluteAngles[cnt - 1] + drawAngles[cnt])
}
cnt++
}
_drawAnglesPerDataSet!.append(drawAngles)
_absoluteAnglesPerDataSet!.append(absoluteAngles)
}
}
}
| apache-2.0 | 3382f7a0daa48ac9a93436d6a7ffd23e | 26.103896 | 112 | 0.573071 | 4.876168 | false | false | false | false |
jaanus/NSProgressExample | NSProgressExample/ViewController.swift | 1 | 4669 | //
// ViewController.swift
// NSProgressExample
//
// Created by Jaanus Kase on 14/08/15.
// Copyright © 2015 Jaanus Kase. All rights reserved.
//
import Cocoa
private var progressObservationContext = 0
class ViewController: NSViewController, ProgressSheetInterface, ProgressSheetDelegate {
@IBOutlet weak var firstTaskDurationField: NSTextField!
@IBOutlet weak var secondTaskDurationField: NSTextField!
@IBOutlet weak var taskWeightSlider: NSSlider!
// Use progress reporting because the sheet asks for our progress
var progress = NSProgress()
var worker1, worker2: NSWindowController?
override func viewDidLoad() {
super.viewDidLoad()
// The child window controllers are long-lived.
worker1 = self.storyboard?.instantiateControllerWithIdentifier("Worker") as? NSWindowController
worker2 = self.storyboard?.instantiateControllerWithIdentifier("Worker") as? NSWindowController
}
@IBAction func start(sender: AnyObject) {
fixWindowPositions()
worker1?.showWindow(self)
worker2?.showWindow(self)
if let worker1 = worker1 as? ChildTaskInterface, worker2 = worker2 as? ChildTaskInterface {
// The actual durations for each task.
let firstTaskDuration = firstTaskDurationField.floatValue
let secondTaskDuration = secondTaskDurationField.floatValue
// The weights to give to each task in accounting for their progress.
let totalWeight = Int64(taskWeightSlider.maxValue)
let secondTaskWeight = Int64(taskWeightSlider.integerValue)
let firstTaskWeight = totalWeight - secondTaskWeight
progress = NSProgress(totalUnitCount: totalWeight)
progress.addObserver(self, forKeyPath: "completedUnitCount", options: [], context: &progressObservationContext)
progress.addObserver(self, forKeyPath: "cancelled", options: [], context: &progressObservationContext)
worker1.startTaskWithDuration(firstTaskDuration)
worker2.startTaskWithDuration(secondTaskDuration)
progress.addChild(worker1.progress, withPendingUnitCount: firstTaskWeight)
progress.addChild(worker2.progress, withPendingUnitCount: secondTaskWeight)
}
// Present the progress sheet with action buttons.
performSegueWithIdentifier("presentProgressSheet", sender: self)
}
// MARK: - ProgressSheetInterface
var sheetIsUserInteractive: Bool {
get {
return true
}
}
var sheetLabel: String? {
get {
return nil
}
}
// MARK: - ProgressSheetDelegate
func cancel() {
progress.cancel()
}
func pause() {
progress.pause()
}
func resume() {
progress.resume()
}
// MARK: - KVO
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &progressObservationContext else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
if let progress = object as? NSProgress {
if keyPath == "completedUnitCount" {
if progress.completedUnitCount >= progress.totalUnitCount {
// Work is done.
self.tasksFinished()
}
} else if keyPath == "cancelled" {
if progress.cancelled {
self.tasksFinished()
}
}
}
}
// MARK: - Utilities
func fixWindowPositions() {
let myWindowFrame = self.view.window?.frame as NSRect!
let x = CGRectGetMaxX(myWindowFrame!) + 32
let y = CGRectGetMaxY(myWindowFrame!)
worker1?.window?.setFrameTopLeftPoint(NSPoint(x: x, y: y))
let y2 = CGRectGetMinY((worker1!.window?.frame)!) - 32
worker2?.window?.setFrameTopLeftPoint(NSPoint(x: x, y: y2))
}
func tasksFinished() {
progress.removeObserver(self, forKeyPath: "cancelled")
progress.removeObserver(self, forKeyPath: "completedUnitCount")
dispatch_async(dispatch_get_main_queue()) {
[weak self] in
self?.dismissViewController((self?.presentedViewControllers?.first)!)
}
}
}
| mit | cbc99a674dd7340917160d81a5aceaaf | 29.710526 | 157 | 0.613967 | 5.340961 | false | false | false | false |
neonichu/jarvis | Sources/Badges.swift | 1 | 1544 | import PathKit
extension Path {
func childrenMatching(string: String) throws -> [Path] {
return try self.children().filter { String($0).rangeOfString(string) != nil }
}
}
public struct Badges {
private static func generateCocoaPodsBadges() throws {
if let podspec = try Path.current.childrenMatching(".podspec").first {
let name = podspec.lastComponentWithoutExtension
for path in ["l": "License", "p": "Platform", "v": "Version"] {
print("[/\(name).svg?style=flat)](http://cocoadocs.org/docsets/\(name))")
}
}
}
private static func generateCoverallBadges() throws {
try generateGitHubBadges(".slather.yml") {
let repo = "\($0.0)/\($0.1)"
print("[.svg)](https://coveralls.io/github/\(repo))")
}
}
private static func generateGitHubBadges(matching: String, action: (gh: (String, String)) -> ()) throws {
if let _ = try Path.current.childrenMatching(matching).first, gh = github_data_from_git() {
action(gh: gh)
}
}
private static func generateTravisBadges() throws {
try generateGitHubBadges(".travis.yml") { gh in
let repo = "\(gh.0)/\(gh.1)"
print("[/master.svg?style=flat)](https://travis-ci.org/\(repo))")
}
}
public static func generate() throws {
try generateCocoaPodsBadges()
try generateTravisBadges()
try generateCoverallBadges()
}
}
| mit | 5b2d17790ebe839b8d7e6f342c8254d2 | 34.090909 | 136 | 0.648316 | 3.775061 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Profile/View/ProfileHeadView.swift | 1 | 7982 | //
// ProfileHeadView.swift
// DYZB
//
// Created by xiudou on 2017/6/19.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
fileprivate let verticalButtonWidth : CGFloat = sScreenW / 4
fileprivate let userIconImageViewHW : CGFloat = 80
fileprivate let arrowImageViewWH : CGFloat = 20
class ProfileHeadView: UIView {
fileprivate lazy var backgroundImageView : UIImageView = {
let backgroundImageView = UIImageView()
backgroundImageView.isUserInteractionEnabled = true
backgroundImageView.contentMode = .center
backgroundImageView.image = UIImage(named: "Image_userView_background")
return backgroundImageView
}()
fileprivate lazy var arrowImageView : UIImageView = {
let arrowImageView = UIImageView()
arrowImageView.contentMode = .center
arrowImageView.image = UIImage(named: "image_my_arrow_right_white")
return arrowImageView
}()
fileprivate lazy var userIconImageView : UserIconView = {
let userIconImageView = UserIconView()
return userIconImageView
}()
fileprivate lazy var userNameLabel : UILabel = {
let userNameLabel = UILabel()
userNameLabel.textColor = UIColor.white
userNameLabel.font = UIFont.systemFont(ofSize: 12)
return userNameLabel
}()
fileprivate lazy var historyButton : VerticalButton = VerticalButton()
fileprivate lazy var mailButton : VerticalButton = VerticalButton()
fileprivate lazy var taskButton : VerticalButton = VerticalButton()
fileprivate lazy var rechargeButton : VerticalButton = VerticalButton()
fileprivate func setupVerticalButton(button : VerticalButton, imageNamed : String, title : String){
button.setImage(UIImage(named : imageNamed), for: .normal)
button.setTitle(title, for: .normal)
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(r: 239, g: 239, b: 239)
addSubview(backgroundImageView)
addSubview(arrowImageView)
backgroundImageView.addSubview(userIconImageView)
// 添加手势
let tap = UITapGestureRecognizer(target: self, action: #selector(myInforClick))
backgroundImageView.addGestureRecognizer(tap)
addSubview(historyButton)
addSubview(mailButton)
addSubview(taskButton)
addSubview(rechargeButton)
historyButton.setTitleColor(.black, for: .normal)
mailButton.setTitleColor(.black, for: .normal)
taskButton.setTitleColor(.black, for: .normal)
rechargeButton.setTitleColor(.black, for: .normal)
historyButton.backgroundColor = .white
mailButton.backgroundColor = .white
taskButton.backgroundColor = .white
rechargeButton.backgroundColor = .white
setupVerticalButton(button: historyButton, imageNamed: "btn_my_mail", title: "观看历史")
setupVerticalButton(button: mailButton, imageNamed: "btn_my_mail", title: "站内信")
setupVerticalButton(button: taskButton, imageNamed: "btn_my_mail", title: "我的任务")
setupVerticalButton(button: rechargeButton, imageNamed: "btn_my_mail", title: "鱼翅充值")
historyButton.addTarget(self, action: #selector(historyButtonAction), for: .touchUpInside)
mailButton.addTarget(self, action: #selector(mailButtonAction), for: .touchUpInside)
taskButton.addTarget(self, action: #selector(taskButtonAction), for: .touchUpInside)
rechargeButton.addTarget(self, action: #selector(rechargeButtonAction), for: .touchUpInside)
}
var user : User?{
didSet{
guard let user = user else { return }
if let avatarModel = user.avatar{
let smallImageName = avatarModel.small
userIconImageView.imageName = smallImageName
}
userNameLabel.text = user.nickname
}
}
override func layoutSubviews() {
super.layoutSubviews()
var backgroundImageViewHeight : CGFloat = 0
if let imagesize = backgroundImageView.image?.size{
backgroundImageView.frame = CGRect(x: 0, y: 0, width: imagesize.width, height: imagesize.height)
backgroundImageViewHeight = imagesize.height
}else{
backgroundImageView.frame = CGRect(x: 0, y: 0, width: sScreenW, height: 200)
backgroundImageViewHeight = 200
}
userIconImageView.frame = CGRect(x: 15, y: backgroundImageView.frame.height - userIconImageViewHW - 20, width: userIconImageViewHW, height: userIconImageViewHW)
if let nickName = user?.nickname{
let userNameLabelSize = nickName.sizeWithFont(userNameLabel.font, size: CGSize(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT)))
userNameLabel.frame = CGRect(x: userIconImageView.frame.maxX + 10, y: userIconImageView.frame.origin.x + 10, width: userNameLabelSize.width, height: userNameLabelSize.height)
}
historyButton.frame = CGRect(x: 0, y: backgroundImageView.frame.maxY, width: verticalButtonWidth, height: frame.height - backgroundImageViewHeight - 10)
mailButton.frame = CGRect(x: historyButton.frame.maxX, y: backgroundImageView.frame.maxY, width: verticalButtonWidth, height: historyButton.frame.height)
taskButton.frame = CGRect(x: mailButton.frame.maxX, y: backgroundImageView.frame.maxY, width: verticalButtonWidth, height: historyButton.frame.height)
rechargeButton.frame = CGRect(x: taskButton.frame.maxX, y: backgroundImageView.frame.maxY, width: verticalButtonWidth, height: historyButton.frame.height)
arrowImageView.frame = CGRect(x: frame.width - arrowImageViewWH - 10, y: 0, width: arrowImageViewWH, height: arrowImageViewWH)
arrowImageView.center.y = userIconImageView.center.y
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 按钮点击事件
extension ProfileHeadView {
@objc fileprivate func historyButtonAction(){
let nav = getNavigation()
let historyVC = WatchHistoryViewController()
nav.pushViewController(historyVC, animated: true)
}
@objc fileprivate func mailButtonAction(){
let nav = getNavigation()
let interalMessageVC = InteralMessageViewController()
nav.pushViewController(interalMessageVC, animated: true)
}
@objc fileprivate func taskButtonAction(){
let nav = getNavigation()
let myTaskVM = MyTaskViewController()
myTaskVM.open_url = "http://capi.douyucdn.cn/api/v1/nc_page_usertask/1?token=\(TOKEN)&idfa=99F096BA-477A-4D0A-AB26-69B76DDB85C6&client_sys=ios"
nav.pushViewController(myTaskVM, animated: true)
}
@objc fileprivate func rechargeButtonAction(){
let fishboneRecharge = FishboneRechargeViewController()
let nav = getNavigation()
nav.pushViewController(fishboneRecharge, animated: true)
}
@objc fileprivate func myInforClick() {
debugLog("-------")
let profileInforViewController = ProfileInforViewController()
// 获取user
// guard let user = user else { return }
// profileInforViewController.user = user
let nav = getNavigation()
nav.pushViewController(profileInforViewController, animated: true)
}
// fileprivate func getNavigation()->MainNavigationController{
// let tabVC = window?.rootViewController as!UITabBarController
// let nav = tabVC.selectedViewController as!MainNavigationController
//
// return nav
// }
}
| mit | 8f4b30cbe5c3c7da9928e0a37746de8e | 37.658537 | 186 | 0.663975 | 4.904084 | false | false | false | false |
dathtcheapgo/Jira-Demo | Driver/Extension/NSLayoutConstraintExtension.swift | 1 | 1507 | //
// NSLayoutConstraintExtension.swift
// Rider
//
// Created by Đinh Anh Huy on 11/3/16.
// Copyright © 2016 Đinh Anh Huy. All rights reserved.
//
import UIKit
extension NSLayoutConstraint {
func isConstraintOfView(view: UIView) -> Bool {
if firstItem as? UIView == view || secondItem as? UIView == view {
return true
}
return false
}
func isTopConstraint() -> Bool {
if firstAttribute == .top && secondAttribute == .top { return true }
return false
}
func isBotConstraint() -> Bool {
if firstAttribute == .bottom && secondAttribute == .bottom { return true }
return false
}
func isLeadConstraint() -> Bool {
if firstAttribute == .leading && secondAttribute == .leading { return true }
return false
}
func isTrailConstraint() -> Bool {
if firstAttribute == .trailing && secondAttribute == .trailing { return true }
return false
}
func isVerticalConstraint() -> Bool {
if (firstAttribute == .top && secondAttribute == .bottom) ||
(firstAttribute == .bottom && secondAttribute == .top) {
return true
}
return false
}
func isHorizonConstraint() -> Bool {
if (firstAttribute == .leading && secondAttribute == .trailing) ||
(firstAttribute == .trailing && secondAttribute == .leading) {
return true
}
return false
}
}
| mit | b9f91ffcfd6ee5e6c48c6cddf625d3c6 | 26.345455 | 86 | 0.571144 | 4.947368 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Browser/GridTabViewController.swift | 2 | 36197 | // 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 Storage
import Shared
struct GridTabTrayControllerUX {
static let CornerRadius = CGFloat(6.0)
static let TextBoxHeight = CGFloat(32.0)
static let NavigationToolbarHeight = CGFloat(44)
static let FaviconSize = CGFloat(20)
static let Margin = CGFloat(15)
static let ToolbarButtonOffset = CGFloat(10.0)
static let CloseButtonSize = CGFloat(32)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(7)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
static let MenuFixedWidth: CGFloat = 320
}
protocol TabTrayDelegate: AnyObject {
func tabTrayDidDismiss(_ tabTray: GridTabViewController)
func tabTrayDidAddTab(_ tabTray: GridTabViewController, tab: Tab)
func tabTrayDidAddBookmark(_ tab: Tab)
func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListItem?
func tabTrayOpenRecentlyClosedTab(_ url: URL)
func tabTrayDidRequestTabsSettings()
}
class GridTabViewController: UIViewController, TabTrayViewDelegate, Themeable {
let tabManager: TabManager
let profile: Profile
weak var delegate: TabTrayDelegate?
var tabDisplayManager: TabDisplayManager!
var tabCellIdentifer: TabDisplayer.TabCellIdentifer = TabCell.cellIdentifier
static let independentTabsHeaderIdentifier = "IndependentTabs"
var otherBrowsingModeOffset = CGPoint.zero
// Backdrop used for displaying greyed background for private tabs
var backgroundPrivacyOverlay = UIView()
var collectionView: UICollectionView!
var recentlyClosedTabsPanel: RecentlyClosedTabsPanel?
var notificationCenter: NotificationProtocol
var contextualHintViewController: ContextualHintViewController
var themeManager: ThemeManager
var themeObserver: NSObjectProtocol?
// This is an optional variable used if we wish to focus a tab that is not the
// currently selected tab. This allows us to force the scroll behaviour to move
// wherever we need to focus the user's attention.
var tabToFocus: Tab?
override var canBecomeFirstResponder: Bool {
return true
}
fileprivate lazy var emptyPrivateTabsView: EmptyPrivateTabsView = {
let emptyView = EmptyPrivateTabsView()
emptyView.learnMoreButton.addTarget(self, action: #selector(didTapLearnMore), for: .touchUpInside)
return emptyView
}()
fileprivate lazy var tabLayoutDelegate: TabLayoutDelegate = {
let delegate = TabLayoutDelegate(tabDisplayManager: self.tabDisplayManager,
traitCollection: self.traitCollection,
scrollView: self.collectionView)
delegate.tabSelectionDelegate = self
delegate.tabPeekDelegate = self
return delegate
}()
var numberOfColumns: Int {
return tabLayoutDelegate.numberOfColumns
}
// MARK: - Inits
init(tabManager: TabManager,
profile: Profile,
tabTrayDelegate: TabTrayDelegate? = nil,
tabToFocus: Tab? = nil,
notificationCenter: NotificationProtocol = NotificationCenter.default,
themeManager: ThemeManager = AppContainer.shared.resolve()
) {
self.tabManager = tabManager
self.profile = profile
self.delegate = tabTrayDelegate
self.tabToFocus = tabToFocus
self.notificationCenter = notificationCenter
let contextualViewModel = ContextualHintViewModel(forHintType: .inactiveTabs,
with: profile)
self.contextualHintViewController = ContextualHintViewController(with: contextualViewModel)
self.themeManager = themeManager
super.init(nibName: nil, bundle: nil)
collectionViewSetup()
}
private func collectionViewSetup() {
collectionView = UICollectionView(frame: .zero,
collectionViewLayout: UICollectionViewFlowLayout())
collectionView.register(cellType: TabCell.self)
collectionView.register(cellType: GroupedTabCell.self)
collectionView.register(cellType: InactiveTabCell.self)
collectionView.register(
LabelButtonHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: GridTabViewController.independentTabsHeaderIdentifier)
tabDisplayManager = TabDisplayManager(collectionView: self.collectionView,
tabManager: self.tabManager,
tabDisplayer: self,
reuseID: TabCell.cellIdentifier,
tabDisplayType: .TabGrid,
profile: profile,
cfrDelegate: self,
theme: themeManager.currentTheme)
collectionView.dataSource = tabDisplayManager
collectionView.delegate = tabLayoutDelegate
tabDisplayManager.tabDisplayCompletionDelegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
tabManager.addDelegate(self)
view.accessibilityLabel = .TabTrayViewAccessibilityLabel
backgroundPrivacyOverlay.alpha = 0
collectionView.alwaysBounceVertical = true
collectionView.keyboardDismissMode = .onDrag
collectionView.dragInteractionEnabled = true
collectionView.dragDelegate = tabDisplayManager
collectionView.dropDelegate = tabDisplayManager
setupView()
if let tab = tabManager.selectedTab, tab.isPrivate {
tabDisplayManager.togglePrivateMode(isOn: true, createTabOnEmptyPrivateMode: false)
}
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
listenForThemeChange()
applyTheme()
setupNotifications(forObserver: self, observing: [
UIApplication.willResignActiveNotification,
UIApplication.didBecomeActiveNotification
])
}
private func setupView() {
// TODO: Remove SNAPKIT - this will require some work as the layouts
// are using other snapkit constraints and this will require modification
// in several places.
[backgroundPrivacyOverlay, collectionView].forEach { view.addSubview($0) }
setupConstraints()
view.insertSubview(emptyPrivateTabsView, aboveSubview: collectionView)
emptyPrivateTabsView.snp.makeConstraints { make in
make.top.bottom.left.right.equalTo(self.collectionView)
}
}
private func setupConstraints() {
backgroundPrivacyOverlay.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
collectionView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.view.layoutIfNeeded()
focusItem()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
// When the app enters split screen mode we refresh the collection view layout to show the proper grid
collectionView.collectionViewLayout.invalidateLayout()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let flowlayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowlayout.invalidateLayout()
}
private func tabManagerTeardown() {
tabManager.removeDelegate(self.tabDisplayManager)
tabManager.removeDelegate(self)
tabDisplayManager = nil
contextualHintViewController.stopTimer()
notificationCenter.removeObserver(self)
}
deinit {
tabManagerTeardown()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Scrolling helper methods
/// The main interface for scrolling to an item, whether that is a group or an individual tab
///
/// This method checks for the existence of a tab to focus on other than the selected tab,
/// and then, focuses on that tab. The byproduct is that if the tab is in a group, the
/// user would then be looking at the group. Generally, if focusing on a group and
/// NOT the selected tab, it is advised to pass in the first tab of that group as
/// the `tabToFocus` in the initializer
func focusItem() {
guard let selectedTab = tabManager.selectedTab else { return }
if tabToFocus == nil { tabToFocus = selectedTab }
guard let tabToFocus = tabToFocus else { return }
if let tabGroups = tabDisplayManager.tabGroups,
!tabGroups.isEmpty,
tabGroups.contains(where: { $0.groupedItems.contains(where: { $0 == tabToFocus }) }) {
focusGroup(from: tabGroups, with: tabToFocus)
} else {
focusTab(tabToFocus)
}
}
func focusGroup(from tabGroups: [ASGroup<Tab>], with tabToFocus: Tab) {
if let tabIndex = tabDisplayManager.indexOfGroupTab(tab: tabToFocus) {
let groupName = tabIndex.groupName
let groupIndex: Int = tabGroups.firstIndex(where: { $0.searchTerm == groupName }) ?? 0
let offSet = Int(GroupedTabCellProperties.CellUX.defaultCellHeight) * groupIndex
let rect = CGRect(origin: CGPoint(x: 0, y: offSet), size: CGSize(width: self.collectionView.frame.width, height: self.collectionView.frame.height))
DispatchQueue.main.async {
self.collectionView.scrollRectToVisible(rect, animated: false)
}
}
}
func focusTab(_ selectedTab: Tab) {
if let indexOfRegularTab = tabDisplayManager.indexOfRegularTab(tab: selectedTab) {
let indexPath = IndexPath(item: indexOfRegularTab, section: TabDisplaySection.regularTabs.rawValue)
guard var rect = self.collectionView.layoutAttributesForItem(at: indexPath)?.frame else { return }
if indexOfRegularTab >= self.tabDisplayManager.dataStore.count - 2 {
DispatchQueue.main.async {
rect.origin.y += 10
self.collectionView.scrollRectToVisible(rect, animated: false)
}
} else {
self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: false)
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// Update the trait collection we reference in our layout delegate
tabLayoutDelegate.traitCollection = traitCollection
}
@objc func didTogglePrivateMode() {
tabManager.willSwitchTabMode(leavingPBM: tabDisplayManager.isPrivate)
tabDisplayManager.togglePrivateMode(isOn: !tabDisplayManager.isPrivate, createTabOnEmptyPrivateMode: false)
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
}
fileprivate func privateTabsAreEmpty() -> Bool {
return tabDisplayManager.isPrivate && tabManager.privateTabs.isEmpty
}
func openNewTab(_ request: URLRequest? = nil, isPrivate: Bool) {
if tabDisplayManager.isDragging {
return
}
// Ensure Firefox home page is refreshed if privacy mode was changed
if tabManager.selectedTab?.isPrivate != isPrivate {
let notificationObject = [Tab.privateModeKey: isPrivate]
NotificationCenter.default.post(name: .TabsPrivacyModeChanged, object: notificationObject)
}
tabManager.selectTab(tabManager.addTab(request, isPrivate: isPrivate))
}
func applyTheme() {
tabDisplayManager.theme = themeManager.currentTheme
emptyPrivateTabsView.applyTheme(themeManager.currentTheme)
backgroundPrivacyOverlay.backgroundColor = themeManager.currentTheme.colors.layerScrim
collectionView.backgroundColor = themeManager.currentTheme.colors.layer3
collectionView.reloadData()
}
}
extension GridTabViewController: TabManagerDelegate {
func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?, isRestoring: Bool) {}
func tabManager(_ tabManager: TabManager, didAddTab tab: Tab, placeNextToParentTab: Bool, isRestoring: Bool) {}
func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab, isRestoring: Bool) {
NotificationCenter.default.post(name: .UpdateLabelOnTabClosed, object: nil)
}
func tabManagerDidAddTabs(_ tabManager: TabManager) {}
func tabManagerDidRestoreTabs(_ tabManager: TabManager) {
self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
}
func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) {
// No need to handle removeAll toast in TabTray.
// When closing all normal tabs we automatically focus a tab and show the BVC. Which will handle the Toast.
// We don't show the removeAll toast in PBM
}
}
extension GridTabViewController: TabDisplayer {
func focusSelectedTab() {
self.focusItem()
}
func cellFactory(for cell: UICollectionViewCell, using tab: Tab) -> UICollectionViewCell {
guard let tabCell = cell as? TabCell else { return cell }
tabCell.animator?.delegate = self
tabCell.delegate = self
let selected = tab == tabManager.selectedTab
tabCell.configureWith(tab: tab, isSelected: selected, theme: themeManager.currentTheme)
return tabCell
}
}
extension GridTabViewController {
@objc func didTapLearnMore() {
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
if let langID = Locale.preferredLanguages.first {
let learnMoreRequest = URLRequest(url: "https://support.mozilla.org/1/mobile/\(appVersion ?? "0.0")/iOS/\(langID)/private-browsing-ios".asURL!)
openNewTab(learnMoreRequest, isPrivate: tabDisplayManager.isPrivate)
}
}
func closeTabsTrayBackground() {
tabDisplayManager.removeAllTabsFromView()
tabManager.backgroundRemoveAllTabs(isPrivate: tabDisplayManager.isPrivate) {
recentlyClosedTabs, isPrivateState, previousTabUUID in
DispatchQueue.main.async { [unowned self] in
if isPrivateState {
let previousTab = self.tabManager.tabs.filter { $0.tabUUID == previousTabUUID }.first
self.tabManager.cleanupClosedTabs(recentlyClosedTabs,
previous: previousTab,
isPrivate: isPrivateState)
} else {
self.tabManager.makeToastFromRecentlyClosedUrls(recentlyClosedTabs,
isPrivate: isPrivateState,
previousTabUUID: previousTabUUID)
}
closeTabsTrayHelper()
}
}
}
func closeTabsTrayHelper() {
if self.tabDisplayManager.isPrivate {
self.emptyPrivateTabsView.isHidden = !self.privateTabsAreEmpty()
if !self.emptyPrivateTabsView.isHidden {
// Fade in the empty private tabs message. This slow fade allows time for the closing tab animations to complete.
self.emptyPrivateTabsView.alpha = 0
UIView.animate(
withDuration: 0.5,
animations: {
self.emptyPrivateTabsView.alpha = 1
})
}
} else if self.tabManager.normalTabs.count == 1, let tab = self.tabManager.normalTabs.first {
self.tabManager.selectTab(tab)
self.dismissTabTray()
notificationCenter.post(name: .TabsTrayDidClose)
}
}
func didTogglePrivateMode(_ togglePrivateModeOn: Bool) {
if togglePrivateModeOn != tabDisplayManager.isPrivate {
didTogglePrivateMode()
}
}
func dismissTabTray() {
self.navigationController?.dismiss(animated: true, completion: nil)
TelemetryWrapper.recordEvent(category: .action, method: .close, object: .tabTray)
}
}
// MARK: - App Notifications
extension GridTabViewController {
@objc func appWillResignActiveNotification() {
if tabDisplayManager.isPrivate {
backgroundPrivacyOverlay.alpha = 1
view.bringSubviewToFront(backgroundPrivacyOverlay)
collectionView.alpha = 0
emptyPrivateTabsView.alpha = 0
}
}
@objc func appDidBecomeActiveNotification() {
// Re-show any components that might have been hidden because they were being displayed
// as part of a private mode tab
UIView.animate(
withDuration: 0.2,
animations: {
self.collectionView.alpha = 1
self.emptyPrivateTabsView.alpha = 1
}) { _ in
self.backgroundPrivacyOverlay.alpha = 0
self.view.sendSubviewToBack(self.backgroundPrivacyOverlay)
}
}
}
extension GridTabViewController: TabSelectionDelegate {
func didSelectTabAtIndex(_ index: Int) {
if let tab = tabDisplayManager.dataStore.at(index) {
if tab.isFxHomeTab {
notificationCenter.post(name: .TabsTrayDidSelectHomeTab)
}
tabManager.selectTab(tab)
dismissTabTray()
}
}
}
// MARK: UIScrollViewAccessibilityDelegate
extension GridTabViewController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatus(for scrollView: UIScrollView) -> String? {
guard var visibleCells = collectionView.visibleCells as? [TabCell] else { return nil }
var bounds = collectionView.bounds
bounds = bounds.offsetBy(dx: collectionView.contentInset.left, dy: collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !$0.frame.intersection(bounds).isEmpty }
let cells = visibleCells.map { self.collectionView.indexPath(for: $0)! }
let indexPaths = cells.sorted { (first: IndexPath, second: IndexPath) -> Bool in
return first.section < second.section || (first.section == second.section && first.row < second.row)
}
guard !indexPaths.isEmpty else {
return .TabTrayNoTabsAccessibilityHint
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItems(inSection: 1)
if firstTab == lastTab {
let format: String = .TabTrayVisibleTabRangeAccessibilityHint
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: tabCount as Int))
} else {
let format: String = .TabTrayVisiblePartialRangeAccessibilityHint
return String(format: format, NSNumber(value: firstTab as Int), NSNumber(value: lastTab as Int), NSNumber(value: tabCount as Int))
}
}
}
// MARK: - SwipeAnimatorDelegate
extension GridTabViewController: SwipeAnimatorDelegate {
func swipeAnimator(_ animator: SwipeAnimator, viewWillExitContainerBounds: UIView) {
guard let tabCell = animator.animatingView as? TabCell, let indexPath = collectionView.indexPath(for: tabCell) else { return }
if let tab = tabDisplayManager.dataStore.at(indexPath.item) {
self.removeByButtonOrSwipe(tab: tab, cell: tabCell)
UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: String.TabTrayClosingTabAccessibilityMessage)
}
}
// Disable swipe delete while drag reordering
func swipeAnimatorIsAnimateAwayEnabled(_ animator: SwipeAnimator) -> Bool {
return !tabDisplayManager.isDragging
}
}
extension GridTabViewController: TabCellDelegate {
func tabCellDidClose(_ cell: TabCell) {
if let indexPath = collectionView.indexPath(for: cell), let tab = tabDisplayManager.dataStore.at(indexPath.item) {
removeByButtonOrSwipe(tab: tab, cell: cell)
}
}
}
extension GridTabViewController: TabPeekDelegate {
func tabPeekDidAddBookmark(_ tab: Tab) {
delegate?.tabTrayDidAddBookmark(tab)
}
func tabPeekDidAddToReadingList(_ tab: Tab) -> ReadingListItem? {
return delegate?.tabTrayDidAddToReadingList(tab)
}
func tabPeekDidCloseTab(_ tab: Tab) {
// Tab peek is only available on regular tabs
if let index = tabDisplayManager.dataStore.index(of: tab),
let cell = self.collectionView?.cellForItem(at: IndexPath(item: index, section: TabDisplaySection.regularTabs.rawValue)) as? TabCell {
cell.close()
NotificationCenter.default.post(name: .UpdateLabelOnTabClosed, object: nil)
}
}
func tabPeekRequestsPresentationOf(_ viewController: UIViewController) {
present(viewController, animated: true, completion: nil)
}
}
// MARK: - TabDisplayCompeltionDelegate & RecentlyClosedPanelDelegate
extension GridTabViewController: TabDisplayCompletionDelegate, RecentlyClosedPanelDelegate {
// RecentlyClosedPanelDelegate
func openRecentlyClosedSiteInSameTab(_ url: URL) {
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .inactiveTabTray, value: .openRecentlyClosedTab, extras: nil)
delegate?.tabTrayOpenRecentlyClosedTab(url)
dismissTabTray()
}
func openRecentlyClosedSiteInNewTab(_ url: URL, isPrivate: Bool) {
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .inactiveTabTray, value: .openRecentlyClosedTab, extras: nil)
openNewTab(URLRequest(url: url), isPrivate: isPrivate)
dismissTabTray()
}
// TabDisplayCompletionDelegate
func completedAnimation(for type: TabAnimationType) {
emptyPrivateTabsView.isHidden = !privateTabsAreEmpty()
switch type {
case .addTab:
dismissTabTray()
case .removedLastTab:
// when removing the last tab (only in normal mode) we will automatically open a new tab.
// When that happens focus it by dismissing the tab tray
notificationCenter.post(name: .TabsTrayDidClose)
if !tabDisplayManager.isPrivate {
self.dismissTabTray()
}
case .removedNonLastTab, .updateTab, .moveTab:
break
}
}
}
extension GridTabViewController {
func removeByButtonOrSwipe(tab: Tab, cell: TabCell) {
tabDisplayManager.tabDisplayCompletionDelegate = self
tabDisplayManager.closeActionPerformed(forCell: cell)
}
}
// MARK: - Toolbar Actions
extension GridTabViewController {
func performToolbarAction(_ action: TabTrayViewAction, sender: UIBarButtonItem) {
switch action {
case .addTab:
didTapToolbarAddTab()
case .deleteTab:
didTapToolbarDelete(sender)
}
}
func didTapToolbarAddTab() {
if tabDisplayManager.isDragging {
return
}
openNewTab(isPrivate: tabDisplayManager.isPrivate)
}
func didTapToolbarDelete(_ sender: UIBarButtonItem) {
if tabDisplayManager.isDragging {
return
}
let controller = AlertController(title: nil, message: nil, preferredStyle: .actionSheet)
controller.addAction(UIAlertAction(title: .AppMenu.AppMenuCloseAllTabsTitleString,
style: .default,
handler: { _ in self.closeTabsTrayBackground() }),
accessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCloseAllButton)
controller.addAction(UIAlertAction(title: .TabTrayCloseAllTabsPromptCancel,
style: .cancel,
handler: nil),
accessibilityIdentifier: AccessibilityIdentifiers.TabTray.deleteCancelButton)
controller.popoverPresentationController?.barButtonItem = sender
present(controller, animated: true, completion: nil)
}
}
// MARK: TabLayoutDelegate
private class TabLayoutDelegate: NSObject, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
weak var tabSelectionDelegate: TabSelectionDelegate?
weak var tabPeekDelegate: TabPeekDelegate?
let scrollView: UIScrollView
var lastYOffset: CGFloat = 0
var tabDisplayManager: TabDisplayManager
var sectionHeaderSize: CGSize {
CGSize(width: 50, height: 40)
}
enum ScrollDirection {
case up
case down
}
fileprivate var scrollDirection: ScrollDirection = .down
fileprivate var traitCollection: UITraitCollection
fileprivate var numberOfColumns: Int {
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .compact && traitCollection.verticalSizeClass == .regular {
return GridTabTrayControllerUX.CompactNumberOfColumnsThin
} else {
return GridTabTrayControllerUX.NumberOfColumnsWide
}
}
init(tabDisplayManager: TabDisplayManager, traitCollection: UITraitCollection, scrollView: UIScrollView) {
self.tabDisplayManager = tabDisplayManager
self.scrollView = scrollView
self.traitCollection = traitCollection
super.init()
}
fileprivate func cellHeightForCurrentDevice() -> CGFloat {
let shortHeight = GridTabTrayControllerUX.TextBoxHeight * 6
if self.traitCollection.verticalSizeClass == .compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == .compact {
return shortHeight
} else {
return GridTabTrayControllerUX.TextBoxHeight * 8
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
switch TabDisplaySection(rawValue: section) {
case .regularTabs:
if let groups = tabDisplayManager.tabGroups, !groups.isEmpty {
return sectionHeaderSize
}
default: return .zero
}
return .zero
}
func gestureRecognizer(
_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer
) -> Bool {
return true
}
@objc func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int
) -> CGFloat {
return GridTabTrayControllerUX.Margin
}
@objc func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
let margin = GridTabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)
let calculatedWidth = collectionView.bounds.width - collectionView.safeAreaInsets.left - collectionView.safeAreaInsets.right - margin
let cellWidth = floor(calculatedWidth / CGFloat(numberOfColumns))
switch TabDisplaySection(rawValue: indexPath.section) {
case .inactiveTabs:
return calculateInactiveTabSizeHelper(collectionView)
case .groupedTabs:
let width = collectionView.frame.size.width
if let groupCount = tabDisplayManager.tabGroups?.count, groupCount > 0 {
let height: CGFloat = GroupedTabCellProperties.CellUX.defaultCellHeight * CGFloat(groupCount)
return CGSize(width: width >= 0 ? Int(width) : 0, height: Int(height))
} else {
return CGSize(width: 0, height: 0)
}
case .regularTabs, .none:
guard !tabDisplayManager.filteredTabs.isEmpty else { return CGSize(width: 0, height: 0) }
return CGSize(width: cellWidth, height: self.cellHeightForCurrentDevice())
}
}
private func calculateInactiveTabSizeHelper(_ collectionView: UICollectionView) -> CGSize {
guard !tabDisplayManager.isPrivate,
let inactiveTabViewModel = tabDisplayManager.inactiveViewModel,
!inactiveTabViewModel.activeTabs.isEmpty
else {
return CGSize(width: 0, height: 0)
}
let closeAllButtonHeight = InactiveTabCell.UX.CloseAllTabRowHeight
let headerHeightWithRoundedCorner = InactiveTabCell.UX.HeaderAndRowHeight + InactiveTabCell.UX.RoundedContainerPaddingClosed
var totalHeight = headerHeightWithRoundedCorner
let width: CGFloat = collectionView.frame.size.width - InactiveTabCell.UX.InactiveTabTrayWidthPadding
let inactiveTabs = inactiveTabViewModel.inactiveTabs
// Calculate height based on number of tabs in the inactive tab section section
let calculatedInactiveTabsTotalHeight = (InactiveTabCell.UX.HeaderAndRowHeight * CGFloat(inactiveTabs.count)) +
InactiveTabCell.UX.RoundedContainerPaddingClosed +
InactiveTabCell.UX.RoundedContainerAdditionalPaddingOpened + closeAllButtonHeight
totalHeight = tabDisplayManager.isInactiveViewExpanded ? calculatedInactiveTabsTotalHeight : headerHeightWithRoundedCorner
if UIDevice.current.userInterfaceIdiom == .pad {
return CGSize(width: collectionView.frame.size.width/1.5, height: totalHeight)
} else {
return CGSize(width: width >= 0 ? width : 0, height: totalHeight)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
switch TabDisplaySection(rawValue: section) {
case .regularTabs, .none:
return UIEdgeInsets(
top: GridTabTrayControllerUX.Margin,
left: GridTabTrayControllerUX.Margin + collectionView.safeAreaInsets.left,
bottom: GridTabTrayControllerUX.Margin,
right: GridTabTrayControllerUX.Margin + collectionView.safeAreaInsets.right)
case .inactiveTabs:
guard !tabDisplayManager.isPrivate,
tabDisplayManager.inactiveViewModel?.inactiveTabs.count ?? 0 > 0
else { return .zero }
return UIEdgeInsets(equalInset: GridTabTrayControllerUX.Margin)
case .groupedTabs:
guard tabDisplayManager.shouldEnableGroupedTabs,
tabDisplayManager.tabGroups?.count ?? 0 > 0
else { return .zero }
return UIEdgeInsets(equalInset: GridTabTrayControllerUX.Margin)
}
}
@objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return GridTabTrayControllerUX.Margin
}
@objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
tabSelectionDelegate?.didSelectTabAtIndex(indexPath.row)
}
func collectionView(_ collectionView: UICollectionView, contextMenuConfigurationForItemAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
guard TabDisplaySection(rawValue: indexPath.section) == .regularTabs,
let tab = tabDisplayManager.dataStore.at(indexPath.row)
else { return nil }
let tabVC = TabPeekViewController(tab: tab, delegate: tabPeekDelegate)
if let browserProfile = tabDisplayManager.profile as? BrowserProfile,
let pickerDelegate = tabPeekDelegate as? DevicePickerViewControllerDelegate {
tabVC.setState(withProfile: browserProfile, clientPickerDelegate: pickerDelegate)
}
return UIContextMenuConfiguration(identifier: nil, previewProvider: { return tabVC }, actionProvider: tabVC.contextActions(defaultActions:))
}
}
// MARK: - DevicePickerViewControllerDelegate
extension GridTabViewController: DevicePickerViewControllerDelegate {
func devicePickerViewController(_ devicePickerViewController: DevicePickerViewController, didPickDevices devices: [RemoteDevice]) {
if let item = devicePickerViewController.shareItem {
_ = self.profile.sendItem(item, toDevices: devices)
}
devicePickerViewController.dismiss(animated: true, completion: nil)
}
func devicePickerViewControllerDidCancel(_ devicePickerViewController: DevicePickerViewController) {
devicePickerViewController.dismiss(animated: true, completion: nil)
}
}
// MARK: - Presentation Delegates
extension GridTabViewController: UIAdaptivePresentationControllerDelegate, UIPopoverPresentationControllerDelegate {
// Returning None here makes sure that the Popover is actually presented as a Popover and
// not as a full-screen modal, which is the default on compact device classes.
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
}
extension GridTabViewController: PresentingModalViewControllerDelegate {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) {
dismiss(animated: animated, completion: { self.collectionView.reloadData() })
}
}
protocol TabCellDelegate: AnyObject {
func tabCellDidClose(_ cell: TabCell)
}
// MARK: - Notifiable
extension GridTabViewController: Notifiable {
func handleNotifications(_ notification: Notification) {
switch notification.name {
case UIApplication.willResignActiveNotification:
appWillResignActiveNotification()
case UIApplication.didBecomeActiveNotification:
appDidBecomeActiveNotification()
default: break
}
}
}
protocol InactiveTabsCFRProtocol {
func setupCFR(with view: UILabel)
func presentCFR()
}
// MARK: - Contextual Hint
extension GridTabViewController: InactiveTabsCFRProtocol {
func setupCFR(with view: UILabel) {
prepareJumpBackInContextualHint(on: view)
}
func presentCFR() {
contextualHintViewController.startTimer()
}
func presentCFROnView() {
present(contextualHintViewController, animated: true, completion: nil)
UIAccessibility.post(notification: .layoutChanged, argument: contextualHintViewController)
}
private func prepareJumpBackInContextualHint(on title: UILabel) {
guard contextualHintViewController.shouldPresentHint() else { return }
contextualHintViewController.configure(
anchor: title,
withArrowDirection: .up,
andDelegate: self,
presentedUsing: { self.presentCFROnView() },
andActionForButton: {
self.dismissTabTray()
self.delegate?.tabTrayDidRequestTabsSettings()
}, andShouldStartTimerRightAway: false
)
}
}
| mpl-2.0 | 3040ab178fe33c366b617ec793f04aa9 | 41.04065 | 194 | 0.678841 | 5.588544 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.