repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ZekeSnider/Jared | Pods/Telegraph/Sources/Protocols/HTTP/Routing/HTTPRoute.swift | 1 | 3787 | //
// HTTPRoute.swift
// Telegraph
//
// Created by Yvo van Beek on 2/4/17.
// Copyright © 2017 Building42. All rights reserved.
//
import Foundation
public struct HTTPRoute {
public let methods: Set<HTTPMethod>?
public let handler: HTTPRequest.Handler
public let regex: Regex?
public let params: [HTTPRequest.Params.Key]
/// Creates a new HTTPRoute based on a regular expression pattern.
public init(methods: Set<HTTPMethod>? = nil, regex pattern: String? = nil, handler: @escaping HTTPRequest.Handler) throws {
self.methods = methods
self.handler = handler
let (regex, params) = try HTTPRoute.regexAndParams(pattern: pattern)
self.regex = regex
self.params = params
}
/// Creates a new HTTPRoute based on a URI.
public init(methods: Set<HTTPMethod>? = nil, uri: String, handler: @escaping HTTPRequest.Handler) throws {
let pattern = try HTTPRoute.routePattern(basedOn: uri)
try self.init(methods: methods, regex: pattern, handler: handler)
}
}
// MARK: Route pattern processing
private extension HTTPRoute {
/// The regular expression to extract parameters definitions.
static let parameterRegex = try! Regex(pattern: #":([\w]+)"#)
/// The regular expression replacement pattern to capture parameters.
static let parameterCaptureGroupPattern: String = {
if #available(iOS 9, *) {
return #"(?<$1>[^\/]+)"#
} else {
return #"([^\/]+)"#
}
}()
/// Breaks a route regular expression up into the regular expression that will be used
/// for matching routes and a list of path parameters.
static func regexAndParams(pattern: String?) throws -> (Regex?, [String]) {
// If no regex is specified this route will match all uris
guard var pattern = pattern else { return (nil, []) }
// Extract the route parameters, for example /user/:id and change them to capture groups
let params = parameterRegex.matchAll(in: pattern).flatMap { $0.groupValues }
pattern = parameterRegex.stringByReplacingMatches(in: pattern, withPattern: parameterCaptureGroupPattern)
return (try Regex(pattern: pattern, options: .caseInsensitive), params)
}
/// Creates a route regular expression pattern based on the provided URI.
static func routePattern(basedOn uri: String) throws -> String {
// Clean up invalid paths
var pattern = URI(path: uri).path
// Allow easy optional slash pattern, for example /hello(/)
pattern = pattern.replacingOccurrences(of: "(/)", with: "/?")
// Limit what the regex will match by fixating the start and the end
if !pattern.hasPrefix("^") { pattern.insert("^", at: pattern.startIndex) }
if !pattern.hasSuffix("*") { pattern.insert("$", at: pattern.endIndex) }
return pattern
}
}
// MARK: Route handling
public extension HTTPRoute {
/// Indicates if the route supports the provided HTTP method.
func canHandle(method: HTTPMethod) -> Bool {
guard let methods = methods else { return true }
return methods.contains(method)
}
/// Indicates if the route matches the provided path. Any route parameters will be extracted
/// and returned as a separate list.
func canHandle(path: String) -> (Bool, HTTPRequest.Params) {
// Should we allow all patterns?
guard let routeRegex = regex else { return (true, [:]) }
// Test if the URI matches our route
let matches = routeRegex.matchAll(in: path)
if matches.isEmpty { return (false, [:]) }
// If the URI matches our route, extract the params
var routeParams = HTTPRequest.Params()
let matchedParams = matches.flatMap { $0.groupValues }
// Create a dictionary of parameter : parameter value
for (key, value) in zip(params, matchedParams) {
routeParams[key] = value
}
return (true, routeParams)
}
}
| apache-2.0 | 0d90716e5469e63e1fa7263bd0f680e8 | 33.733945 | 125 | 0.690174 | 4.192691 | false | false | false | false |
mhplong/Projects | iOS/VoiceTester/WaveFormView.swift | 1 | 3466 | //
// WaveFormView.swift
// VoiceTester
//
// Created by Mark Long on 6/9/16.
// Copyright © 2016 Mark Long. All rights reserved.
//
import UIKit
func normalize(value: CGFloat, max : CGFloat, min: CGFloat) -> CGFloat {
return (value - min)/(max - min)
}
func lerp(norm: CGFloat, max : CGFloat, min: CGFloat) -> CGFloat {
return (max - min) * norm + min
}
func map(value: CGFloat, maxTarget: CGFloat, minTarget: CGFloat, maxDest : CGFloat, minDest: CGFloat) -> CGFloat {
return lerp(norm: normalize(value: value, max: maxTarget, min: minTarget), max: maxDest, min: minDest)
}
class WaveFormView: UIView {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
var stepWaveFormData = [Int16]()
var wholeWaveFormData = [[Int16]]()
var stepOffset = 0
let stepLength = 4
override func draw(_ rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
context?.clear(rect)
drawStuff(size: rect.size)
}
func drawStuff(size: CGSize) {
var count : CGFloat = 0
var maxHeight : Int16 = 0
var minHeight : Int16 = 0
for sample in stepWaveFormData {
if sample > maxHeight {
maxHeight = sample
}
if sample < minHeight {
minHeight = sample
}
}
print("\(minHeight) - \(maxHeight)")
let baseline = CGFloat(size.height / 2)
var xPos = map(value: count, maxTarget: CGFloat(stepWaveFormData.count), minTarget: 0, maxDest: size.width, minDest: 0)
var lastPoint = CGPoint(x: xPos, y:baseline)
for sample in stepWaveFormData {
let path = UIBezierPath()
xPos = map(value: count, maxTarget: CGFloat(stepWaveFormData.count), minTarget: 0, maxDest: size.width, minDest: 0)
let offset = map(value: CGFloat(sample), maxTarget: CGFloat(Int16.max), minTarget: 0, maxDest: size.height, minDest: 0)
let linePoint = CGPoint(x: xPos, y: (baseline + offset))
path.move(to: lastPoint)
path.addLine(to: linePoint)
UIColor.yellow().setStroke()
path.stroke()
lastPoint = linePoint
count = count + 1
}
}
func updateWaveForm(data:[[Int16]]?) {
if data != nil {
wholeWaveFormData = data!
updateForm()
}
}
func updateForm() {
stepWaveFormData = [Int16]()
print(stepOffset)
let endStep = stepOffset + stepLength
for c in stepOffset..<endStep {
if c < wholeWaveFormData.count {
stepWaveFormData.append(contentsOf: wholeWaveFormData[c])
}
}
self.setNeedsDisplay()
}
func Previous(step: Int) -> Bool {
if stepOffset <= 0 {
return false
} else {
stepOffset = stepOffset - stepLength
updateForm()
return true
}
}
func Next(step: Int) -> Bool {
if (stepOffset + stepLength) >= wholeWaveFormData.count {
return false
} else {
stepOffset = stepOffset + stepLength
updateForm()
return true
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 087c1402a065774dbb5eb08a2d47b67f | 29.130435 | 131 | 0.56912 | 4.272503 | false | false | false | false |
yoavlt/LiquidFloatingActionButton | Pod/Classes/LiquittableCircle.swift | 1 | 2257 | //
// LiquittableCircle.swift
// LiquidLoading
//
// Created by Takuma Yoshida on 2015/08/17.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
open class LiquittableCircle : UIView {
var points: [CGPoint] = []
var radius: CGFloat {
didSet {
self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)
setup()
}
}
var color: UIColor = UIColor.red {
didSet {
setup()
}
}
override open var center: CGPoint {
didSet {
self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)
setup()
}
}
let circleLayer = CAShapeLayer()
init(center: CGPoint, radius: CGFloat, color: UIColor) {
let frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)
self.radius = radius
self.color = color
super.init(frame: frame)
setup()
self.layer.addSublayer(circleLayer)
self.isOpaque = false
}
init() {
self.radius = 0
super.init(frame: CGRect.zero)
setup()
self.layer.addSublayer(circleLayer)
self.isOpaque = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func setup() {
self.frame = CGRect(x: center.x - radius, y: center.y - radius, width: 2 * radius, height: 2 * radius)
drawCircle()
}
func drawCircle() {
let bezierPath = UIBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: CGSize(width: radius * 2, height: radius * 2)))
draw(bezierPath)
}
@discardableResult
func draw(_ path: UIBezierPath) -> CAShapeLayer {
circleLayer.lineWidth = 3.0
circleLayer.fillColor = self.color.cgColor
circleLayer.path = path.cgPath
return circleLayer
}
func circlePoint(_ rad: CGFloat) -> CGPoint {
return CGMath.circlePoint(center, radius: radius, rad: rad)
}
open override func draw(_ rect: CGRect) {
drawCircle()
}
}
| mit | 0ea09a79e055b0f42aabe1879f782dc0 | 25.845238 | 128 | 0.581818 | 4.160517 | false | false | false | false |
Frainbow/ShaRead.frb-swift | ShaRead/ShaRead/MailAdminViewController.swift | 1 | 5782 | //
// MailAdminViewController.swift
// ShaRead
//
// Created by martin on 2016/5/14.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import UIKit
import Firebase
class MailAdminViewController: UIViewController {
@IBOutlet weak var userTableView: UITableView!
var users: [ShaUser] = []
var uid: String?
var authHandler: FIRAuthStateDidChangeListenerHandle?
deinit {
if let authHandler = authHandler {
FIRAuth.auth()?.removeAuthStateDidChangeListener(authHandler)
self.uid = nil
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initFirebase()
}
override func viewWillAppear(animated: Bool) {
// deselect row on appear
if let indexPath = userTableView.indexPathForSelectedRow {
userTableView.deselectRowAtIndexPath(indexPath, animated: false)
}
}
override func viewDidAppear(animated: Bool) {
setTabBarVisible(true, animated: false)
}
override func viewWillDisappear(animated: Bool) {
setTabBarVisible(false, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Custom method
func initFirebase() {
self.authHandler = FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth, user) in
if let user = user {
self.uid = user.uid
self.getRoomList()
}
else {
// redirect to login page
self.uid = nil
}
})
}
func getRoomList() {
guard let currentUID = self.uid else {
return
}
let rootRef = FIRDatabase.database().reference()
rootRef
.child("rooms")
.queryOrderedByChild("admin-uid")
.queryEqualToValue("\(currentUID)")
.observeEventType(.ChildAdded, withBlock: { snapshot in
let instance = ShaManager.sharedInstance
let dic = snapshot.value as! NSDictionary
let key = dic["key"] as! String
let uid = key.componentsSeparatedByString(" - ")[1]
if instance.users[uid] == nil {
instance.getUserByUid(uid,
success: {
self.users.append(instance.users[uid]!)
self.userTableView.reloadData()
},
failure: {
}
)
}
else {
self.users.append(instance.users[uid]!)
self.userTableView.reloadData()
}
})
}
// MARK: - TabBar
func setTabBarVisible(visible:Bool, animated:Bool) {
//* This cannot be called before viewDidLayoutSubviews(), because the frame is not set before this time
// bail if the current state matches the desired state
if (tabBarIsVisible() == visible) { return }
// get a frame calculation ready
let frame = self.tabBarController?.tabBar.frame
let height = frame?.size.height
let offsetY = (visible ? -height! : height)
// zero duration means no animation
let duration:NSTimeInterval = (animated ? 0.3 : 0.0)
// animate the tabBar
if frame != nil {
UIView.animateWithDuration(duration) {
self.tabBarController?.tabBar.frame = CGRectOffset(frame!, 0, offsetY!)
return
}
}
}
func tabBarIsVisible() ->Bool {
return self.tabBarController?.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame)
}
/*
// 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.
}
*/
}
extension MailAdminViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count > 0 ? users.count : 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("userCell", forIndexPath: indexPath) as! MailAdminTableViewCell
if users.count == 0 {
cell.nameLabel.text = "系統管理員:無信件"
return cell
}
cell.avatarImageView.image = nil
cell.nameLabel.text = users[indexPath.row].name
if let url = NSURL(string: users[indexPath.row].avatar) {
cell.avatarImageView.sd_setImageWithURL(url, placeholderImage: ShaDefault.defaultAvatar)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if users.count == 0 {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("MessageController") as! MessageTableViewController
controller.isAdmin = true
controller.targetUser = users[indexPath.row]
self.navigationController?.pushViewController(controller, animated: true)
}
}
| mit | 4f1f778df0862ed486b770f1772c9bd0 | 29.643617 | 127 | 0.597813 | 5.227768 | false | false | false | false |
koyachi/swift-GIFMetadata | Sources/GIFMetadata.swift | 1 | 10388 | // Related:
// - https://github.com/voidless/Animated-GIF-iPhone
// - https://github.com/drewnoakes/metadata-extractor/blob/master/Source/com/drew/metadata/gif/GifReader.java
import Foundation
@objc public class GIFMetadata: NSObject {
public var logicalScreenDescriptor: LogicalScreenDescriptor?
public var applicationExtensions: [ApplicationExtension] = []
public var imageDescriptors: [ImageDescriptor] = []
public var imageDataCount: Int = 0
private var data: Data?
private var pointerIndex: Int? /*{
didSet {
print("pointerIndex = \(String(format: "%08x", pointerIndex!))")
}
}*/
private var globalColorTableSize: Int?
@objc public func preferredLoopCount() -> Int {
if applicationExtensions.count == 0 && imageDescriptors.count > 0 {
return 1
} else {
for appExt in applicationExtensions {
switch appExt {
case .netscapeLooping(let lc):
return Int(lc)
}
}
}
return 0
}
@objc public init(_ data: Data) {
super.init()
self.data = data
pointerIndex = 0
if data.count == 0 {
return
}
readHeader()
logicalScreenDescriptor = readLogicalScreenDescriptor()
readGlobalColorTable()
readBody()
}
func readHeader() {
//print("\(#function)")
skipBytes(6)
}
func readLogicalScreenDescriptor() -> LogicalScreenDescriptor {
//print("\(#function)")
let width = readBytes(2)
pointerIndex? += 2
let height = readBytes(2)
pointerIndex? += 2
let packedField = readByte()
pointerIndex? += 1
let globalColorTableFlag: Bool = packedField & 0x80 == 0x80
let colorResolution: UInt8 = (packedField & 0x70 >> 4) & 0x07
let sortFlag: Bool = packedField & 0x08 == 0x08
let sizeOfGlobalColorTable = packedField & 0x07
let backgroundColorIndex = readByte()
pointerIndex? += 1
let pixelAspectRatio = readByte()
pointerIndex? += 1
return LogicalScreenDescriptor(
width: uint16(width),
height: uint16(height),
globalColorTableFlag: globalColorTableFlag,
colorResolution: colorResolution,
sortFlag: sortFlag,
sizeOfGlobalColorTable: sizeOfGlobalColorTable,
backgroundColorIndex: backgroundColorIndex,
pixelAspectRatio: pixelAspectRatio)
}
func readGlobalColorTable() {
//print("\(#function)")
if let logicalScreenDescriptor = logicalScreenDescriptor,
logicalScreenDescriptor.globalColorTableFlag {
/*
let numberOfColors = 2 ^ (logicalScreenDescriptor.colorResolution + 1)
let byteLength = 3 * numberOfColors
pointerIndex? += Int(byteLength)
*/
_readColorTable(sizeOfColorTable: Int(logicalScreenDescriptor.sizeOfGlobalColorTable))
}
}
func readBody() {
//print("\(#function)")
let dataLength = data?.count
while pointerIndex! < dataLength! {
/*
let byte = data?.subdata(in: pointerIndex!..<pointerIndex!+1)
let byteValue = [UInt8](byte!).first!
*/
let byteValue = readByte()
pointerIndex? += 1
//print("readBody.byteValue = \(byteValue)")
if byteValue == 0x3B {
// Trailer block
break
}
switch byteValue {
case 0x21:
readExtensions()
case 0x2C:
let imageDescriptor = readImageDescriptor()
imageDescriptors.append(imageDescriptor)
if imageDescriptor.localColorTabelFlag {
readLocalColorTable(sizeOfColorTable: Int(imageDescriptor.sizeOfLocalColorTable))
}
readImageData()
default:
// TODO:
break
}
}
}
func readExtensions() {
//print("\(#function)")
let byteValue = readByte()
//print("readExtensions.byteValue = \(byteValue)")
pointerIndex? += 1
switch byteValue {
case 0xF9:
readGraphicsControleExtension()
case 0x01:
readPlainTextExtension()
case 0xFF:
readApplicationExtension()
case 0xFE:
readCommentExtension()
default:
// TODO
break
}
}
func readImageDescriptor() -> ImageDescriptor {
//print("\(#function)")
let imageLeft = readBytes(2)
pointerIndex? += 2
let imageTop = readBytes(2)
pointerIndex? += 2
let imageWidth = readBytes(2)
pointerIndex? += 2
let imageHeight = readBytes(2)
pointerIndex? += 2
let packedField = readByte()
pointerIndex? += 1
let localColorTableFlag = packedField & 0x80 == 0x80
let interlaceFlag = packedField & 0x40 == 0x40
let sortFlag = packedField & 0x20 == 0x20
// reserbed for future use, 2 bit
let sizeOfLocalColorTable = packedField & 0x07
return ImageDescriptor(
imageLeft: uint16(imageLeft),
imageTop: uint16(imageTop),
imageWidth: uint16(imageWidth),
imageHeight: uint16(imageHeight),
localColorTabelFlag: localColorTableFlag,
interlaceFlag: interlaceFlag,
sortFlag: sortFlag,
sizeOfLocalColorTable: sizeOfLocalColorTable)
}
func readLocalColorTable(sizeOfColorTable: Int) {
//print("\(#function)")
_readColorTable(sizeOfColorTable: sizeOfColorTable)
}
func readImageData(){
//print("\(#function)")
let _ = readByte() // LZWMinimumCodeSize
pointerIndex? += 1
while true {
let byte = readByte()
pointerIndex? += 1
if byte == 0x00 {
return
}
let blockSize = byte
skipBytes(Int(blockSize))
imageDataCount += 1
}
}
func readGraphicsControleExtension() {
//print("\(#function)")
// block size
skipBytes(1)
// - Packed Field
// - Delay Time(2 byte)
// - Transparent Color Index
// - Block Terminator(0x00)
skipBytes(5)
}
func readPlainTextExtension() {
//print("\(#function)")
// block size, 0x0c
skipBytes(1)
while true {
// - Text Grid Left Position
// - Text Grid Right Position
// - Text Grid Width
// - Text Grid Height
// - Character Cell Width
// - Character Cell Height
// - Text Foreground Color Index
// - Text Background Color Index
skipBytes(0x0c)
// - Block Terminator(0x00)
if readByte() == 0x00 {
return
}
}
}
func readApplicationExtension() {
//print("\(#function)")
// block size, 0x0b
skipBytes(1)
let applicationIdentifier = readBytes(8)
let applicationIdentifierStr = String(bytes: applicationIdentifier, encoding: .utf8)
pointerIndex? += 8
let _ = readBytes(3) // applicationAuthenticationCode
pointerIndex? += 3
while true {
let byte = readByte()
pointerIndex? += 1
if byte == 0x00 {
return
} else {
let blockSize = byte
let bytes = readBytes(Int(blockSize))
// TODO animation GIF
if (applicationIdentifierStr == "NETSCAPE" || applicationIdentifierStr == "ANIMEXTS") {
let loopCount: UInt16 = uint16(Array(bytes[1..<3])) // TODO:
applicationExtensions.append(.netscapeLooping(loopCount: loopCount))
}
pointerIndex? += Int(blockSize)
}
}
}
func readCommentExtension() {
//print("\(#function)")
let blockSize = readByte()
pointerIndex? += 1
// comment data
skipBytes(Int(blockSize))
while true {
let byte = readByte()
pointerIndex? += 1
if byte == 0x00 {
return
} else {
let blockSize = byte
// comment data
skipBytes(Int(blockSize))
}
}
}
func _readColorTable(sizeOfColorTable: Int) {
//print("_ \(#function), sizeOfColorTable = \(sizeOfColorTable)")
let numberOfColors: Int = Int(pow(Double(2), Double(sizeOfColorTable + 1)))
let byteLength = 3 * numberOfColors
//print(" numberOfColors = \(numberOfColors), byteLength = \(byteLength)")
pointerIndex? += Int(byteLength)
}
func skipBytes(_ byteCount: Int) {
//print("_ \(#function), byteCount = \(byteCount)")
pointerIndex? += byteCount
}
func readBytes(_ byteCount: Int) -> [UInt8] {
//print("_ \(#function), byteCount = \(byteCount)")
let bytes = data?.subdata(in: pointerIndex!..<pointerIndex!+byteCount)
let bytesValue = [UInt8](bytes!)
return bytesValue
}
func readByte() -> UInt8 {
//print("_ \(#function)")
let byte = data?.subdata(in: pointerIndex!..<pointerIndex!+1)
let byteValue = [UInt8](byte!).first!
return byteValue
}
func uint16(_ bytes: [UInt8]) -> UInt16 {
let result: UInt16 = (UInt16(bytes[1]) << 8) + UInt16(bytes[0])
return result
}
}
extension GIFMetadata /*: CustomStringConvertible*/ {
override public var description: String {
return [
"<\(String(describing: type(of: self)))",
"logicalScreenDescriptor: \(logicalScreenDescriptor as Optional)",
"applicationExtensions: \(applicationExtensions)",
"imageDescriptors: \(imageDescriptors)",
"imageDataCount: \(imageDataCount)",
"preferredLoopCount: \(preferredLoopCount())",
">",
].joined(separator: "\n ")
}
}
| mit | fa873ad00c36abf649b41feb898bf93f | 30.289157 | 109 | 0.54794 | 4.831628 | false | false | false | false |
yashwanth777/YKExpandTableView | viewcontroller.swift | 1 | 3611 | import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var expandedSections: NSMutableIndexSet! = nil;
override func viewDidLoad() {
super.viewDidLoad()
if self.expandedSections == nil{
expandedSections = NSMutableIndexSet() as NSMutableIndexSet;
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView:UITableView,canCollapseSection section:NSInteger) -> Bool{
if section >= 0{
return true;
}
else{
return false;
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 3;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (self.tableView(tableView, canCollapseSection: section)) {
if(self.expandedSections.containsIndex(section)){
return 5;
}
return 1;
}
return 1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
if (self.tableView(tableView, canCollapseSection: indexPath.section)){
if (indexPath.row >= 0){
cell.textLabel?.text = "Expandable";
if expandedSections.containsIndex(indexPath.section){
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
}
else{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark;
}
}
else{
cell.textLabel?.text = "SomeDetail";
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator;
}
}
else{
cell.accessoryView = nil;
cell.textLabel?.text = "Normal Cell";
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
if (self.tableView(tableView, canCollapseSection: indexPath.section)){
if(indexPath.row >= 0){
tableView.deselectRowAtIndexPath(indexPath, animated: true);
var section = indexPath.section;
var currentlyExpanded = expandedSections.containsIndex(section);
var rows:NSInteger;
var tempArray = NSMutableArray();
if(currentlyExpanded){
rows = self.tableView(tableView, numberOfRowsInSection: section);
expandedSections.removeIndex(section);
}
else{
expandedSections.addIndex(section);
rows = self.tableView(tableView, numberOfRowsInSection: section);
}
for(var i=1; i<rows; i++){
var tempIndexPath = NSIndexPath(forRow: i, inSection: section);
tempArray.addObject(tempIndexPath);
}
var cell = self.tableView(tableView, cellForRowAtIndexPath: indexPath);
if currentlyExpanded{
tableView.deleteRowsAtIndexPaths(tempArray, withRowAnimation: UITableViewRowAnimation.Top);
}
else{
tableView.insertRowsAtIndexPaths(tempArray, withRowAnimation: UITableViewRowAnimation.Top);
}
}
}
}
}
| mit | be25ce65a85da1d2457ef0b00323dda5 | 35.11 | 110 | 0.616173 | 5.704581 | false | false | false | false |
FienMaandag/spick-and-span | spick_and_span/spick_and_span/HouseViewController.swift | 1 | 4022 | //
// HouseViewController.swift
// spick_and_span
//
// Created by Fien Maandag on 07-06-17.
// Copyright © 2017 Fien Maandag. All rights reserved.
//
import UIKit
import Firebase
class HouseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var houseName = String()
var houseKey = String()
var rooms: [Rooms] = []
let ref = Database.database().reference()
let currentUser = Auth.auth().currentUser
override func viewDidLoad() {
super.viewDidLoad()
// Lookup housekey and name for current user
ref.child("users").child((currentUser?.uid)!).observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
self.houseName = value?["houseName"] as? String ?? ""
self.houseKey = value?["houseKey"] as? String ?? ""
self.navigationItem.title = self.houseName
self.loadRooms()
}) { (error) in
print(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// Set amount rows
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rooms.count
}
// Fill cells of tableview with rooms
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "RoomsCell", for: indexPath as IndexPath) as! RoomTableViewCell
cell.roomNameLabel.text = rooms[indexPath.row].nameRoom.uppercased()
return cell
}
// Load rooms for current house
func loadRooms(){
let searchRef = ref.child("houses/\(self.houseKey)/rooms")
searchRef.observe(.value, with: { snapshot in
var newRooms: [Rooms] = []
for item in snapshot.children {
let room = Rooms(snapshot: item as! DataSnapshot)
newRooms.append(room)
}
self.rooms = newRooms
self.tableView.reloadData()
})
}
// Add a new room
@IBAction func addRoomButtonClicked(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "New Room",
message: "Choose a name for your room",
preferredStyle: .alert)
// Save room for house
let saveAction = UIAlertAction(title: "Save", style: .default) { action in
guard let roomNameField = alert.textFields![0].text, !roomNameField.isEmpty else{
self.simpleAlert(title: "No Input", message: "Please enter a room name", actionTitle: "ok")
return
}
let text = roomNameField.capitalized
// add room to firebase
let newRoom = Rooms(addedByUser: (self.currentUser?.uid)!,
nameRoom: text)
let houseRef = self.ref.child("houses/\(self.houseKey)/rooms/\(text)")
houseRef.setValue(newRoom.toAnyObject())
}
// Closes alert
let cancelAction = UIAlertAction(title: "Cancel",
style: .default)
alert.addTextField { roomName in
roomName.placeholder = "Room Name"
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let roomVC = segue.destination as? RoomViewController{
if let path = tableView.indexPathForSelectedRow{
roomVC.roomName = self.rooms[path.row].nameRoom
}
}
}
}
| mit | f3d87906f355ce8c4bc54fd1e4d8bddb | 33.076271 | 133 | 0.573738 | 5.051508 | false | false | false | false |
QQLS/YouTobe | YouTube/Class/Base/Controller/BQBaseCollectionViewController.swift | 1 | 4726 |
//
// BQBaseCollectionViewController.swift
// YouTube
//
// Created by xiupai on 2017/3/21.
// Copyright © 2017年 QQLS. All rights reserved.
//
import UIKit
let videoCellReuseID = BQVideoListCell.nameOfClass
class BQBaseCollectionViewController: UICollectionViewController {
// MARK: - Properties
var videoList = [BQVideoItem]()
let refreshControl = UIRefreshControl()
var lastContentOffset: CGFloat = 0
var loadNewDataURL = URLLink.home.link()
var loadMoreDataURL = URLLink.trending.link()
// MARK: - Initial
override func viewDidLoad() {
super.viewDidLoad()
p_setupView()
loadNewData()
}
func p_setupView() {
self.clearsSelectionOnViewWillAppear = true
// 设置并添加刷新控件
refreshControl.addTarget(self, action: #selector(BQBaseCollectionViewController.loadNewData), for: .valueChanged)
refreshControl.tintColor = kSchemeColor
collectionView?.addSubview(refreshControl)
collectionView?.register(UINib.init(nibName: videoCellReuseID, bundle: nil), forCellWithReuseIdentifier: videoCellReuseID)
}
// MARK: - Action
func loadNewData() {
videoList.removeAll()
fetchVideoList(with: loadNewDataURL)
}
func loadMoreData() {
fetchVideoList(with: loadMoreDataURL)
}
func fetchVideoList(with url: URL) {
BQVideoItem.fetchVideoItemList(from: url) { (itemList: [BQVideoItem]?) in
guard let itemList = itemList else {
return
}
self.videoList += itemList
DispatchQueue.main.async(execute: {
self.collectionView?.reloadData()
self.refreshControl.endRefreshing()
})
}
}
}
// MARK: - UICollectionViewDataSource
extension BQBaseCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return videoList.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: videoCellReuseID, for: indexPath) as! BQVideoListCell
cell.videoModel = videoList[indexPath.item]
return cell
}
}
// MARK: - UICollectionViewDelegate
extension BQBaseCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
NotificationCenter.default.post(name: NSNotification.Name(PlayChangeNotification), object: nil)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension BQBaseCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemHeight = collectionView.width * (9 / 16.0) + 67.0
return CGSize(width: collectionView.width, height: itemHeight)
}
}
// MARK: - UIScrollViewDelegate
extension BQBaseCollectionViewController {
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
lastContentOffset = scrollView.contentOffset.y
}
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y + scrollView.height > scrollView.contentSize.height - 100 {
loadMoreData()
}
}
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.height {
lastContentOffset = scrollView.contentSize.height - scrollView.height
return
}
if let hidden = navigationController?.navigationBar.isHidden {
if scrollView.contentOffset.y > 100 {
if lastContentOffset > scrollView.contentOffset.y {
if hidden {
NotificationCenter.default.post(name: NSNotification.Name(NavigationWillHiddenNotification), object: false)
}
} else {
if !hidden {
NotificationCenter.default.post(name: NSNotification.Name(NavigationWillHiddenNotification), object: true)
}
}
} else {
if hidden {
NotificationCenter.default.post(name: NSNotification.Name(NavigationWillHiddenNotification), object: false)
}
}
}
}
}
| apache-2.0 | b497cbc48623c968e1ced90f6a433f90 | 34.37594 | 160 | 0.662274 | 5.62799 | false | false | false | false |
soflare/XWebShell | XWebShell/ModalDialogBox.swift | 1 | 3033 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
class ModalDialogBox {
let title: String
let message: String
unowned let parent: UIViewController
var done = false
init(title: String, message: String, parent: UIViewController) {
self.title = title
self.message = message
self.parent = parent
}
func alert(handler: ()->Void) {
let controller = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
controller.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
(UIAlertAction)->Void in
handler()
self.done = true
})
show(controller)
}
func confirm(handler: (Bool)->Void) {
let controller = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
controller.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
(UIAlertAction)->Void in
handler(true)
self.done = true
})
controller.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
(UIAlertAction)->Void in
handler(false)
self.done = true
})
show(controller)
}
func prompt(value: String!, handler: (String!)->Void) {
let controller = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
controller.addTextFieldWithConfigurationHandler {
$0.text = value
}
controller.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
(UIAlertAction)->Void in
let field = controller.textFields?[0] as? UITextField
handler(field?.text)
self.done = true
})
controller.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
(UIAlertAction)->Void in
handler(nil)
self.done = true
})
show(controller)
}
private func show(controller: UIAlertController) {
parent.presentViewController(controller, animated: true, completion: nil)
while !done {
let reason = CFRunLoopRunInMode(kCFRunLoopDefaultMode, NSDate.distantFuture().timeIntervalSinceNow, Boolean(1))
if Int(reason) != kCFRunLoopRunHandledSource {
break
}
}
}
}
| apache-2.0 | f2804a902874ad14370db07da1b46822 | 34.682353 | 123 | 0.6515 | 5.021523 | false | false | false | false |
tectijuana/patrones | Bloque1SwiftArchivado/PracticasSwift/PalaciosArlette/Ejercicio19.swift | 1 | 1406 | /*
Palacios Lee Arlette 12211431
Programa para resolver el siguiente problema:
19. Dadas las medidas de los lados a y b y el ángulo C, con la ley de los cosenos determinar la medida del lado c y los ángulos A y B.
*/
//Librería para utilizar funciones trigonométricas
import Foundation
//Declaración de variables
var ladoa: Float = 4
var ladob: Float = 5
var anguloC: Float = 126.42
//Procedimientos
var coseno = cos(anguloC * Float.pi / 180) //Calcular el coseno
var lados = pow(ladoa,2) + pow(ladob,2) //Realizar la suma del cuadrado de los lados
//Se obtiene el doble del la suma de los lados por el coseno y se le resta el cuadrado de los lados y se obtiene la raíz cuadrada de esto
var ladoc = sqrt(lados - (2*ladoa*ladob*coseno))
//Se calcula el ángulo B utilizando la ley de senos
var anguloB = asin((ladob * sin(anguloC * Float.pi / 180))/ladoc) * 180 / Float.pi
//Se calcula el ángulo C utilizando la ley de senos
var anguloA = asin((ladoa * sin(anguloB * Float.pi / 180))/ladob) * 180 / Float.pi
//Se imprime el problema
print("Problema \n19. Dadas las medidas de los lados a y b y el ángulo C, con la ley de los cosenos determinar la medida del lado c y los ángulos A y B. ")
//Se imprime el resultado
print(" \nLado a: \(ladoa) \nLado b: \(ladob) \nLado c: \(ladoc) \nÁngulo A: \(anguloA) \nÁngulo B: \(anguloB) \nÁngulo C: \(anguloC)")
| gpl-3.0 | 15f6831575f75d4d8a0da26ec79f34ac | 41.212121 | 155 | 0.7028 | 2.752964 | false | false | false | false |
thedreamer979/Calvinus | Calvin/LoginController.swift | 1 | 1659 | //
// LoginViewController.swift
// Calvin
//
// Created by Arion Zimmermann on 05.03.17.
// Copyright © 2017 AZEntreprise. All rights reserved.
//
import UIKit
class LoginController : UIViewController {
@IBOutlet weak var progress: UIProgressView!
@IBOutlet weak var state: UILabel!
@IBOutlet weak var name: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
@IBAction func onContinue(_ sender: UIButton) {
self.progress.alpha = 1.0
self.state.text = "Téléchargement en cours..."
let hash = AZEntrepriseServer.sha256(forInput: (name.text?.uppercased().trimmingCharacters(in: .whitespaces))!)
AZEntrepriseServer.login(controller: self, userHash: hash, onResponse: loginResponse)
self.progress.setProgress(0.1, animated: true)
}
@IBAction func dismiss(_ sender: UITextField) {
self.view.endEditing(true)
}
func loginResponse(success : Bool) {
DispatchQueue.main.sync {
if success {
self.progress.setProgress(1.0, animated: true)
let controller = self.storyboard?.instantiateViewController(withIdentifier: "Dashboard")
self.present(controller!, animated: true, completion: nil)
} else {
self.progress.setProgress(0.0, animated: true)
self.state.text = "La vérification du nom a échouée."
}
}
}
}
| gpl-3.0 | 8a8a68b991fddf1b8ffcecb6bae2fec1 | 29.611111 | 119 | 0.607381 | 4.443548 | false | false | false | false |
sergiog90/PagedUITableViewController | PagedUITableViewController/Classes/PagedUITableViewController.swift | 1 | 6640 | //
// PagedUITableViewController.swift
//
//
// Created by Sergio Garcia on 9/9/16.
// Copyright © 2016 Sergio Garcia. All rights reserved.
//
import UIKit
private extension UIViewController {
func isVisible() -> Bool {
return self.isViewLoaded() && self.view.window != nil
}
func delayMainQueue(delay: Double, actions: ()->()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))),
dispatch_get_main_queue(), actions)
}
}
private extension UITableView {
private func deselectRowsCoordinated(transitionCoordinator: UIViewControllerTransitionCoordinator?) {
let selectedRows = self.indexPathsForSelectedRows
for row in selectedRows ?? [] {
self.deselectRowAtIndexPath(row, animated: true)
transitionCoordinator?.notifyWhenInteractionEndsUsingBlock({ context in
if (context.isCancelled()) {
self.selectRowAtIndexPath(row, animated: false, scrollPosition: .None)
}
})
}
}
}
extension PagedUITableViewController: PagedUITableViewActionsDelegate {
public func reloadData() {
downloadNextDataPage(true)
}
public func deleteItem(atIndexPath indexPath: NSIndexPath) {
currentOffset -= 1
dispatch_async(dispatch_get_main_queue(), {
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
})
}
}
public class PagedUITableViewController: UITableViewController {
public var pagedDelegate: PagedUITableViewDelegate?
public var pagedDataSource: PagedUITableViewDataSource?
public var pagedActionsDelegate: PagedUITableViewActionsDelegate!
private var downloading = false
private var currentOffset = 0
private var pageSize = 0
private var totalItems: Int?
override public func awakeFromNib() {
pagedActionsDelegate = self
super.awakeFromNib()
}
override public func viewDidLoad() {
super.viewDidLoad()
downloadNextDataPage()
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(self.reloadData), forControlEvents: .ValueChanged)
if let refresh = self.refreshControl {
self.tableView.addSubview(refresh)
}
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.deselectRowsCoordinated(self.transitionCoordinator())
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let refreshControl = self.refreshControl {
refreshControl.superview?.sendSubviewToBack(refreshControl)
}
}
private func downloadNextDataPage(resetDatasource: Bool = false) {
if resetDatasource {
pagedDelegate?.cancelCurrentRequest()
downloading = false
self.refreshControl?.beginRefreshing()
currentOffset = 0
totalItems = nil
}
guard !downloading else {
return
}
if let totalItems = totalItems {
guard currentOffset < totalItems else {
print("All pages downloaded.")
return
}
}
downloading = true
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
downloadData()
}
private func downloadData() {
pagedDataSource?.downloadData(offset: currentOffset, onSuccess: { (pageSize, data, totalItems) in
if self.refreshControl?.refreshing ?? false {
dispatch_async(dispatch_get_main_queue()) {
self.refreshControl?.endRefreshing()
}
self.pagedDelegate?.resetDataSource()
}
self.totalItems = totalItems
self.pagedDataSource?.appendData(data, forOffset: self.currentOffset)
self.currentOffset += data.count
self.downloading = false
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}, onError: { (delayTime) in
if self.isVisible() {
self.delayMainQueue(delayTime, actions: {
self.downloadData()
})
} else {
if self.refreshControl?.refreshing ?? false {
dispatch_async(dispatch_get_main_queue()) {
self.refreshControl?.endRefreshing()
}
}
self.downloading = false
self.tableView.reloadData()
}
})
}
// MARK: - Table view data source
override public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let sections = pagedDataSource?.numberOfSectionsInPagedTableView(tableView) ?? 0
if downloading {
return sections + 1
}
return sections
}
override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sections = pagedDataSource?.numberOfSectionsInPagedTableView(tableView) ?? 0
if downloading && section == sections {
// Loading cell
return 1
} else {
let rows = pagedDataSource?.pagedTableView(tableView, numberOfRowsInPagedSection: section) ?? 0
return rows
}
}
override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let sections = pagedDataSource?.numberOfSectionsInPagedTableView(tableView) ?? 0
if downloading && indexPath.section == sections {
// Loading cell
return pagedDataSource?.loadingCellForPagedTableView(tableView, forIndexPath: indexPath) ?? UITableViewCell()
} else {
return pagedDataSource?.pagedTableView(tableView, cellForRowAtIndexPath: indexPath) ?? UITableViewCell()
}
}
// MARK: UITableViewDelegate
override public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == tableView.numberOfSections - 1
&& self.currentOffset < self.totalItems {
downloadNextDataPage()
}
}
}
| mit | ed8593cfeea56731976cc57f9af96a57 | 33.942105 | 141 | 0.607471 | 5.763021 | false | false | false | false |
cxpyear/spdbapp | spdbapp/LaunchViewController.swift | 1 | 992 | //
// LaunchViewController.swift
// spdbapp
//
// Created by GBTouchG3 on 15/6/4.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
class LaunchViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
println("123====launch my screen==================")
self.view.backgroundColor = UIColor.purpleColor()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause | 3aa8336124d40a823787522fd8996246 | 25.756757 | 106 | 0.659596 | 4.805825 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/ThirdLibrary/GDPerformanceMonitoring/GDPerformanceMonitor.swift | 2 | 8178 | //
// Copyright © 2017 Gavrilov Daniil
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
public class GDPerformanceMonitor: NSObject {
// MARK: Public Properties
/**
GDPerformanceMonitorDelegate delegate.
*/
public weak var delegate: GDPerformanceMonitorDelegate? {
didSet {
self.performanceView?.performanceDelegate = self.delegate
}
}
/**
Change it to hide or show application version from monitoring view. Default is false.
*/
public var appVersionHidden: Bool = false {
didSet {
self.performanceView?.appVersionHidden = self.appVersionHidden
}
}
/**
Change it to hide or show device iOS version from monitoring view. Default is false.
*/
public var deviceVersionHidden: Bool = false {
didSet {
self.performanceView?.deviceVersionHidden = self.deviceVersionHidden
}
}
/**
Instance of GDPerformanceMonitor as singleton.
*/
public static let sharedInstance: GDPerformanceMonitor = GDPerformanceMonitor.init()
// MARK: Private Properties
private var performanceView: GDPerformanceView?
private var performanceViewPaused: Bool = false
private var performanceViewHidden: Bool = false
private var performanceViewStopped: Bool = false
private var prefersStatusBarHidden: Bool = false
private var preferredStatusBarStyle: UIStatusBarStyle = UIStatusBarStyle.default
// MARK: Init Methods & Superclass Overriders
/**
Creates and returns instance of GDPerformanceMonitor.
*/
public override init() {
super.init()
self.subscribeToNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Notifications & Observers
@objc private func applicationDidBecomeActive(notification: NSNotification) {
if self.performanceViewPaused {
return
}
self.startOrResumeMonitoring()
}
@objc private func applicationWillResignActive(notification: NSNotification) {
self.performanceView?.pauseMonitoring()
}
// MARK: Public Methods
/**
Overrides prefersStatusBarHidden and preferredStatusBarStyle properties to return the desired status bar attributes.
Default prefersStatusBarHidden is false, preferredStatusBarStyle is UIStatusBarStyle.default.
*/
public func configureStatusBarAppearance(prefersStatusBarHidden: Bool, preferredStatusBarStyle: UIStatusBarStyle) {
self.prefersStatusBarHidden = prefersStatusBarHidden
self.preferredStatusBarStyle = preferredStatusBarStyle
self.checkAndApplyStatusBarAppearance(prefersStatusBarHidden: prefersStatusBarHidden, preferredStatusBarStyle: preferredStatusBarStyle)
}
/**
Starts or resumes performance monitoring, initialize monitoring view if not initialized and shows monitoring view. Use configuration block to change appearance as you like.
*/
public func startMonitoring(configuration: (UILabel?) -> Void) {
self.performanceViewPaused = false
self.performanceViewHidden = false
self.performanceViewStopped = false
self.startOrResumeMonitoring()
let textLabel = self.performanceView?.textLabel()
configuration(textLabel)
}
/**
Starts or resumes performance monitoring, initialize monitoring view if not initialized and shows monitoring view.
*/
public func startMonitoring() {
self.performanceViewPaused = false
self.performanceViewHidden = false
self.performanceViewStopped = false
self.startOrResumeMonitoring()
}
/**
Pauses performance monitoring and hides monitoring view.
*/
public func pauseMonitoring() {
self.performanceViewPaused = true
self.performanceView?.pauseMonitoring()
}
/**
Hides monitoring view.
*/
public func hideMonitoring() {
self.performanceViewHidden = true
self.performanceView?.hideMonitoring()
}
/**
Stops and removes monitoring view. Call when you're done with performance monitoring.
*/
public func stopMonitoring() {
self.performanceViewStopped = true
self.performanceView?.stopMonitoring()
self.performanceView = nil
}
/**
Use configuration block to change appearance as you like.
*/
public func configure(configuration: (UILabel?) -> Void) {
let textLabel = self.performanceView?.textLabel()
configuration(textLabel)
}
// MARK: Private Methods
// MARK: Default Setups
private func subscribeToNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(GDPerformanceMonitor.applicationDidBecomeActive(notification:)), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(GDPerformanceMonitor.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
}
// MARK: Monitoring
private func startOrResumeMonitoring() {
if self.performanceView == nil {
self.setupPerformanceView()
} else {
self.performanceView?.resumeMonitoring(shouldShowMonitoringView: !self.performanceViewHidden)
}
if UIApplication.shared.applicationState == UIApplicationState.active {
self.performanceView?.addMonitoringViewAboveStatusBar()
}
}
private func setupPerformanceView() {
if self.performanceViewStopped {
return
}
self.performanceView = GDPerformanceView.init()
self.performanceView?.appVersionHidden = self.appVersionHidden
self.performanceView?.deviceVersionHidden = self.deviceVersionHidden
self.performanceView?.performanceDelegate = self.delegate
self.checkAndApplyStatusBarAppearance(prefersStatusBarHidden: self.prefersStatusBarHidden, preferredStatusBarStyle: self.preferredStatusBarStyle)
if self.performanceViewPaused {
self.performanceView?.pauseMonitoring()
}
if self.performanceViewHidden {
self.performanceView?.hideMonitoring()
}
}
// MARK: Other Methods
private func checkAndApplyStatusBarAppearance(prefersStatusBarHidden: Bool, preferredStatusBarStyle: UIStatusBarStyle) {
if self.performanceView?.prefersStatusBarHidden != prefersStatusBarHidden || self.performanceView?.preferredStatusBarStyle != preferredStatusBarStyle {
self.performanceView?.prefersStatusBarHidden = prefersStatusBarHidden
self.performanceView?.preferredStatusBarStyle = preferredStatusBarStyle
self.performanceView?.configureRootViewController()
}
}
}
| mit | c7d292ccfad771f0f49edc0055e2fb67 | 34.398268 | 208 | 0.690106 | 5.828225 | false | false | false | false |
jimmy54/iRime | iRime/Keyboard/tasty-imitation-keyboard/Demo/spi/TypingLabel.swift | 2 | 452 |
import UIKit
class TypingLabel: UILabel {
override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
}
func updateAppearance() {
if candidatesBannerAppearanceIsDark == true {
self.textColor = UIColor.white
} else {
self.textColor = UIColor.darkText
}
}
}
| gpl-3.0 | 919d42429f7c7a65a5f62db0f37d0583 | 22.789474 | 72 | 0.599558 | 4.475248 | false | false | false | false |
benlangmuir/swift | test/attr/attr_convention.swift | 4 | 2105 | // RUN: %target-typecheck-verify-swift
let f1: (Int) -> Int = { $0 }
let f2: @convention(swift) (Int) -> Int = { $0 }
let f2a: @convention(swift, cType: "int *(int)") (Int32) -> Int32 = { $0 } // expected-error{{convention 'swift' does not support the 'cType' argument label, did you mean @convention(c, cType: "int *(int)") or @convention(block, cType: "int *(int)") instead?}}
let f3: @convention(block) (Int) -> Int = { $0 }
let f4: @convention(c) (Int) -> Int = { $0 }
let f4a: @convention(c, cType: "int (int)") (Int32) -> Int32 = { $0 } // expected-error{{unable to parse 'int (int)'; it should be a C function pointer type or a block pointer type}}
let f4b: @convention(c, cType: "void *") (Int32) -> Int32 = { $0 } // expected-error{{unable to parse 'void *'; it should be a C function pointer type or a block pointer type}}
let f4c: @convention(c, cType: "int (*)(int)") (Int32) -> Int32 = { $0 }
let f5: @convention(INTERCAL) (Int) -> Int = { $0 } // expected-error{{convention 'INTERCAL' not supported}}
// https://github.com/apple/swift/issues/53417
do {
func block(_ f: @convention(block) @autoclosure () -> Int) -> Void {} // expected-error {{'@convention(block)' attribute is not allowed on '@autoclosure' types}}
block(1)
func c(_ f: @convention(c) @autoclosure () -> Int) -> Void {} // expected-error{{'@convention(c)' attribute is not allowed on '@autoclosure' types}}
c(1)
func swift(_ f: @convention(swift) @autoclosure () -> Int) -> Void {} // OK
swift(1)
func thin(_ f: @convention(thin) @autoclosure () -> Int) -> Void {} // OK
thin(1)
func block2(_ f: @autoclosure @convention(block) () -> Int) -> Void {} // expected-error {{'@convention(block)' attribute is not allowed on '@autoclosure' types}}
block2(1)
func c2(_ f: @autoclosure @convention(c) () -> Int) -> Void {} // expected-error {{'@convention(c)' attribute is not allowed on '@autoclosure' types}}
c2(1)
func swift2(_ f: @autoclosure @convention(swift) () -> Int) -> Void {} // OK
swift2(1)
func thin2(_ f: @autoclosure @convention(thin) () -> Int) -> Void {} // OK
thin2(1)
}
| apache-2.0 | 9ffab007775aed0bbfd300d0f5cf5bcf | 51.625 | 260 | 0.625178 | 3.189394 | false | false | false | false |
andresilvagomez/Localize | Tests/JSONBadSources.swift | 2 | 1724 | //
// JSONBadSources.swift
// LocalizeTests
//
// Copyright © 2019 @andresilvagomez.
//
import XCTest
import Localize
class JSONBadSources: XCTestCase {
override func setUp() {
super.setUp()
Localize.update(provider: .json)
Localize.update(bundle: Bundle(for: type(of: self)))
Localize.update(language: "en")
Localize.update(defaultLanguage: "rs")
}
func testLocalizeInAnyDictionary() {
let localized = "heymomhowareyoy".localized
XCTAssertEqual(localized, "heymomhowareyoy")
}
func testLocalizeProperty() {
let localized = "hello.world".localized
XCTAssertEqual(localized, "Hello world!")
}
func testLocalizeKey() {
let localized = "hello.world".localize()
XCTAssertEqual(localized, "Hello world!")
}
func testWithTableName() {
let localized = "test.in.table".localize(tableName: "langTable")
XCTAssertEqual(localized, "Test in table name")
}
func testWithBadTableName() {
let localized = "test.in.table".localize(tableName: "langTablesss")
XCTAssertEqual(localized, "test.in.table")
}
func testBadValueForKeyInLevels() {
let localized = "test.in.table".localized
XCTAssertEqual(localized, "test.in.table")
}
func testBadJSONFormat() {
let localized = "test.in.table".localize(tableName: "badJSON")
XCTAssertEqual(localized, "test.in.table")
}
func testNameForLanguage() {
let localized = Localize.displayNameForLanguage("es")
XCTAssertEqual(localized, "Spanish")
}
func testRestDefaultLang() {
Localize.resetLanguage()
XCTAssertTrue(true)
}
}
| mit | d620552b7853f0551f8c3d82cc0255c7 | 25.921875 | 75 | 0.644806 | 4.233415 | false | true | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/General/Intro/IntroViewController.swift | 1 | 2943 | //
// IntroViewController.swift
// Habitica
//
// Created by Phillip Thelen on 31/12/2016.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var endButton: UIButton!
@IBOutlet weak var skipButton: UIButton!
@IBOutlet weak var indicatorStackView: UIStackView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var cardOneTitle: UILabel!
@IBOutlet weak var cardOneText: UILabel!
@IBOutlet weak var cardTwoTitle: UILabel!
@IBOutlet weak var cardTwoSubtitle: UILabel!
@IBOutlet weak var cardTwoText: UILabel!
@IBOutlet weak var cardThreeTitle: UILabel!
@IBOutlet weak var cardThreeSubtitle: UILabel!
@IBOutlet weak var cardThreeText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
populateText()
endButton.isHidden = true
}
func populateText() {
endButton.setTitle(L10n.Intro.letsGo, for: .normal)
skipButton.setTitle(L10n.skip, for: .normal)
cardOneTitle.text = L10n.Intro.Card1.title
cardOneText.text = L10n.Intro.Card1.text
cardTwoTitle.text = L10n.Intro.Card2.title
cardTwoSubtitle.text = L10n.Intro.Card2.subtitle
cardTwoText.text = L10n.Intro.Card2.text
cardThreeTitle.text = L10n.Intro.Card3.title
cardThreeSubtitle.text = L10n.Intro.Card3.subtitle
cardThreeText.text = L10n.Intro.Card3.text
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentPage = getCurrentPage()
updateIndicator(currentPage)
if currentPage == 2 {
skipButton.isHidden = true
endButton.isHidden = false
} else {
skipButton.isHidden = false
endButton.isHidden = true
}
}
func updateIndicator(_ currentPage: Int) {
for (index, element) in indicatorStackView.arrangedSubviews.enumerated() {
if let indicatorView = element as? UIImageView {
if index == currentPage {
indicatorView.image = #imageLiteral(resourceName: "indicatorDiamondSelected")
} else {
indicatorView.image = #imageLiteral(resourceName: "indicatorDiamondUnselected")
}
}
}
}
func getCurrentPage() -> Int {
return Int(scrollView.contentOffset.x / scrollView.frame.size.width)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "LoginSegue" {
if let loginViewController = segue.destination as? LoginTableViewController {
loginViewController.isRootViewController = true
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| gpl-3.0 | 0bc77c0411aa6106574da20b1d5dd842 | 32.431818 | 99 | 0.64446 | 4.73752 | false | false | false | false |
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorStyle.swift | 1 | 28807 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
import YYImage
public class ActorStyle {
//
// Main colors of app
//
/// Is Application have dark theme. Default is false.
public var isDarkApp = false
/// Tint Color. Star button
public var vcStarButton = UIColor(red: 75/255.0, green: 110/255.0, blue: 152/255.0, alpha: 1)
/// Tint Color. Used for "Actions". Default is sytem blue.
public var vcTintColor = UIColor(rgb: 0x5085CB)
/// Color of desctructive actions. Default is red
public var vcDestructiveColor = UIColor.redColor()
/// Default background color
public var vcDefaultBackgroundColor = UIColor.whiteColor()
/// Main Text color of app
public var vcTextColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0)
/// Text Hint colors
public var vcHintColor = UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1)
/// App's main status bar style. Default is light content.
public var vcStatusBarStyle = UIStatusBarStyle.Default
/// UITableView separator color. Also used for other separators or borders.
public var vcSeparatorColor = UIColor(rgb: 0xd4d4d4)
/// Cell Selected color
public var vcSelectedColor = UIColor(rgb: 0xd9d9d9)
/// Header/Footer text color
public var vcSectionColor = UIColor(rgb: 0x5b5a60)
/// Pacgkround of various panels like UITabBar. Default is white.
public var vcPanelBgColor = UIColor.whiteColor()
/// UISwitch off border color
public var vcSwitchOff = UIColor(rgb: 0xe6e6e6)
/// UISwitch on color
public var vcSwitchOn = UIColor(rgb: 0x4bd863)
/// View Controller background color
public var vcBgColor = UIColor.whiteColor()
/// View Controller background color for settings
public var vcBackyardColor = UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1)
//
// UINavigationBar
//
/// Main Navigation bar color
public var navigationBgColor: UIColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1)
/// Main Navigation bar hairline color
public var navigationHairlineHidden = false
/// Navigation Bar icons colors
public var navigationTintColor: UIColor = UIColor(rgb: 0x5085CB)
/// Navigation Bar title color
public var navigationTitleColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0)
/// Navigation Bar subtitle color, default is 0.8 alhpa of navigationTitleColor
public var navigationSubtitleColor: UIColor {
get { return _navigationSubtitleColor != nil ? _navigationSubtitleColor! : navigationTitleColor.alpha(0.8) }
set(v) { _navigationSubtitleColor = v }
}
private var _navigationSubtitleColor: UIColor?
/// Navigation Bar actove subtitle color, default is navigationTitleColor
public var navigationSubtitleActiveColor: UIColor {
get { return _navigationSubtitleActiveColor != nil ? _navigationSubtitleActiveColor! : navigationTitleColor }
set(v) { _navigationSubtitleActiveColor = v }
}
private var _navigationSubtitleActiveColor: UIColor?
//
// Token Field. Used at entering members of new group.
//
/// Token Text Color. Default is vcTextColor.
public var vcTokenFieldTextColor: UIColor {
get { return _vcTokenFieldTextColor != nil ? _vcTokenFieldTextColor! : vcTextColor }
set(v) { _vcTokenFieldTextColor = v }
}
private var _vcTokenFieldTextColor: UIColor?
/// Background Color of Token field. Default is vcBgColor.
public var vcTokenFieldBgColor: UIColor {
get { return _vcTokenFieldBgColor != nil ? _vcTokenFieldBgColor! : vcBgColor }
set(v) { _vcTokenFieldBgColor = v }
}
private var _vcTokenFieldBgColor: UIColor?
/// Token Tint Color. Default is vcTintColor.
public var vcTokenTintColor: UIColor {
get { return _vcTokenTintColor != nil ? _vcTokenTintColor! : vcTintColor }
set(v) { _vcTokenTintColor = v }
}
private var _vcTokenTintColor: UIColor?
//
// Search style
//
/// Style of status bar when search is active.
public var searchStatusBarStyle = UIStatusBarStyle.Default
/// Background Color of search bar
public var searchBackgroundColor: UIColor {
get { return _searchBackgroundColor != nil ? _searchBackgroundColor! : UIColor.whiteColor() }
set(v) { _searchBackgroundColor = v }
}
private var _searchBackgroundColor: UIColor?
/// Cancel button color
public var searchCancelColor: UIColor {
get { return _searchCancelColor != nil ? _searchCancelColor! : vcTintColor }
set(v) { _searchCancelColor = v }
}
private var _searchCancelColor: UIColor?
/// Search Input Field background color
public var searchFieldBgColor = UIColor(rgb: 0xededed)
/// Search Input Field text color
public var searchFieldTextColor = UIColor.blackColor().alpha(0.56)
//
// UITabBarView style
//
/// Selected Text Color of UITabViewItem. Default is vcTintColor.
public var tabSelectedTextColor: UIColor {
get { return _tabSelectedTextColor != nil ? _tabSelectedTextColor! : vcTintColor }
set(v) { _tabSelectedTextColor = v }
}
private var _tabSelectedTextColor: UIColor?
/// Selected Icon Color of UITableViewItem. Default is vcTintColor.
public var tabSelectedIconColor: UIColor {
get { return _tabSelectedIconColor != nil ? _tabSelectedIconColor! : vcTintColor }
set(v) { _tabSelectedIconColor = v }
}
private var _tabSelectedIconColor: UIColor?
/// Unselected Text Color of UITabViewItem. Default is vcHintColor.
public var tabUnselectedTextColor: UIColor {
get { return _tabUnselectedTextColor != nil ? _tabUnselectedTextColor! : vcHintColor }
set(v) { _tabUnselectedTextColor = v }
}
private var _tabUnselectedTextColor: UIColor?
/// Unselected Icon Color of UITableViewItem. Default is vcHintColor.
private var _tabUnselectedIconColor: UIColor?
public var tabUnselectedIconColor: UIColor {
get { return _tabUnselectedIconColor != nil ? _tabUnselectedIconColor! : vcHintColor }
set(v) { _tabUnselectedIconColor = v }
}
/// Background color of UITabBarView. Default is vcPanelBgColor.
private var _tabBgColor: UIColor?
public var tabBgColor: UIColor {
get { return _tabBgColor != nil ? _tabBgColor! : vcPanelBgColor }
set(v) { _tabBgColor = v }
}
//
// Cell View style
//
/// Cell Background color. Default is vcBgColor.
public var cellBgColor: UIColor {
get { return _cellBgColor != nil ? _cellBgColor! : vcBgColor }
set(v) { _cellBgColor = v }
}
private var _cellBgColor: UIColor?
/// Cell Background selected color. Default is vcSelectedColor.
public var cellBgSelectedColor: UIColor {
get { return _cellBgSelectedColor != nil ? _cellBgSelectedColor! : vcSelectedColor }
set(v) { _cellBgSelectedColor = v }
}
private var _cellBgSelectedColor: UIColor?
/// Cell text color. Default is vcTextColor.
public var cellTextColor: UIColor {
get { return _cellTextColor != nil ? _cellTextColor! : vcTextColor }
set(v) { _cellTextColor = v }
}
private var _cellTextColor: UIColor?
/// Cell hint text color. Default is vcHintColor.
public var cellHintColor: UIColor {
get { return _cellHintColor != nil ? _cellHintColor! : vcHintColor }
set(v) { _cellHintColor = v }
}
private var _cellHintColor: UIColor?
/// Cell action color. Default is vcTintColor.
public var cellTintColor: UIColor {
get { return _cellTintColor != nil ? _cellTintColor! : vcTintColor }
set(v) { _cellTintColor = v }
}
private var _cellTintColor: UIColor?
/// Cell desctructive color. Default is vcDestructiveColor.
public var cellDestructiveColor: UIColor {
get { return _cellDestructiveColor != nil ? _cellDestructiveColor! : vcDestructiveColor }
set(v) { _cellDestructiveColor = v }
}
private var _cellDestructiveColor: UIColor?
/// Section header color. Default is vcSectionColor.
public var cellHeaderColor: UIColor {
get { return _cellHeaderColor != nil ? _cellHeaderColor! : vcSectionColor }
set(v) { _cellHeaderColor = v }
}
private var _cellHeaderColor: UIColor?
/// Section footer color. Default is vcSectionColor.
public var cellFooterColor: UIColor {
get { return _cellFooterColor != nil ? _cellFooterColor! : vcSectionColor }
set(v) { _cellFooterColor = v }
}
private var _cellFooterColor: UIColor?
//
// Full screen placeholder style
//
/// Big Placeholder background color
public var placeholderBgColor: UIColor {
get { return _placeholderBgColor != nil ? _placeholderBgColor! : navigationBgColor.fromTransparentBar() }
set(v) { _placeholderBgColor = v }
}
private var _placeholderBgColor: UIColor?
/// Big placeholder title color
public var placeholderTitleColor: UIColor {
get { return _placeholderTitleColor != nil ? _placeholderTitleColor! : vcTextColor }
set(v) { _placeholderTitleColor = v }
}
private var _placeholderTitleColor: UIColor?
/// Bit Placeholder hint color
public var placeholderHintColor: UIColor {
get { return _placeholderHintColor != nil ? _placeholderHintColor! : vcHintColor }
set(v) { _placeholderHintColor = v }
}
private var _placeholderHintColor: UIColor?
//
// Avatar Placeholder and name colors
//
public var avatarTextColor = UIColor.whiteColor()
public var avatarLightBlue = UIColor(rgb: 0x59b7d3)
public var nameLightBlue = UIColor(rgb: 0x59b7d3)
public var avatarDarkBlue = UIColor(rgb: 0x1d4e6f)
public var nameDarkBlue = UIColor(rgb: 0x1d4e6f)
public var avatarPurple = UIColor(rgb: 0x995794)
public var namePurple = UIColor(rgb: 0x995794)
public var avatarPink = UIColor(rgb: 0xff506c)
public var namePink = UIColor(rgb: 0xff506c)
public var avatarOrange = UIColor(rgb: 0xf99341)
public var nameOrange = UIColor(rgb: 0xf99341)
public var avatarYellow = UIColor(rgb: 0xe4d027)
public var nameYellow = UIColor(rgb: 0xe4d027)
public var avatarGreen = UIColor(rgb: 0xe4d027)
public var nameGreen = UIColor(rgb: 0xe4d027)
private var _avatarColors: [UIColor]?
public var avatarColors: [UIColor] {
get {
if _avatarColors == nil {
return [
avatarLightBlue,
avatarDarkBlue,
avatarPurple,
avatarPink,
avatarOrange,
avatarYellow,
avatarGreen
]
} else {
return _avatarColors!
}
}
set(v) { _avatarColors = v }
}
private var _nameColors: [UIColor]?
public var nameColors: [UIColor] {
get {
if _nameColors == nil {
return [
nameLightBlue,
nameDarkBlue,
namePurple,
namePink,
nameOrange,
nameYellow,
nameGreen
]
} else {
return _nameColors!
}
}
set(v) { _nameColors = v }
}
//
// Bubble styles
//
// Text colors
private var _chatTextColor: UIColor?
public var chatTextColor: UIColor {
get { return _chatTextColor != nil ? _chatTextColor! : vcTextColor }
set(v) { _chatTextColor = v }
}
private var _chatUrlColor: UIColor?
public var chatUrlColor: UIColor {
get { return _chatUrlColor != nil ? _chatUrlColor! : vcTintColor }
set(v) { _chatUrlColor = v }
}
private var _chatTextUnsupportedColor: UIColor?
public var chatTextUnsupportedColor: UIColor {
get { return _chatTextUnsupportedColor != nil ? _chatTextUnsupportedColor! : vcTintColor.alpha(0.54) }
set(v) { _chatTextUnsupportedColor = v }
}
private var _chatTextOutColor: UIColor?
public var chatTextOutColor: UIColor {
get { return _chatTextOutColor != nil ? _chatTextOutColor! : chatTextColor }
set(v) { _chatTextOutColor = v }
}
private var _chatTextInColor: UIColor?
public var chatTextInColor: UIColor {
get { return _chatTextInColor != nil ? _chatTextInColor! : chatTextColor }
set(v) { _chatTextInColor = v }
}
private var _chatTextOutUnsupportedColor: UIColor?
public var chatTextOutUnsupportedColor: UIColor {
get { return _chatTextOutUnsupportedColor != nil ? _chatTextOutUnsupportedColor! : chatTextUnsupportedColor }
set(v) { _chatTextOutUnsupportedColor = v }
}
private var _chatTextInUnsupportedColor: UIColor?
public var chatTextInUnsupportedColor: UIColor {
get { return _chatTextInUnsupportedColor != nil ? _chatTextInUnsupportedColor! : chatTextUnsupportedColor }
set(v) { _chatTextInUnsupportedColor = v }
}
public var chatDateTextColor = UIColor.whiteColor()
public var chatServiceTextColor = UIColor.whiteColor()
public var chatUnreadTextColor = UIColor.whiteColor()
// Date colors
public var chatTextDateOutColor = UIColor.alphaBlack(0.27)
public var chatTextDateInColor = UIColor(rgb: 0x979797)
public var chatMediaDateColor = UIColor.whiteColor()
public var chatMediaDateBgColor = UIColor(rgb: 0x2D394A, alpha: 0.54)
// Bubble Colors
public var chatTextBubbleOutColor = UIColor(rgb: 0xD2FEFD)
public var chatTextBubbleOutSelectedColor = UIColor.lightGrayColor()
public var chatTextBubbleOutBorderColor = UIColor(rgb: 0x99E4E3)
public var chatTextBubbleInColor = UIColor.whiteColor()
public var chatTextBubbleInSelectedColor = UIColor.blueColor()
public var chatTextBubbleInBorderColor = UIColor(rgb: 0xCCCCCC)
public var chatMediaBubbleColor = UIColor.whiteColor()
public var chatMediaBubbleBorderColor = UIColor(rgb: 0xCCCCCC)
public var chatDateBubbleColor = UIColor(rgb: 0x2D394A, alpha: 0.56)
public var chatServiceBubbleColor = UIColor(rgb: 0x2D394A, alpha: 0.56)
public var chatUnreadBgColor = UIColor.alphaBlack(0.3)
public var chatReadMediaColor = UIColor(red: 46.6/255.0, green: 211.3/255.0, blue: 253.6/255.0, alpha: 1.0)
// Status Colors
public lazy var chatIconCheck1 = UIImage.templated("msg_check_1")
public lazy var chatIconCheck2 = UIImage.templated("msg_check_2")
public lazy var chatIconError = UIImage.templated("msg_error")
public lazy var chatIconWarring = UIImage.templated("msg_warring")
public lazy var chatIconClock = UIImage.templated("msg_clock")
private var _chatStatusActive: UIColor?
public var chatStatusActive: UIColor {
get { return _chatStatusActive != nil ? _chatStatusActive! : vcTintColor }
set(v) { _chatStatusActive = v }
}
private var _chatStatusPassive: UIColor?
public var chatStatusPassive: UIColor {
get { return _chatStatusPassive != nil ? _chatStatusPassive! : vcHintColor }
set(v) { _chatStatusPassive = v }
}
private var _chatStatusDanger: UIColor?
public var chatStatusDanger: UIColor {
get { return _chatStatusDanger != nil ? _chatStatusDanger! : vcDestructiveColor }
set(v) { _chatStatusDanger = v }
}
private var _chatStatusMediaActive: UIColor?
public var chatStatusMediaActive: UIColor {
get { return _chatStatusMediaActive != nil ? _chatStatusMediaActive! : chatReadMediaColor }
set(v) { _chatStatusMediaActive = v }
}
private var _chatStatusMediaPassive: UIColor?
public var chatStatusMediaPassive: UIColor {
get { return _chatStatusMediaPassive != nil ? _chatStatusMediaPassive! : UIColor.whiteColor() }
set(v) { _chatStatusMediaPassive = v }
}
private var _chatStatusMediaDanger: UIColor?
public var chatStatusMediaDanger: UIColor {
get { return _chatStatusMediaDanger != nil ? _chatStatusMediaDanger! : chatStatusDanger }
set(v) { _chatStatusMediaDanger = v }
}
private var _chatStatusSending: UIColor?
public var chatStatusSending: UIColor {
get { return _chatStatusSending != nil ? _chatStatusSending! : chatStatusPassive }
set(v) { _chatStatusSending = v }
}
private var _chatStatusSent: UIColor?
public var chatStatusSent: UIColor {
get { return _chatStatusSent != nil ? _chatStatusSent! : chatStatusPassive }
set(v) { _chatStatusSent = v }
}
private var _chatStatusReceived: UIColor?
public var chatStatusReceived: UIColor {
get { return _chatStatusReceived != nil ? _chatStatusReceived! : chatStatusPassive }
set(v) { _chatStatusReceived = v }
}
private var _chatStatusRead: UIColor?
public var chatStatusRead: UIColor {
get { return _chatStatusRead != nil ? _chatStatusRead! : chatStatusActive }
set(v) { _chatStatusRead = v }
}
private var _chatStatusError: UIColor?
public var chatStatusError: UIColor {
get { return _chatStatusError != nil ? _chatStatusError! : chatStatusDanger }
set(v) { _chatStatusError = v }
}
private var _chatStatusMediaSending: UIColor?
public var chatStatusMediaSending: UIColor {
get { return _chatStatusMediaSending != nil ? _chatStatusMediaSending! : chatStatusMediaPassive }
set(v) { _chatStatusMediaSending = v }
}
private var _chatStatusMediaSent: UIColor?
public var chatStatusMediaSent: UIColor {
get { return _chatStatusMediaSent != nil ? _chatStatusMediaSent! : chatStatusMediaPassive }
set(v) { _chatStatusMediaSent = v }
}
private var _chatStatusMediaReceived: UIColor?
public var chatStatusMediaReceived: UIColor {
get { return _chatStatusMediaReceived != nil ? _chatStatusMediaReceived! : chatStatusMediaPassive }
set(v) { _chatStatusMediaReceived = v }
}
private var _chatStatusMediaRead: UIColor?
public var chatStatusMediaRead: UIColor {
get { return _chatStatusMediaRead != nil ? _chatStatusMediaRead! : chatStatusMediaActive }
set(v) { _chatStatusMediaRead = v }
}
private var _chatStatusMediaError: UIColor?
public var chatStatusMediaError: UIColor {
get { return _chatStatusMediaError != nil ? _chatStatusMediaError! : chatStatusMediaDanger }
set(v) { _chatStatusMediaError = v }
}
// Chat screen
private var _chatInputField: UIColor?
public var chatInputFieldBgColor: UIColor {
get { return _chatInputField != nil ? _chatInputField! : vcPanelBgColor }
set(v) { _chatInputField = v }
}
private var _chatAttachColor: UIColor?
public var chatAttachColor: UIColor {
get { return _chatAttachColor != nil ? _chatAttachColor! : vcTintColor }
set(v) { _chatAttachColor = v }
}
private var _chatSendColor: UIColor?
public var chatSendColor: UIColor {
get { return _chatSendColor != nil ? _chatSendColor! : vcTintColor }
set(v) { _chatSendColor = v }
}
private var _chatSendDisabledColor: UIColor?
public var chatSendDisabledColor: UIColor {
get { return _chatSendDisabledColor != nil ? _chatSendDisabledColor! : vcTintColor.alpha(0.64) }
set(v) { _chatSendDisabledColor = v }
}
private var _chatAutocompleteHighlight: UIColor?
public var chatAutocompleteHighlight: UIColor {
get { return _chatAutocompleteHighlight != nil ? _chatAutocompleteHighlight! : vcTintColor }
set(v) { _chatAutocompleteHighlight = v }
}
public lazy var chatBgColor = UIColor(patternImage: UIImage.bundled("chat_bg")!)
//
// Dialogs styles
//
private var _dialogTitleColor: UIColor?
public var dialogTitleColor: UIColor {
get { return _dialogTitleColor != nil ? _dialogTitleColor! : vcTextColor }
set(v) { _dialogTitleColor = v }
}
private var _dialogTextColor: UIColor?
public var dialogTextColor: UIColor {
get { return _dialogTextColor != nil ? _dialogTextColor! : dialogTitleColor.alpha(0.64) }
set(v) { _dialogTextColor = v }
}
private var _dialogTextActiveColor: UIColor?
public var dialogTextActiveColor: UIColor {
get { return _dialogTextActiveColor != nil ? _dialogTextActiveColor! : vcTextColor }
set(v) { _dialogTextActiveColor = v }
}
private var _dialogDateColor: UIColor?
public var dialogDateColor: UIColor {
get { return _dialogDateColor != nil ? _dialogDateColor! : vcHintColor }
set(v) { _dialogDateColor = v }
}
public var dialogCounterBgColor: UIColor = UIColor(rgb: 0x50A1D6)
public var dialogCounterColor: UIColor = UIColor.whiteColor()
private var _dialogStatusActive: UIColor?
public var dialogStatusActive: UIColor {
get { return _dialogStatusActive != nil ? _dialogStatusActive! : chatStatusActive }
set(v) { _dialogStatusActive = v }
}
private var _dialogStatusPassive: UIColor?
public var dialogStatusPassive: UIColor {
get { return _dialogStatusPassive != nil ? _dialogStatusPassive! : chatStatusPassive }
set(v) { _dialogStatusPassive = v }
}
private var _dialogStatusDanger: UIColor?
public var dialogStatusDanger: UIColor {
get { return _dialogStatusDanger != nil ? _dialogStatusDanger! : chatStatusDanger }
set(v) { _dialogStatusDanger = v }
}
private var _dialogStatusSending: UIColor?
public var dialogStatusSending: UIColor {
get { return _dialogStatusSending != nil ? _dialogStatusSending! : dialogStatusPassive }
set(v) { _dialogStatusSending = v }
}
private var _dialogStatusSent: UIColor?
public var dialogStatusSent: UIColor {
get { return _dialogStatusSent != nil ? _dialogStatusSent! : dialogStatusPassive }
set(v) { _dialogStatusSent = v }
}
private var _dialogStatusReceived: UIColor?
public var dialogStatusReceived: UIColor {
get { return _dialogStatusReceived != nil ? _dialogStatusReceived! : dialogStatusPassive }
set(v) { _dialogStatusReceived = v }
}
private var _dialogStatusRead: UIColor?
public var dialogStatusRead: UIColor {
get { return _dialogStatusRead != nil ? _dialogStatusRead! : dialogStatusActive }
set(v) { _dialogStatusRead = v }
}
private var _dialogStatusError: UIColor?
public var dialogStatusError: UIColor {
get { return _dialogStatusError != nil ? _dialogStatusError! : dialogStatusDanger }
set(v) { _dialogStatusError = v }
}
private var _statusBackgroundIcon: UIImage?
public var statusBackgroundImage:UIImage {
get {
if (_statusBackgroundIcon == nil){
let statusImage:UIImage = UIImage.bundled("bubble_service_bg")!.aa_imageWithColor(UIColor.blackColor().colorWithAlphaComponent(0.7)).imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
let center:CGPoint = CGPointMake(statusImage.size.width / 2.0, statusImage.size.height / 2.0);
let capInsets:UIEdgeInsets = UIEdgeInsetsMake(center.y, center.x, center.y, center.x);
_statusBackgroundIcon = statusImage.resizableImageWithCapInsets(capInsets, resizingMode: UIImageResizingMode.Stretch)
return _statusBackgroundIcon!
} else {
return _statusBackgroundIcon!
}
}
}
//
// Contacts styles
//
private var _contactTitleColor: UIColor?
public var contactTitleColor: UIColor {
get { return _contactTitleColor != nil ? _contactTitleColor! : vcTextColor }
set(v) { _contactTitleColor = v }
}
//
// Online styles
//
private var _userOnlineColor: UIColor?
public var userOnlineColor: UIColor {
get { return _userOnlineColor != nil ? _userOnlineColor! : vcTintColor }
set(v) { _userOnlineColor = v }
}
private var _userOfflineColor: UIColor?
public var userOfflineColor: UIColor {
get { return _userOfflineColor != nil ? _userOfflineColor! : vcTextColor.alpha(0.54) }
set(v) { _userOfflineColor = v }
}
private var _userOnlineNavigationColor: UIColor?
public var userOnlineNavigationColor: UIColor {
get { return _userOnlineNavigationColor != nil ? _userOnlineNavigationColor! : userOnlineColor }
set(v) { _userOnlineNavigationColor = v }
}
private var _userOfflineNavigationColor: UIColor?
public var userOfflineNavigationColor: UIColor {
get { return _userOfflineNavigationColor != nil ? _userOfflineNavigationColor! : navigationSubtitleColor }
set(v) { _userOfflineNavigationColor = v }
}
//
// Compose styles
//
private var _composeAvatarBgColor: UIColor?
public var composeAvatarBgColor: UIColor {
get { return _composeAvatarBgColor != nil ? _composeAvatarBgColor! : vcBgColor }
set(v) { _composeAvatarBgColor = v }
}
private var _composeAvatarBorderColor: UIColor?
public var composeAvatarBorderColor: UIColor {
get { return _composeAvatarBorderColor != nil ? _composeAvatarBorderColor! : vcSeparatorColor }
set(v) { _composeAvatarBorderColor = v }
}
private var _composeAvatarTextColor: UIColor?
public var composeAvatarTextColor: UIColor {
get { return _composeAvatarTextColor != nil ? _composeAvatarTextColor! : vcHintColor }
set(v) { _composeAvatarTextColor = v }
}
//
// Status Bar progress
//
/// Is Status Bar connecting status hidden
public var statusBarConnectingHidden = false
/// Is Status Bar background color
private var _statusBarConnectingBgColor : UIColor?
public var statusBarConnectingBgColor: UIColor {
get { return _statusBarConnectingBgColor != nil ? _statusBarConnectingBgColor! : navigationBgColor }
set(v) { _statusBarConnectingBgColor = v }
}
/// Is Status Bar background color
private var _statusBarConnectingTextColor : UIColor?
public var statusBarConnectingTextColor: UIColor {
get { return _statusBarConnectingTextColor != nil ? _statusBarConnectingTextColor! : navigationTitleColor }
set(v) { _statusBarConnectingTextColor = v }
}
//
// Welcome
//
/// Welcome Page Background color
public var welcomeBgColor = UIColor(red: 94, green: 142, blue: 192)
/// Welcome Page Background image
public var welcomeBgImage: UIImage? = nil
/// Welcome Page Title Color
public var welcomeTitleColor = UIColor.whiteColor()
/// Welcome Page Tagline Color
public var welcomeTaglineColor = UIColor.whiteColor()
/// Welcome Page Signup Background Color
public var welcomeSignupBgColor = UIColor.whiteColor()
/// Welcome Page Signup Text Color
public var welcomeSignupTextColor = UIColor(red: 94, green: 142, blue: 192)
/// Welcome Page Login Text Color
public var welcomeLoginTextColor = UIColor.whiteColor()
/// Welcome Logo
public var welcomeLogo: UIImage? = UIImage.bundled("logo_welcome")
public var welcomeLogoSize: CGSize = CGSize(width: 90, height: 90)
public var logoViewVerticalGap: CGFloat = 145
//
// Auth Screen
//
public var authTintColor = UIColor(rgb: 0x007aff)
public var authTitleColor = UIColor.blackColor().alpha(0.87)
public var authHintColor = UIColor.alphaBlack(0.64)
public var authTextColor = UIColor.alphaBlack(0.87)
public var authSeparatorColor = UIColor.blackColor().alpha(0.2)
//
// Settings VC
//
public var vcSettingsContactsHeaderTextColor: UIColor {
get { return _vcSettingsContactsHeaderTextColor != nil ? _vcSettingsContactsHeaderTextColor! : vcTextColor }
set(v) { _vcSettingsContactsHeaderTextColor = v }
}
private var _vcSettingsContactsHeaderTextColor : UIColor?
}
| agpl-3.0 | c2ce7e1d9c8aa6bc7b26a0e9ed36b10d | 36.754915 | 208 | 0.657653 | 4.389304 | false | false | false | false |
FirebaseExtended/firebase-video-samples | fundamentals/apple/gettingstarted/final/Favourites/Shared/FavouriteNumberView.swift | 1 | 2218 | //
// FavouriteNumberView.swift
// Shared
//
// Created by Peter Friese on 05.07.22.
// Copyright © 2022 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import SwiftUI
import Combine
import FirebaseAnalytics
import FirebaseAnalyticsSwift
class FavouriteNumberViewModel: ObservableObject {
@Published var favouriteNumber = 42
private var defaults = UserDefaults.standard
private let favouriteNumberKey = "favouriteNumber"
private var cancellables = Set<AnyCancellable>()
init() {
if let number = defaults.object(forKey: favouriteNumberKey) as? Int {
favouriteNumber = number
}
$favouriteNumber
.sink { number in
self.defaults.set(number, forKey: self.favouriteNumberKey)
Analytics.logEvent("stepper", parameters: ["value" : number])
}
.store(in: &cancellables)
}
}
struct FavouriteNumberView: View {
@StateObject var viewModel = FavouriteNumberViewModel()
var body: some View {
VStack {
Text("What's your favourite number?")
.font(.title)
.multilineTextAlignment(.center)
Spacer()
Stepper(value: $viewModel.favouriteNumber, in: 0...100) {
Text("\(viewModel.favouriteNumber)")
}
}
.frame(maxHeight: 150)
.foregroundColor(.white)
.padding()
#if os(iOS)
.background(Color(UIColor.systemPink))
#endif
.clipShape(RoundedRectangle(cornerRadius: 16))
.padding()
.shadow(radius: 8)
.navigationTitle("Favourite Number")
.analyticsScreen(name: "\(FavouriteNumberView.self)")
}
}
struct FavouriteNumberView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
FavouriteNumberView()
}
}
}
| apache-2.0 | 0aa44ec658724c4f0c3e36489180c3ec | 27.792208 | 75 | 0.698692 | 4.364173 | false | false | false | false |
rock3r/androidtool-mac | AndroidTool/Device.swift | 1 | 3355 | //
// Device.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/22/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol DeviceDelegate{
//
}
enum DeviceType:String {
case Phone="Phone", Watch="Watch", Tv="Tv", Auto="Auto"
}
class Device: NSObject {
var model : String? // Nexus 6
var name : String? // Shamu
var manufacturer : String? // Motorola
var type: DeviceType?
var brand: String? // google
var serial: String?
var properties: [String:String]?
var firstBoot : NSTimeInterval?
var firstBootString : NSString?
var adbIdentifier : String?
var isEmulator : Bool = false
var displayHeight : Int?
var resolution : (width:Double, height:Double)?
convenience init(properties:[String:String], adbIdentifier:String) {
self.init()
self.adbIdentifier = adbIdentifier.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
model = properties["ro.product.model"]
name = properties["ro.product.name"]
manufacturer = properties["ro.product.manufacturer"]
brand = properties["ro.product.brand"]
firstBootString = properties["ro.runtime.firstboot"]
firstBoot = firstBootString?.doubleValue
if let deviceSerial = properties["ro.serialno"]{
serial = deviceSerial
} else {
isEmulator = true
serial = adbIdentifier
}
if let characteristics = properties["ro.build.characteristics"] {
if characteristics.rangeOfString("watch") != nil {
type = DeviceType.Watch
} else {
type = DeviceType.Phone
}
}
ShellTasker(scriptFile: "getResolutionForSerial").run(arguments: ["\(self.serial!)"], isUserScript: false) { (output) -> Void in
let res = output as! String
if res.rangeOfString("Physical size:") != nil {
self.resolution = self.getResolutionFromString(output as! String)
} else {
println("Awkward. No size found. What I did find was \(res)")
}
}
}
func readableIdentifier() -> String {
if let modelString = model {
return modelString
} else if let nameString = name {
return nameString
} else if let manufacturerString = manufacturer {
return manufacturerString
} else if let serialString = serial {
return serialString
} else {
return "Android device"
}
}
func getResolutionFromString(string:String) -> (width:Double, height:Double) {
let re = NSRegularExpression(pattern: "Physical size: (.*)x(.*)", options: nil, error: nil)!
let matches = re.matchesInString(string, options: nil, range: NSRange(location: 0, length: count(string.utf16)))
let result = matches[0] as! NSTextCheckingResult
let width:NSString = (string as NSString).substringWithRange(result.rangeAtIndex(1))
let height:NSString = (string as NSString).substringWithRange(result.rangeAtIndex(2))
return (width:width.doubleValue, height:height.doubleValue)
}
}
| apache-2.0 | 0f06ca36d9cc2bcaf20c58fd62492624 | 33.234694 | 136 | 0.605663 | 4.820402 | false | false | false | false |
jiaxw32/ZRSwiftKit | ZRSwiftKit/UI/ZRPlaceholderTextView.swift | 1 | 5918 | //
// ZRPlaceholderTextView.swift
// ZRSwiftKit
//
// Created by jiaxw-mac on 2017/9/10.
// Copyright © 2017年 jiaxw32. All rights reserved.
//
import UIKit
class ZRPlaceholderTextView: UITextView{
// MARK: - init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
initialize()
}
// MARK: - deinit
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name.UITextViewTextDidChange, object: nil)
}
//MARK: - override attributes
override var text: String! {
didSet {
if self.text != oldValue {
setNeedsDisplay()
}
}
}
override var attributedText: NSAttributedString! {
didSet {
if self.attributedText != oldValue {
setNeedsDisplay()
}
}
}
override var font: UIFont? {
didSet{
setNeedsDisplay()
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
//MARK: - custom attribute
var placeholder: String? {
get {
return attributedPlaceholder?.string
}
set {
guard let newPlaceholder = newValue else { return }
guard newPlaceholder != attributedPlaceholder?.string else {
return
}
var attributes = [String: Any]()
if isFirstResponder {
attributes = typingAttributes
} else {
attributes[NSFontAttributeName] = font
attributes[NSForegroundColorAttributeName] = UIColor.init(white: 0.702, alpha: 1.0)
if textAlignment != NSTextAlignment.left {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = textAlignment
attributes[NSParagraphStyleAttributeName] = paragraph
}
}
self.attributedPlaceholder = NSAttributedString(string: newPlaceholder, attributes: attributes)
}
}
var attributedPlaceholder: NSAttributedString? {
didSet{
setNeedsDisplay()
}
}
var maxCount: UInt? {
didSet{
setNeedsDisplay()
}
}
var maxCountTextAttribute: [String:Any]? {
didSet{
setNeedsDisplay()
}
}
//MARK: - override method
override func insertText(_ text: String) {
super.insertText(text)
setNeedsDisplay()
}
override func layoutSubviews() {
super.layoutSubviews()
if text.characters.count == 0 && attributedPlaceholder != nil {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
super.draw(rect)
if text.characters.count == 0 && attributedPlaceholder != nil {
let placeholderRect = placeholderRectForBounds(bounds: rect)
attributedPlaceholder!.draw(in: placeholderRect)
}
if maxCount != nil {
if maxCountTextAttribute == nil {
var attributes = [String: Any]()
attributes[NSFontAttributeName] = font
attributes[NSForegroundColorAttributeName] = UIColor.init(white: 0.702, alpha: 1.0)
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .right
attributes[NSParagraphStyleAttributeName] = paragraph
maxCountTextAttribute = attributes
}
let maxCountAttributeString = NSAttributedString(string: "\(text.characters.count)/\(maxCount!)", attributes: maxCountTextAttribute)
maxCountAttributeString.draw(in: self.maxCountRectForBounds(bounds: rect))
}
}
//MARK: - custom method
private func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var rect = UIEdgeInsetsInsetRect(bounds, contentInset)
if self.responds(to: #selector(getter: textContainer)) {
rect = UIEdgeInsetsInsetRect(rect, self.textContainerInset)
let padding = textContainer.lineFragmentPadding
rect.origin.x += padding
rect.size.width -= 2 * padding
} else {
if contentInset.left == 0 {
rect.origin.x += 6.0
}
}
return rect
}
func maxCountRectForBounds(bounds: CGRect) -> CGRect {
let padding: CGFloat = 16
let font = maxCountTextAttribute![NSFontAttributeName] as? UIFont
let fontSize = font?.pointSize ?? 16
let y = bounds.size.height - padding - fontSize + contentOffset.y
let width = bounds.size.width - padding * 2
return CGRect(x: padding, y: y, width: width, height: fontSize)
}
func initialize() -> Void {
NotificationCenter.default.addObserver(self, selector: #selector(textChanged(notification:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
}
func textChanged(notification: Notification) -> Void {
if maxCount != nil && UInt(text.characters.count) > maxCount! {
let startIndex = text.startIndex
let lastIndex = text.index(text.startIndex, offsetBy: Int(maxCount!))
text = text[startIndex..<lastIndex]
}
setNeedsDisplay()
}
}
| mit | f2f0e908646fd9be53bf0e13f4b7fd6f | 27.713592 | 165 | 0.559087 | 5.682037 | false | false | false | false |
mikaoj/EnigmaKit | Sources/EnigmaKit/Reflector.swift | 1 | 2257 | // The MIT License (MIT)
//
// Copyright (c) 2017 Joakim Gyllström
//
// 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
public struct Reflector {
public var name: String
private var wheel: Wheel
public init(name: String, wiring: String) {
self.name = name
self.wheel = try! Wheel(inner: Array(wiring))
}
}
extension Reflector {
public static var A: Reflector {
return Reflector(name: "A", wiring: "EJMZALYXVBWFCRQUONTSPIKHGD")
}
public static var B: Reflector {
return Reflector(name: "B (wide)", wiring: "YRUHQSLDPXNGOKMIEBFZCWVJAT")
}
public static var C: Reflector {
return Reflector(name: "C (wide)", wiring: "FVPJIAOYEDRZXWGCTKUQSBNMHL")
}
public static var BThin: Reflector {
return Reflector(name: "B (thin)", wiring: "ENKQAUYWJICOPBLMDXZVFTHRGS")
}
public static var CThin: Reflector {
return Reflector(name: "C (thin)", wiring: "RDOBJNTKVEHMLFCWZAXGYIPSUQ")
}
}
extension Reflector {
func encode(_ character: Character) -> Character {
return wheel.encode(character)
}
}
extension Reflector: Equatable {
public static func ==(lhs: Reflector, rhs: Reflector) -> Bool {
return lhs.name == rhs.name && lhs.wheel == rhs.wheel
}
}
| mit | 68a8afa1eae4fd76e8489bb5a4b5978f | 32.671642 | 81 | 0.726507 | 3.728926 | false | false | false | false |
HongxiangShe/STV | STV/STV/Classes/Home/Controller/HomeViewController.swift | 1 | 2946 | //
// HomeViewController.swift
// STV
//
// Created by 佘红响 on 2017/6/16.
// Copyright © 2017年 she. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension HomeViewController {
fileprivate func setupUI() {
setupNavigationBar()
setupContentView()
}
fileprivate func setupNavigationBar() {
let logoImage = UIImage(named: "home-logo")
navigationItem.leftBarButtonItem = UIBarButtonItem(image: logoImage, style: .plain, target: nil, action: nil)
let collectImage = UIImage(named: "search_btn_follow")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: collectImage, style: .plain, target: self, action: #selector(collectItemClick))
let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
searchBar.placeholder = "主播昵称/房间号/链接";
navigationItem.titleView = searchBar
searchBar.searchBarStyle = .minimal
let searchField = searchBar.value(forKey: "_searchField") as! UITextField
searchField.textColor = UIColor.white
navigationController?.navigationBar.barTintColor = UIColor.black
}
fileprivate func setupContentView() {
automaticallyAdjustsScrollViewInsets = false;
let typeArr = loadTypeDatas()
var style = SHXPageStyle()
style.isShowCover = true
style.isScrollEnabel = true
style.normalColor = UIColor(r: 40, g: 40, b: 40)
let frame = CGRect(x: 0, y: kNavigationBarH + kStatusBarH, width: kScreenW, height: kScreenH - kNavigationBarH - kStatusBarH - style.titleHeight)
/*
let titles = typeArr.map { (type: HomeType) -> String in
return type.title
}
*/
let titles = typeArr.map({ $0.title })
var childVcs = [AnchorViewController]()
for type in typeArr {
let child = AnchorViewController()
child.homeType = type
childVcs.append(child)
}
let pageView = SHXPageView(frame: frame, titles: titles, style: style, childVcs: childVcs, parentVc: self)
view.addSubview(pageView)
}
// 从plist中加载数据
fileprivate func loadTypeDatas() -> [HomeType] {
let path = Bundle.main.path(forResource: "types.plist", ofType: nil)!
let arr = NSArray(contentsOfFile: path) as! [[String : Any]]
var typeArr = [HomeType]()
for dict in arr {
typeArr.append(HomeType(dict))
}
return typeArr
}
}
extension HomeViewController {
@objc fileprivate func collectItemClick() {
HXPrint("点击了收藏按钮")
}
}
| apache-2.0 | f3678e73e4bf55ecbf510416b962f3ae | 28.222222 | 153 | 0.601797 | 4.805648 | false | false | false | false |
pyanfield/ataturk_olympic | swift_programming_classes_structures.playground/section-1.swift | 1 | 2744 | // Playground - noun: a place where people can play
import UIKit
// 2.9
/*
类和结构体的共同点:
Define properties to store values
Define methods to provide functionality
Define subscripts to provide access to their values using subscript syntax
Define initializers to set up their initial state
Be extended to expand their functionality beyond a default implementation
Conform to protocols to provide standard functionality of a certain kind”
类相对结构体来说还具有:
Inheritance enables one class to inherit the characteristics of another.
Type casting enables you to check and interpret the type of a class instance at runtime.
Deinitializers enable an instance of a class to free up any resources it has assigned.
Reference counting allows more than one reference to a class instance.
*/
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String? // 默认值为 nil
}
let someResolution = Resolution() // 设置默认值
let vga = Resolution(width:640, height: 480)
let someVideoMode = VideoMode()
// 在 Swift 中,所有的基本类型:整数(Integer)、浮点数(floating-point)、布尔值(Booleans)、字符串(string)、数组(array)和字典(dictionaries),都是值类型,
// 并且都是以结构体的形式在后台所实现。结构体和枚举也是值类型。
// 类是引用类型,引用类型在被赋予到一个变量、常量或者被传递到一个函数时,操作的是引用,其并不是拷贝。
// 如果能够判定两个常量或者变量是否引用同一个类实例将会很有帮助。为了达到这个目的,Swift 内建了两个恒等运算符:
// 等价于 ( === ) : 两个类类型(class type)的常量或者变量引用同一个类实例。
// 不等价于 ( !== )
// 一个 Swift 常量或者变量引用一个引用类型的实例与 C 语言中的指针类似,不同的是并不直接指向内存中的某个地址,而且也不要求你使用星号(*)来表明你在创建一个引用。
// Swift 中这些引用与其它的常量或变量的定义方式相同。
/*
按照通用的准则,当符合一条或多条以下条件时,请考虑构建结构体:
结构体的主要目的是用来封装少量相关简单数据值。
有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。
任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。
结构体不需要去继承另一个已存在类型的属性或者行为。
*/ | mit | 301a85464c1dd338540e3e6b72248631 | 33.134615 | 112 | 0.748591 | 3.085217 | false | false | false | false |
powerytg/Accented | Accented/UI/Home/HomeStreamViewController.swift | 1 | 2182 | //
// HomeStreamViewController.swift
// Accented
//
// Created by Tiangong You on 5/2/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class HomeStreamViewController: StreamViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Events
NotificationCenter.default.addObserver(self, selector: #selector(appThemeDidChange(_:)), name: ThemeManagerEvents.appThemeDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func createViewModel() {
let viewModelClass = ThemeManager.sharedInstance.currentTheme.streamViewModelClass
viewModel = viewModelClass.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: self)
}
// MARK: - UICollectionViewDelegateFlowLayout
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
// Section 0 is reserved for stream headers
return CGSize.zero
} else {
return CGSize(width: collectionView.bounds.width, height: 8)
}
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 0 {
return CGSize.zero
}
return CGSize(width: collectionView.bounds.width, height: 26)
}
// MARK: - Events
func appThemeDidChange(_ notification : Notification) {
let viewModelClass = ThemeManager.sharedInstance.currentTheme.streamViewModelClass
viewModel = viewModelClass.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: self)
viewModel?.delegate = self
collectionView.dataSource = viewModel
viewModel!.updateCollectionView(true)
}
}
| mit | 0fb8c4c012f3f5de904e0b8f9a575ebe | 34.754098 | 179 | 0.690967 | 5.635659 | false | false | false | false |
ggu/2D-RPG-Template | Borba/UI/HUD/ResourceBar.swift | 2 | 1346 | //
// HealthBar.swift
// Borba
//
// Created by Gabriel Uribe on 8/2/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
import SpriteKit
class ResourceBar: SKSpriteNode {
var resourceMeter: SKSpriteNode = SKSpriteNode(texture: nil, color: UIColor.greenColor(), size: CGSize(width: 192, height: 14))
init(width: CGFloat, height: CGFloat, xPosition: CGFloat, color: UIColor) {
super.init(texture: nil, color: Color.resourceFrame, size: CGSize(width: 200, height: 16))
setup(width, height: height, xPosition: xPosition, color: color)
}
private func setup(width: CGFloat, height: CGFloat, xPosition: CGFloat, color: UIColor) {
let yPos = height - size.height / 2
position = CGPoint(x: xPosition, y: yPos)
zPosition = 10
resourceMeter.anchorPoint = CGPoint(x: 0, y: 0)
resourceMeter.color = color
resourceMeter.position = CGPoint(x: -96, y: -6)
addChild(resourceMeter)
}
func setMeterScaleAnimated(scale: CGFloat) {
if resourceMeter.xScale > scale {
resourceMeter.xScale = 0
}
let animateX = SKAction.scaleXTo(scale, duration: 0.05)
resourceMeter.runAction(animateX)
}
func setMeterScale(scale: Double) {
resourceMeter.xScale = CGFloat(scale)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | 32723c2941cf9416d72284e24d999b4d | 28.911111 | 129 | 0.68425 | 3.718232 | false | false | false | false |
myteeNatanwit/webview5 | webview5/my_functions.swift | 1 | 3477 | //
// my_functions.swift
// swift_bridge
//
// Created by Michael Tran on 8/10/2015.
// Copyright © 2015 intcloud. All rights reserved.
//
import Foundation
import UIKit
import SystemConfiguration
let bridge_theme = "bridge";
var myrecord = (function:"", param:"");
func process_scheme(url: String) -> (String, String) {
var functionName = "";
var param = "";
let urlString = url;
let theme_length = bridge_theme.characters.count + 1; // take away the :
//delete first 7 chars
let str = urlString.substringFromIndex(urlString.startIndex.advancedBy(theme_length));
//look for the ? char
let needle: Character = "?";
//if it is not nul -> found
if let idx = str.characters.indexOf(needle) {
//the pos of it from 1
let pos = str.startIndex.distanceTo(idx);
//how many char for the param
let count_back = str.characters.count - pos;
//take only whatever before the ?
functionName = str.substringToIndex(str.endIndex.advancedBy(-1 * count_back));
//take the whole param string
param=str.substringFromIndex(str.endIndex.advancedBy(-1 * count_back));
//delete the '?param=' part, it is 7 character length
param=param.substringFromIndex(param.startIndex.advancedBy(7));
//remove the uuencode for space
param = param.stringByReplacingOccurrencesOfString("%20",
withString: " ",
options: NSStringCompareOptions.LiteralSearch,
range: param.startIndex..<param.endIndex)
}
else {
functionName = urlString.substringFromIndex(urlString.startIndex.advancedBy(7));
}
print("function = " + functionName + "\n" + "param= '" + param + "'");
return (functionName, param);
}
// pop message or notify depending to active mode.
func pop_message(my_message: String) {
var window: UIWindow?
// Show an alert if application is active
if UIApplication.sharedApplication().applicationState == .Active {
alert("", message: my_message);
} else {
// Otherwise present a local notification
let notification = UILocalNotification()
notification.alertBody = my_message;
notification.soundName = "Default";
UIApplication.sharedApplication().presentLocalNotificationNow (notification)
}
}
// usage : alert("network", message: "alive");
func alert (title: String, message: String) {
let myalert = UIAlertView();
myalert.title = title;
myalert.message = message;
myalert.addButtonWithTitle("OK");
myalert.show();
}
// string class
extension String {
var lastPathComponent: String {
get {
return (self as NSString).lastPathComponent
}
}
var pathExtension: String {
get {
return (self as NSString).pathExtension
}
}
var stringByDeletingLastPathComponent: String {
get {
return (self as NSString).stringByDeletingLastPathComponent
}
}
var stringByDeletingPathExtension: String {
get {
return (self as NSString).stringByDeletingPathExtension
}
}
var pathComponents: [String] {
get {
return (self as NSString).pathComponents
}
}
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
func stringByAppendingPathExtension(ext: String) -> String? {
let nsSt = self as NSString
return nsSt.stringByAppendingPathExtension(ext)
}
} // string extention
| mit | 9205bb768a759c6aca4ca41541ff936b | 25.945736 | 90 | 0.671174 | 4.467866 | false | false | false | false |
zapdroid/RXWeather | Weather/AddLocationViewController.swift | 1 | 3323 | //
// AddLocationViewController.swift
// Weather
//
// Created by Boran ASLAN on 13/05/2017.
// Copyright © 2017 Boran ASLAN. All rights reserved.
//
import UIKit
import MapKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class AddLocationViewController: BaseViewController {
// MARK: - Outlets
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var closeButton: UIButton!
// MARK: - Properties
var userLocation: CLLocation = CLLocation(latitude: 0, longitude: 0)
// MARK: - Dependencies
// MARK: - Init
override func initDependencies() {
super.initDependencies()
presenter = initPresenter()
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
configureMapView()
}
// MARK: - Configure
func configureMapView() {
mapView.showsUserLocation = true
let regionRadius = 100
let coordinateRegion = MKCoordinateRegionMakeWithDistance(userLocation.coordinate, CLLocationDistance(regionRadius), CLLocationDistance(regionRadius))
mapView.setRegion(coordinateRegion, animated: true)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(addAnnotationOnLongPress(gesture:)))
longPressGesture.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPressGesture)
}
// MARK: - Observe
override func subscribeViewTap() {
super.subscribeViewTap()
_ = compositeDisposable.insert(observeCloseButtonTap())
}
// MARK: - Actions
func addAnnotationOnLongPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
let point = gesture.location(in: mapView)
let coordinate = mapView.convert(point, toCoordinateFrom: mapView)
let alert = UIAlertController(title: "add_location_new_location_title".localized, message: "add_location_new_location_message".localized, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "no".localized, style: UIAlertActionStyle.destructive, handler: nil))
alert.addAction(UIAlertAction(title: "add_location_new_location_yes".localized, style: UIAlertActionStyle.default, handler: { _ in
self.presenter.saveBookmark(coordinate: coordinate)
self.dismiss(animated: true, completion: nil)
}))
present(alert, animated: true, completion: nil)
}
}
func observeCloseButtonTap() -> Disposable {
return closeButton.rx.tap
.asDriver()
.drive(onNext: { _ in
self.dismiss(animated: true, completion: nil)
})
}
}
// MARK: - Extensions
extension AddLocationViewController {
var presenter: AddLocationPresenter {
set {
basePresenter = newValue
}
get {
if let presenter = basePresenter as? AddLocationPresenter {
return presenter
}
return initPresenter()
}
}
fileprivate func initPresenter() -> AddLocationPresenter {
let interactor = AddLocationInteractor(coreDataService: CoreDataService.sharedInstance)
return AddLocationPresenter(interactor: interactor)
}
}
| mit | a8327f7b97cab28c5eafe06833e908d4 | 27.886957 | 195 | 0.659843 | 5.150388 | false | false | false | false |
MotivatedCreation/JPSTextKit | JPSLayoutManager.swift | 1 | 2037 | //
// JPSLayoutManager.swift
//
// Created by Jonathan Sullivan on 6/20/17.
//
import Foundation
open class JPSTextContainer: NSTextContainer {
public weak var containerView: UIView?
}
open class JPSLayoutManager: NSLayoutManager
{
override open func drawGlyphs(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint)
{
super.drawGlyphs(forGlyphRange: glyphsToShow, at: origin)
guard let textStorage = self.textStorage else { return }
if textStorage.containsAttachments(in: glyphsToShow)
{
let characterRange = self.characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)
textStorage.enumerateAttribute(NSAttachmentAttributeName, in: characterRange, options: [], using: { (value, range, stop) in
guard let textAttachment = value as? JPSTextAttachment else { return }
let glyphRange = self.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
self.draw(textAttachment: textAttachment, at: origin, forGlyphAt: glyphRange.location)
})
}
}
}
extension JPSLayoutManager
{
internal func draw(textAttachment: JPSTextAttachment, at origin: CGPoint, forGlyphAt glyphIndex: Int)
{
guard let textContainer = self.textContainer(forGlyphAt: glyphIndex, effectiveRange: nil, withoutAdditionalLayout: true) as? JPSTextContainer else { return }
guard let containerView = textContainer.containerView else { return }
let glyphRange = NSRange(location: glyphIndex, length: 0)
let attachmentSize = self.attachmentSize(forGlyphAt: glyphIndex)
var boundingRect = self.boundingRect(forGlyphRange: glyphRange, in: textContainer)
boundingRect.origin.x += origin.x
boundingRect.origin.y += origin.y
let frame = CGRect(origin: boundingRect.origin, size: attachmentSize)
textAttachment.draw(frame: frame, in: containerView)
}
}
| gpl-3.0 | 34ea6424320d0630ed7794e1c51b6850 | 37.433962 | 165 | 0.680412 | 5.017241 | false | false | false | false |
Verchen/Swift-Project | JinRong/JinRong/Classes/Main(主控制器)/BaseNavigationController.swift | 1 | 1387 | //
// BaseNavigationController.swift
// JinRong
//
// Created by 乔伟成 on 2017/7/12.
// Copyright © 2017年 乔伟成. All rights reserved.
//
import UIKit
class BaseNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
navigationBar.setBackgroundImage(UIImage.colorImage(color: .theme), for: .default)
navigationBar.shadowImage = UIImage.colorImage(color: .clear)
navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white, NSFontAttributeName : UIFont.boldSystemFont(ofSize: 20)]
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if childViewControllers.count > 0 {
viewController.hidesBottomBarWhenPushed = true
let item = UIBarButtonItem(image: #imageLiteral(resourceName: "back_white").withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(BaseNavigationController.pop))
viewController.navigationItem.leftBarButtonItem = item
self.interactivePopGestureRecognizer?.delegate = viewController as? UIGestureRecognizerDelegate
}
super.pushViewController(viewController, animated: animated)
}
func pop() -> Void {
self.popViewController(animated: true)
}
}
| mit | 7ecc5fb9931029f39132d6ee596906f7 | 34.179487 | 200 | 0.697522 | 5.380392 | false | false | false | false |
zhanggaoqiang/SwiftLearn | Swift语法/Swift构造过程/Swift构造过程/main.swift | 1 | 8992 | //
// main.swift
// Swift构造过程
//
// Created by zgq on 16/4/22.
// Copyright © 2016年 zgq. All rights reserved.
//
import Foundation
//Swift构造过程是为了使用某个类,结构体或者枚举类型的实例而进行的准备过程,这个过程包含了为实例中的每个属性
//设置初始值和为其执行必要的准备和初始化任务
//Swift中构造函数用init()方法
//与OC构造器不同,Swift构造器无需返回值,它们的主要任务是保证实例在第一次使用前完成正确的初始化
//类实例也可以通过定义析构器在类实例释放之前执行清理内存的工作
//以下结构体定义一个不带参数的构造器init,并在里面将存储性属性length和breadth的值初始化为6和12
struct rectangle {
var length:Double=0;
var breadth:Double = 0
init() {
length=6
breadth=12;
}
}
var area = rectangle()
print("矩形的面积 \(area.length*area.breadth)")
//moren默认属性值,同样也可以在属性声明时为其设置默认值
struct rectangle1 {
var length = 6
var breadth = 12
}
var area1 = rectangle()
print("矩形的面积 \(area1.length*area1.breadth)")
//构造参数
//你可以在定义构造器init()时提供构造参数
struct rectangle2 {
var length:Double=0
var breadth:Double = 0
var area:Double = 0
init(fromLength length:Double,fromeBreadth breadth:Double){
self.length=length
self.breadth=breadth
area=length*breadth
}
}
let ar = rectangle2(fromLength: 6, fromeBreadth: 12)
print("面积为: \(ar.area)")
//内部和外部参数名
//跟函数和方法参数相同,构造函数也存在一个在构造器内部使用的参数名字和一个在调用构造器时使用的外部参数名字
//构造器并不像函数和方法那样在括号前有一个可以辨别的名字。所以在调用构造器时,主要通过构造器中参数名和类型来确定需要调用的构造器
//如果你在定义构造器时没有提供参数的外部名字,Swift会为每个构造器的参数自动生成一个跟内部名字相同的外部名
struct Color {
let red,green,blue:Double
init(red:Double,green:Double,blue:Double) {
self.red = red
self.green=green
self.blue=blue
}
init(white:Double){
red=white
green=white
blue=white
}
}
//创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器
let magenta = Color(red:1.0,green:0.0,blue:1.0)
print("red 值为:\(magenta.red)")
print("green 值为:\(magenta.green)")
print("blue 值为:\(magenta.blue)")
//创建一个新的Color实例,通过三种颜色的外部参数名来传值,并调用构造器
let halfGray = Color(white:0.5)
print("red 值为:\(halfGray.red)")
print("green 值为:\(halfGray.green)")
print("blue 值为:\(halfGray.blue)")
//没有外部名称参数
//如果你不希望为构造器的某个参数提供外部名字,你可以使用下划线来现实和描述它的外部名
struct Rectangle3 {
var length:Double
init(frombreadth breadth:Double) {
length=breadth*10
}
init(frombre bre:Double) {
length=bre * 30
}
//不提供外部名字
init(_ area:Double){
length = area
}
}
//调用不提供外部名字
let rectarea3=Rectangle3(180.0)
print("面积为:\(rectarea3.length)")
//调用提供外部名字
let rectarea4=Rectangle3(frombreadth:30)
print("调用外部名字:\(rectarea4.length)")
//可选属性设置
//如果你定制的类型包含一个逻辑上允许取值为空的存储型属性,,你都需要将它定义为可选属性optional type(可选属性类型)
//当存储属性声明为可选时,将自动初始化为空nil
struct Rectangle4{
var length:Double?
init(frombreadth breadth:Double){
length=breadth * 10
}
init(fromble bre:Double) {
length = bre * 30
}
init(_ area:Double){
length = area
}
}
let rect1 = Rectangle4(180.0)
print("面积:\(rect1.length)")
//构造过程中修改常量属性
//只要在构造过程结束前常量的值能确定,你可以再构造过程中的任意时间点修改常量属性的值
//对某个类实例来说,它的常量属性只能在定义它的的类的构造过程中秀发,不能在子类中修改
//尽管length属性是常量,我们仍然可以在其类的构造器中设置它的值
struct recttangle5 {
let length:Double?
init(frombreadth breadth:Double){
length = breadth * 10
}
init(frombre bre:Double){
length = bre * 20
}
init(_ area:Double){
length = area
}
}
let rect5 = recttangle5(180.0)
print("面积为:\(rect5.length)")
//默认构造器
//默认构造器将简单的创建一个所有属性值都设置为默认值的实例
//以下实例中,ShoppingList类中的所有属性都有默认值,它是没有父类的基类,它将自动获得一个可以为所有属性值的默认构造器
class ShoppingListItem {
var name :String?
var quantity = 1
var purchase = false
}
var item = ShoppingListItem()
print("名字为:\(item.name)")
//结构体的逐一成员构造器
//如果结构体对所有存储行属性提供了默认值且自身没有提供定制的构造器,它们能自动获得一个逐一成员构造器
//我们在调用逐一成员构造器时,通过与成员属性名相同的参数名进行传值来完成对成员属性的初始赋值
//由于这两个存储性属性都有默认值,结构体自动获得了一个逐一成员构造器init(width:height).你可以用它为结构欧体创建新的实例
struct Rectangle6 {
var length = 100.0,breadth=200.0
}
let area6 = Rectangle6(length: 24.0,breadth: 32.0)
print("矩形的面积:\(area6.length)")
//值类型的构造器代理
//构造器可以通过调用其它构造器来完成实例的部分构造过程。这个过程成为构造器代理,它能减少多个构造器间的代码重复
//struct Size {
// var width = 0.0,height = 0.0
//
//
//}
//struct Point {
// var x = 0.0,y = 0.0
//
//}
//
//struct Rect7 {
// var original = Point()
// var size = Size()
// init(){
//
// }
//
// init(original:Point,size:Size) {
// self.original=original
// self.size=size
// }
//
// init(center:Point,size:Size){
// let originX = center.x-(size.width/2)
// let originY = center.y-(size.height/2)
// self.init()
//
//
// }
//
//
//
//
//}
//
//构造器的继承和重载:
/*
Swift中子类不会默认继承父类的构造器
父类的构造器仅在确定和安全的情况下被继承
当你重写一个父类指定构造器时,你需要写override修饰符
*/
class SuperClass{
var corners = 4
var description :String {
return "\(corners) 边"
}
}
let rectangle8 = SuperClass()
print("矩形:\(rectangle8.description)")
class SubClass: SuperClass {
override init() {
super.init()
corners = 5
}
}
let subClass = SubClass()
print("五角型:\(subClass.description)")
//指定构造器和便利构造器实例:
/*
接下来的例子将在操作中展示指定构造器,便利构造器和自动构造器的继承
它定义了包含两个类MainClass,SubClass的类层次结构,并将演示它们的构造器是如何相互作用的
*/
/*
构造器链:
为了简化指定构造器和便利构造器之间的调用关系,Swift采用以下三条规则来限制构造器之间的代理调用:
规则1:指定构造器必须调用其直接父类的指定构造器
规则2:便利构造器必须调用同一类中定义的其它构造器
规则3:便利构造器必须最终以调用一个指定构造器结束
一个更方便记忆的方法是:
指定构造器必须总是向上代理
便利构造器必须总是横向代理
*/
class MainClass {
var name:String
init(name:String){
self.name = name
}
convenience init() {
self.init(name:"[匿名]")
}
}
let main = MainClass(name:"Runoob")
print("MainClass 名字为: \(main.name)")
let main2 = MainClass()
print("没有对应名字:\(main2.name)")
class SubClass8: MainClass {
var count:Int
init(name:String,count:Int){
self.count = count
super.init(name: name)
}
override convenience init(name: String) {
self.init(name:name,count: 1)
}
}
let sub8 = SubClass8(name:"Runoob")
print("MainClass 名字为:\(sub8.name)")
let sub9 = SubClass8(name:"Runoob",count:3)
print("count 变量: \(sub9.count)")
| mit | f763510fe6d34544460ea662917af0ad | 14.325871 | 70 | 0.638046 | 2.69628 | false | false | false | false |
johnno1962d/swift | test/stmt/statements.swift | 1 | 12530 | // RUN: %target-parse-verify-swift
/* block comments */
/* /* nested too */ */
func markUsed<T>(_ t: T) {}
func f1(_ a: Int, _ y: Int) {}
func f2() {}
func f3() -> Int {}
func invalid_semi() {
; // expected-error {{';' statements are not allowed}} {{3-5=}}
}
func nested1(_ x: Int) {
var y : Int
func nested2(_ z: Int) -> Int {
return x+y+z
}
nested2(1)
}
func funcdecl5(_ a: Int, y: Int) {
var x : Int
// a few statements
if (x != 0) {
if (x != 0 || f3() != 0) {
// while with and without a space after it.
while(true) { 4; 2; 1 }
while (true) { 4; 2; 1 }
}
}
// Assignment statement.
x = y
(x) = y
1 = x // expected-error {{cannot assign to a literal value}}
(1) = x // expected-error {{cannot assign to a literal value}}
(x:1).x = 1 // expected-error {{cannot assign to immutable expression of type 'Int'}}
var tup : (x:Int, y:Int)
tup.x = 1
_ = tup
let B : Bool
// if/then/else.
if (B) {
} else if (y == 2) {
}
// FIXME: This diagnostic is terrible - rdar://12939553
if x {} // expected-error {{type 'Int' does not conform to protocol 'Boolean'}}
if true {
if (B) {
} else {
}
}
if (B) {
f1(1,2)
} else {
f2()
}
if (B) {
if (B) {
f1(1,2)
} else {
f2()
}
} else {
f2()
}
// while statement.
while (B) {
}
// It's okay to leave out the spaces in these.
while(B) {}
if(B) {}
}
struct infloopbool {
var boolValue: infloopbool {
return self
}
}
func infloopbooltest() {
if (infloopbool()) {} // expected-error {{type 'infloopbool' does not conform to protocol 'Boolean'}}
}
// test "builder" API style
extension Int {
static func builder() -> Int { }
var builderProp: Int { return 0 }
func builder2() {}
}
Int
.builder()
.builderProp
.builder2()
struct SomeGeneric<T> {
static func builder() -> SomeGeneric<T> { }
var builderProp: SomeGeneric<T> { return .builder() }
func builder2() {}
}
SomeGeneric<Int>
.builder()
.builderProp
.builder2()
break // expected-error {{'break' is only allowed inside a loop, if, do, or switch}}
continue // expected-error {{'continue' is only allowed inside a loop}}
while true {
func f() {
break // expected-error {{'break' is only allowed inside a loop}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
// Labeled if
MyIf: if 1 != 2 {
break MyIf
continue MyIf // expected-error {{'continue' cannot be used with if statements}}
break // break the while
continue // continue the while.
}
}
// Labeled if
MyOtherIf: if 1 != 2 {
break MyOtherIf
continue MyOtherIf // expected-error {{'continue' cannot be used with if statements}}
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if}}
continue // expected-error {{'continue' is only allowed inside a loop}}
}
do {
break // expected-error {{unlabeled 'break' is only allowed inside a loop or switch, a labeled break is required to exit an if or do}}
}
func tuple_assign() {
var a,b,c,d : Int
(a,b) = (1,2)
func f() -> (Int,Int) { return (1,2) }
((a,b), (c,d)) = (f(), f())
}
func missing_semicolons() {
var w = 321
func g() {}
g() w += 1 // expected-error{{consecutive statements}} {{6-6=;}}
var z = w"hello" // expected-error{{consecutive statements}} {{12-12=;}}
class C {}class C2 {} // expected-error{{consecutive statements}} {{14-14=;}}
struct S {}struct S2 {} // expected-error{{consecutive statements}} {{14-14=;}}
func j() {}func k() {} // expected-error{{consecutive statements}} {{14-14=;}}
}
//===--- Return statement.
return 42 // expected-error {{return invalid outside of a func}}
return // expected-error {{return invalid outside of a func}}
func NonVoidReturn1() -> Int {
return // expected-error {{non-void function should return a value}}
}
func NonVoidReturn2() -> Int {
return + // expected-error {{unary operator cannot be separated from its operand}} {{11-1=}} expected-error {{expected expression in 'return' statement}}
}
func VoidReturn1() {
if true { return }
// Semicolon should be accepted -- rdar://11344875
return; // no-error
}
func VoidReturn2() {
return () // no-error
}
func VoidReturn3() {
return VoidReturn2() // no-error
}
//===--- If statement.
func IfStmt1() {
if 1 > 0 // expected-error {{expected '{' after 'if' condition}}
_ = 42
}
func IfStmt2() {
if 1 > 0 {
} else // expected-error {{expected '{' after 'else'}}
_ = 42
}
//===--- While statement.
func WhileStmt1() {
while 1 > 0 // expected-error {{expected '{' after 'while' condition}}
_ = 42
}
//===-- Do statement.
func DoStmt() {
// This is just a 'do' statement now.
do {
}
}
func DoWhileStmt() {
do { // expected-error {{'do-while' statement is not allowed; use 'repeat-while' instead}} {{3-5=repeat}}
} while true
}
//===--- Repeat-while statement.
func RepeatWhileStmt1() {
repeat {} while true
repeat {} while false
repeat { break } while true
repeat { continue } while true
}
func RepeatWhileStmt2() {
repeat // expected-error {{expected '{' after 'repeat'}} expected-error {{expected 'while' after body of 'repeat' statement}}
}
func RepeatWhileStmt4() {
repeat {
} while + // expected-error {{unary operator cannot be separated from its operand}} {{12-1=}} expected-error {{expected expression in 'repeat-while' condition}}
}
func brokenSwitch(_ x: Int) -> Int {
switch x {
case .Blah(var rep): // expected-error{{enum case 'Blah' not found in type 'Int'}}
return rep
}
}
func switchWithVarsNotMatchingTypes(_ x: Int, y: Int, z: String) -> Int {
switch (x,y,z) {
case (let a, 0, _), (0, let a, _): // OK
return a
case (let a, _, _), (_, _, let a): // expected-error {{pattern variable bound to type 'String', expected type 'Int'}}
return a
}
}
func breakContinue(_ x : Int) -> Int {
Outer:
for _ in 0...1000 {
Switch:
switch x {
case 42: break Outer
case 97: continue Outer
case 102: break Switch
case 13: continue
case 139: break // <rdar://problem/16563853> 'break' should be able to break out of switch statements
}
}
// <rdar://problem/16692437> shadowing loop labels should be an error
Loop: // expected-note {{previously declared here}}
for _ in 0...2 {
Loop: // expected-error {{label 'Loop' cannot be reused on an inner statement}}
for _ in 0...2 {
}
}
// <rdar://problem/16798323> Following a 'break' statement by another statement on a new line result in an error/fit-it
switch 5 {
case 5:
markUsed("before the break")
break
markUsed("after the break") // 'markUsed' is not a label for the break.
default:
markUsed("")
}
let x : Int? = 42
// <rdar://problem/16879701> Should be able to pattern match 'nil' against optionals
switch x {
case .some(42): break
case nil: break
}
}
enum MyEnumWithCaseLabels {
case Case(one: String, two: Int)
}
func testMyEnumWithCaseLabels(_ a : MyEnumWithCaseLabels) {
// <rdar://problem/20135489> Enum case labels are ignored in "case let" statements
switch a {
case let .Case(one: _, two: x): break // ok
case let .Case(xxx: _, two: x): break // expected-error {{tuple pattern element label 'xxx' must be 'one'}}
// TODO: In principle, reordering like this could be supported.
case let .Case(two: _, one: x): break // expected-error {{tuple pattern element label}}
}
}
// "defer"
func test_defer(_ a : Int) {
defer { VoidReturn1() }
defer { breakContinue(1)+42 }
// Ok:
defer { while false { break } }
// Not ok.
while false { defer { break } } // expected-error {{'break' cannot transfer control out of a defer statement}}
defer { return } // expected-error {{'return' cannot transfer control out of a defer statement}}
}
class SomeTestClass {
var x = 42
func method() {
defer { x = 97 } // self. not required here!
}
}
func test_require(_ x : Int, y : Int??, cond : Bool) {
// These are all ok.
guard let a = y else {}
markUsed(a)
guard let b = y where cond else {}
guard case let c = x where cond else {}
guard case let Optional.some(d) = y else {}
guard x != 4, case _ = x else { }
guard let e where cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard case let f? : Int? where cond else {} // expected-error {{variable binding in a condition requires an initializer}}
guard let g = y else {
markUsed(g) // expected-error {{variable declared in 'guard' condition is not usable in its body}}
}
guard let h = y where cond {} // expected-error {{expected 'else' after 'guard' condition}}
guard case _ = x else {} // expected-warning {{'guard' condition is always true, body is unreachable}}
}
func test_is_as_patterns() {
switch 4 {
case is Int: break // expected-warning {{'is' test is always true}}
case _ as Int: break // expected-warning {{'as' test is always true}}
case _: break
}
}
// <rdar://problem/21387308> Fuzzing SourceKit: crash in Parser::parseStmtForEach(...)
func matching_pattern_recursion() {
switch 42 {
case { // expected-error {{expression pattern of type '() -> ()' cannot match values of type 'Int'}}
for i in zs {
}
}: break
}
}
// <rdar://problem/18776073> Swift's break operator in switch should be indicated in errors
func r18776073(_ a : Int?) {
switch a {
case nil: // expected-error {{'case' label in a 'switch' should have at least one executable statement}} {{14-14= break}}
case _?: break
}
}
// <rdar://problem/22491782> unhelpful error message from "throw nil"
func testThrowNil() throws {
throw nil // expected-error {{cannot infer concrete ErrorProtocol for thrown 'nil' value}}
}
// rdar://problem/23684220
// Even if the condition fails to typecheck, save it in the AST anyway; the old
// condition may have contained a SequenceExpr.
func r23684220(_ b: Any) {
if let _ = b ?? b {} // expected-error {{initializer for conditional binding must have Optional type, not 'Any' (aka 'protocol<>')}}
}
// <rdar://problem/21080671> QoI: try/catch (instead of do/catch) creates silly diagnostics
func f21080671() {
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
} catch { }
try { // expected-error {{the 'do' keyword is used to specify a 'catch' region}} {{3-6=do}}
f21080671()
} catch let x as Int {
} catch {
}
}
// <rdar://problem/24467411> QoI: Using "&& #available" should fixit to comma
// https://twitter.com/radexp/status/694561060230184960
func f(_ x : Int, y : Int) {
if x == y && #available(iOS 52, *) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{13-15=,}}
if #available(iOS 52, *) && x == y {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{28-30=,}}
// https://twitter.com/radexp/status/694790631881883648
if x == y && let _ = Optional(y) {} // expected-error {{expected ',' joining parts of a multi-clause condition}} {{13-15=,}}
}
// <rdar://problem/25178926> QoI: Warn about cases where switch statement "ignores" where clause
enum Type {
case Foo
case Bar
}
func r25178926(_ a : Type) {
switch a {
case .Foo, .Bar where 1 != 100:
// expected-warning @-1 {{'where' only applies to the second pattern match in this case}}
// expected-note @-2 {{disambiguate by adding a line break between them if this is desired}} {{14-14=\n }}
// expected-note @-3 {{duplicate the 'where' on both patterns to check both patterns}} {{12-12= where 1 != 100}}
break
}
switch a {
case .Foo: break
case .Bar where 1 != 100: break
}
switch a {
case .Foo, // no warn
.Bar where 1 != 100:
break
}
switch a {
case .Foo where 1 != 100, .Bar where 1 != 100:
break
}
}
// Errors in case syntax
class
case, // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{expected pattern}}
case // expected-error {{expected identifier after comma in enum 'case' declaration}} expected-error {{expected identifier in enum 'case' declaration}} expected-error {{enum 'case' is not allowed outside of an enum}} expected-error {{expected pattern}}
// NOTE: EOF is important here to properly test a code path that used to crash the parser
| apache-2.0 | ae412a422b3716e806e652d30d9cfe52 | 25.323529 | 253 | 0.623304 | 3.510787 | false | false | false | false |
rolson/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Display information/Show legend/MILShowLegendViewController.swift | 1 | 3742 | // Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class MILShowLegendViewController: UIViewController, UIAdaptivePresentationControllerDelegate {
@IBOutlet private weak var mapView:AGSMapView!
@IBOutlet private weak var legendBBI:UIBarButtonItem!
private var map:AGSMap!
private var mapImageLayer:AGSArcGISMapImageLayer!
private var popover:UIPopoverPresentationController!
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["MILShowLegendViewController", "MILLegendTableViewController"]
//initialize the map
self.map = AGSMap(basemap: AGSBasemap.topographicBasemap())
//create tiled layer
let tiledLayer = AGSArcGISTiledLayer(URL: NSURL(string: "https://services.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer")!)
self.map.operationalLayers.addObject(tiledLayer)
//create a map image layer using a url
self.mapImageLayer = AGSArcGISMapImageLayer(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer")!)
//add the image layer to the map
self.map.operationalLayers.addObject(self.mapImageLayer)
//create feature table using a url
let featureTable = AGSServiceFeatureTable(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0")!)
//create feature layer using this feature table
let featureLayer = AGSFeatureLayer(featureTable: featureTable)
//add feature layer to the map
self.map.operationalLayers.addObject(featureLayer)
self.map.loadWithCompletion { [weak self] (error:NSError?) -> Void in
if error == nil {
self?.legendBBI.enabled = true
}
}
self.mapView.map = self.map
//zoom to a custom viewpoint
self.mapView.setViewpointCenter(AGSPoint(x: -11e6, y: 6e6, spatialReference: AGSSpatialReference.webMercator()), scale: 9e7, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "LegendTableSegue" {
let controller = segue.destinationViewController as! MILLegendTableViewController
controller.presentationController?.delegate = self
controller.preferredContentSize = CGSize(width: 300, height: 200)
controller.operationalLayers = self.map.operationalLayers
}
}
//MARK: - UIAdaptivePresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return UIModalPresentationStyle.None
}
}
| apache-2.0 | 8e0a8c0e82f41a02c6cdf56a6a6f74c1 | 43.023529 | 163 | 0.704169 | 5.009371 | false | false | false | false |
crspybits/SyncServerII | Sources/Server/Controllers/FileController/FileController+DownloadFile.swift | 1 | 9555 | //
// FileController+DownloadFile.swift
// Server
//
// Created by Christopher Prince on 3/22/17.
//
//
import Foundation
import LoggerAPI
import SyncServerShared
import Kitura
extension FileController {
func downloadFile(params:RequestProcessingParameters) {
guard let downloadRequest = params.request as? DownloadFileRequest else {
let message = "Did not receive DownloadFileRequest"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard sharingGroupSecurityCheck(sharingGroupUUID: downloadRequest.sharingGroupUUID, params: params) else {
let message = "Failed in sharing group security check."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
// TODO: *0* What would happen if someone else deletes the file as we we're downloading it? It seems a shame to hold a lock for the entire duration of the download, however.
// TODO: *0* Related question: With transactions, if we just select from a particular row (i.e., for the master version for this user, as immediately below) does this result in a lock for the duration of the transaction? We could test for this by sleeping in the middle of the download below, and seeing if another request could delete the file at the same time. This should make a good test case for any mechanism that I come up with.
Controllers.getMasterVersion(sharingGroupUUID: downloadRequest.sharingGroupUUID, params: params) { (error, masterVersion) in
if error != nil {
params.completion(.failure(.message("\(error!)")))
return
}
if masterVersion != downloadRequest.masterVersion {
let response = DownloadFileResponse()
Log.warning("Master version update: \(String(describing: masterVersion))")
response.masterVersionUpdate = masterVersion
params.completion(.success(response))
return
}
// Need to get the file from the cloud storage service:
// First, lookup the file in the FileIndex. This does an important security check too-- make sure the fileUUID is in the sharing group.
let key = FileIndexRepository.LookupKey.primaryKeys(sharingGroupUUID: downloadRequest.sharingGroupUUID, fileUUID: downloadRequest.fileUUID)
let lookupResult = params.repos.fileIndex.lookup(key: key, modelInit: FileIndex.init)
var fileIndexObj:FileIndex?
switch lookupResult {
case .found(let modelObj):
fileIndexObj = modelObj as? FileIndex
if fileIndexObj == nil {
let message = "Could not convert model object to FileIndex"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
case .noObjectFound:
let message = "Could not find file in FileIndex"
Log.error(message)
params.completion(.failure(.message(message)))
return
case .error(let error):
let message = "Error looking up file in FileIndex: \(error)"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard downloadRequest.fileVersion == fileIndexObj!.fileVersion else {
let message = "Expected file version \(String(describing: downloadRequest.fileVersion)) was not the same as the actual version \(String(describing: fileIndexObj!.fileVersion))"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard downloadRequest.appMetaDataVersion == fileIndexObj!.appMetaDataVersion else {
let message = "Expected app meta data version \(String(describing: downloadRequest.appMetaDataVersion)) was not the same as the actual version \(String(describing: fileIndexObj!.appMetaDataVersion))"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
if fileIndexObj!.deleted! {
let message = "The file you are trying to download has been deleted!"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
// TODO: *5*: Eventually, this should bypass the middle man and stream from the cloud storage service directly to the client.
// Both the deviceUUID and the fileUUID must come from the file index-- They give the specific name of the file in cloud storage. The deviceUUID of the requesting device is not the right one.
guard let deviceUUID = fileIndexObj!.deviceUUID else {
let message = "No deviceUUID!"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
let cloudFileName = fileIndexObj!.cloudFileName(deviceUUID:deviceUUID, mimeType: fileIndexObj!.mimeType)
// OWNER
// The cloud storage for the file is the original owning user's storage.
guard let owningUserCreds = FileController.getCreds(forUserId: fileIndexObj!.userId, from: params.db, delegate: params.accountDelegate) else {
let message = "Could not obtain owning users creds"
Log.error(message)
params.completion(.failure(.message(message)))
return
}
guard let cloudStorageCreds = owningUserCreds.cloudStorage,
let cloudStorageType = owningUserCreds.accountScheme.cloudStorageType else {
let message = "Could not obtain cloud storage creds or cloud storage type."
Log.error(message)
params.completion(.failure(.message(message)))
return
}
let options = CloudStorageFileNameOptions(cloudFolderName: owningUserCreds.cloudFolderName, mimeType: fileIndexObj!.mimeType)
cloudStorageCreds.downloadFile(cloudFileName: cloudFileName, options:options) { result in
switch result {
case .success(let downloadResult):
// I used to check the file size as downloaded against the file size in the file index (last uploaded). And call it an error if they didn't match. But we're being fancier now. Going to let the client see if this is an error. https://github.com/crspybits/SyncServerII/issues/93
Log.debug("CheckSum: \(downloadResult.checkSum)")
var contentsChanged = false
// 11/4/18; This is conditional because for migration purposes, the FileIndex may not contain a lastUploadedCheckSum. i.e., it comes from a FileIndex record before we added the lastUploadedCheckSum field.
if let lastUploadedCheckSum = fileIndexObj!.lastUploadedCheckSum {
contentsChanged = downloadResult.checkSum != lastUploadedCheckSum
}
let response = DownloadFileResponse()
response.appMetaData = fileIndexObj!.appMetaData
response.data = downloadResult.data
response.checkSum = downloadResult.checkSum
response.cloudStorageType = cloudStorageType
response.contentsChanged = contentsChanged
params.completion(.success(response))
// Don't consider the following two cases as HTTP status errors, so we can return appMetaData back to client. appMetaData, for v0 files, can be necessary for clients to deal more completely with these error conditions.
case .accessTokenRevokedOrExpired:
let message = "Access token revoked or expired."
Log.error(message)
let response = DownloadFileResponse()
response.appMetaData = fileIndexObj!.appMetaData
response.cloudStorageType = cloudStorageType
response.gone = GoneReason.authTokenExpiredOrRevoked.rawValue
params.completion(.success(response))
case .fileNotFound:
let message = "File not found."
Log.error(message)
let response = DownloadFileResponse()
response.appMetaData = fileIndexObj!.appMetaData
response.cloudStorageType = cloudStorageType
response.gone = GoneReason.fileRemovedOrRenamed.rawValue
params.completion(.success(response))
case .failure(let error):
let message = "Failed downloading file: \(error)"
Log.error(message)
params.completion(.failure(.message(message)))
}
}
}
}
}
| mit | a104ba7df1259e3ec4f6cca58730c06d | 51.790055 | 443 | 0.594349 | 5.694279 | false | false | false | false |
Ossey/WeiBo | XYWeiBo/XYWeiBo/Classes/Main(主要)/Controller/XYBaseViewController.swift | 1 | 2332 | //
// XYBaseViewController.swift
// XYWeiBo
//
// Created by mofeini on 16/9/28.
// Copyright © 2016年 sey. All rights reserved.
//
import UIKit
class XYBaseViewController: UITableViewController {
// MARK:- 懒加载
lazy var visitorView : XYVisitorView = XYVisitorView.visitorView()
// 根据沙盒中取出用户的信息,判断用户是否已经登录
var isLogin = XYUserAccountViewModel.shareInstance.isLogin
// MARK:- 控制器view的声明周期
override func loadView() {
// 根据用户登录状态,确定要加载的view
isLogin ? super.loadView() : setupVisitorView()
}
override func viewDidLoad() {
super.viewDidLoad()
// 添加导航条上的item
addNavigationBarItem()
}
// MARK:- 自定义的函数
func setupVisitorView() {
// 设置访客视图成为控制器的view
view = visitorView
// 给访客视图中的【注册】和【登录】按钮添加点击事件
visitorView.registerButton.addTarget(self, action: #selector(registerBarButtonItemClick), for: .touchUpInside)
visitorView.loginButton.addTarget(self, action: #selector(loginBarButtonItemClick), for: .touchUpInside)
}
/// 在导航条上添加【注册】和【登录】按钮
func addNavigationBarItem() {
// 左侧按钮
navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "注册", style: .plain, target: self, action: #selector(registerBarButtonItemClick))
// 右侧按钮
navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "登录", style: .plain, target: self, action: #selector(loginBarButtonItemClick))
}
}
// MARK:- 事件处理
extension XYBaseViewController {
/// 监听注册按钮的点击事件
func registerBarButtonItemClick() {
print("点击了注册按钮")
}
/// 监听登录按钮的点击事件
func loginBarButtonItemClick() {
// 创建OAuthVc
let OAuthVc = XYOAuthViewController()
// 包装为导航控制器
let nav = UINavigationController.init(rootViewController: OAuthVc)
// 弹出控制器
self.present(nav, animated: true, completion: nil)
}
}
| apache-2.0 | 9626260b8bac183e43600f5ba47e7a43 | 25.716216 | 152 | 0.637329 | 4.472851 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Threads/MXThreadModel.swift | 1 | 3080 | //
// Copyright 2021 The Matrix.org Foundation C.I.C
//
// 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
@objcMembers
public class MXThreadModel: NSObject, MXThreadProtocol {
public let id: String
public let roomId: String
public let notificationCount: UInt
public let highlightCount: UInt
public let isParticipated: Bool
public private(set) var rootMessage: MXEvent?
public private(set) var lastMessage: MXEvent?
public private(set) var numberOfReplies: Int
public init(withRootEvent rootEvent: MXEvent,
notificationCount: UInt = 0,
highlightCount: UInt = 0) {
self.id = rootEvent.eventId
self.roomId = rootEvent.roomId
self.notificationCount = notificationCount
self.highlightCount = highlightCount
self.rootMessage = rootEvent
if let thread = rootEvent.unsignedData?.relations?.thread {
self.lastMessage = thread.latestEvent
isParticipated = thread.hasParticipated
numberOfReplies = Int(thread.numberOfReplies)
} else {
self.lastMessage = nil
isParticipated = false
numberOfReplies = 0
}
super.init()
}
internal func updateRootMessage(_ rootMessage: MXEvent) {
self.rootMessage = rootMessage
}
internal func updateLastMessage(_ lastMessage: MXEvent) {
self.lastMessage = lastMessage
}
internal func updateNumberOfReplies(_ numberOfReplies: Int) {
self.numberOfReplies = numberOfReplies
}
}
// MARK: - Comparable
extension MXThreadModel: Comparable {
/// Comparator for thread instances, to compare two threads according to their last message time.
/// - Parameters:
/// - lhs: left operand
/// - rhs: right operand
/// - Returns: true if left operand's last message is newer than the right operand's last message, false otherwise
public static func < (lhs: MXThreadModel, rhs: MXThreadModel) -> Bool {
// thread will be 'smaller' than an other thread if it's last message is newer
let leftLastMessage = lhs.lastMessage
let rightLastMessage = rhs.lastMessage
if let leftLastMessage = leftLastMessage {
if let rightLastMessage = rightLastMessage {
return leftLastMessage < rightLastMessage
} else {
return true
}
} else if rightLastMessage != nil {
return false
} else {
return false
}
}
}
| apache-2.0 | 8c48a63b038932a1e2368ab5dd0c048e | 30.428571 | 118 | 0.66039 | 4.652568 | false | false | false | false |
ReactKit/SwiftTask | SwiftTask/_Atomic.swift | 2 | 1957 | //
// _Atomic.swift
// SwiftTask
//
// Created by Yasuhiro Inami on 2015/05/18.
// Copyright (c) 2015年 Yasuhiro Inami. All rights reserved.
//
import Darwin
internal final class _Atomic<T>
{
private var _spinlock = OS_SPINLOCK_INIT
fileprivate var _rawValue: T
internal init(_ rawValue: T)
{
self._rawValue = rawValue
}
internal func withRawValue<U>(_ f: (T) -> U) -> U
{
self._lock()
defer { self._unlock() }
return f(self._rawValue)
}
internal func update(_ f: (T) -> T) -> T
{
return self.updateIf { f($0) }!
}
internal func updateIf(_ f: (T) -> T?) -> T?
{
return self.modify { value in f(value).map { ($0, value) } }
}
internal func modify<U>(_ f: (T) -> (T, U)?) -> U?
{
self._lock()
defer { self._unlock() }
let oldValue = self._rawValue
if let (newValue, retValue) = f(oldValue) {
self._rawValue = newValue
return retValue
}
else {
return nil
}
}
fileprivate func _lock()
{
withUnsafeMutablePointer(to: &self._spinlock, OSSpinLockLock)
}
fileprivate func _unlock()
{
withUnsafeMutablePointer(to: &self._spinlock, OSSpinLockUnlock)
}
}
extension _Atomic: RawRepresentable
{
internal convenience init(rawValue: T)
{
self.init(rawValue)
}
internal var rawValue: T
{
get {
self._lock()
defer { self._unlock() }
return self._rawValue
}
set(newValue) {
self._lock()
defer { self._unlock() }
self._rawValue = newValue
}
}
}
extension _Atomic: CustomStringConvertible
{
internal var description: String
{
return String(describing: self.rawValue)
}
}
| mit | 7310ec1aa2d2589463f8515d37b6e7e8 | 19.364583 | 71 | 0.508951 | 4.204301 | false | false | false | false |
efremidze/Alarm | Alarm/Extensions.swift | 1 | 1490 | //
// Extensions.swift
// Alarm
//
// Created by Lasha Efremidze on 2/8/17.
// Copyright © 2017 Lasha Efremidze. All rights reserved.
//
import UIKit
extension UIView {
@discardableResult
func constrainToEdges(_ inset: UIEdgeInsets = UIEdgeInsets()) -> [NSLayoutConstraint] {
return constrain {[
$0.topAnchor.constraint(equalTo: $0.superview!.topAnchor, constant: inset.top),
$0.leadingAnchor.constraint(equalTo: $0.superview!.leadingAnchor, constant: inset.left),
$0.bottomAnchor.constraint(equalTo: $0.superview!.bottomAnchor, constant: inset.bottom),
$0.trailingAnchor.constraint(equalTo: $0.superview!.trailingAnchor, constant: inset.right)
]}
}
@discardableResult
func constrain(constraints: (UIView) -> [NSLayoutConstraint]) -> [NSLayoutConstraint] {
let constraints = constraints(self)
self.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints)
return constraints
}
}
extension UIImage {
convenience init(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
var rect = CGRect()
rect.size = size
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
color.setFill()
UIRectFill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: image!.cgImage!)
}
}
| apache-2.0 | 93996fce7ec72c949e2e2fee6e641f78 | 31.369565 | 102 | 0.663533 | 4.81877 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Playgrounds/Filters.playground/Pages/Resonant Filter Operation.xcplaygroundpage/Contents.swift | 2 | 677 | //: ## Resonant Filter Operation
//:
import XCPlayground
import AudioKit
let file = try AKAudioFile(readFileName: filtersPlaygroundFiles[0],
baseDir: .Resources)
let player = try AKAudioPlayer(file: file)
player.looping = true
let effect = AKOperationEffect(player) { player, _ in
let frequency = AKOperation.sineWave(frequency: 0.5).scale(minimum: 2000, maximum: 5000)
let bandwidth = abs(AKOperation.sineWave(frequency: 0.3)) * 1000
return player.resonantFilter(frequency: frequency, bandwidth: bandwidth) * 0.1
}
AudioKit.output = effect
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | mit | f5ad1db982ef6eee6f6ed9ee7d2c84a1 | 28.478261 | 92 | 0.734121 | 4.28481 | false | false | false | false |
PJayRushton/TeacherTools | Pods/Whisper/Source/ShoutFactory.swift | 4 | 8362 | import UIKit
let shoutView = ShoutView()
open class ShoutView: UIView {
public struct Dimensions {
public static let indicatorHeight: CGFloat = 6
public static let indicatorWidth: CGFloat = 50
public static let imageSize: CGFloat = 48
public static let imageOffset: CGFloat = 18
public static var textOffset: CGFloat = 75
public static var touchOffset: CGFloat = 40
}
open fileprivate(set) lazy var backgroundView: UIView = {
let view = UIView()
view.backgroundColor = ColorList.Shout.background
view.alpha = 0.98
view.clipsToBounds = true
return view
}()
open fileprivate(set) lazy var indicatorView: UIView = {
let view = UIView()
view.backgroundColor = ColorList.Shout.dragIndicator
view.layer.cornerRadius = Dimensions.indicatorHeight / 2
view.isUserInteractionEnabled = true
return view
}()
open fileprivate(set) lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.layer.cornerRadius = Dimensions.imageSize / 2
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
return imageView
}()
open fileprivate(set) lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = FontList.Shout.title
label.textColor = ColorList.Shout.title
label.numberOfLines = 2
return label
}()
open fileprivate(set) lazy var subtitleLabel: UILabel = {
let label = UILabel()
label.font = FontList.Shout.subtitle
label.textColor = ColorList.Shout.subtitle
label.numberOfLines = 2
return label
}()
open fileprivate(set) lazy var tapGestureRecognizer: UITapGestureRecognizer = { [unowned self] in
let gesture = UITapGestureRecognizer()
gesture.addTarget(self, action: #selector(ShoutView.handleTapGestureRecognizer))
return gesture
}()
open fileprivate(set) lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in
let gesture = UIPanGestureRecognizer()
gesture.addTarget(self, action: #selector(ShoutView.handlePanGestureRecognizer))
return gesture
}()
open fileprivate(set) var announcement: Announcement?
open fileprivate(set) var displayTimer = Timer()
open fileprivate(set) var panGestureActive = false
open fileprivate(set) var shouldSilent = false
open fileprivate(set) var completion: (() -> ())?
private var subtitleLabelOriginalHeight: CGFloat = 0
private var internalHeight: CGFloat = 0
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(backgroundView)
[imageView, titleLabel, subtitleLabel, indicatorView].forEach {
$0.autoresizingMask = []
backgroundView.addSubview($0)
}
clipsToBounds = false
isUserInteractionEnabled = true
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0.5)
layer.shadowOpacity = 0.1
layer.shadowRadius = 0.5
backgroundView.addGestureRecognizer(tapGestureRecognizer)
addGestureRecognizer(panGestureRecognizer)
NotificationCenter.default.addObserver(self, selector: #selector(ShoutView.orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
// MARK: - Configuration
open func craft(_ announcement: Announcement, to: UIViewController, completion: (() -> ())?) {
panGestureActive = false
shouldSilent = false
configureView(announcement)
shout(to: to)
self.completion = completion
}
open func configureView(_ announcement: Announcement) {
self.announcement = announcement
imageView.image = announcement.image
titleLabel.text = announcement.title
subtitleLabel.text = announcement.subtitle
displayTimer.invalidate()
displayTimer = Timer.scheduledTimer(timeInterval: announcement.duration,
target: self, selector: #selector(ShoutView.displayTimerDidFire), userInfo: nil, repeats: false)
setupFrames()
}
open func shout(to controller: UIViewController) {
controller.view.addSubview(self)
frame.size.height = 0
UIView.animate(withDuration: 0.35, animations: {
self.frame.size.height = self.internalHeight + Dimensions.touchOffset
})
}
// MARK: - Setup
public func setupFrames() {
internalHeight = (UIApplication.shared.isStatusBarHidden ? 55 : 65)
let totalWidth = UIScreen.main.bounds.width
let offset: CGFloat = UIApplication.shared.isStatusBarHidden ? 2.5 : 5
let textOffsetX: CGFloat = imageView.image != nil ? Dimensions.textOffset : 18
let imageSize: CGFloat = imageView.image != nil ? Dimensions.imageSize : 0
[titleLabel, subtitleLabel].forEach {
$0.frame.size.width = totalWidth - imageSize - (Dimensions.imageOffset * 2)
$0.sizeToFit()
}
internalHeight += subtitleLabel.frame.height
imageView.frame = CGRect(x: Dimensions.imageOffset, y: (internalHeight - imageSize) / 2 + offset,
width: imageSize, height: imageSize)
let textOffsetY = imageView.image != nil ? imageView.frame.origin.x + 3 : textOffsetX + 5
titleLabel.frame.origin = CGPoint(x: textOffsetX, y: textOffsetY)
subtitleLabel.frame.origin = CGPoint(x: textOffsetX, y: titleLabel.frame.maxY + 2.5)
if subtitleLabel.text?.isEmpty ?? true {
titleLabel.center.y = imageView.center.y - 2.5
}
frame = CGRect(x: 0, y: safeYCoordinate,
width: totalWidth, height: internalHeight + Dimensions.touchOffset)
}
// MARK: - Frame
open override var frame: CGRect {
didSet {
backgroundView.frame = CGRect(x: 0, y: safeYCoordinate,
width: frame.size.width,
height: frame.size.height - Dimensions.touchOffset)
indicatorView.frame = CGRect(x: (backgroundView.frame.size.width - Dimensions.indicatorWidth) / 2,
y: backgroundView.frame.height - Dimensions.indicatorHeight - 5,
width: Dimensions.indicatorWidth,
height: Dimensions.indicatorHeight)
}
}
// MARK: - Actions
open func silent() {
UIView.animate(withDuration: 0.35, animations: {
self.frame.size.height = 0
}, completion: { finished in
self.completion?()
self.displayTimer.invalidate()
self.removeFromSuperview()
})
}
// MARK: - Timer methods
@objc open func displayTimerDidFire() {
shouldSilent = true
if panGestureActive { return }
silent()
}
// MARK: - Gesture methods
@objc fileprivate func handleTapGestureRecognizer() {
guard let announcement = announcement else { return }
announcement.action?()
silent()
}
@objc private func handlePanGestureRecognizer() {
let translation = panGestureRecognizer.translation(in: self)
if panGestureRecognizer.state == .began {
subtitleLabelOriginalHeight = subtitleLabel.bounds.size.height
subtitleLabel.numberOfLines = 0
subtitleLabel.sizeToFit()
} else if panGestureRecognizer.state == .changed {
panGestureActive = true
let maxTranslation = subtitleLabel.bounds.size.height - subtitleLabelOriginalHeight
if translation.y >= maxTranslation {
frame.size.height = internalHeight + maxTranslation
+ (translation.y - maxTranslation) / 25 + Dimensions.touchOffset
} else {
frame.size.height = internalHeight + translation.y + Dimensions.touchOffset
}
} else {
panGestureActive = false
let height = translation.y < -5 || shouldSilent ? 0 : internalHeight
subtitleLabel.numberOfLines = 2
subtitleLabel.sizeToFit()
UIView.animate(withDuration: 0.2, animations: {
self.frame.size.height = height + Dimensions.touchOffset
}, completion: { _ in
if translation.y < -5 {
self.completion?()
self.removeFromSuperview()
}
})
}
}
// MARK: - Handling screen orientation
@objc func orientationDidChange() {
setupFrames()
}
}
| mit | dd2abbab10b0deef9d3d2cb9a5a17bcb | 30.201493 | 170 | 0.68309 | 4.753837 | false | false | false | false |
bigscreen/mangindo-ios | Mangindo/Modules/Chapters/ChaptersResponse.swift | 1 | 744 | //
// ChaptersResponse.swift
// Mangindo
//
// Created by Gallant Pratama on 4/23/17.
// Copyright © 2017 Gallant Pratama. All rights reserved.
//
import ObjectMapper
class ChaptersResponse: Mappable {
var chapters: [Chapter] = []
required init?(map: Map) {
}
func mapping(map: Map) {
chapters <- map["komik"]
}
}
class Chapter: Mappable {
var title: String = ""
var number: Int = 0
var time: String = ""
var comicTitleId: String = ""
required init?(map: Map) {
}
func mapping(map: Map) {
title <- map["judul"]
number <- map["hidden_chapter"]
time <- map["waktu"]
comicTitleId <- map["hidden_komik"]
}
}
| mit | 0b09efd55e2d5fbeae96cb083afbb315 | 17.121951 | 58 | 0.549125 | 3.572115 | false | false | false | false |
andrewwoz/LineReader | LineReader/LineReader/LineReader.swift | 1 | 837 | // Copyright © 2017 andrewwoz
import Foundation
/// Read text file line by line in efficient way
public class LineReader {
public let path: String
fileprivate let file: UnsafeMutablePointer<FILE>!
init?(path: String) {
self.path = path
file = fopen(path, "r")
guard file != nil else { return nil }
}
public var nextLine: String? {
var line:UnsafeMutablePointer<CChar>? = nil
var linecap:Int = 0
defer { if (line != nil) { free(line!) } }
return getline(&line, &linecap, file) > 0 ? String(cString: line!) : nil
}
deinit {
fclose(file)
}
}
extension LineReader: Sequence {
public func makeIterator() -> AnyIterator<String> {
return AnyIterator<String> {
return self.nextLine
}
}
}
| mit | 46ff33e9037fff98a96275159eef673e | 22.885714 | 80 | 0.582536 | 4.18 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/FacebookCore/Sources/Core/Internal/Extensions/Dictionary+KeyValueMap.swift | 19 | 1704 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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.
extension Dictionary {
func keyValueMap<K, V>(_ transform: (Element) throws -> (K, V)) rethrows -> [K:V] {
var dictionary: [K:V] = [:]
try forEach {
let transformed = try transform($0)
dictionary[transformed.0] = transformed.1
}
return dictionary
}
func keyValueFlatMap<K, V>(_ transform: (Element) throws -> (K?, V?)) rethrows -> [K:V] {
var dictionary: [K:V] = [:]
try forEach {
let transformed = try transform($0)
if let key = transformed.0,
let value = transformed.1 {
dictionary[key] = value
}
}
return dictionary
}
}
| apache-2.0 | 33471f8275248b33d7ef5e56c9e58db6 | 41.6 | 91 | 0.701291 | 4.26 | false | false | false | false |
JPMartha/FounDarwin | Tests/Directory/DirectoryTests.swift | 1 | 6482 | @testable import Directory
import XCTest
#if os(Linux)
import Glibc
#else
import Darwin
#endif
final class DirectoryTests: XCTestCase {
func testCurrentDirectory() {
var cd = String()
do {
cd = try currentDirectoryPath()
} catch {
XCTAssertThrowsError(DirectoryError.CannotGetCurrentDirectory)
return
}
guard let path = String(validatingUTF8: cd) else {
XCTFail()
return
}
XCTAssertNotNil(path)
print("CurrentDirectoryPath: \(path)")
}
func currentDirectoryForTest() -> String? {
#if os(Linux)
let cwd = getcwd(nil, 0)
guard let cd = cwd else {
free(cwd)
XCTFail("Cannot getcwd.")
return nil
}
#else
let cwd = getcwd(nil, Int(PATH_MAX))
guard let cd = cwd else {
free(cwd)
XCTFail("Cannot getcwd.")
return nil
}
#endif
guard let path = String(validatingUTF8: cd) else {
XCTFail("Cannot validatingUTF8.")
return nil
}
return path
}
func testChangeDirectory() {
guard let path1 = currentDirectoryForTest() else {
XCTFail()
return
}
print("CurrentDirectoryPath: \(path1)")
do {
try changeDirectory(path: "\(path1)/.build")
} catch {
XCTAssertThrowsError(DirectoryError.CannotChangeDirectory)
return
}
// TODO: Verify
guard let path2 = currentDirectoryForTest() else {
XCTFail()
return
}
print("CurrentDirectoryPath: \(path2)")
// It is necessary for making a success of the other tests
// to change working directory into path1.
do {
try changeDirectory(path: path1)
} catch {
XCTAssertThrowsError(DirectoryError.CannotChangeDirectory)
return
}
}
func testCreateDirectory() {
guard let path = currentDirectoryForTest() else {
XCTFail("Failed: currentDirectoryForTest")
return
}
print("CurrentDirectoryPath: \(path)")
let testCreateDirectoryName = "testCreateDirectory"
do {
try createDirectory(path: "\(path)/\(testCreateDirectoryName)")
} catch {
XCTAssertThrowsError(DirectoryError.CannotCreateDirectory)
return
}
#if os(Linux)
guard chdir(path) == 0 else {
XCTFail("Cannot chdir")
return
}
XCTAssertEqual(access(testCreateDirectoryName, F_OK), 0)
print("Access: \(testCreateDirectoryName)")
#else
XCTAssertEqual(access("\(path)/\(testCreateDirectoryName)", F_OK), 0)
print("Access: \(path)/\(testCreateDirectoryName)")
#endif
rmdir("\(path)/\(testCreateDirectoryName)")
}
func testIsAccessibleDirectory() {
guard let path = currentDirectoryForTest() else {
XCTFail("Failed: currentDirectoryForTest")
return
}
print("CurrentDirectoryPath: \(path)")
let testAccessibleDirectoryName = "testAccessibleDirectory"
#if os(Linux)
XCTAssertFalse(isAccessibleDirectory(name: testAccessibleDirectoryName))
print("Cannot access: \(testAccessibleDirectoryName)")
#else
XCTAssertFalse(isAccessibleDirectory(path: "\(path)/\(testAccessibleDirectoryName)"))
print("Cannot access \(path)/\(testAccessibleDirectoryName)")
#endif
guard mkdir("\(path)/\(testAccessibleDirectoryName)", S_IRWXU | S_IRWXG | S_IRWXO) == 0 || errno == EEXIST else {
XCTFail("Cannot mkdir")
return
}
#if os(Linux)
XCTAssertTrue(isAccessibleDirectory(name: testAccessibleDirectoryName))
print("Access \(testAccessibleDirectoryName)")
#else
XCTAssertTrue(isAccessibleDirectory(path: "\(path)/\(testAccessibleDirectoryName)"))
print("Access \(path)/\(testAccessibleDirectoryName)")
#endif
rmdir("\(path)/\(testAccessibleDirectoryName)")
#if os(Linux)
XCTAssertFalse(isAccessibleDirectory(name: testAccessibleDirectoryName))
print("Cannot access: \(testAccessibleDirectoryName)")
#else
XCTAssertFalse(isAccessibleDirectory(path: "\(path)/\(testAccessibleDirectoryName)"))
print("Cannot access \(path)/\(testAccessibleDirectoryName)")
#endif
}
func testRemoveDirectory() {
guard let path = currentDirectoryForTest() else {
XCTFail()
return
}
print("CurrentDirectoryPath: \(path)")
let testRemoveDirectoryName = "testRemoveDirectory"
guard mkdir("\(path)/\(testRemoveDirectoryName)", S_IRWXU | S_IRWXG | S_IRWXO) == 0 || errno == EEXIST else {
XCTFail()
return
}
#if os(Linux)
XCTAssertEqual(access(testRemoveDirectoryName, F_OK), 0)
print("Access \(testRemoveDirectoryName)")
#else
XCTAssertEqual(access("\(path)/\(testRemoveDirectoryName)", F_OK), 0)
#endif
removeDirectory(path: "\(path)/\(testRemoveDirectoryName)")
#if os(Linux)
XCTAssertNotEqual(access(testRemoveDirectoryName, F_OK), 0)
print("Cannot access \(testRemoveDirectoryName)")
#else
XCTAssertNotEqual(access("\(path)/\(testRemoveDirectoryName)", F_OK), 0)
print("Cannot access \(path)/\(testRemoveDirectoryName)")
#endif
}
}
extension DirectoryTests {
static var allTests : [(String, (DirectoryTests) -> () throws -> Void)] {
return [
("testCurrentDirectory", testCurrentDirectory),
("testChangeDirectory", testChangeDirectory),
("testCreateDirectory", testCreateDirectory),
("testIsAccessibleDirectory", testIsAccessibleDirectory),
("testRemoveDirectory", testRemoveDirectory),
]
}
}
| mit | 6c497cdcdc8226406ac46420d05500eb | 32.241026 | 121 | 0.558007 | 5.474662 | false | true | false | false |
phatblat/realm-cocoa | RealmSwift/MutableSet.swift | 1 | 26086 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2020 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
`MutableSet` is the container type in Realm used to define to-many relationships with distinct values as objects.
Like Swift's `Set`, `MutableSet` is a generic type that is parameterized on the type it stores. This can be either an `Object`
subclass or one of the following types: `Bool`, `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`,
`String`, `Data`, `Date`, `Decimal128`, and `ObjectId` (and their optional versions)
Unlike Swift's native collections, `MutableSet`s are reference types, and are only immutable if the Realm that manages them
is opened as read-only.
MutableSet's can be filtered and sorted with the same predicates as `Results<Element>`.
Properties of `MutableSet` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`.
*/
public final class MutableSet<Element: RealmCollectionValue>: RLMSwiftCollectionBase {
// MARK: Properties
/// The Realm which manages the set, or `nil` if the set is unmanaged.
public var realm: Realm? {
return rlmSet.realm.map { Realm($0) }
}
/// Indicates if the set can no longer be accessed.
public var isInvalidated: Bool { return rlmSet.isInvalidated }
/// Contains the last accessed property names when tracing the key path.
internal var lastAccessedNames: NSMutableArray?
internal var rlmSet: RLMSet<AnyObject> {
_rlmCollection as! RLMSet
}
// MARK: Initializers
/// Creates a `MutableSet` that holds Realm model objects of type `Element`.
public override init() {
super.init()
}
internal init(objc rlmSet: RLMSet<AnyObject>) {
super.init(collection: rlmSet)
}
// MARK: Count
/// Returns the number of objects in this MutableSet.
public var count: Int { return Int(rlmSet.count) }
// MARK: KVC
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's
objects.
*/
@nonobjc public func value(forKey key: String) -> [AnyObject] {
return (rlmSet.value(forKeyPath: key)! as! NSSet).allObjects as [AnyObject]
}
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
@nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] {
return (rlmSet.value(forKeyPath: keyPath)! as! NSSet).allObjects as [AnyObject]
}
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(_ value: Any?, forKey key: String) {
return rlmSet.setValue(value, forKeyPath: key)
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the set.
- parameter predicate: The predicate with which to filter the objects.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> {
return Results<Element>(rlmSet.objects(with: predicate))
}
/**
Returns a Boolean value indicating whether the Set contains the
given object.
- parameter object: The element to find in the MutableSet.
*/
public func contains(_ object: Element) -> Bool {
return rlmSet.contains(dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Returns a Boolean value that indicates whether this set is a subset
of the given set.
- Parameter object: Another MutableSet to compare.
*/
public func isSubset(of possibleSuperset: MutableSet<Element>) -> Bool {
return rlmSet.isSubset(of: possibleSuperset.rlmSet)
}
/**
Returns a Boolean value that indicates whether this set intersects
with another given set.
- Parameter object: Another MutableSet to compare.
*/
public func intersects(_ otherSet: MutableSet<Element>) -> Bool {
return rlmSet.intersects(otherSet.rlmSet)
}
// MARK: Sorting
/**
Returns a `Results` containing the objects in the set, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a set of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: MutableSets may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> {
return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)])
}
/**
Returns a `Results` containing the objects in the set, but sorted.
- warning: MutableSets may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return Results<Element>(rlmSet.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue }))
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the set, or `nil` if the set is
empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmSet.min(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the set, or `nil` if the set
is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose maximum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return rlmSet.max(ofProperty: property).map(dynamicBridgeCast)
}
/**
Returns the sum of the values of a given property over all the objects in the set.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T {
return dynamicBridgeCast(fromObjectiveC: rlmSet.sum(ofProperty: property))
}
/**
Returns the average value of a given property over all the objects in the set, or `nil` if the set is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average<T: AddableType>(ofProperty property: String) -> T? {
return rlmSet.average(ofProperty: property).map(dynamicBridgeCast)
}
// MARK: Mutation
/**
Inserts an object to the set if not already present.
- warning: This method may only be called during a write transaction.
- parameter object: An object.
*/
public func insert(_ object: Element) {
rlmSet.add(dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Inserts the given sequence of objects into the set if not already present.
- warning: This method may only be called during a write transaction.
*/
public func insert<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element {
for obj in objects {
rlmSet.add(dynamicBridgeCast(fromSwift: obj) as AnyObject)
}
}
/**
Removes an object in the set if present. The object is not removed from the Realm that manages it.
- warning: This method may only be called during a write transaction.
- parameter object: The object to remove.
*/
public func remove(_ object: Element) {
rlmSet.remove(dynamicBridgeCast(fromSwift: object) as AnyObject)
}
/**
Removes all objects from the set. The objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
public func removeAll() {
rlmSet.removeAllObjects()
}
/**
Mutates the set in place with the elements that are common to both this set and the given sequence.
- warning: This method may only be called during a write transaction.
- parameter other: Another set.
*/
public func formIntersection(_ other: MutableSet<Element>) {
rlmSet.intersect(other.rlmSet)
}
/**
Mutates the set in place and removes the elements of the given set from this set.
- warning: This method may only be called during a write transaction.
- parameter other: Another set.
*/
public func subtract(_ other: MutableSet<Element>) {
rlmSet.minus(other.rlmSet)
}
/**
Inserts the elements of the given sequence into the set.
- warning: This method may only be called during a write transaction.
- parameter other: Another set.
*/
public func formUnion(_ other: MutableSet<Element>) {
rlmSet.union(other.rlmSet)
}
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let dogs = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.insert(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(on queue: DispatchQueue? = nil,
_ block: @escaping (RealmCollectionChange<MutableSet>) -> Void) -> NotificationToken {
return rlmSet.addNotificationBlock(wrapObserveBlock(block), queue: queue)
}
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let dogs = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.insert(dog)
}
// end of run loop execution context
```
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
@Persisted var toys: List<Toy>
}
// ...
let dogs = realm.objects(Dog.self)
let token = dogs.observe(keyPaths: ["name"]) { changes in
switch changes {
case .initial(let dogs):
// ...
case .update:
// This case is hit:
// - after the token is intialized
// - when the name property of an object in the
// collection is modified
// - when an element is inserted or removed
// from the collection.
// This block is not triggered:
// - when a value other than name is modified on
// one of the elements.
case .error:
// ...
}
}
// end of run loop execution context
```
- If the observed key path were `["toys.brand"]`, then any insertion or
deletion to the `toys` list on any of the collection's elements would trigger the block.
Changes to the `brand` value on any `Toy` that is linked to a `Dog` in this
collection will trigger the block. Changes to a value other than `brand` on any `Toy` that
is linked to a `Dog` in this collection would not trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would also trigger a notification.
- If the above example observed the `["toys"]` key path, then any insertion,
deletion, or modification to the `toys` list for any element in the collection
would trigger the block.
Changes to any value on any `Toy` that is linked to a `Dog` in this collection
would *not* trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would still trigger a notification.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(keyPaths: [String]? = nil,
on queue: DispatchQueue? = nil,
_ block: @escaping (RealmCollectionChange<MutableSet>) -> Void) -> NotificationToken {
return rlmSet.addNotificationBlock(wrapObserveBlock(block), keyPaths: keyPaths, queue: queue)
}
// MARK: Frozen Objects
public var isFrozen: Bool {
return rlmSet.isFrozen
}
public func freeze() -> MutableSet {
return MutableSet(objc: rlmSet.freeze())
}
public func thaw() -> MutableSet? {
return MutableSet(objc: rlmSet.thaw())
}
// swiftlint:disable:next identifier_name
@objc class func _unmanagedCollection() -> RLMSet<AnyObject> {
if let type = Element.self as? ObjectBase.Type {
return RLMSet(objectClassName: type.className())
}
return RLMSet(objectType: Element._rlmType, optional: Element._rlmOptional)
}
/// :nodoc:
@objc public override class func _backingCollectionType() -> AnyClass {
return RLMManagedSet.self
}
// Printable requires a description property defined in Swift (and not obj-c),
// and it has to be defined as override, which can't be done in a
// generic class.
/// Returns a human-readable description of the objects contained in the MutableSet.
@objc public override var description: String {
return descriptionWithMaxDepth(RLMDescriptionMaxDepth)
}
@objc private func descriptionWithMaxDepth(_ depth: UInt) -> String {
return RLMDescriptionWithMaxDepth("MutableSet", rlmSet, depth)
}
}
extension MutableSet where Element: MinMaxType {
/**
Returns the minimum (lowest) value in the set, or `nil` if the set is empty.
*/
public func min() -> Element? {
return rlmSet.min(ofProperty: "self").map(dynamicBridgeCast)
}
/**
Returns the maximum (highest) value in the set, or `nil` if the set is empty.
*/
public func max() -> Element? {
return rlmSet.max(ofProperty: "self").map(dynamicBridgeCast)
}
}
extension MutableSet where Element: AddableType {
/**
Returns the sum of the values in the set.
*/
public func sum() -> Element {
return sum(ofProperty: "self")
}
/**
Returns the average of the values in the set, or `nil` if the set is empty.
*/
public func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
extension MutableSet: RealmCollection {
/// The type of the objects stored within the set.
public typealias ElementType = Element
// MARK: Sequence Support
/// Returns a `RLMIterator` that yields successive elements in the `MutableSet`.
public func makeIterator() -> RLMIterator<Element> {
return RLMIterator(collection: rlmSet)
}
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return count }
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// :nodoc:
public func _observe(_ keyPaths: [String]?,
_ queue: DispatchQueue?,
_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void)
-> NotificationToken {
return rlmSet.addNotificationBlock(wrapObserveBlock(block), keyPaths: keyPaths, queue: queue)
}
// MARK: Object Retrieval
/**
- warning: Ordering is not guaranteed on a MutableSet. Subscripting is implemented for
convenience should not be relied on.
*/
public subscript(position: Int) -> Element {
if let lastAccessedNames = lastAccessedNames {
return Element._rlmKeyPathRecorder(with: lastAccessedNames)
}
throwForNegativeIndex(position)
return dynamicBridgeCast(fromObjectiveC: rlmSet.object(at: UInt(position)))
}
/// :nodoc:
public func index(of object: Element) -> Int? {
fatalError("index(of:) is not available on MutableSet")
}
/// :nodoc:
public func index(matching predicate: NSPredicate) -> Int? {
fatalError("index(matching:) is not available on MutableSet")
}
/// :nodoc:
public func objects(at indexes: IndexSet) -> [Element] {
fatalError("objects(at indexes:) is not available on MutableSet")
}
/**
- warning: Ordering is not guaranteed on a MutableSet. `first` is implemented for
convenience should not be relied on.
*/
public var first: Element? {
guard count > 0 else {
return nil
}
return self[0]
}
}
// MARK: - Codable
extension MutableSet: Decodable where Element: Decodable {
public convenience init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
insert(try container.decode(Element.self))
}
}
}
extension MutableSet: Encodable where Element: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for value in self {
try container.encode(value)
}
}
}
// MARK: - AssistedObjectiveCBridgeable
extension MutableSet: AssistedObjectiveCBridgeable {
internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> MutableSet {
guard let objectiveCValue = objectiveCValue as? RLMSet<AnyObject> else { preconditionFailure() }
return MutableSet(objc: objectiveCValue)
}
internal var bridged: (objectiveCValue: Any, metadata: Any?) {
return (objectiveCValue: rlmSet, metadata: nil)
}
}
// MARK: Key Path Strings
extension MutableSet: PropertyNameConvertible {
var propertyInformation: (key: String, isLegacy: Bool)? {
return (key: rlmSet.propertyKey, isLegacy: rlmSet.isLegacyProperty)
}
}
| apache-2.0 | 9bb0edcb6add9a2eaeaaed771dab92b8 | 37.645926 | 127 | 0.663114 | 4.758482 | false | false | false | false |
willpowell8/ConfigKit | ConfigKit/Classes/Configuration.swift | 1 | 1426 | //
// Configuration.swift
// Pods
//
// Created by Will Powell on 01/04/2017.
//
//
import Foundation
public class Configuration : NSObject {
public var data:[String:Any]?
public init(data:[String:Any]){
super.init()
self.data = data
}
public func getParam(dictionary:[AnyHashable:Any], param: String) -> Any? {
var paramParts = param.components(separatedBy: ".")
var currentElement = dictionary
for i in 0..<paramParts.count {
let part = paramParts[i]
if i < paramParts.count - 1 {
// sub property needed
guard let childElement = currentElement[part] as? [AnyHashable:Any] else {
return nil
}
currentElement = childElement
}else{
return currentElement[part]
}
}
return nil
}
public func getString(dictionary:[AnyHashable:Any], param: String) -> String? {
return self.getParam(dictionary: dictionary, param: param) as? String
}
public func getInt(dictionary:[AnyHashable:Any], param: String) -> Int? {
return self.getParam(dictionary: dictionary, param: param) as? Int
}
public func getBool(dictionary:[AnyHashable:Any], param: String) -> Bool? {
return self.getParam(dictionary: dictionary, param: param) as? Bool
}
}
| mit | e4b8c80157cd48ba0af6ac321058a2b3 | 28.102041 | 90 | 0.579243 | 4.526984 | false | false | false | false |
wayfinders/WRCalendarView | Example/Tests/Tests.swift | 1 | 1164 | // https://github.com/Quick/Quick
import Quick
import Nimble
import WRCalendarView
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | e9e4b2a551cba5310ba08885030fea6b | 22.16 | 60 | 0.360104 | 5.54067 | false | false | false | false |
HassanEskandari/Eureka | Source/Rows/Common/DecimalFormatter.swift | 4 | 2947 | // DecimalFormatter.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// 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
/// A custom formatter for numbers with two digits after the decimal mark
open class DecimalFormatter: NumberFormatter, FormatterProtocol {
/// Creates the formatter with 2 Fraction Digits, Locale set to .current and .decimal NumberFormatter.Style
public override init() {
super.init()
locale = Locale.current
numberStyle = .decimal
minimumFractionDigits = 2
maximumFractionDigits = 2
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Creates an NSNumber from the given String
/// - Parameter obj: Pointer to NSNumber object to assign
/// - Parameter for: String with number assumed to have the configured min. fraction digits.
/// - Parameter range: Unused range parameter
override open func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, range rangep: UnsafeMutablePointer<NSRange>?) throws {
guard obj != nil else { return }
let str = string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined(separator: "")
// Recover the number from the string in a way that forces the formatter's fraction digits
// numberWithoutDecimals / 10 ^ minimumFractionDigits
obj?.pointee = NSNumber(value: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
}
open func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.position(from: position, offset:((newValue?.count ?? 0) - (oldValue?.count ?? 0))) ?? position
}
}
| mit | 136d79659fbded978a123699e796c388 | 49.810345 | 167 | 0.726162 | 4.83908 | false | false | false | false |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/Pods/Nimble/Nimble/FailureMessage.swift | 28 | 1580 | import Foundation
/// Encapsulates the failure message that matchers can report to the end user.
///
/// This is shared state between Nimble and matchers that mutate this value.
@objc public class FailureMessage {
public var expected: String = "expected"
public var actualValue: String? = "" // empty string -> use default; nil -> exclude
public var to: String = "to"
public var postfixMessage: String = "match"
public var postfixActual: String = ""
public var stringValue: String {
get {
if let value = _stringValueOverride {
return value
} else {
return computeStringValue()
}
}
set {
_stringValueOverride = newValue
}
}
internal var _stringValueOverride: String?
public init() {
}
public init(stringValue: String) {
_stringValueOverride = stringValue
}
internal func stripNewlines(str: String) -> String {
var lines: [String] = (str as NSString).componentsSeparatedByString("\n") as! [String]
let whitespace = NSCharacterSet.whitespaceAndNewlineCharacterSet()
lines = lines.map { line in line.stringByTrimmingCharactersInSet(whitespace) }
return "".join(lines)
}
internal func computeStringValue() -> String {
var value = "\(expected) \(to) \(postfixMessage)"
if let actualValue = actualValue {
value = "\(expected) \(to) \(postfixMessage), got \(actualValue)\(postfixActual)"
}
return stripNewlines(value)
}
} | mit | 2a416c692e5c90e8da09eb39d765929b | 31.265306 | 94 | 0.621519 | 5.096774 | false | false | false | false |
zenghaojim33/BeautifulShop | BeautifulShop/BeautifulShop/Charts/Renderers/ChartLegendRenderer.swift | 1 | 18898 | //
// ChartLegendRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
import CoreGraphics;
public class ChartLegendRenderer: ChartRendererBase
{
/// the legend object this renderer renders
internal var _legend: ChartLegend!;
public init(viewPortHandler: ChartViewPortHandler, legend: ChartLegend?)
{
super.init(viewPortHandler: viewPortHandler);
_legend = legend;
}
/// Prepares the legend and calculates all needed forms, labels and colors.
public func computeLegend(data: ChartData)
{
var labels = [String?]();
var colors = [UIColor?]();
// loop for building up the colors and labels used in the legend
for (var i = 0, count = data.dataSetCount; i < count; i++)
{
var dataSet = data.getDataSetByIndex(i)!;
var clrs: [UIColor] = dataSet.colors;
var entryCount = dataSet.entryCount;
// if we have a barchart with stacked bars
if (dataSet.isKindOfClass(BarChartDataSet) && (dataSet as! BarChartDataSet).isStacked)
{
var bds = dataSet as! BarChartDataSet;
var sLabels = bds.stackLabels;
for (var j = 0; j < clrs.count && j < bds.stackSize; j++)
{
labels.append(sLabels[j % sLabels.count]);
colors.append(clrs[j]);
}
// add the legend description label
colors.append(UIColor.clearColor());
labels.append(bds.label);
}
else if (dataSet.isKindOfClass(PieChartDataSet))
{
var xVals = data.xVals;
var pds = dataSet as! PieChartDataSet;
for (var j = 0; j < clrs.count && j < entryCount && j < xVals.count; j++)
{
labels.append(xVals[j]);
colors.append(clrs[j]);
}
// add the legend description label
colors.append(UIColor.clearColor());
labels.append(pds.label);
}
else
{ // all others
for (var j = 0; j < clrs.count && j < entryCount; j++)
{
// if multiple colors are set for a DataSet, group them
if (j < clrs.count - 1 && j < entryCount - 1)
{
labels.append(nil);
}
else
{ // add label to the last entry
labels.append(dataSet.label);
}
colors.append(clrs[j]);
}
}
}
_legend.colors = colors;
_legend.labels = labels;
// calculate all dimensions of the legend
_legend.calculateDimensions(_legend.font);
}
public func renderLegend(#context: CGContext)
{
if (_legend === nil || !_legend.enabled)
{
return;
}
var labelFont = _legend.font;
var labelTextColor = _legend.textColor;
var labelLineHeight = labelFont.lineHeight;
var labels = _legend.labels;
var formSize = _legend.formSize;
var formToTextSpace = _legend.formToTextSpace;
var xEntrySpace = _legend.xEntrySpace;
var direction = _legend.direction;
// space between text and shape/form of entry
var formTextSpaceAndForm = formToTextSpace + formSize;
// space between the entries
var stackSpace = _legend.stackSpace;
// the amount of pixels the text needs to be set down to be on the same height as the form
var textDrop = (labelFont.lineHeight + formSize) / 2.0;
// contains the stacked legend size in pixels
var stack = CGFloat(0.0);
var wasStacked = false;
var yoffset = _legend.yOffset;
var xoffset = _legend.xOffset;
switch (_legend.position)
{
case .BelowChartLeft:
var posX = viewPortHandler.contentLeft + xoffset;
var posY = viewPortHandler.chartHeight - yoffset;
if (direction == .RightToLeft)
{
posX += _legend.neededWidth;
}
for (var i = 0, count = labels.count; i < count; i++)
{
var drawingForm = _legend.colors[i] != UIColor.clearColor();
if (drawingForm)
{
if (direction == .RightToLeft)
{
posX -= formSize;
}
drawForm(context, x: posX, y: posY - _legend.textHeightMax / 2.0, colorIndex: i, legend: _legend);
if (direction == .LeftToRight)
{
posX += formSize;
}
}
// grouped forms have null labels
if (labels[i] != nil)
{
// spacing between form and label
if (drawingForm)
{
posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace;
}
if (direction == .RightToLeft)
{
posX -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
drawLabel(context, x: posX, y: posY - _legend.textHeightMax, label: labels[i]!, font: labelFont, textColor: labelTextColor);
if (direction == .LeftToRight)
{
posX += (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace;
}
else
{
posX += direction == .RightToLeft ? -stackSpace : stackSpace;
}
}
break;
case .BelowChartRight:
var posX = viewPortHandler.contentRight - xoffset;
var posY = viewPortHandler.chartHeight - yoffset;
for (var i = labels.count - 1; i >= 0; i--)
{
var drawingForm = _legend.colors[i] != UIColor.clearColor();
if (direction == .RightToLeft && drawingForm)
{
posX -= formSize;
drawForm(context, x: posX, y: posY - _legend.textHeightMax / 2.0, colorIndex: i, legend: _legend);
posX -= formToTextSpace;
}
if (labels[i] != nil)
{
posX -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
drawLabel(context, x: posX, y: posY - _legend.textHeightMax, label: labels[i]!, font: labelFont, textColor: labelTextColor);
}
if (direction == .LeftToRight && drawingForm)
{
posX -= formToTextSpace + formSize;
drawForm(context, x: posX, y: posY - _legend.textHeightMax / 2.0, colorIndex: i, legend: _legend);
}
posX -= labels[i] != nil ? xEntrySpace : stackSpace;
}
break;
case .BelowChartCenter:
var posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.neededWidth / 2.0 : _legend.neededWidth / 2.0);
var posY = viewPortHandler.chartHeight - yoffset;
for (var i = 0; i < labels.count; i++)
{
var drawingForm = _legend.colors[i] != UIColor.clearColor();
if (drawingForm)
{
if (direction == .RightToLeft)
{
posX -= formSize;
}
drawForm(context, x: posX, y: posY - _legend.textHeightMax / 2.0, colorIndex: i, legend: _legend);
if (direction == .LeftToRight)
{
posX += formSize;
}
}
// grouped forms have null labels
if (labels[i] != nil)
{
// spacing between form and label
if (drawingForm)
{
posX += direction == .RightToLeft ? -formToTextSpace : formToTextSpace;
}
if (direction == .RightToLeft)
{
posX -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
drawLabel(context, x: posX, y: posY - _legend.textHeightMax, label: labels[i]!, font: labelFont, textColor: labelTextColor);
if (direction == .LeftToRight)
{
posX += (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
posX += direction == .RightToLeft ? -xEntrySpace : xEntrySpace;
}
else
{
posX += direction == .RightToLeft ? -stackSpace : stackSpace;
}
}
break;
case .PiechartCenter:
var posX = viewPortHandler.chartWidth / 2.0 + (direction == .LeftToRight ? -_legend.textWidthMax / 2.0 : _legend.textWidthMax / 2.0);
var posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0;
for (var i = 0; i < labels.count; i++)
{
var drawingForm = _legend.colors[i] != UIColor.clearColor();
var x = posX;
if (drawingForm)
{
if (direction == .LeftToRight)
{
x += stack;
}
else
{
x -= formSize - stack;
}
drawForm(context, x: x, y: posY, colorIndex: i, legend: _legend);
if (direction == .LeftToRight)
{
x += formSize;
}
}
if (labels[i] != nil)
{
if (drawingForm && !wasStacked)
{
x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace;
}
else if (wasStacked)
{
x = posX;
}
if (direction == .RightToLeft)
{
x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
if (!wasStacked)
{
drawLabel(context, x: x, y: posY - _legend.textHeightMax / 2.0, label: labels[i]!, font: labelFont, textColor: labelTextColor);
posY += textDrop;
}
else
{
posY += _legend.textHeightMax * 3.0;
drawLabel(context, x: x, y: posY - _legend.textHeightMax * 2.0, label: labels[i]!, font: labelFont, textColor: labelTextColor);
}
// make a step down
posY += _legend.yEntrySpace;
stack = 0.0;
}
else
{
stack += formSize + stackSpace;
wasStacked = true;
}
}
break;
case .RightOfChart: fallthrough
case .RightOfChartCenter: fallthrough
case .RightOfChartInside: fallthrough
case .LeftOfChart: fallthrough
case .LeftOfChartCenter: fallthrough
case .LeftOfChartInside:
var isRightAligned = _legend.position == .RightOfChart ||
_legend.position == .RightOfChartCenter ||
_legend.position == .RightOfChartInside;
var posX: CGFloat = 0.0, posY: CGFloat = 0.0;
if (isRightAligned)
{
posX = viewPortHandler.chartWidth - xoffset;
if (direction == .LeftToRight)
{
posX -= _legend.textWidthMax;
}
}
else
{
posX = xoffset;
if (direction == .RightToLeft)
{
posX += _legend.textWidthMax;
}
}
if (_legend.position == .RightOfChart ||
_legend.position == .LeftOfChart)
{
posY = viewPortHandler.contentTop + yoffset
}
else if (_legend.position == .RightOfChartCenter ||
_legend.position == .LeftOfChartCenter)
{
posY = viewPortHandler.chartHeight / 2.0 - _legend.neededHeight / 2.0;
}
else /*if (legend.position == .RightOfChartInside ||
legend.position == .LeftOfChartInside)*/
{
posY = viewPortHandler.contentTop + yoffset;
}
for (var i = 0; i < labels.count; i++)
{
var drawingForm = _legend.colors[i] != UIColor.clearColor();
var x = posX;
if (drawingForm)
{
if (direction == .LeftToRight)
{
x += stack;
}
else
{
x -= formSize - stack;
}
drawForm(context, x: x, y: posY, colorIndex: i, legend: _legend);
if (direction == .LeftToRight)
{
x += formSize;
}
}
if (labels[i] != nil)
{
if (drawingForm && !wasStacked)
{
x += direction == .LeftToRight ? formToTextSpace : -formToTextSpace;
}
else if (wasStacked)
{
x = posX;
}
if (direction == .RightToLeft)
{
x -= (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont]).width;
}
if (!wasStacked)
{
drawLabel(context, x: x, y: posY - _legend.textHeightMax / 2.0, label: _legend.getLabel(i)!, font: labelFont, textColor: labelTextColor);
posY += textDrop;
}
else
{
posY += _legend.textHeightMax * 3.0;
drawLabel(context, x: x, y: posY - _legend.textHeightMax * 2.0, label: _legend.getLabel(i)!, font: labelFont, textColor: labelTextColor);
}
// make a step down
posY += _legend.yEntrySpace;
stack = 0.0;
}
else
{
stack += formSize + stackSpace;
wasStacked = true;
}
}
break;
}
}
private var _formLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint());
/// Draws the Legend-form at the given position with the color at the given index.
internal func drawForm(context: CGContext, x: CGFloat, y: CGFloat, colorIndex: Int, legend: ChartLegend)
{
var formColor = legend.colors[colorIndex];
if (formColor === nil || formColor == UIColor.clearColor())
{
return;
}
var formsize = legend.formSize;
CGContextSaveGState(context);
switch (legend.form)
{
case .Circle:
CGContextSetFillColorWithColor(context, formColor!.CGColor);
CGContextFillEllipseInRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize));
break;
case .Square:
CGContextSetFillColorWithColor(context, formColor!.CGColor);
CGContextFillRect(context, CGRect(x: x, y: y - formsize / 2.0, width: formsize, height: formsize));
break;
case .Line:
CGContextSetLineWidth(context, legend.formLineWidth);
CGContextSetStrokeColorWithColor(context, formColor!.CGColor);
_formLineSegmentsBuffer[0].x = x;
_formLineSegmentsBuffer[0].y = y;
_formLineSegmentsBuffer[1].x = x + formsize;
_formLineSegmentsBuffer[1].y = y;
CGContextStrokeLineSegments(context, _formLineSegmentsBuffer, 2);
break;
}
CGContextRestoreGState(context);
}
/// Draws the provided label at the given position.
internal func drawLabel(context: CGContext, x: CGFloat, y: CGFloat, label: String, font: UIFont, textColor: UIColor)
{
ChartUtils.drawText(context: context, text: label, point: CGPoint(x: x, y: y), align: .Left, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: textColor]);
}
} | apache-2.0 | 0e982e4f9f4bfab4709122e0eaf2aaa4 | 35.768482 | 185 | 0.44084 | 5.8799 | false | false | false | false |
aliceatlas/daybreak | Classes/SBWebView.swift | 1 | 6729 | /*
SBWebView.swift
Copyright (c) 2014, Alice Atlas
Copyright (c) 2010, Atsushi Jike
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
@objc protocol SBWebViewDelegate {
optional func webViewShouldOpenFindbar(_: SBWebView)
optional func webViewShouldCloseFindbar(_: SBWebView) -> Bool
}
class SBWebView: WebView, SBFindbarTarget {
weak var delegate: SBWebViewDelegate?
var showFindbar = false
private var magnified = false
var _textEncodingName: String?
var textEncodingName: String {
get { return _textEncodingName ?? preferences.defaultTextEncodingName }
set(textEncodingName) { _textEncodingName = textEncodingName }
}
var documentString: String {
return (mainFrame.frameView.documentView as! WebDocumentText).string()
}
var isEmpty: Bool {
let URLString = mainFrame.dataSource?.request.URL?.absoluteString
return (URLString ?? "") == ""
}
// MARK: Menu Actions
func performFind(sender: AnyObject) {
if bounds.size.width >= SBFindbar.availableWidth {
executeOpenFindbar()
} else {
NSBeep()
}
}
func performFindNext(sender: AnyObject) {
if let string = NSPasteboard(name: NSFindPboard).stringForType(NSStringPboardType)?.ifNotEmpty {
let caseFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindCaseFlag)
let wrapFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindWrapFlag)
searchFor(string, direction: true, caseSensitive: caseFlag, wrap: wrapFlag, continuous: false)
} else {
performFind(sender)
}
}
func performFindPrevious(sender: AnyObject) {
if let string = NSPasteboard(name: NSFindPboard).stringForType(NSStringPboardType)?.ifNotEmpty {
let caseFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindCaseFlag)
let wrapFlag = NSUserDefaults.standardUserDefaults().boolForKey(kSBFindWrapFlag)
searchFor(string, direction: false, caseSensitive: caseFlag, wrap: wrapFlag, continuous: false)
} else {
performFind(sender)
}
}
func searchFor(searchString: String, direction forward: Bool, caseSensitive caseFlag: Bool, wrap wrapFlag: Bool, continuous: Bool) -> Bool {
var r = false
if continuous {
let range = rangeOfStringInWebDocument(searchString, caseSensitive: caseFlag) // Flip case flag
r = range != nil
} else {
r = searchFor(searchString, direction: forward, caseSensitive: !caseFlag, wrap: wrapFlag)
}
if respondsToSelector(#selector(unmarkAllTextMatches)) {
unmarkAllTextMatches()
}
if r {
if respondsToSelector(#selector(markAllMatchesForText(_:caseSensitive:highlight:limit:))) {
markAllMatchesForText(searchString, caseSensitive: !caseFlag, highlight: true, limit: 0)
}
} else {
NSBeep()
}
return r
}
func executeOpenFindbar() {
if let f = delegate?.webViewShouldOpenFindbar {
f(self)
showFindbar = true
}
}
func executeCloseFindbar() -> Bool {
if let f = delegate?.webViewShouldCloseFindbar {
let r = f(self)
showFindbar = false
return r
}
return false
}
// Return range of string in web document
func rangeOfStringInWebDocument(string: String, caseSensitive caseFlag: Bool) -> Range<String.Index>? {
return documentString.ifNotEmpty?.rangeOfString(string, options:(caseFlag ? [.CaseInsensitiveSearch] : []))
}
override func keyDown(event: NSEvent) {
let character = (event.characters! as NSString).characterAtIndex(0)
if character == 0x1B {
if !executeCloseFindbar() {
super.keyDown(event)
}
} else {
super.keyDown(event)
}
}
// MARK: Gesture
override func beginGestureWithEvent(event: NSEvent) {
magnified = false
}
override func endGestureWithEvent(event: NSEvent) {
magnified = true
}
override func magnifyWithEvent(event: NSEvent) {
if !magnified {
let magnification = event.magnification
if magnification > 0 {
zoomPageIn(nil)
magnified = true
} else if magnification < 0 {
zoomPageOut(nil)
magnified = true
}
}
}
override func swipeWithEvent(event: NSEvent) {
let deltaX = event.deltaX
if deltaX > 0 { // Left
if canGoBack {
if loading {
stopLoading(nil)
}
goBack(nil)
} else {
NSBeep()
}
} else if deltaX < 0 { // Right
if canGoForward {
if loading {
stopLoading(nil)
}
goForward(nil)
} else {
NSBeep()
}
}
}
// MARK: Private API
func showWebInspector(sender: AnyObject?) {
inspector.show(nil)
}
override func showConsole(sender: AnyObject?) {
inspector.show(nil)
SBDispatchDelay(0.25) {
self.inspector.showConsole(nil)
}
}
} | bsd-2-clause | c1927bed53d1b661de3fc65f5fe238b1 | 33.512821 | 144 | 0.626542 | 4.908096 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Extensions/NSMutableAttributedString+trim.swift | 1 | 714 | import Foundation
extension NSMutableAttributedString {
public func trim(using charSet: CharacterSet) {
var range = (string as NSString).rangeOfCharacter(from: charSet)
// Trim leading characters from character set.
while range.length != 0 && range.location == 0 {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet)
}
// Trim trailing characters from character set.
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
while range.length != 0 && NSMaxRange(range) == length {
replaceCharacters(in: range, with: "")
range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
}
}
}
| mit | ef355610129d58452b9e36f826ca8b75 | 34.7 | 84 | 0.721289 | 4.08 | false | false | false | false |
devroo/onTodo | Swift/Functions.playground/section-1.swift | 1 | 6989 | // Playground - noun: a place where people can play
import UIKit
/*
* 함수 (Functions)
*/
// 함수 정의와 호출
func sayHello(personName: String) -> String {
let greeting = "Hello, " + personName + "!"
return greeting
}
println(sayHello("Anna"))
// prints "Hello, Anna!"
println(sayHello("Brian"))
// prints "Hello, Brian!"
func sayHelloAgain(personName: String) -> String {
return "Helloagain, " + personName + "!"
}
println(sayHelloAgain("Anna"))
// prints "Helloagain, Anna!"
// 함수 파라메터와 반환값
func halfOpenRangeLength(start: Int, end: Int) -> Int {
return end - start
}
println(halfOpenRangeLength(1, 10))
// prints "9"
func sayHelloWorld() -> String {
return "hello, world"
}
println(sayHelloWorld())
// prints "hello, world"
func sayGoodbye(personName: String) {
println("Goodbye, ` \(personName)! ")
}
sayGoodbye("Dave")
// prints "Goodbye, Dave!"
func printAndCount(stringToPrint: String) -> Int {
println(stringToPrint)
return countElements(stringToPrint)
}
func printWithoutCounting(stringToPrint: String) {
printAndCount(stringToPrint)
}
printAndCount("hello, world")
// prints "hello, world" and returns a value of 12
printWithoutCounting("hello, world")
// prints "hello, world" but does not return a value
// 여러개의 반환값을 가지는 함수
func count(string: String) -> (vowels: Int, consonants: Int, others: Int) {
var vowels = 0, consonants = 0, others = 0
for character in string {
switch String(character).lowercaseString {
case "a", "e", "i ", "o", "u":
++vowels
case "b", "c", "d", "f", "g", "h", "j", "k", "l ", "m",
"n", "p", "q", "r", "s", "t", "v", "w ", "x", "y", "z":
++consonants
default:
++others
}
}
return (vowels, consonants, others)
}
let total = count("some arbitrary string! ")
println("\(total.0) vowels and \(total.consonants) consonants")
// prints "6 vowels and 13 consonants"
// 함수 파라미터 이름
func someFunction(parameterName: Int) {
// function body goes here, and can use parameterName
// to refer to the argument value for that parameter
}
// 외부 파라미터 이름(External Parameter Names)
func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use local ParameterName
// to refer to the argument value for that parameter
}
func join(s1: String, s2: String, joiner: String) -> String {
return s1 + joiner + s2
}
join("hello", "world", ", ")
// returns "hello, world"
func join(string s1: String, toString s2: String, withJoiner joiner: String)
-> String {
return s1 + joiner + s2
}
join(string: "hello", toString: "world", withJoiner: ", ")
// returns "hello, world"
// 코드를 처음 보았을때 명확하지 않을 수 있다면 외부 파라메터 이름을 쓰는것을 언제나 고려하는 것이 가독성이 좋음
// 단축 외부 파라미터 이름
func containsCharacter(#string: String, #characterToFind: Character) -> Bool {
for character in string {
if character == characterToFind {
return true
}
}
return false
}
let containsAVee = containsCharacter(string: "aardvark", characterToFind: "v")
// containsAVee equals true, because "aardvark" contai ns a "v"
// 기본(default) 파라미터 값
func join2(string s1: String, toString s2: String, withJoiner joiner: String = " ")
-> String {
return s1 + joiner + s2
}
join2(string: "hello", toString: "world", withJoiner: "-")
// returns "hello-world
join2(string: "hello", toString: "world")
// returns "hello world"
// 기본값을 가지는 외부 파라미터 이름
func join3(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
join3("hello", "world", joiner: "-")
// returns "hello-world"
// 가변 갯수(Variadic) 파라미터
func arithmeticMean(numbers: Double...) -> Double {
var total : Double = 0
for number in numbers {
total += number
}
return total / Double(numbers.count)
}
arithmeticMean(1, 2, 3, 4, 5)
// returns 3.0, which is the arithmetic mean of these five numbers
arithmeticMean(3, 8, 19)
// returns 10.0, which is the arithmetic mean of these three numbers
// 상수(Constant)와 가변(Variable) 파라미터
func alignRight(var string: String, count: Int, pad: Character) -> String {
let amountToPad = count - countElements(string)
for _ in 1...amountToPad {
string = pad + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, "-")
// paddedString is equal to "-----hello"
// originalString is still equal to "hello"
// 입출력(In-Out)파라미터
func swapTwoInts(inout a: Int, inout b: Int) {
let temporaryA = a
a = b
b = temporaryA
}
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
println("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// prints "someInt is now 107, and anotherInt is now 3"
// 함수 타입
func addTwoInts(a: Int, b: Int) -> Int {
return a + b
}
func multiplyTwoInts(a: Int, b: Int) -> Int {
return a * b
}
func printHelloWorld() {
println("hello, world")
}
var mathFunction: (Int, Int) -> Int = addTwoInts
println("Result: \(mathFunction(2, 3))")
// prints "Result: 5"
mathFunction = multiplyTwoInts
println("Result: \(mathFunction(2, 3))")
// prints "Result: 6"
let anotherMathFunction = addTwoInts
// anotherMathFunction is inferred to be of type (Int, Int) -> Int페
func printMathResult(mathFunction: (Int, Int) -> Int, a: Int, b: Int) {
println("Result: \(mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
// prints "Result: 8"
// 함수 타입과 반환 타입
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearerToZero = chooseStepFunction(currentValue > 0)
// moveNearerToZero now refers to the stepBackward() function
println("Counting to zero:")
// Counting to zero:
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero(currentValue)
}
println("zero!")
// 3...
// 2...
// 1...
// zero!
// 중첩된 함수들
func chooseStepFunction2(backwards: Bool) -> (Int) -> Int {
func stepForward(input: Int) -> Int { return input + 1 }
func stepBackward(input: Int) -> Int { return input - 1 }
return backwards ? stepBackward : stepForward
}
currentValue = -4
let moveNearerToZero2 = chooseStepFunction2(currentValue > 0)
// moveNearerToZero now refers to the nested stepForward() function
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearerToZero2(currentValue)
}
println("zero!")
// -4...
// -3...
// -2...
// -1...
// zero!
| gpl-2.0 | 75e800abd6d585f0ab5299213218101f | 25.272727 | 83 | 0.655183 | 3.271161 | false | false | false | false |
coolryze/YZPlayer | YZPlayerDemo/YZPlayerDemo/Tools/CommonTools.swift | 1 | 2863 | //
// CommonTools.swift
// MU
//
// Created by heyuze on 16/7/8.
// Copyright © 2016年 HYZ. All rights reserved.
//
import UIKit
// MARK: - 随机字符串
func randomSmallCaseString(length: Int) -> String {
var output = ""
for _ in 0..<length {
let randomNumber = arc4random() % 26 + 97
let randomChar = Character(UnicodeScalar(randomNumber)!)
output.append(randomChar)
}
return output
}
// MARK: - Color
// 随机颜色
func randomColor() -> UIColor {
return UIColor(red: CGFloat(arc4random() % 256) / 255, green: CGFloat(arc4random() % 256) / 255, blue: CGFloat(arc4random() % 256) / 255, alpha: 1)
}
public extension UIColor {
public convenience init(colorHex: UInt32, alpha: CGFloat = 1.0) {
let red = CGFloat((colorHex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((colorHex & 0x00FF00) >> 8 ) / 255.0
let blue = CGFloat((colorHex & 0x0000FF) ) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
// MARK: - 时间
// 秒数转换为时间
func secondsConverToTimeStr(seconds: Int) -> String {
if seconds >= 3600 {
let hour = seconds / 3600
let minute = (seconds - 3600*hour) / 60
let second = seconds % 60
return String.init(format: "%02d:%02d:%02d", hour, minute, second)
} else {
let minute = seconds / 60
let second = seconds % 60
return String.init(format: "%02d:%02d", minute, second)
}
}
// 把时间戳和当前时间做比较,转换为xxx天前
func compareNowTimeToStr(time: Int) -> String {
let nowTime = Int(Date().timeIntervalSince1970)
let diffSecond = nowTime - time
if diffSecond < 60 {
return "\(diffSecond)秒前"
} else if diffSecond < 3600 {
let minute = diffSecond / 60
return "\(minute)分钟前"
} else if diffSecond < 3600*24 {
let hour = diffSecond / 3600
return "\(hour)小时前"
} else {
let day = diffSecond / (3600*24)
return "\(day)天前"
}
}
func convertToDate(time: Int) -> String {
let timeDouble = Double(time)
// 时间转换
let dateFormatter = DateFormatter()
dateFormatter.dateFormat="yyyy/MM/dd"
let date = Date.init(timeIntervalSince1970: timeDouble)
let dateStr = dateFormatter.string(from: date)
return dateStr
}
// 获取时间长度
func getTimeLengthStr(length: Int) -> String {
let minute = length / 60
let second = length % 60
let lengthStr = String.init(format: "%02d′%02d″", minute, second)
return lengthStr
}
/*
// MARK: - 自定义Log
func printLog(_ message: Any, file: String = #file, line: Int = #line, function: String = #function)
{
#if DEBUG
print("\((file as NSString).lastPathComponent)[\(line)], \(function): \(message)\n")
#endif
}
*/
| mit | e78262987dc7ce32b74af2e1cc864a8b | 26.656566 | 151 | 0.609569 | 3.483461 | false | false | false | false |
Heisenbean/PopView | PopView/ViewController.swift | 1 | 1159 | //
// ViewController.swift
// PopView
//
// Created by Heisenbean on 15/11/30.
// Copyright © 2015年 Heisenbean. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func didClickedLeftButton() {
modalPopView(PopViewType.left)
}
@IBAction func didClickedCenterButton() {
modalPopView(PopViewType.center)
}
@IBAction func didClickeRightButton() {
modalPopView(PopViewType.right)
}
let animationDelegate = PopoverAnimation()
func modalPopView(_ type:PopViewType){
let popVc = PopViewController()
popVc.popType = type
popVc.transitioningDelegate = animationDelegate
animationDelegate.popViewType = type
popVc.modalPresentationStyle = UIModalPresentationStyle.custom
popVc.selectDelegate = self
present(popVc, animated: true, completion: nil)
}
}
extension ViewController:DidSelectPopViewCellDelegate{
func didSelectRowAtIndexPath(_ indexPath: IndexPath) {
print("点击了第\(indexPath.row)个")
}
}
| mit | aed8f833ba9139e4060529a0f6a1146f | 22.387755 | 70 | 0.679756 | 4.620968 | false | false | false | false |
Chriskuei/Bon-for-Mac | Bon/MainViewController.swift | 1 | 2536 | //
// MainViewController.swift
// Bon
//
// Created by Chris on 16/5/14.
// Copyright © 2016年 Chris. All rights reserved.
//
import Cocoa
class MainViewController: NSViewController {
let statusItem = NSStatusBar.system.statusItem(withLength: -2)
let popover = NSPopover()
var eventMonitor: EventMonitor?
var refreshTimer: Timer?
override func awakeFromNib() {
if let button = statusItem.button {
let icon = NSImage(named: NSImage.Name(rawValue: "icon_status"))
icon?.isTemplate = false
button.image = icon
button.action = #selector(self.togglePopover(_:))
}
popover.behavior = .transient
popover.contentViewController = BonViewController(nibName: NSNib.Name(rawValue: "BonViewController"), bundle: nil)
popover.appearance = NSAppearance(named: NSAppearance.Name.aqua)
popover.behavior = .transient
eventMonitor = EventMonitor(mask: [NSEvent.EventTypeMask.leftMouseDown, NSEvent.EventTypeMask.rightMouseDown]) { [unowned self] event in
if self.popover.isShown {
self.closePopover(event)
}
}
eventMonitor?.start()
refreshTimer = Timer.every(3.minutes) {
NotificationCenter.default.post(name: Notification.Name(rawValue: BonConfig.BonNotification.GetOnlineInfo), object: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
@objc func togglePopover(_ sender: AnyObject?) {
if popover.isShown {
closePopover(sender)
} else {
showPopover(sender)
}
}
func showPopover(_ sender: AnyObject?) {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
eventMonitor?.start()
}
func closePopover(_ sender: AnyObject?) {
popover.performClose(sender)
eventMonitor?.stop()
}
@objc func openGithub() {
let path = "https://github.com/Chriskuei"
let url = URL(string: path)!
NSWorkspace.shared.open(url)
}
@objc func openWeibo() {
let path = "https://weibo.com/chenjiangui"
let url = URL(string: path)!
NSWorkspace.shared.open(url)
}
@objc func quit() {
NSApplication.shared.terminate(self)
}
}
| mit | 997a1c100c08c9134322926c3bbd2809 | 27.784091 | 144 | 0.594552 | 4.716946 | false | false | false | false |
mominul/swiftup | Sources/libNix/libNix.swift | 1 | 2163 | import Glibc
import StringPlus
// This is only for compability...
public enum NixError: Error {
case errorOccurred
case fileOpenError
}
public func contentsOfDirectory(atPath path: String) throws -> [String] {
var contents : [String] = [String]()
let dir = opendir(path)
if dir == nil {
throw NixError.errorOccurred
}
defer {
closedir(dir!)
}
while let entry = readdir(dir!) {
let entryName = withUnsafePointer(to: &entry.pointee.d_name) {
String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
if entryName != "." && entryName != ".." {
contents.append(entryName)
}
}
return contents
}
public func getContentsOf(file: String) throws -> String {
let fp = fopen(file, "r")
if fp == nil {
throw NixError.fileOpenError
}
let contents = UnsafeMutablePointer<CChar>.allocate(capacity: Int(BUFSIZ))
defer {
contents.deinitialize(count: Int(BUFSIZ))
contents.deallocate(capacity: Int(BUFSIZ))
fclose(fp)
}
fgets(contents, BUFSIZ, fp)
return String(cString: contents)
}
public func writeTo(file: String, with: String) throws {
let fp = fopen(file, "w")
if fp == nil {
throw NixError.errorOccurred
}
fputs(with, fp)
fclose(fp)
}
public func fileExists(atPath path: String) -> Bool {
var s = stat()
if lstat(path, &s) >= 0 {
// don't chase the link for this magic case -- we might be /Net/foo
// which is a symlink to /private/Net/foo which is not yet mounted...
if (s.st_mode & S_IFMT) == S_IFLNK {
if (s.st_mode & S_ISVTX) == S_ISVTX {
return true
}
// chase the link; too bad if it is a slink to /Net/foo
stat(path, &s)
}
} else {
return false
}
return true
}
public func createDirectory(atPath path: String) throws {
if !fileExists(atPath: path) {
let parent = path.deletingLastPathComponent
if !fileExists(atPath: parent) {
try createDirectory(atPath: parent)
}
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw NixError.errorOccurred
}
}
}
| apache-2.0 | d94965deeac1f08ceee0205a81403103 | 22.258065 | 80 | 0.643088 | 3.534314 | false | false | false | false |
rnystrom/GitHawk | Classes/Views/FeedRefresh.swift | 1 | 1733 | //
// FeedRefreshControl.swift
// Freetime
//
// Created by Ryan Nystrom on 8/12/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
final class FeedRefresh {
let refreshControl = FixedRefreshControl()
private var refreshBegin: TimeInterval = -1
init() {
refreshControl.layer.zPosition = -1
refreshControl.addTarget(self, action: #selector(FeedRefresh.setRefreshing), for: .valueChanged)
}
// MARK: Public API
func beginRefreshing() {
refreshControl.beginRefreshing()
if let scrollView = refreshControl.superview as? UIScrollView {
let contentOffset = scrollView.contentOffset
scrollView.setContentOffset(
CGPoint(
x: contentOffset.x,
y: contentOffset.y - refreshControl.bounds.height),
animated: trueUnlessReduceMotionEnabled
)
}
setRefreshing()
}
@objc func setRefreshing() {
refreshBegin = CFAbsoluteTimeGetCurrent()
}
func endRefreshing(updates: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
let block = {
updates?()
CATransaction.begin()
CATransaction.setCompletionBlock(completion)
self.refreshControl.endRefreshing()
CATransaction.commit()
}
// delay the refresh control dismissal so the UI isn't too spazzy on fast or non-existent connections
let remaining = 0.5 - (CFAbsoluteTimeGetCurrent() - refreshBegin)
if remaining > 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + remaining, execute: block)
} else {
block()
}
}
}
| mit | 947909da2ec8e4f6839912a7325ee7c0 | 27.393443 | 109 | 0.603926 | 5.170149 | false | false | false | false |
iOS-mamu/SS | P/Pods/PSOperations/PSOperationsHealth/HealthCapability.swift | 1 | 3038 | //
// HealthCapability.swift
// PSOperations
//
// Created by Dev Team on 10/4/15.
// Copyright © 2015 Pluralsight. All rights reserved.
//
#if os(iOS) || os(watchOS)
import Foundation
import HealthKit
import PSOperations
public struct Health: CapabilityType {
public static let name = "Health"
fileprivate let readTypes: Set<HKSampleType>
fileprivate let writeTypes: Set<HKSampleType>
public init(typesToRead: Set<HKSampleType>, typesToWrite: Set<HKSampleType>) {
self.readTypes = typesToRead
self.writeTypes = typesToWrite
}
public func requestStatus(_ completion: @escaping (CapabilityStatus) -> Void) {
guard HKHealthStore.isHealthDataAvailable() else {
completion(.notAvailable)
return
}
let notDeterminedTypes = writeTypes.filter { SharedHealthStore.authorizationStatus(for: $0) == .notDetermined }
if notDeterminedTypes.isEmpty == false {
completion(.notDetermined)
return
}
let deniedTypes = writeTypes.filter { SharedHealthStore.authorizationStatus(for: $0) == .sharingDenied }
if deniedTypes.isEmpty == false {
completion(.denied)
return
}
// if we get here, then every write type has been authorized
// there's no way to know if we have read permissions,
// so the best we can do is see if we've ever asked for authorization
let unrequestedReadTypes = readTypes.subtracting(requestedReadTypes)
if unrequestedReadTypes.isEmpty == false {
completion(.notDetermined)
return
}
// if we get here, then there was nothing to request for reading or writing
// thus, everything is authorized
completion(.authorized)
}
public func authorize(_ completion: @escaping (CapabilityStatus) -> Void) {
guard HKHealthStore.isHealthDataAvailable() else {
completion(.notAvailable)
return
}
// make a note that we've requested these types before
requestedReadTypes.formUnion(readTypes)
// This method is smart enough to not re-prompt for access if it has already been granted.
SharedHealthStore.requestAuthorization(toShare: writeTypes, read: readTypes) { _, error in
if let error = error {
completion(.error(error as NSError))
} else {
self.requestStatus(completion)
}
}
}
}
/**
HealthKit does not report on whether or not you're allowed to read certain data types.
Instead, we'll keep track of which types we've already request to read. If a new request
comes along for a type that's not in here, we know that we'll need to re-prompt for
permission to read that particular type.
*/
private var requestedReadTypes = Set<HKSampleType>()
private let SharedHealthStore = HKHealthStore()
#endif
| mit | 59cf4c28d7473e9706b37cd53848ebba | 32.744444 | 119 | 0.6378 | 4.962418 | false | false | false | false |
svbeemen/Eve | Eve/Eve/InstructionView.swift | 1 | 1358 | //
// InstructionView.swift
// Eve
//
// Created by Sangeeta van Beemen on 24/06/15.
// Copyright (c) 2015 Sangeeta van Beemen. All rights reserved.
//
import UIKit
class InstructionView: UIVisualEffectView
{
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)!
}
override init(effect: UIVisualEffect?)
{
super.init(effect: UIBlurEffect(style: UIBlurEffectStyle.Light))
let tapRegonizer = UITapGestureRecognizer(target: self, action: #selector(InstructionView.viewTapped))
self.addGestureRecognizer(tapRegonizer)
let label = UILabel(frame: CGRectMake(120, 80, 300, 400));
label.center = CGPointMake(UIScreen.mainScreen().bounds.width / 2, UIScreen.mainScreen().bounds.height / 2.5)
label.textAlignment = NSTextAlignment.Center
label.font = UIFont(name: "Arial", size: 22)
label.text = "Welcome To Eve. Select the dates you last had your period. For the most accurate results please set as many previous period dates as possible. Press the ♀ for your predicted ovulation and menstruation dates."
label.numberOfLines = 10
label.textColor = UIColor.darkGrayColor()
self.addSubview(label)
}
func viewTapped()
{
self.removeFromSuperview()
}
} | mit | 2bf877354ec4b6d723538b6c800d8074 | 32.925 | 248 | 0.661504 | 4.431373 | false | false | false | false |
adrfer/swift | test/SILGen/external_definitions.swift | 4 | 2582 | // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen | FileCheck %s
// REQUIRES: objc_interop
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @_TFCSo7AnsibleC
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: release_value [[ANSIBLE]] : $ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<AnyObject>, @thick Ansible.Type) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject
// -- Native Swift thunk for NSAnse
// CHECK: sil shared @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible> {
// CHECK: bb0(%0 : $ImplicitlyUnwrappedOptional<Ansible>):
// CHECK: %1 = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: %2 = apply %1(%0) : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: release_value %0 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: return %2 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@thick Ansible.Type) -> @owned Ansible
| apache-2.0 | f52b0bd35c09b7ae911b4a4254551861 | 56.377778 | 193 | 0.711851 | 4.184765 | false | false | false | false |
qualaroo/QualarooSDKiOS | Qualaroo/Survey/Body/Question/Text/AnswerTextView.swift | 1 | 2091 | //
// AnswerTextView.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import UIKit
class AnswerTextView: UIView, FocusableAnswerView {
private var interactor: AnswerTextInteractor!
private var inactiveTextBorderColor: UIColor = UIColor.clear
private var activeTextBorderColor: UIColor = UIColor.clear
@IBOutlet weak var responseTextView: UITextView!
func setupView(backgroundColor: UIColor,
activeTextBorderColor: UIColor,
inactiveTextBorderColor: UIColor,
keyboardStyle: UIKeyboardAppearance,
interactor: AnswerTextInteractor) {
self.backgroundColor = backgroundColor
self.inactiveTextBorderColor = inactiveTextBorderColor
self.activeTextBorderColor = activeTextBorderColor
responseTextView.layer.borderColor = inactiveTextBorderColor.cgColor
responseTextView.layer.borderWidth = 1.0
responseTextView.layer.cornerRadius = 4.0
responseTextView.keyboardAppearance = keyboardStyle
responseTextView.delegate = self
self.interactor = interactor
}
func getFocus() {
responseTextView.becomeFirstResponder()
}
private func changeBorderColor(_ newColor: UIColor) {
let animation = CABasicAnimation(keyPath: "borderColor")
animation.fromValue = responseTextView.layer.borderColor
animation.toValue = newColor.cgColor
animation.duration = kAnimationTime
animation.repeatCount = 1
responseTextView.layer.add(animation, forKey: "borderColor")
responseTextView.layer.borderColor = newColor.cgColor
}
}
extension AnswerTextView: UITextViewDelegate {
func textViewDidChange(_ textView: UITextView) {
interactor.setAnswer(textView.text)
}
func textViewDidBeginEditing(_ textView: UITextView) {
changeBorderColor(activeTextBorderColor)
}
func textViewDidEndEditing(_ textView: UITextView) {
changeBorderColor(inactiveTextBorderColor)
}
}
| mit | 3979a01c9f4ce272193d3ef7524e477c | 32.190476 | 72 | 0.751315 | 5.014388 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift | 42 | 4067 | //
// TailRecursiveSink.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
enum TailRecursiveSinkCommand {
case MoveNext
case Dispose
}
#if DEBUG || TRACE_RESOURCES
public var maxTailRecursiveSinkStackSize = 0
#endif
/// This class is usually used with `Generator` version of the operators.
class TailRecursiveSink<S: SequenceType, O: ObserverType where S.Generator.Element: ObservableConvertibleType, S.Generator.Element.E == O.E>
: Sink<O>
, InvocableWithValueType {
typealias Value = TailRecursiveSinkCommand
typealias E = O.E
typealias SequenceGenerator = (generator: S.Generator, remaining: IntMax?)
var _generators: [SequenceGenerator] = []
var _disposed = false
var _subscription = SerialDisposable()
// this is thread safe object
var _gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<S, O>>>()
override init(observer: O) {
super.init(observer: observer)
}
func run(sources: SequenceGenerator) -> Disposable {
_generators.append(sources)
schedule(.MoveNext)
return _subscription
}
func invoke(command: TailRecursiveSinkCommand) {
switch command {
case .Dispose:
disposeCommand()
case .MoveNext:
moveNextCommand()
}
}
// simple implementation for now
func schedule(command: TailRecursiveSinkCommand) {
_gate.invoke(InvocableScheduledItem(invocable: self, state: command))
}
func done() {
forwardOn(.Completed)
dispose()
}
func extract(observable: Observable<E>) -> SequenceGenerator? {
abstractMethod()
}
// should be done on gate locked
private func moveNextCommand() {
var next: Observable<E>? = nil
repeat {
if _generators.count == 0 {
break
}
if _disposed {
return
}
var (e, left) = _generators.last!
_generators.removeLast()
guard let nextCandidate = e.next()?.asObservable() else {
continue
}
// `left` is a hint of how many elements are left in generator.
// In case this is the last element, then there is no need to push
// that generator on stack.
//
// This is an optimization used to make sure in tail recursive case
// there is no memory leak in case this operator is used to generate non terminating
// sequence.
if let knownOriginalLeft = left {
// `- 1` because generator.next() has just been called
if knownOriginalLeft - 1 >= 1 {
_generators.append((e, knownOriginalLeft - 1))
}
}
else {
_generators.append((e, nil))
}
let nextGenerator = extract(nextCandidate)
if let nextGenerator = nextGenerator {
_generators.append(nextGenerator)
#if DEBUG || TRACE_RESOURCES
if maxTailRecursiveSinkStackSize < _generators.count {
maxTailRecursiveSinkStackSize = _generators.count
}
#endif
}
else {
next = nextCandidate
}
} while next == nil
if next == nil {
done()
return
}
let disposable = SingleAssignmentDisposable()
_subscription.disposable = disposable
disposable.disposable = subscribeToNext(next!)
}
func subscribeToNext(source: Observable<E>) -> Disposable {
abstractMethod()
}
func disposeCommand() {
_disposed = true
_generators.removeAll(keepCapacity: false)
}
override func dispose() {
super.dispose()
_subscription.dispose()
schedule(.Dispose)
}
}
| mit | 11b73cebc1256581ae88dd2c067dc293 | 25.75 | 140 | 0.572061 | 5.057214 | false | false | false | false |
dnseitz/YAPI | YAPI/YAPI/V3/YelpV3SearchRequest.swift | 1 | 1618 | //
// YelpV3SearchRequest.swift
// YAPI
//
// Created by Daniel Seitz on 10/3/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
import OAuthSwift
public final class YelpV3SearchRequest : YelpRequest {
public typealias Response = YelpV3SearchResponse
public let oauthVersion: OAuthSwiftCredential.Version = .oauth2
public let path: String = YelpEndpoints.V3.search
public let parameters: [String : String]
public var requestMethod: OAuthSwiftHTTPRequest.Method {
return .GET
}
public let session: YelpHTTPClient
init(searchParameters: YelpV3SearchParameters, session: YelpHTTPClient = YelpHTTPClient.sharedSession) {
var parameters = [String: String]()
parameters.insertParameter(searchParameters.term)
parameters.insertParameter(searchParameters.location.location)
parameters.insertParameter(searchParameters.location.latitude)
parameters.insertParameter(searchParameters.location.longitude)
parameters.insertParameter(searchParameters.radius)
parameters.insertParameter(searchParameters.categories)
parameters.insertParameter(searchParameters.locale)
parameters.insertParameter(searchParameters.limit)
parameters.insertParameter(searchParameters.offset)
parameters.insertParameter(searchParameters.sortMode)
parameters.insertParameter(searchParameters.price)
parameters.insertParameter(searchParameters.openNow)
parameters.insertParameter(searchParameters.openAt)
parameters.insertParameter(searchParameters.attributes)
self.parameters = parameters
self.session = session
}
}
| mit | 97ac53a4fa2fc4a6d34b3aa4e4795bb8 | 34.933333 | 106 | 0.793445 | 4.633238 | false | false | false | false |
ibm-cloud-security/appid-serversdk-swift | Sources/IBMCloudAppID/UserProfileManager.swift | 1 | 6842 | /*
Copyright 2018 IBM Corp.
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 Kitura
import Credentials
import KituraNet
import SwiftyJSON
import LoggerAPI
import KituraSession
@available(OSX 10.12, *)
public class UserProfileManager {
var serviceConfig: AppIDPluginConfig
public init(options: [String: Any]?) {
serviceConfig = AppIDPluginConfig(options: options, required: \.userProfileServerUrl, \.serverUrl)
}
public func setAttribute (accessToken: String,
attributeName: String,
attributeValue: String,
completionHandler: @escaping (Swift.Error?, [String:Any]?) -> Void) {
handleAttributeRequest(attributeName: attributeName, attributeValue: attributeValue, method: "put", accessToken: accessToken, completionHandler: completionHandler)
}
public func getAttribute (accessToken: String,
attributeName: String,
completionHandler: @escaping (Swift.Error?, [String:Any]?) -> Void) {
handleAttributeRequest(attributeName: attributeName, attributeValue: nil, method: "get", accessToken: accessToken, completionHandler: completionHandler)
}
public func getAllAttributes (accessToken: String,
completionHandler: @escaping (Swift.Error?, [String:Any]?) -> Void) {
handleAttributeRequest(attributeName: nil, attributeValue: nil, method: "get", accessToken: accessToken, completionHandler: completionHandler)
}
public func deleteAttribute (accessToken: String,
attributeName: String,
completionHandler: @escaping (Swift.Error?, [String:Any]?) -> Void) {
handleAttributeRequest(attributeName: attributeName, attributeValue: nil, method: "delete", accessToken: accessToken, completionHandler: completionHandler)
}
public func getUserInfo(accessToken: String, identityToken: String? = nil, completionHandler: @escaping (Swift.Error?, [String: Any]?) -> Void) {
handleUserInfoRequest(accessToken: accessToken, identityToken: identityToken, completionHandler: completionHandler)
}
private func handleUserInfoRequest(accessToken: String, identityToken: String?, completionHandler: @escaping (Swift.Error?, [String: Any]?) -> Void) {
Log.debug("UserProfileManager :: handle Request - User Info")
guard let url = serviceConfig.serverUrl else {
completionHandler(AppIDRequestError.invalidOauthServerUrl, nil)
return
}
handleRequest(accessToken: accessToken, url: url + Constants.Endpoints.userInfo, method: "GET", body: nil) { (error, userInfo) in
guard error == nil, let userInfo = userInfo else {
Log.debug("Error: Unexpected error while retrieving User Info. Msg: \(error?.localizedDescription ?? "")")
return completionHandler(error ?? AppIDRequestError.unexpectedError, nil)
}
// Validate userinfo response has subject field
guard let subject = userInfo["sub"] as? String else {
Log.error("Error: Invalid response user info response must contain the subject field.")
return completionHandler(error ?? AppIDRequestError.unexpectedError, nil)
}
if let identityToken = identityToken {
guard let identityToken = try? Utils.parseToken(from: identityToken) else {
Log.debug("Error: Invalid identity Token")
return completionHandler(UserProfileError.invalidIdentityToken, nil)
}
if let idSubject = identityToken["payload"]["sub"].string, subject != idSubject {
Log.debug("Error: IdentityToken.sub does not match UserInfoResult.sub.")
return completionHandler(UserProfileError.conflictingSubjects, nil)
}
}
completionHandler(nil, userInfo)
}
}
private func handleAttributeRequest(attributeName: String?, attributeValue: String?, method: String, accessToken: String, completionHandler: @escaping (Swift.Error?, [String:Any]?) -> Void) {
Log.debug("UserProfileManager :: handle Request - " + method + " " + (attributeName ?? "all"))
guard let profileURL = serviceConfig.userProfileServerUrl else {
completionHandler(AppIDRequestError.invalidProfileServerUrl, nil)
return
}
var url = profileURL + Constants.Endpoints.attributes + "/"
if let attributeName = attributeName {
url += attributeName
}
handleRequest(accessToken: accessToken, url: url, method: method, body: attributeValue, completionHandler: completionHandler)
}
internal func handleRequest(accessToken: String, url: String, method: String, body: String?, completionHandler: @escaping (Swift.Error?, [String: Any]?) -> Void) {
let request = HTTP.request(url) {response in
if response?.status == 401 || response?.status == 403 {
Log.error("Unauthorized")
completionHandler(AppIDRequestError.unauthorized, nil)
} else if response?.status == 404 {
Log.error("Not found")
completionHandler(AppIDRequestError.notFound, nil)
} else if let responseStatus = response?.status, responseStatus >= 200 && responseStatus < 300 {
var responseJson: [String: Any] = [:]
do {
if let body = try response?.readString() {
responseJson = try Utils.parseJsonStringtoDictionary(body)
}
completionHandler(nil, responseJson)
} catch _ {
completionHandler(AppIDRequestError.parsingError, nil)
}
} else {
Log.error("Unexpected error")
completionHandler(AppIDRequestError.unexpectedError, nil)
}
}
if let body = body {
request.write(from: body)
}
request.set(.method(method))
request.set(.headers(["Authorization": "Bearer " + accessToken]))
request.end()
}
}
| apache-2.0 | f6bed753cdc1bf9129ecf2c031464b40 | 42.579618 | 195 | 0.638118 | 5.4736 | false | false | false | false |
mathcamp/Carlos | FuturesTests/PromiseTests.swift | 1 | 38165 | import Foundation
import Quick
import Nimble
import PiedPiper
class PromiseTests: QuickSpec {
private class MemoryHelper {
weak var weakVarSuccess: MemorySentinel?
weak var weakVarFailure: MemorySentinel?
weak var weakVarCancel: MemorySentinel?
weak var referencedPromise: Promise<String>?
func setupWithPromise(promise: Promise<String>) {
referencedPromise = promise
promise.onSuccess { _ in
self.weakVarSuccess?.doFoo()
}
promise.onFailure { _ in
self.weakVarFailure?.doFoo()
}
promise.onCancel {
self.weakVarCancel?.doFoo()
}
}
}
private class MemorySentinel {
var didFoo = false
func doFoo() {
didFoo = true
}
}
override func spec() {
describe("Promise") {
var request: Promise<String>!
let sentinelsCount = 3
var successSentinels: [String?]!
var failureSentinels: [ErrorType?]!
var cancelSentinels: [Bool?]!
var successCompletedSentinels: [String?]!
var failureCompletedSentinels: [ErrorType?]!
var cancelCompletedSentinels: [Bool?]!
let resetSentinels: Void -> Void = {
successSentinels = [String?](count: sentinelsCount, repeatedValue: nil)
failureSentinels = [ErrorType?](count: sentinelsCount, repeatedValue: nil)
cancelSentinels = [Bool?](count: sentinelsCount, repeatedValue: nil)
successCompletedSentinels = [String?](count: sentinelsCount, repeatedValue: nil)
failureCompletedSentinels = [ErrorType?](count: sentinelsCount, repeatedValue: nil)
cancelCompletedSentinels = [Bool?](count: sentinelsCount, repeatedValue: nil)
}
context("when managing its listeners") {
weak var weakSut: MemoryHelper?
var promise: Promise<String>!
var successSentinel: MemorySentinel!
var failureSentinel: MemorySentinel!
var cancelSentinel: MemorySentinel!
beforeEach {
let sut = MemoryHelper()
successSentinel = MemorySentinel()
failureSentinel = MemorySentinel()
cancelSentinel = MemorySentinel()
sut.weakVarSuccess = successSentinel
sut.weakVarFailure = failureSentinel
sut.weakVarCancel = cancelSentinel
promise = Promise<String>()
sut.setupWithPromise(promise)
weakSut = sut
}
it("should not release the subject under test because of the listeners retaining it") {
expect(weakSut).notTo(beNil())
}
context("when the promise succeeds") {
beforeEach {
promise.succeed("test")
}
it("should call doFoo on the weak sentinel") {
expect(successSentinel.didFoo).to(beTrue())
}
it("should not call doFoo on the other sentinels") {
expect(failureSentinel.didFoo).to(beFalse())
expect(cancelSentinel.didFoo).to(beFalse())
}
it("should release the subject under test because the listeners are not retaining it anymore") {
expect(weakSut).to(beNil())
}
}
context("when the promise is canceled") {
beforeEach {
promise.cancel()
}
it("should call doFoo on the weak sentinel") {
expect(cancelSentinel.didFoo).to(beTrue())
}
it("should not call doFoo on the other sentinels") {
expect(failureSentinel.didFoo).to(beFalse())
expect(successSentinel.didFoo).to(beFalse())
}
it("should release the subject under test because the listeners are not retaining it anymore") {
expect(weakSut).to(beNil())
}
}
context("when the promise fails") {
beforeEach {
promise.fail(TestError.SimpleError)
}
it("should call doFoo on the weak sentinel") {
expect(failureSentinel.didFoo).to(beTrue())
}
it("should not call doFoo on the other sentinels") {
expect(successSentinel.didFoo).to(beFalse())
expect(cancelSentinel.didFoo).to(beFalse())
}
it("should release the subject under test because the listeners are not retaining it anymore") {
expect(weakSut).to(beNil())
}
}
}
context("when mimicing another future") {
var mimiced: Promise<String>!
var successValue: String!
var errorValue: ErrorType!
var canceled: Bool!
beforeEach {
successValue = nil
errorValue = nil
canceled = false
mimiced = Promise<String>()
request = Promise<String>()
.onSuccess({ successValue = $0 })
.onFailure({ errorValue = $0 })
.onCancel({ canceled = true })
.mimic(mimiced.future)
}
context("when the other future succeeds") {
let value = "success value"
beforeEach {
mimiced.succeed(value)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the error closure") {
expect(errorValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the other future fails") {
let error = TestError.AnotherError
beforeEach {
mimiced.fail(error)
}
it("should call the error closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the other future is canceled") {
beforeEach {
mimiced.cancel()
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
context("when the promise itself succeeds") {
let value = "also a success value"
beforeEach {
request.succeed(value)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the promise itself fails") {
let error = TestError.SimpleError
beforeEach {
request.fail(error)
}
it("should call the failure closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the promise itself is canceled") {
beforeEach {
request.cancel()
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
context("when mimicing two futures at the same time") {
var mimiced2: Promise<String>!
beforeEach {
mimiced2 = Promise<String>()
request.mimic(mimiced2.future)
}
context("when the other future succeeds") {
let value = "still a success value"
beforeEach {
mimiced2.succeed(value)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the other future fails") {
let error = TestError.AnotherError
beforeEach {
mimiced2.fail(error)
}
it("should call the failure closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the other future is canceled") {
beforeEach {
mimiced2.cancel()
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
}
}
context("when mimicing a result") {
var mimiced: Result<String>!
var successValue: String!
var errorValue: ErrorType!
var canceled: Bool!
beforeEach {
successValue = nil
errorValue = nil
canceled = false
request = Promise<String>()
.onSuccess({ successValue = $0 })
.onFailure({ errorValue = $0 })
.onCancel({ canceled = true })
}
context("when the result succeeds") {
let value = "success value"
beforeEach {
mimiced = Result.Success(value)
request.mimic(mimiced)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the error closure") {
expect(errorValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the other future fails") {
let error = TestError.AnotherError
beforeEach {
mimiced = Result.Error(error)
request.mimic(mimiced)
}
it("should call the error closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the other future is canceled") {
beforeEach {
mimiced = Result.Cancelled
request.mimic(mimiced)
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
context("when the promise itself succeeds") {
let value = "also a success value"
beforeEach {
request.succeed(value)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the promise itself fails") {
let error = TestError.SimpleError
beforeEach {
request.fail(error)
}
it("should call the failure closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the cancel closure") {
expect(canceled).to(beFalse())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the promise itself is canceled") {
beforeEach {
request.cancel()
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
context("when mimicing two results at the same time") {
var mimiced2: Result<String>!
context("when the other future succeeds") {
let value = "still a success value"
beforeEach {
mimiced2 = Result.Success(value)
request.mimic(mimiced2)
}
it("should call the success closure") {
expect(successValue).notTo(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
it("should pass the right value") {
expect(successValue).to(equal(value))
}
}
context("when the other future fails") {
let error = TestError.AnotherError
beforeEach {
mimiced2 = Result.Error(error)
request.mimic(mimiced2)
}
it("should call the failure closure") {
expect(errorValue).notTo(beNil())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should pass the right error") {
expect(errorValue as? TestError).to(equal(error))
}
}
context("when the other future is canceled") {
beforeEach {
mimiced2 = Result.Cancelled
request.mimic(mimiced2)
}
it("should call the cancel closure") {
expect(canceled).to(beTrue())
}
it("should not call the success closure") {
expect(successValue).to(beNil())
}
it("should not call the failure closure") {
expect(errorValue).to(beNil())
}
}
}
}
context("when returning its associated Future") {
var future: Future<String>!
beforeEach {
request = Promise<String>()
future = request.future
}
it("should return always the same instance") {
expect(future).to(beIdenticalTo(request.future))
}
itBehavesLike("a Future") {
[
FutureSharedExamplesContext.Future: future,
FutureSharedExamplesContext.Promise: request
]
}
}
context("when initialized with the designated initializer") {
beforeEach {
request = Promise<String>()
resetSentinels()
for idx in 0..<sentinelsCount {
request
.onSuccess { result in
successSentinels[idx] = result
}
.onFailure { error in
failureSentinels[idx] = error
}
.onCancel {
cancelSentinels[idx] = true
}
.onCompletion { result in
switch result {
case .Success(let value):
successCompletedSentinels[idx] = value
case .Error(let error):
failureCompletedSentinels[idx] = error
case .Cancelled:
cancelCompletedSentinels[idx] = true
}
}
}
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
context("when calling succeed") {
let value = "success value"
beforeEach {
request.succeed(value)
}
it("should call the success closures") {
expect(successSentinels).to(allPass({ $0! == value }))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(failureSentinels.count))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(cancelSentinels.count))
}
it("should call the completion closures passing a value") {
for sSentinel in successCompletedSentinels {
expect(sSentinel).to(equal(value))
}
}
it("should not call the completion closures passing an error") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
context("when calling onSuccess again") {
var subsequentSuccessSentinel: String?
beforeEach {
request.onSuccess { result in
subsequentSuccessSentinel = result
}
}
it("should immediately call the closure") {
expect(subsequentSuccessSentinel).to(equal(value))
}
}
context("when calling onCompletion again") {
var subsequentSuccessSentinel: String?
beforeEach {
request.onCompletion { result in
if case .Success(let value) = result {
subsequentSuccessSentinel = value
}
}
}
it("should immediately call the closure") {
expect(subsequentSuccessSentinel).to(equal(value))
}
}
context("when calling succeed again") {
let anotherValue = "another success value"
beforeEach {
resetSentinels()
request.succeed(anotherValue)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling fail") {
beforeEach {
resetSentinels()
request.fail(TestError.SimpleError)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling cancel") {
beforeEach {
resetSentinels()
request.cancel()
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
}
context("when calling fail") {
let errorCode = TestError.AnotherError
beforeEach {
request.fail(errorCode)
}
it("should call the failure closures") {
for fSentinel in failureSentinels {
expect(fSentinel as? TestError).to(equal(errorCode))
}
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(cancelSentinels.count))
}
it("should call the completion closures passing an error") {
for fSentinel in failureCompletedSentinels {
expect(fSentinel as? TestError).to(equal(errorCode))
}
}
it("should not call the completion closures passing a value") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
context("when calling onFailure again") {
var subsequentFailureSentinel: ErrorType?
beforeEach {
request.onFailure { error in
subsequentFailureSentinel = error
}
}
it("should immediately call the closures") {
expect(subsequentFailureSentinel as? TestError).to(equal(errorCode))
}
}
context("when calling onCompletion again") {
var subsequentFailureSentinel: ErrorType?
beforeEach {
request.onCompletion { result in
if case .Error(let error) = result {
subsequentFailureSentinel = error
}
}
}
it("should immediately call the closure") {
expect(subsequentFailureSentinel as? TestError).to(equal(errorCode))
}
}
context("when calling succeed") {
let anotherValue = "a success value"
beforeEach {
resetSentinels()
request.succeed(anotherValue)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling fail again") {
beforeEach {
resetSentinels()
request.fail(TestError.SimpleError)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling cancel") {
beforeEach {
resetSentinels()
request.cancel()
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
}
context("when calling cancel") {
beforeEach {
request.cancel()
}
it("should call the cancel closures") {
for cSentinel in cancelSentinels {
expect(cSentinel).to(beTrue())
}
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(successSentinels.count))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(cancelSentinels.count))
}
it("should call the completion closures passing no error and no value") {
for cSentinel in cancelCompletedSentinels {
expect(cSentinel).to(beTrue())
}
}
context("when calling onCancel again") {
var subsequentCancelSentinel: Bool?
beforeEach {
request.onCancel {
subsequentCancelSentinel = true
}
}
it("should immediately call the closures") {
expect(subsequentCancelSentinel).to(beTrue())
}
}
context("when calling onCompletion again") {
var subsequentCancelSentinel: Bool?
beforeEach {
request.onCompletion { result in
if case .Cancelled = result {
subsequentCancelSentinel = true
} else {
subsequentCancelSentinel = false
}
}
}
it("should immediately call the closure") {
expect(subsequentCancelSentinel).to(beTrue())
}
}
context("when calling succeed") {
let anotherValue = "a success value"
beforeEach {
resetSentinels()
request.succeed(anotherValue)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling fail") {
beforeEach {
resetSentinels()
request.fail(TestError.SimpleError)
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
context("when calling cancel again") {
beforeEach {
resetSentinels()
request.cancel()
}
it("should not call any success closure") {
expect(successSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any failure closure") {
expect(failureSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any cancel closure") {
expect(cancelSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with values") {
expect(successCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with errors") {
expect(failureCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
it("should not call any completion closure with nil error and nil value") {
expect(cancelCompletedSentinels.filter({ $0 == nil }).count).to(equal(sentinelsCount))
}
}
}
}
}
}
} | mit | 7048d521db23b127249d20c85e5de8c0 | 32.745358 | 106 | 0.497 | 5.55208 | false | false | false | false |
XCEssentials/ProjectGenerator | Sources/Spec/Spec.swift | 1 | 826 | import Foundation
//===
typealias SpecLine = (idention: Int, line: String)
typealias RawSpec = [SpecLine]
//===
func <<< (list: inout RawSpec, element: SpecLine)
{
list.append(element)
}
func <<< (list: inout RawSpec, elements: RawSpec)
{
list.append(contentsOf: elements)
}
//===
public
enum Spec
{
public
enum Format: String
{
case
v1_2_1 = "1.2.1",
v1_3_0 = "1.3.0",
v2_0_0 = "2.0.0",
v2_1_0 = "2.1.0"
}
}
//===
extension Spec
{
static
func ident(_ idention: Int) -> String
{
return Array(repeating: " ", count: idention).joined()
}
static
func key(_ v: Any) -> String
{
return "\(v):"
}
static
func value(_ v: Any) -> String
{
return " \"\(v)\""
}
}
| mit | 5ccaf8ebb869764812c5d3610ae2a03c | 13.491228 | 63 | 0.492736 | 3.140684 | false | false | false | false |
fhchina/KZBootstrap | Pod/Assets/Scripts/processEnvironments.swift | 1 | 5124 | #!/usr/bin/xcrun swift
// Playground - noun: a place where people can play
import Foundation
let envKey = "KZBEnvironments"
let overrideKey = "KZBEnvOverride"
func validateEnvSettings(envSettings: NSDictionary?, prependMessage: NSString? = nil) -> Bool {
if envSettings == nil {
return false
}
var settings = envSettings! as! Dictionary<String, AnyObject>
let allowedEnvs = settings[envKey] as! [String]
settings.removeValueForKey(envKey)
var missingOptions = [String : [String]]()
for (name, values) in settings {
let variable = name as String
let envValues = values as! [String: AnyObject]
let notConfiguredOptions = allowedEnvs.filter {
return envValues.indexForKey($0) == nil
}
if notConfiguredOptions.count > 0 {
missingOptions[variable] = notConfiguredOptions
}
}
for (variable, options) in missingOptions {
if let prepend = prependMessage {
println("\(prepend) error:\(variable) is missing values for '\(options)'")
} else {
println("error:\(variable) is missing values for '\(options)'")
}
}
return missingOptions.count == 0
}
func filterEnvSettings(entries: NSDictionary, forEnv env: String, prependMessage: String? = nil) -> NSDictionary {
var settings = entries as! Dictionary<String, AnyObject>
settings[envKey] = [env]
for (name, values) in entries {
let variable = name as! String
if let envValues = values as? [String: AnyObject] {
if let allowedValue: AnyObject = envValues[env] {
settings[variable] = [env: allowedValue]
} else {
if let prepend = prependMessage {
println("\(prepend) missing value of variable \(name) for env \(env) available values \(values)")
} else {
println("missing value of variable \(name) for env \(env) available values \(values)")
}
}
}
}
return settings
}
func processSettings(var settingsPath: String, availableEnvs:[String], allowedEnv: String? = nil) -> Bool {
let preferenceKey = "PreferenceSpecifiers"
settingsPath = (settingsPath as NSString).stringByAppendingPathComponent("Root.plist") as String
if var settings = NSMutableDictionary(contentsOfFile: settingsPath) {
if var existing = settings[preferenceKey] as? [AnyObject] {
existing = existing.filter {
if let dictionary = $0 as? [String:AnyObject] {
let value = dictionary["Key"] as? String
if value == overrideKey {
return false
}
}
return true
}
//! only add env switch if there isnt allowedEnv override
var updatedPreferences = existing as [AnyObject]
if allowedEnv == nil {
updatedPreferences.append(
[ "Type" : "PSMultiValueSpecifier",
"Title" : "Environment",
"Key" : overrideKey,
"Titles" : availableEnvs,
"Values" : availableEnvs,
"DefaultValue" : ""
])
}
settings[preferenceKey] = updatedPreferences
println("Updating settings at \(settingsPath)")
return settings.writeToFile(settingsPath, atomically: true)
}
}
return false
}
func processEnvs(bundledPath: String, #sourcePath: String, #settingsPath: String, allowedEnv: String? = nil, dstPath: String? = nil) -> Bool {
let settings = NSDictionary(contentsOfFile: bundledPath)
let availableEnvs = (settings as! [String:AnyObject])[envKey] as! [String]
if validateEnvSettings(settings, prependMessage: "\(sourcePath):1:") {
if let filterEnv = allowedEnv {
let productionSettings = filterEnvSettings(settings!, forEnv: filterEnv, prependMessage: "\(sourcePath):1:")
productionSettings.writeToFile(dstPath ?? bundledPath, atomically: true)
}
let settingsAdjusted = processSettings(settingsPath, availableEnvs, allowedEnv: allowedEnv)
if settingsAdjusted == false {
println("\(__FILE__):\(__LINE__): Unable to adjust settings bundle")
}
return settingsAdjusted
}
return false
}
let count = Process.arguments.count
if count == 1 || count > 5 {
println("\(__FILE__):\(__LINE__): Received \(count) arguments, Proper usage: processEnvironments.swift -- [bundledPath] [srcPath] [settingsPath] [allowedEnv]")
exit(1)
}
let path = Process.arguments[1]
let srcPath = Process.arguments[2]
let settingsPath = Process.arguments[3]
let allowedEnv: String? = (count != 5 ? nil : Process.arguments[4])
if (processEnvs(path, sourcePath: srcPath, settingsPath: settingsPath, allowedEnv:allowedEnv) == true)
{
exit (0)
}
else
{
exit (1)
}
| mit | a689669f791c6b9294a2c555f9d80605 | 35.084507 | 163 | 0.594848 | 4.658182 | false | false | false | false |
fuzongjian/SwiftStudy | SwiftStudy/Project/动画集锦/TableView小动画/TableAnimationController.swift | 1 | 1974 | //
// TableAnimationController.swift
// SwiftStudy
//
// Created by 付宗建 on 16/8/19.
// Copyright © 2016年 youran. All rights reserved.
//
import UIKit
class TableAnimationController: SuperViewController,UITableViewDelegate,UITableViewDataSource {
let cellID = "cellID"
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView!)
}
// TableView Delegate Method
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cellID", forIndexPath: indexPath) as! CustomTableCell
cell.bgImageView?.image = UIImage.init(named: String(format: String(indexPath.row + 1) + ".jpg"))
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
var transform = CATransform3DIdentity
transform = CATransform3DRotate(transform, 0, 0, 0, 1);//渐变
transform = CATransform3DTranslate(transform, -200, 0, 0);//左边水平移动
transform = CATransform3DScale(transform, 0, 0, 0);//由小变大
cell.layer.transform = transform;
cell.layer.opacity = 0.0;
UIView.animateWithDuration(0.5) {
cell.layer.transform = CATransform3DIdentity;
cell.layer.opacity = 1;
}
}
lazy var tableView : UITableView? = {
let table = UITableView.init(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), style: .Plain)
table.delegate = self;
table.dataSource = self
table.rowHeight = 150
table.registerNib(UINib.init(nibName: "CustomTableCell", bundle: nil), forCellReuseIdentifier: "cellID")
table.tableFooterView = UIView.init()
return table
}()
}
| apache-2.0 | 1d0b79a0e9221284fd199c90f7058b0b | 38.612245 | 125 | 0.675425 | 4.643541 | false | false | false | false |
raulriera/Bike-Compass | App/Carthage/Checkouts/Decodable/Generator/Generator.swift | 1 | 7527 | #!/usr/bin/xcrun --sdk macosx swift
//
// Generator.swift
// Decodable
//
// Created by Johannes Lund on 2016-02-27.
// Copyright © 2016 anviking. All rights reserved.
//
// For generating overloads
import Foundation
class TypeNameProvider {
var names = Array(["A", "B", "C", "D", "E", "F", "G"].reversed())
var takenNames: [Unique: String] = [:]
subscript(key: Unique) -> String {
if let name = takenNames[key] {
return name
}
let n = names.popLast()!
takenNames[key] = n
return n
}
}
struct Unique: Hashable, Equatable {
static var counter = 0
let value: Int
init() {
Unique.counter += 1
value = Unique.counter
}
var hashValue: Int {
return value.hashValue
}
}
func == (a: Unique, b: Unique) -> Bool {
return a.value == b.value
}
indirect enum Decodable {
case T(Unique)
// case AnyObject
case Array(Decodable)
case Optional(Decodable)
case Dictionary(Decodable, Decodable)
func decodeClosure(_ provider: TypeNameProvider) -> String {
switch self {
case T(let key):
return "\(provider[key]).decode"
// case .AnyObject:
// return "{$0}"
case Optional(let T):
return "catchNull(\(T.decodeClosure(provider)))"
case Array(let T):
return "decodeArray(\(T.decodeClosure(provider)))"
case .Dictionary(let K, let T):
return "decodeDictionary(\(K.decodeClosure(provider)), elementDecodeClosure: \(T.decodeClosure(provider)))"
}
}
func typeString(_ provider: TypeNameProvider) -> String {
switch self {
case .T(let unique):
return provider[unique]
case Optional(let T):
return "\(T.typeString(provider))?"
case Array(let T):
return "[\(T.typeString(provider))]"
case .Dictionary(let K, let T):
return "[\(K.typeString(provider)): \(T.typeString(provider))]"
}
}
func generateAllPossibleChildren(_ deepness: Int) -> [Decodable] {
guard deepness > 0 else { return [.T(Unique())] }
var array = [Decodable]()
array += generateAllPossibleChildren(deepness - 1).flatMap(filterChainedOptionals)
array += generateAllPossibleChildren(deepness - 1).map { .Array($0) }
array += generateAllPossibleChildren(deepness - 1).map { .Dictionary(.T(Unique()),$0) }
array += [.T(Unique())]
return array
}
func wrapInOptionalIfNeeded() -> Decodable {
switch self {
case .Optional:
return self
default:
return .Optional(self)
}
}
var isOptional: Bool {
switch self {
case .Optional:
return true
default:
return false
}
}
func generateOverloads(_ operatorString: String) -> [String] {
let provider = TypeNameProvider()
let returnType: String
let parseCallString: String
let behaviour: Behaviour
switch operatorString {
case "=>":
returnType = typeString(provider)
behaviour = Behaviour(throwsIfKeyMissing: true, throwsIfNull: !isOptional, throwsFromDecodeClosure: true)
parseCallString = "parse"
case "=>?":
returnType = typeString(provider) + "?"
behaviour = Behaviour(throwsIfKeyMissing: false, throwsIfNull: !isOptional, throwsFromDecodeClosure: true)
parseCallString = "parseAndAcceptMissingKey"
default:
fatalError()
}
let arguments = provider.takenNames.values.sorted().map { $0 + ": Decodable" }
let generics = arguments.count > 0 ? "<\(arguments.joined(separator: ", "))>" : ""
let documentation = generateDocumentationComment(behaviour)
let throwKeyword = "throws"
return [documentation + "public func \(operatorString) \(generics)(json: AnyObject, path: String)\(throwKeyword)-> \(returnType) {\n" +
" return try \(parseCallString)(json, path: [path], decode: \(decodeClosure(provider)))\n" +
"}", documentation + "public func \(operatorString) \(generics)(json: AnyObject, path: [String])\(throwKeyword)-> \(returnType) {\n" +
" return try \(parseCallString)(json, path: path, decode: \(decodeClosure(provider)))\n" +
"}"
]
}
}
func filterChainedOptionals(type: Decodable) -> Decodable? {
switch type {
case .Optional:
return nil
default:
return .Optional(type)
}
}
func filterOptionals(type: Decodable) -> Decodable? {
switch type {
case .Optional:
return nil
default:
return type
}
}
struct Behaviour {
let throwsIfKeyMissing: Bool
let throwsIfNull: Bool
let throwsFromDecodeClosure: Bool
}
func generateDocumentationComment(_ behaviour: Behaviour) -> String {
var string =
"/**\n" +
" Retrieves the object at `path` from `json` and decodes it according to the return type\n" +
"\n" +
" - parameter json: An object from NSJSONSerialization, preferably a `NSDictionary`.\n" +
" - parameter path: A null-separated key-path string. Can be generated with `\"keyA\" => \"keyB\"`\n"
switch (behaviour.throwsIfKeyMissing, behaviour.throwsIfNull) {
case (true, true):
string += " - Throws: `MissingKeyError` if `path` does not exist in `json`. `TypeMismatchError` or any other error thrown in the decode-closure\n"
case (true, false):
string += " - Returns: nil if the pre-decoded object at `path` is `NSNull`.\n"
string += " - Throws: `MissingKeyError` if `path` does not exist in `json`. `TypeMismatchError` or any other error thrown in the decode-closure\n"
case (false, false):
string += " - Returns: nil if `path` does not exist in `json`, or if that object is `NSNull`.\n"
string += " - Throws: `TypeMismatchError` or any other error thrown in the decode-closure\n"
case (false, true):
break
}
return string + "*/\n"
}
let file = "Overloads.swift"
let fileManager = FileManager.default()
let sourcesDirectory = fileManager.currentDirectoryPath + "/../Sources"
let filename = "Overloads.swift"
let path = sourcesDirectory + "/" + filename
var dateFormatter = DateFormatter()
dateFormatter.dateStyle = .shortStyle
let date = dateFormatter.string(from: Date())
let overloads = Decodable.T(Unique()).generateAllPossibleChildren(4)
let types = overloads.map { $0.typeString(TypeNameProvider()) }
let all = overloads.flatMap { $0.generateOverloads("=>") } + overloads.flatMap(filterOptionals).flatMap { $0.generateOverloads("=>?") }
do {
var template = try String(contentsOfFile: fileManager.currentDirectoryPath + "/Template.swift") as NSString
template = template.replacingOccurrences(of: "{filename}", with: filename)
template = template.replacingOccurrences(of: "{by}", with: "Generator.swift")
template = template.replacingOccurrences(of: "{overloads}", with: types.joined(separator: ", "))
template = template.replacingOccurrences(of: "{count}", with: "\(all.count)")
let text = (template as String) + "\n" + all.joined(separator: "\n\n")
try text.write(toFile: sourcesDirectory + "/Overloads.swift", atomically: false, encoding: String.Encoding.utf8)
}
catch {
print(error)
}
| mit | a573a16809562ca8e684d4ce3d8ec68e | 33.682028 | 154 | 0.613208 | 4.230467 | false | false | false | false |
sclark01/Swift_VIPER_Demo | VIPER_Demo/VIPER_Demo/Modules/PersonDetails/Interactor/PersonDetailsData.swift | 1 | 434 | import Foundation
struct PersonDetailsData {
let name: String
let age: String
let phone: String
init(person: Person) {
name = person.name
age = person.age
phone = person.phone
}
}
extension PersonDetailsData : Equatable {}
func ==(lhs: PersonDetailsData, rhs: PersonDetailsData) -> Bool {
return lhs.name == rhs.name &&
lhs.age == rhs.age &&
lhs.phone == rhs.phone
} | mit | 36c30a6ff9b971e69022b4a7876dbd4c | 19.714286 | 65 | 0.615207 | 4.056075 | false | false | false | false |
TigerWolf/LoginKit | LoginKit/Models/User.swift | 1 | 2943 | import Foundation
import KeychainAccess
open class User: NSObject, NSCoding {
open let id: String
let username: String
var password: String? {
didSet {
if LoginService.storePassword && LoginKitConfig.authType == AuthType.basic {
// Store to keychain
if password != nil {
do {
try keychain.set(password!, key: "password")
} catch {
NSLog("Failed to set password")
}
} else {
self.clearPassword()
}
}
}
}
let keychain = Keychain(service: Bundle.main.bundleIdentifier ?? "com.loginkit.keychain")
var authToken: String? {
didSet {
if LoginService.storePassword {
// Store to keychain
if LoginKitConfig.authType == AuthType.jwt {
if authToken != nil {
do {
try keychain.set(authToken!, key: "authToken")
} catch {
NSLog("Failed to set authToken")
}
} else {
self.clearToken()
}
}
}
}
}
func clearToken() {
do {
try keychain.remove("authToken")
} catch {
NSLog("Failed to clear authToken")
}
}
func clearPassword() {
do {
try keychain.remove("password")
} catch {
NSLog("Failed to clear password")
}
}
init(id: String, username: String) {
self.id = id
self.username = username
}
public required init(coder aDecoder: NSCoder) {
if let username = aDecoder.decodeObject(forKey: "username") as? String,
let id = aDecoder.decodeObject(forKey: "id") as? String {
self.id = id
self.username = username
} else {
self.id = ""
self.username = ""
}
do {
if let password = try keychain.get("password") {
self.password = password
}
} catch {
NSLog("Failed to set password")
}
if (LoginKitConfig.savedLogin == false) {
do {
if let authToken = try keychain.get("authToken") {
self.authToken = authToken
}
} catch {
NSLog("Failed to set authToken")
}
}
}
open func encode(with aCoder: NSCoder) {
aCoder.encode(self.id, forKey: "id")
aCoder.encode(self.username, forKey: "username")
if let authToken = self.authToken {
aCoder.encode(authToken, forKey: "authToken")
}
}
}
| bsd-3-clause | d2211cbd9ca7a5e9ff5f919acdc5273b | 26.504673 | 93 | 0.448182 | 5.302703 | false | false | false | false |
duycao2506/SASCoffeeIOS | SAS Coffee/Services/DataService.swift | 1 | 3720 | //
// DataService.swift
// SAS Coffee
//
// Created by Duy Cao on 9/14/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
import ObjectMapper
class DataService: NSObject {
static func assignUser(response : [String:Any], vc : KasperViewController) -> Bool{
let succ = (response["statuskey"] as! Bool)
if succ {
let basicuser = response["data"] as! [String: Any]
let token = response["token"] as! String
AppSetting.sharedInstance().mainUser = UserModel.init()
AppSetting.sharedInstance().mainUser.mapping(map: Map.init(mappingType: .fromJSON, JSON: basicuser ))
AppSetting.sharedInstance().mainUser.token = token
return true
}else{
vc.notiTextview?.text = response["message"] as? String
vc.showNotification()
return false
}
}
static func parsePromotionList(response : [[String:Any]]) -> [PromotionModel]{
var promotions : [PromotionModel] = [PromotionModel]()
for item in response {
var promotion : PromotionModel!
if let eventkey = item[PromoEventModel.FULL_DESC] {
promotion = PromoEventModel.init()
}else{
promotion = PromoVisitModel.init()
}
promotion.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
promotions.append(promotion)
}
return promotions
}
static func parseBranchList (response: [[String : Any]]) -> [BranchModel]{
var branches : [BranchModel] = [BranchModel].init()
for item in response {
let branch = BranchModel.init()
branch.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
branches.append(branch)
}
return branches
}
static func parseDictionary(resp : [[String : Any]]) -> [DictionaryModel]{
var dictions : [DictionaryModel] = [DictionaryModel].init()
for item in resp {
let dict = DictionaryModel.init()
dict.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
dictions.append(dict)
}
return dictions
}
static func parseTopics (resp : [[String:Any]]) -> [TopicModel]{
var topics : [TopicModel] = [TopicModel].init()
for item in resp {
let topic = TopicModel.init()
topic.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
topics.append(topic)
}
return topics
}
static func parseVideos(resp: [[String:Any]]) -> [VideoModel] {
var videos : [VideoModel] = [VideoModel].init()
for item in resp {
let vid = VideoModel.init()
vid.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
videos.append(vid)
}
return videos
}
static func findEventByIdInPromotionList(id : Int, promotelistRaw : [[String : Any]]) -> PromoEventModel? {
for item in promotelistRaw {
if let check = item[PromoEventModel.FULL_DESC], (item["id"] as! Int) == id{
let event = PromoEventModel.init()
event.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
return event
}
}
return nil
}
static func parseNews(resp : [[String : Any]]) -> [NewsModel]{
var newses : [NewsModel] = [NewsModel].init()
for item in resp {
let news = NewsModel.init()
news.mapping(map: Map.init(mappingType: .fromJSON, JSON: item))
newses.append(news)
}
return newses
}
}
| gpl-3.0 | 8b619e5521845acc109dc01fd01c1d49 | 34.419048 | 113 | 0.57139 | 4.334499 | false | false | false | false |
yuanhao/unu-demo-ios | SocketIOClientSwift/SocketEngine.swift | 2 | 24569 | //
// SocketEngine.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/3/15.
//
// 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
public final class SocketEngine: NSObject, SocketEngineSpec, WebSocketDelegate {
public private(set) var sid = ""
public private(set) var cookies: [NSHTTPCookie]?
public private(set) var socketPath = "/engine.io"
public private(set) var urlPolling = ""
public private(set) var urlWebSocket = ""
public private(set) var ws: WebSocket?
public weak var client: SocketEngineClient?
private typealias Probe = (msg: String, type: SocketEnginePacketType, data: [NSData]?)
private typealias ProbeWaitQueue = [Probe]
private let allowedCharacterSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" {}").invertedSet
private let emitQueue = dispatch_queue_create("com.socketio.engineEmitQueue", DISPATCH_QUEUE_SERIAL)
private let handleQueue = dispatch_queue_create("com.socketio.engineHandleQueue", DISPATCH_QUEUE_SERIAL)
private let logType = "SocketEngine"
private let parseQueue = dispatch_queue_create("com.socketio.engineParseQueue", DISPATCH_QUEUE_SERIAL)
private let url: String
private let workQueue = NSOperationQueue()
private var closed = false
private var extraHeaders: [String: String]?
private var fastUpgrade = false
private var forcePolling = false
private var forceWebsockets = false
private var invalidated = false
private var pingInterval: Double?
private var pingTimer: NSTimer?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var postWait = [String]()
private var probing = false
private var probeWait = ProbeWaitQueue()
private var secure = false
private var session: NSURLSession!
private var voipEnabled = false
private var waitingForPoll = false
private var waitingForPost = false
private var websocketConnected = false
private(set) var connected = false
private(set) var polling = true
private(set) var websocket = false
public init(client: SocketEngineClient, url: String, options: Set<SocketIOClientOption>) {
self.client = client
self.url = url
for option in options {
switch option {
case .SessionDelegate(let delegate):
session = NSURLSession(configuration: .defaultSessionConfiguration(),
delegate: delegate,
delegateQueue: workQueue)
case .ForcePolling(let force):
forcePolling = force
case .ForceWebsockets(let force):
forceWebsockets = force
case .Cookies(let cookies):
self.cookies = cookies
case .Path(let path):
socketPath = path
case .ExtraHeaders(let headers):
extraHeaders = headers
case .VoipEnabled(let enable):
voipEnabled = enable
case .Secure(let secure):
self.secure = secure
default:
continue
}
}
if session == nil {
session = NSURLSession(configuration: .defaultSessionConfiguration(),
delegate: nil,
delegateQueue: workQueue)
}
}
public convenience init(client: SocketEngineClient, url: String, options: NSDictionary?) {
self.init(client: client, url: url,
options: Set<SocketIOClientOption>.NSDictionaryToSocketOptionsSet(options ?? [:]))
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being deinit", type: logType)
closed = true
stopPolling()
}
private func checkIfMessageIsBase64Binary(var message: String) {
if message.hasPrefix("b4") {
// binary in base64 string
message.removeRange(Range<String.Index>(start: message.startIndex,
end: message.startIndex.advancedBy(2)))
if let data = NSData(base64EncodedString: message,
options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
client?.parseBinaryData(data)
}
}
}
public func close() {
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
pingTimer?.invalidate()
closed = true
if websocket {
sendWebSocketMessage("", withType: .Close)
} else {
sendPollMessage("", withType: .Close)
}
ws?.disconnect()
stopPolling()
client?.engineDidClose("Disconnect")
}
private func createBinaryDataForSend(data: NSData) -> Either<NSData, String> {
if websocket {
var byteArray = [UInt8](count: 1, repeatedValue: 0x0)
byteArray[0] = 4
let mutData = NSMutableData(bytes: &byteArray, length: 1)
mutData.appendData(data)
return .Left(mutData)
} else {
let str = "b4" + data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return .Right(str)
}
}
private func createURLs(params: [String: AnyObject]?) -> (String, String) {
if client == nil {
return ("", "")
}
let socketURL = "\(url)\(socketPath)/?transport="
var urlPolling: String
var urlWebSocket: String
if secure {
urlPolling = "https://" + socketURL + "polling"
urlWebSocket = "wss://" + socketURL + "websocket"
} else {
urlPolling = "http://" + socketURL + "polling"
urlWebSocket = "ws://" + socketURL + "websocket"
}
if params != nil {
for (key, value) in params! {
let keyEsc = key.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "&\(keyEsc)="
urlWebSocket += "&\(keyEsc)="
if value is String {
let valueEsc = (value as! String).stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacterSet)!
urlPolling += "\(valueEsc)"
urlWebSocket += "\(valueEsc)"
} else {
urlPolling += "\(value)"
urlWebSocket += "\(value)"
}
}
}
return (urlPolling, urlWebSocket)
}
private func createWebsocketAndConnect(connect: Bool) {
let wsUrl = urlWebSocket + (sid == "" ? "" : "&sid=\(sid)")
ws = WebSocket(url: NSURL(string: wsUrl)!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.queue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
if connect {
ws?.connect()
}
}
private func doFastUpgrade() {
if waitingForPoll {
DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .Upgrade, datas: nil)
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
dispatch_async(emitQueue) {[weak self] in
if let this = self {
for waiter in this.probeWait {
this.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
this.probeWait.removeAll(keepCapacity: false)
if this.postWait.count != 0 {
this.flushWaitingForPostToWebSocket()
}
}
}
}
private func handleClose() {
if let client = client where polling == true {
client.engineDidClose("Disconnect")
}
}
private func handleMessage(message: String) {
client?.parseSocketMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
let mesData = openData.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
do {
let json = try NSJSONSerialization.JSONObjectWithData(mesData,
options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if let sid = json?["sid"] as? String {
let upgradeWs: Bool
self.sid = sid
connected = true
if let upgrades = json?["upgrades"] as? [String] {
upgradeWs = upgrades.filter {$0 == "websocket"}.count != 0
} else {
upgradeWs = false
}
if let pingInterval = json?["pingInterval"] as? Double, pingTimeout = json?["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect(true)
}
}
} catch {
DefaultSocketLogger.Logger.error("Error parsing open packet", type: logType)
return
}
startPingTimer()
if !forceWebsockets {
doPoll()
}
}
private func handlePong(pongMessage: String) {
pongsMissed = 0
// We should upgrade
if pongMessage == "3probe" {
upgradeTransport()
}
}
// A poll failed, tell the client about it
private func handlePollingFailed(reason: String) {
connected = false
ws?.disconnect()
pingTimer?.invalidate()
waitingForPoll = false
waitingForPost = false
if !closed {
client?.didError(reason)
client?.engineDidClose(reason)
}
}
public func open(opts: [String: AnyObject]? = nil) {
if connected {
DefaultSocketLogger.Logger.error("Tried to open while connected", type: logType)
client?.didError("Tried to open while connected")
return
}
DefaultSocketLogger.Logger.log("Starting engine", type: logType)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
closed = false
(urlPolling, urlWebSocket) = createURLs(opts)
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect(true)
return
}
let reqPolling = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(reqPolling)
}
private func parseEngineData(data: NSData) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseBinaryData(data.subdataWithRange(NSMakeRange(1, data.length - 1)))
}
private func parseEngineMessage(var message: String, fromPolling: Bool) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let type = SocketEnginePacketType(rawValue: Int((message["^(\\d)"].groups()?[1]) ?? "") ?? -1) ?? {
self.checkIfMessageIsBase64Binary(message)
return .Noop
}()
if fromPolling && type != .Noop {
fixDoubleUTF8(&message)
}
switch type {
case .Message:
message.removeAtIndex(message.startIndex)
handleMessage(message)
case .Noop:
handleNOOP()
case .Pong:
handlePong(message)
case .Open:
message.removeAtIndex(message.startIndex)
handleOpen(message)
case .Close:
handleClose()
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
private func probeWebSocket() {
if websocketConnected {
sendWebSocketMessage("probe", withType: .Ping)
}
}
/// Send an engine message (4)
public func send(msg: String, withData datas: [NSData]?) {
if probing {
probeWait.append((msg, .Message, datas))
} else {
write(msg, withType: .Message, withData: datas)
}
}
@objc private func sendPing() {
//Server is not responding
if pongsMissed > pongsMissedMax {
pingTimer?.invalidate()
client?.engineDidClose("Ping timeout")
return
}
++pongsMissed
write("", withType: .Ping, withData: nil)
}
// Starts the ping timer
private func startPingTimer() {
if let pingInterval = pingInterval {
pingTimer?.invalidate()
pingTimer = nil
dispatch_async(dispatch_get_main_queue()) {
self.pingTimer = NSTimer.scheduledTimerWithTimeInterval(pingInterval, target: self,
selector: Selector("sendPing"), userInfo: nil, repeats: true)
}
}
}
private func upgradeTransport() {
if websocketConnected {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: .Noop)
// After this point, we should not send anymore polling messages
}
}
/**
Write a message, independent of transport.
*/
public func write(msg: String, withType type: SocketEnginePacketType, withData data: [NSData]?) {
dispatch_async(emitQueue) {
if self.connected {
if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendWebSocketMessage(msg, withType: type, datas: data)
} else {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@", type: self.logType, args: msg,
data == nil ? false : true)
self.sendPollMessage(msg, withType: type, datas: data)
}
}
}
}
}
// Polling methods
extension SocketEngine {
private func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
waitingForPoll = true
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)&b64=1")!)
if cookies != nil {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(req)
}
private func doRequest(req: NSMutableURLRequest,
withCallback callback: (NSData?, NSURLResponse?, NSError?) -> Void) {
if !polling || closed || invalidated {
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: logType)
req.cachePolicy = .ReloadIgnoringLocalAndRemoteCacheData
session.dataTaskWithRequest(req, completionHandler: callback).resume()
}
private func doLongPoll(req: NSMutableURLRequest) {
doRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil || data == nil {
if this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
} else {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: this.logType)
}
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: this.logType)
if let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as? String {
dispatch_async(this.parseQueue) {[weak this] in
this?.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
var postStr = ""
for packet in postWait {
let len = packet.characters.count
postStr += "\(len):\(packet)"
}
postWait.removeAll(keepCapacity: false)
let req = NSMutableURLRequest(URL: NSURL(string: urlPolling + "&sid=\(sid)")!)
if let cookies = cookies {
let headers = NSHTTPCookie.requestHeaderFieldsWithCookies(cookies)
req.allHTTPHeaderFields = headers
}
req.HTTPMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postData = postStr.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false)!
req.HTTPBody = postData
req.setValue(String(postData.length), forHTTPHeaderField: "Content-Length")
waitingForPost = true
DefaultSocketLogger.Logger.log("POSTing: %@", type: logType, args: postStr)
doRequest(req) {[weak self] data, res, err in
if let this = self {
if err != nil && this.polling {
this.handlePollingFailed(err?.localizedDescription ?? "Error")
return
} else if err != nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: this.logType)
return
}
this.waitingForPost = false
dispatch_async(this.emitQueue) {[weak this] in
if !(this?.fastUpgrade ?? true) {
this?.flushWaitingForPost()
this?.doPoll()
}
}
}
}
}
// We had packets waiting for send when we upgraded
// Send them raw
private func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else {return}
for msg in postWait {
ws.writeString(msg)
}
postWait.removeAll(keepCapacity: true)
}
func parsePollingMessage(str: String) {
guard str.characters.count != 1 else {
return
}
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilStringOccurence(":")) {
let str = reader.read(n)
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
} else {
dispatch_async(handleQueue) {
self.parseEngineMessage(str, fromPolling: true)
}
break
}
}
}
/// Send polling message.
/// Only call on emitQueue
private func sendPollMessage(var msg: String, withType type: SocketEnginePacketType,
datas:[NSData]? = nil) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: logType, args: msg, type.rawValue)
doubleEncodeUTF8(&msg)
let strMsg = "\(type.rawValue)\(msg)"
postWait.append(strMsg)
for data in datas ?? [] {
if case let .Right(bin) = createBinaryDataForSend(data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
private func stopPolling() {
invalidated = true
session.finishTasksAndInvalidate()
}
}
// WebSocket methods
extension SocketEngine {
/// Send message on WebSockets
/// Only call on emitQueue
private func sendWebSocketMessage(str: String, withType type: SocketEnginePacketType,
datas:[NSData]? = nil) {
DefaultSocketLogger.Logger.log("Sending ws: %@ as type: %@", type: logType, args: str, type.rawValue)
ws?.writeString("\(type.rawValue)\(str)")
for data in datas ?? [] {
if case let Either.Left(bin) = createBinaryDataForSend(data) {
ws?.writeData(bin)
}
}
}
// Delagate methods
public func websocketDidConnect(socket:WebSocket) {
websocketConnected = true
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
websocketConnected = false
probing = false
if closed {
client?.engineDidClose("Disconnect")
return
}
if websocket {
pingTimer?.invalidate()
connected = false
websocket = false
let reason = error?.localizedDescription ?? "Socket Disconnected"
if error != nil {
client?.didError(reason)
}
client?.engineDidClose(reason)
} else {
flushProbeWait()
}
}
public func websocketDidReceiveMessage(socket: WebSocket, text: String) {
parseEngineMessage(text, fromPolling: false)
}
public func websocketDidReceiveData(socket: WebSocket, data: NSData) {
parseEngineData(data)
}
}
| apache-2.0 | 2e71528841a66e43d7676641d20d64f6 | 32.201351 | 119 | 0.556759 | 5.404531 | false | false | false | false |
allsome/LSYPaper | LSYPaper/Extension.swift | 1 | 4841 | //
// Extension.swift
// LSYPaper
//
// Created by 梁树元 on 1/2/16.
// Copyright © 2016 allsome.love. All rights reserved.
//
import UIKit
public extension NSObject {
public func delay(_ delay:Double, closure:(() -> Void)) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
}
public extension UIView {
public func setSpecialCorner(_ cornerOption:UIRectCorner) {
self.setSpecialCornerWith(frame: self.bounds, cornerOption: cornerOption)
}
public func setSpecialCornerWith(frame:CGRect,cornerOption:UIRectCorner) {
let maskPath = UIBezierPath(roundedRect: frame, byRoundingCorners: cornerOption, cornerRadii: CGSize(width: CORNER_REDIUS, height: CORNER_REDIUS))
let maskLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = maskPath.cgPath
self.layer.mask = maskLayer
}
public func safeSetAnchorPoint(_ anchorPoint:CGPoint) {
let oldFrame = self.frame
self.layer.anchorPoint = anchorPoint
self.frame = oldFrame
}
public func addSpringAnimation(_ duration:TimeInterval,durationArray:[Double],delayArray:[Double],scaleArray:[CGFloat]) {
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(), animations: { () -> Void in
var startTime:Double = 0
for index in 0..<durationArray.count {
let relativeDuration = durationArray[index]
let scale = scaleArray[index]
let delay = delayArray[index]
UIView.addKeyframe(withRelativeStartTime: startTime + delay, relativeDuration: relativeDuration, animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: scale, y: scale)
})
startTime += relativeDuration
}
}, completion: { (stop:Bool) -> Void in
})
}
public func addSpringAnimation() {
self.addSpringAnimation(0.6, durationArray: [0.20,0.275,0.275,0.25], delayArray: [0.0,0.0,0.0,0.0], scaleArray: [0.7,1.05,0.95,1.0])
}
public func addPopSpringAnimation() {
self.addSpringAnimation(0.8, durationArray: [0.20,0.275,0.275,0.25], delayArray: [0.0,0.0,0.0,0.0], scaleArray: [1.4,0.8,1.2,1.0])
}
public func addFadeAnimation() {
let anim = CATransition()
anim.type = kCATransitionFade
anim.duration = 0.2
self.layer.add(anim, forKey: nil)
}
}
public extension UIColor {
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
if hex.hasPrefix("#") {
hex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 1))
}
if (hex.range(of: "(^[0-9A-Fa-f]{6}$)|(^[0-9A-Fa-f]{3}$)", options: .regularExpression) != nil) {
if hex.characters.count == 3 {
let redHex = hex.substring(to: hex.index(hex.startIndex, offsetBy: 1))
let greenHex = hex.substring(with: Range<String.Index>(hex.index(hex.startIndex, offsetBy: 1)..<hex.index(hex.startIndex, offsetBy: 2)))
let blueHex = hex.substring(from: hex.index(hex.startIndex, offsetBy: 2))
hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
}
let redHex = hex.substring(to: hex.index(hex.startIndex, offsetBy: 2))
let greenHex = hex.substring(with: Range<String.Index>(hex.index(hex.startIndex, offsetBy: 2)..<hex.index(hex.startIndex, offsetBy: 4)))
let blueHex = hex.substring(with: Range<String.Index>(hex.index(hex.startIndex, offsetBy: 4)..<hex.index(hex.startIndex, offsetBy: 6)))
var redInt: CUnsignedInt = 0
var greenInt: CUnsignedInt = 0
var blueInt: CUnsignedInt = 0
Scanner(string: redHex).scanHexInt32(&redInt)
Scanner(string: greenHex).scanHexInt32(&greenInt)
Scanner(string: blueHex).scanHexInt32(&blueInt)
self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
}
else {
self.init()
return nil
}
}
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
public convenience init?(hex: Int, alpha: Float) {
let hexString = NSString(format: "%2X", hex)
self.init(hexString: hexString as String , alpha: alpha)
}
}
| mit | ef4ec3b81d775df795f2fe6ff2c4b07b | 39.621849 | 154 | 0.605916 | 4.08277 | false | false | false | false |
zxwWei/SwfitZeng | XWWeibo接收数据/XWWeibo/Classes/LIbrary(第三方库)/Emotion/UITextView+extension.swift | 1 | 3907 | //
// UITextView+extension.swift
// emotion
//
// Created by apple1 on 15/11/6.
// Copyright © 2015年 apple1. All rights reserved.
//
import UIKit
extension UITextView {
/// 获取带表情图片的文本字符串
func emoticonText() -> String {
// 定义可变字符串
var strM = ""
// 遍历textView里面的每一个文本
attributedText.enumerateAttributesInRange(NSRange(location: 0, length:attributedText.length ), options: NSAttributedStringEnumerationOptions(rawValue: 0), usingBlock: { (dict , range , _ ) -> Void in
if let attachmet = dict["NSAttachment"] as? XWAttachment {
strM += attachmet.name!
}
else {
// 不是附件,截取对应的文本
let str = (self.attributedText.string as NSString).substringWithRange(range)
strM += str
}
})
return strM
}
// MARK: - 插入表情的方法
func insertEmotion(emotion: XWEmotion) {
//
// // 判断文本是否有值
// guard let textView = self.textView else {
// print("textView没有值")
// return
// }
//
// 当是删除按钮时,删除文本
if emotion.removeEmotion{
deleteBackward()
}
// 当emoji有值的时候 插入
if let emoji = emotion.emoji{
insertText(emoji)
}
// 当图片有路径的时候
if let pngPath = emotion.pngPath{
// 创建附件
let attachment = XWAttachment()
attachment.name = emotion.chs
// attachment.image = UIImage(named: pngPath)
attachment.image = UIImage(contentsOfFile: pngPath)
let height = font?.lineHeight ?? 10
attachment.bounds = CGRect(x: 0, y: -height*0.25, width: height, height: height)
// 创建带附件的属性文本 此时并没有设定font 图片的本质是文字
let attributeStr = NSAttributedString(attachment:attachment)
let attstr = NSMutableAttributedString(attributedString: attributeStr)
// NSAttachmentAttributeName 这个属性错误
attstr.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location:0, length: 1))
// 让textView的文本等于属性文本 这种是完全替代
// textView.attributedText = attributeStr
// 取到光标位置
let selectedRange = self.selectedRange
// 获取现有文本 textView.attributedText 让textView的属性文本转化成带附件的属性文本
let attributeStrM = NSMutableAttributedString(attributedString: attributedText)
// 替代属性文本到对应位置
attributeStrM.replaceCharactersInRange(selectedRange, withAttributedString: attstr)
// 将文本放在textView
attributedText = attributeStrM
// 因为光标会自动到最后一位 所以需重新设定光标 偏移到光标的后一位
self.selectedRange = NSRange(location: selectedRange.location + 1 , length: 0)
// 目的是是发送按钮能被点击
// 主动调用键盘的通知和textView的代理 ? 前面的执行了才执行后面的
delegate?.textViewDidChange?(self)
// 主动发送通知
NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
}
}
} | apache-2.0 | 9d474afcc28d0b725c77491682748db9 | 29.809091 | 207 | 0.536895 | 5.04918 | false | true | false | false |
iosprogrammingwithswift/iosprogrammingwithswift | 13_GesturesTutorial/GesturesTutorial/GesturesViewController.swift | 1 | 2418 | //
// ViewController.swift
// GesturesTutorial
//
// Copyright (c) 2015 Flori & Andy. All rights reserved.
//
import UIKit
class GesturesViewController: UIViewController {
@IBOutlet weak var gestureName: UILabel!
@IBOutlet weak var tapView: UIView!
@IBOutlet weak var rotateView: UIView!
@IBOutlet weak var longPressView: UIView!
@IBOutlet weak var pinchView: UIView!
@IBOutlet weak var panView: UIView!
@IBOutlet weak var swipeView: UIView!
var rotation = CGFloat()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tap = UITapGestureRecognizer(target: self, action: "tappedView:")
tap.numberOfTapsRequired = 1
tapView.addGestureRecognizer(tap)
}
func tappedView(recognizer : UITapGestureRecognizer) {
//message: "tapped"
print("tapped")
showGestureName("Tapped")
}
func swipedView(recognizer : UISwipeGestureRecognizer) {
//message: "Swiped"
showGestureName("Swiped")
}
func longPressedView(recognizer : UILongPressGestureRecognizer) {
//message: "longpress"
showGestureName("LongPress")
}
func rotatedView(sender: UIRotationGestureRecognizer) {
showGestureName("Rotated")
}
func draggedView(sender: UIPanGestureRecognizer) {
showGestureName("Dragged")
}
/*
@IBAction func pinchedView(sender: UIPinchGestureRecognizer) {
print("Pinch ")
showGestureName("Pinch")
}
*/
@IBAction func pinchedView(sender: UIPinchGestureRecognizer) {
print("Pinch ")
showGestureName("Pinch")
}
func showAlertViewControllerWith(title: String, message: String) {
let tapAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
func showGestureName(name: String) {
gestureName.text = name
UIView.animateWithDuration(1.0,
animations: { self.gestureName.alpha = 1.0 },
completion: { _ in
UIView.animateWithDuration(1.0) { self.gestureName.alpha = 0 }
})
}
}
| mit | eba983cc696d492a01d67f53ff8249d5 | 27.447059 | 118 | 0.649711 | 4.826347 | false | false | false | false |
timestocome/SloMoVideo | SloMoVideo/ViewController.swift | 1 | 8027 | //
// ViewController.swift
// SloMoVideo
//
// Created by Linda Cobb on 6/19/15.
// Copyright © 2015 TimesToCome Mobile. All rights reserved.
//
import UIKit
import Accelerate
import AVFoundation
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate
{
// camera stuff
var session:AVCaptureSession!
var videoInput : AVCaptureDeviceInput!
var videoDevice:AVCaptureDevice!
var fps:Float = 30.0
// used to compute frames per second
var newDate:NSDate = NSDate()
var oldDate:NSDate = NSDate()
// needed to init image context
var context:CIContext!
override func viewDidLoad() {
super.viewDidLoad()
}
// set up to grab live images from the camera
func setupDevice (){
// inputs - find and use back facing camera
let videoDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
for device in videoDevices{
if device.position == AVCaptureDevicePosition.Back {
videoDevice = device as! AVCaptureDevice
}
}
// set video input to back camera
do { videoInput = try AVCaptureDeviceInput(device: videoDevice) } catch { return }
// supporting formats 240 fps
var bestFormat = AVCaptureDeviceFormat()
var bestFrameRate = AVFrameRateRange()
for format in videoDevice.formats {
let ranges = format.videoSupportedFrameRateRanges as! [AVFrameRateRange]
for range in ranges {
if range.maxFrameRate >= 240 {
bestFormat = format as! AVCaptureDeviceFormat
bestFrameRate = range
}
}
}
// set highest fps
do { try videoDevice.lockForConfiguration()
videoDevice.activeFormat = bestFormat
videoDevice.activeVideoMaxFrameDuration = bestFrameRate.maxFrameDuration
videoDevice.activeVideoMinFrameDuration = bestFrameRate.minFrameDuration
videoDevice.unlockForConfiguration()
} catch { return }
}
func setupCaptureSession () {
// set up session
let dataOutput = AVCaptureVideoDataOutput()
let sessionQueue = dispatch_queue_create("AVSessionQueue", DISPATCH_QUEUE_SERIAL)
dataOutput.setSampleBufferDelegate(self, queue: sessionQueue)
session = AVCaptureSession()
// ** need this to override default settings, otherwise reverts to 30fps
session.sessionPreset = AVCaptureSessionPresetInputPriority
// turn on light
session.beginConfiguration()
do { try videoDevice.lockForConfiguration()
do { try videoDevice.setTorchModeOnWithLevel(AVCaptureMaxAvailableTorchLevel )
} catch { return } // torch mode
videoDevice.unlockForConfiguration()
} catch { return } // lock for config
session.commitConfiguration()
// start session
session.addInput(videoInput)
session.addOutput(dataOutput)
session.startRunning()
}
// grab each camera image,
// split into color and brightness
// processing slows camera down to 12fps
// need to cut image size and speed up processing
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
// calculate our actual fps
newDate = NSDate()
fps = 1.0/Float(newDate.timeIntervalSinceDate(oldDate))
oldDate = newDate
print("fps \(fps)")
// get the image from the camera
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
// lock buffer
CVPixelBufferLockBaseAddress(imageBuffer!, 0)
//*************************************************************************
// incoming is YUV format - get format info using this
// let description = CMSampleBufferGetFormatDescription(sampleBuffer)
//print(description)
// 2 planes
// width, height plane 0
// width/2, height/2 plane 1
// bits per block 8
// CVImageBufferYCbCrMatrix
/*
// collect brightness data
let pixelsLuma = 1280 * 720 // Luma buffer (brightness)
let baseAddressLuma = CVPixelBufferGetBaseAddressOfPlane(imageBuffer!, 0)
let dataBufferLuma = UnsafeMutablePointer<UInt8>(baseAddressLuma)
*/
// collect color data
// let pixelsChroma = 174 * 144 // Chromiance buffer (color)
// let baseAddressChroma = CVPixelBufferGetBaseAddressOfPlane(imageBuffer!, 1)
// let dataBufferChroma = UnsafeMutablePointer<UInt8>(baseAddressChroma)
// split into U and V colors
//let pixelsUorVChroma = pixelsChroma / 2
CVPixelBufferUnlockBaseAddress(imageBuffer!, 0)
/*
// get pixel data
// brightness
var lumaVector:[Float] = Array(count: pixelsLuma, repeatedValue: 0.0)
vDSP_vfltu8(dataBufferLuma, 1, &lumaVector, 1, vDSP_Length(pixelsLuma))
var averageLuma:Float = 0.0
vDSP_meamgv(&lumaVector, 1, &averageLuma, vDSP_Length(pixelsLuma))
*/
/*
// pixel color data
var chromaVector:[Float] = Array(count: pixelsChroma, repeatedValue: 0.0)
vDSP_vfltu8(dataBufferChroma, 1, &chromaVector, 1, vDSP_Length(pixelsChroma))
var averageChroma:Float = 0.0
vDSP_meamgv(&chromaVector, 1, &averageChroma, vDSP_Length(pixelsChroma))
// split color into U/V
var chromaUVector:[Float] = Array(count: pixelsUorVChroma, repeatedValue: 0.0) // Cb
var chromaVVector:[Float] = Array(count: pixelsUorVChroma, repeatedValue: 0.0) // Cr
vDSP_vfltu8(dataBufferChroma, 2, &chromaUVector, 1, vDSP_Length(pixelsUorVChroma))
vDSP_vfltu8(dataBufferChroma+1, 2, &chromaVVector, 1, vDSP_Length(pixelsUorVChroma))
var averageUChroma:Float = 0.0
var averageVChroma:Float = 0.0
vDSP_meamgv(&chromaUVector, 1, &averageUChroma, vDSP_Length(pixelsUorVChroma))
vDSP_meamgv(&chromaVVector, 1, &averageVChroma, vDSP_Length(pixelsUorVChroma))
*/
// use this to convert image if the luma/chroma doesn't work ?
// ? R = Y - 1.403V'
// B = Y + 1.770U'
// G = Y - 0.344U' - 0.714V'
}
//////////////////////////////////////////////////////////////
// UI start/stop camera
//////////////////////////////////////////////////////////////
@IBAction func stop(){
session.stopRunning() // stop camera
}
@IBAction func start(){
setupDevice() // setup camera
setupCaptureSession() // start camera
}
//////////////////////////////////////////////////////////
// cleanup //////////////////////////////////
//////////////////////////////////////////////////////////
override func viewDidDisappear(animated: Bool){
super.viewDidDisappear(animated)
stop()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 4f78b78a23af3aac1884c2ece94d7cde | 26.965157 | 159 | 0.545103 | 5.624387 | false | false | false | false |
kevinsumios/KSiShuHui | Project/Model/Chapter+extension.swift | 1 | 1640 | //
// Chapter+extension.swift
// KSiShuHui
//
// Created by Kevin Sum on 21/7/2017.
// Copyright © 2017 Kevin iShuHui. All rights reserved.
//
import Foundation
import MagicalRecord
import SwiftyJSON
extension Chapter {
var chapterTitle: String {
get {
return "第\(chapterNo)\(chapterType > 0 ? "卷" : "話")"
}
}
class func create(by chapter: Chapter, at context: NSManagedObjectContext) -> Chapter? {
let entity = Chapter.mr_createEntity(in: context)
entity?.chapterNo = chapter.chapterNo
entity?.chapterType = chapter.chapterType
entity?.cover = chapter.cover
entity?.id = chapter.id
entity?.refreshTime = chapter.refreshTime
entity?.title = chapter.title
return entity
}
class func serialize(_ json: JSON) -> Chapter? {
if let data = json.dictionary {
let chapter = Chapter.mr_createEntity()
chapter?.id = data["Id"]?.int16 ?? 0
chapter?.title = data["Title"]?.string
chapter?.cover = data["FrontCover"]?.string
chapter?.chapterNo = data["ChapterNo"]?.int16 ?? 0
chapter?.chapterType = data["ChapterType"]?.int16 ?? 0
let refresh = data["RefreshTime"]?.string ?? ""
let range = refresh.index(refresh.startIndex, offsetBy: 6)..<refresh.index(refresh.endIndex, offsetBy: -2)
let refreshTime = (Double(refresh.substring(with: range)) ?? 0)/1000
chapter?.refreshTime = NSDate(timeIntervalSince1970: refreshTime)
return chapter
}
return nil
}
}
| mit | 76f9dabefbcf8c26a06485bca1d115d8 | 33.020833 | 118 | 0.603184 | 4.343085 | false | false | false | false |
practicalswift/swift | validation-test/compiler_crashers_fixed/01671-swift-structtype-get.swift | 65 | 1105 | // 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
// RUN: not %target-swift-frontend %s -typecheck
}
struct c
enum B {
func a<T> Any) -> V, length: AnyObject) {
let i<1 {
protocol a {
return { c: (Any) -> String {
extension NSSet {
}
}
typealias f : a {
}
}
}
print().c where A, a(T, A = { }
struct c in 0.Type
struct S<e<h : Int) -> <T.e = 0] {
}
let start = nil
class A = b: b> String
}
case C(start: b in c = i() {
}
func ^([c] = T: T
}
enum S<S {
}
}
b) {
typealias e() -> {
}
func a<T) {
return b: B
var b(g, length: NSObject {
case C(("")
import Foundation
var b = b()(p
typealias b = Swift.Type
self..c()
public subscript () {
typealias d {
assert(h>((a!(() -> d
typealias d.b {
switch x })
}
func compose() -> S : C(h: c: c("]
}
class B<d where B : Any, A<H : T -> (array: P> Any) {
protocol B : B
| apache-2.0 | d819a42e242a5b3d48047b8531cbcbc0 | 18.385965 | 79 | 0.625339 | 2.769424 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | Carthage/Checkouts/APIKit/Tests/APIKitTests/BodyParametersType/MultipartFormDataParametersTests.swift | 1 | 6884 | import Foundation
import XCTest
@testable import APIKit
class MultipartFormDataParametersTests: XCTestCase {
// MARK: Entity
func testDataEntitySuccess() {
let value1 = "1".data(using: .utf8)!
let value2 = "2".data(using: .utf8)!
let parameters = MultipartFormDataBodyParameters(parts: [
MultipartFormDataBodyParameters.Part(data: value1, name: "foo"),
MultipartFormDataBodyParameters.Part(data: value2, name: "bar"),
])
do {
guard case .data(let data) = try parameters.buildEntity() else {
XCTFail()
return
}
let encodedData = String(data: data, encoding:.utf8)!
let returnCode = "\r\n"
let pattern = "^multipart/form-data; boundary=([\\w.]+)$"
let regexp = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: parameters.contentType.characters.count)
let match = regexp.matches(in: parameters.contentType, options: [], range: range)
XCTAssertTrue(match.count > 0)
let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1))
XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)")
XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"foo\"\(returnCode)\(returnCode)1\(returnCode)--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"bar\"\(returnCode)\(returnCode)2\(returnCode)--\(boundary)--\(returnCode)")
} catch {
XCTFail()
}
}
func testInputStreamEntitySuccess() {
let value1 = "1".data(using: .utf8)!
let value2 = "2".data(using: .utf8)!
let parameters = MultipartFormDataBodyParameters(parts: [
MultipartFormDataBodyParameters.Part(data: value1, name: "foo"),
MultipartFormDataBodyParameters.Part(data: value2, name: "bar"),
], entityType: .inputStream)
do {
guard case .inputStream(let inputStream) = try parameters.buildEntity() else {
XCTFail()
return
}
let data = try Data(inputStream: inputStream)
let encodedData = String(data: data, encoding:.utf8)!
let returnCode = "\r\n"
let pattern = "^multipart/form-data; boundary=([\\w.]+)$"
let regexp = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: parameters.contentType.characters.count)
let match = regexp.matches(in: parameters.contentType, options: [], range: range)
XCTAssertTrue(match.count > 0)
let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1))
XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)")
XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"foo\"\(returnCode)\(returnCode)1\(returnCode)--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"bar\"\(returnCode)\(returnCode)2\(returnCode)--\(boundary)--\(returnCode)")
} catch {
XCTFail()
}
}
// MARK: Values
// Skip test cases that uses files until SwiftPM supports resources.
#if !SWIFT_PACKAGE
func testFileValue() {
let fileURL = Bundle(for: type(of: self)).url(forResource: "test", withExtension: "json")!
let part = try! MultipartFormDataBodyParameters.Part(fileURL: fileURL, name: "test")
let parameters = MultipartFormDataBodyParameters(parts: [part])
do {
guard case .data(let data) = try parameters.buildEntity() else {
XCTFail()
return
}
let testData = try! Data(contentsOf: fileURL)
let testString = String(data: testData, encoding: .utf8)!
let encodedData = String(data: data, encoding:.utf8)!
let returnCode = "\r\n"
let pattern = "^multipart/form-data; boundary=([\\w.]+)$"
let regexp = try NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: parameters.contentType.characters.count)
let match = regexp.matches(in: parameters.contentType, options: [], range: range)
XCTAssertTrue(match.count > 0)
let boundary = (parameters.contentType as NSString).substring(with: match.first!.rangeAt(1))
XCTAssertEqual(parameters.contentType, "multipart/form-data; boundary=\(boundary)")
XCTAssertEqual(encodedData, "--\(boundary)\(returnCode)Content-Disposition: form-data; name=\"test\"; filename=\"test.json\"\r\nContent-Type: application/json\(returnCode)\(returnCode)\(testString)\(returnCode)--\(boundary)--\(returnCode)")
} catch {
XCTFail()
}
}
#endif
func testStringValue() {
let part = try! MultipartFormDataBodyParameters.Part(value: "abcdef", name: "foo")
let parameters = MultipartFormDataBodyParameters(parts: [part])
do {
guard case .data(let data) = try parameters.buildEntity() else {
XCTFail()
return
}
let string = String(data: data, encoding:.utf8)!
XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nabcdef\r\n--\(parameters.boundary)--\r\n")
} catch {
XCTFail()
}
}
func testIntValue() {
let part = try! MultipartFormDataBodyParameters.Part(value: 123, name: "foo")
let parameters = MultipartFormDataBodyParameters(parts: [part])
do {
guard case .data(let data) = try parameters.buildEntity() else {
XCTFail()
return
}
let string = String(data: data, encoding:.utf8)!
XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\n123\r\n--\(parameters.boundary)--\r\n")
} catch {
XCTFail()
}
}
func testDoubleValue() {
let part = try! MultipartFormDataBodyParameters.Part(value: 3.14, name: "foo")
let parameters = MultipartFormDataBodyParameters(parts: [part])
do {
guard case .data(let data) = try parameters.buildEntity() else {
XCTFail()
return
}
let string = String(data: data, encoding:.utf8)!
XCTAssertEqual(string, "--\(parameters.boundary)\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\n3.14\r\n--\(parameters.boundary)--\r\n")
} catch {
XCTFail()
}
}
}
| mit | 180c26ad4eff3ba44e600b92cf03b4c2 | 42.56962 | 291 | 0.603138 | 4.663957 | false | true | false | false |
no13bus/besike-ios-Fortuna | Fortuna/Fortuna/AppDelegate.swift | 1 | 3250 | //
// AppDelegate.swift
// Fortuna
//
// Created by no13bus on 14-10-17.
// Copyright (c) 2014年 no13bus. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var positiveQuotes: [String]!
var negativeQuotes: [String]!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let positiveQuotes_path = NSBundle.mainBundle().pathForResource("positiveQuotes", ofType: "json")
let negativeQuotes_path = NSBundle.mainBundle().pathForResource("negativeQuotes", ofType: "json")
println("positive quotes path: \(positiveQuotes_path)")
positiveQuotes = loadJSON(positiveQuotes_path!) as [String]!
negativeQuotes = loadJSON(negativeQuotes_path!) as [String]!
assert(positiveQuotes.count > 0, "should load positive quotes")
assert(negativeQuotes.count > 0, "should load negative quotes")
return true
}
func loadJSON(path: String) -> AnyObject? {
// Load data from path
let data = NSData(contentsOfFile: path)
assert(data != nil, "Failed to read data from: \(path)")
// Parse JSON data
var err : NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: &err)
assert(err == nil, "Error parsing json: \(err)")
return json
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | c8d3442b7c81cf978d0593632d6b3622 | 47.477612 | 285 | 0.718288 | 5.1968 | false | false | false | false |
cristianodp/Aulas-IOS | Aula4/ParametrosEntreTelas/ParametrosEntreTelas/ViewController.swift | 2 | 785 | //
// ViewController.swift
// ParametrosEntreTelas
//
// Created by Cristiano Diniz Pinto on 01/06/17.
// Copyright © 2017 Cristiano Diniz Pinto. All rights reserved.
//
import UIKit
class ViewController: UIViewController,ParametroDelegate {
@IBOutlet weak var textEdit: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
func retornoPage2(text: String) {
textEdit.text = text
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue1" {
let vc = segue.destination as? ViewController2
vc?.textoRecebido = textEdit.text!
vc?.delegateRetorno = self
}
}
}
| apache-2.0 | 23152d3fb2020d9c70e60bdc580b6d93 | 20.189189 | 71 | 0.591837 | 4.307692 | false | false | false | false |
faimin/ZDOpenSourceDemo | ZDOpenSourceSwiftDemo/Pods/PromiseKit/Extensions/Foundation/Sources/afterlife.swift | 7 | 789 | import Foundation
#if !PMKCocoaPods
import PromiseKit
#endif
/**
- Returns: A promise that resolves when the provided object deallocates
- Important: The promise is not guarenteed to resolve immediately when the provided object is deallocated. So you cannot write code that depends on exact timing.
*/
public func after(life object: NSObject) -> Guarantee<Void> {
var reaper = objc_getAssociatedObject(object, &handle) as? GrimReaper
if reaper == nil {
reaper = GrimReaper()
objc_setAssociatedObject(object, &handle, reaper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return reaper!.promise
}
private var handle: UInt8 = 0
private class GrimReaper: NSObject {
deinit {
fulfill(())
}
let (promise, fulfill) = Guarantee<Void>.pending()
}
| mit | 4bdef90733bd309a94b012773e60d3d8 | 29.346154 | 162 | 0.713561 | 4.152632 | false | false | false | false |
kylef/Requests | Sources/Socket.swift | 1 | 3855 | #if os(Linux)
import Glibc
private let sock_stream = Int32(SOCK_STREAM.rawValue)
private let system_accept = Glibc.accept
private let system_bind = Glibc.bind
private let system_close = Glibc.close
private let system_listen = Glibc.listen
private let system_read = Glibc.read
private let system_send = Glibc.send
private let system_write = Glibc.write
private let system_shutdown = Glibc.shutdown
private let system_select = Glibc.select
private let system_pipe = Glibc.pipe
private let system_connect = Glibc.connect
#else
import Darwin.C
private let sock_stream = SOCK_STREAM
private let system_accept = Darwin.accept
private let system_bind = Darwin.bind
private let system_close = Darwin.close
private let system_listen = Darwin.listen
private let system_read = Darwin.read
private let system_send = Darwin.send
private let system_write = Darwin.write
private let system_shutdown = Darwin.shutdown
private let system_select = Darwin.select
private let system_pipe = Darwin.pipe
private let system_connect = Darwin.connect
#endif
@_silgen_name("fcntl") private func fcntl(descriptor: Int32, _ command: Int32, _ flags: Int32) -> Int32
struct SocketError : ErrorType, CustomStringConvertible {
let function: String
let number: Int32
init(function: String = __FUNCTION__) {
self.function = function
self.number = errno
}
var description: String {
return "Socket.\(function) failed [\(number)]"
}
}
/// Represents a TCP AF_INET socket
class Socket {
typealias Descriptor = Int32
typealias Port = UInt16
let descriptor: Descriptor
class func pipe() throws -> [Socket] {
var fds: [Int32] = [0, 0]
if system_pipe(&fds) == -1 {
throw SocketError()
}
return [Socket(descriptor: fds[0]), Socket(descriptor: fds[1])]
}
init() throws {
#if os(Linux)
descriptor = socket(AF_INET, sock_stream, 0)
#else
descriptor = socket(AF_INET, sock_stream, IPPROTO_TCP)
#endif
assert(descriptor > 0)
var value: Int32 = 1
guard setsockopt(descriptor, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(sizeof(Int32))) != -1 else {
throw SocketError(function: "setsockopt()")
}
}
init(descriptor: Descriptor) {
self.descriptor = descriptor
}
func connect(hostname: String, port: Int16) throws {
let host = hostname.withCString { gethostbyname($0) }
if host == nil {
throw SocketError()
}
var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = in_port_t(htons(in_port_t(port)))
addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
memcpy(&addr.sin_addr, host.memory.h_addr_list[0], Int(host.memory.h_length))
let len = socklen_t(UInt8(sizeof(sockaddr_in)))
guard system_connect(descriptor, sockaddr_cast(&addr), len) != -1 else {
throw SocketError()
}
}
func close() {
system_close(descriptor)
}
func shutdown() {
system_shutdown(descriptor, Int32(SHUT_RDWR))
}
func send(output: String) {
output.withCString { bytes in
system_send(descriptor, bytes, Int(strlen(bytes)), 0)
}
}
func write(output: String) {
output.withCString { bytes in
system_write(descriptor, bytes, Int(strlen(bytes)))
}
}
func write(output: [UInt8]) {
output.withUnsafeBufferPointer { bytes in
system_write(descriptor, bytes.baseAddress, bytes.count)
}
}
func read(bytes: Int) throws -> [CChar] {
let data = Data(capacity: bytes)
let bytes = system_read(descriptor, data.bytes, data.capacity)
if bytes > 0 {
return Array(data.characters[0..<bytes])
}
return []
}
private func htons(value: CUnsignedShort) -> CUnsignedShort {
return (value << 8) + (value >> 8)
}
private func sockaddr_cast(p: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<sockaddr> {
return UnsafeMutablePointer<sockaddr>(p)
}
}
| bsd-2-clause | ae9809dc8e1d4f6de5038ca43c41298f | 25.047297 | 105 | 0.683787 | 3.657495 | false | false | false | false |
OctMon/OMExtension | OMExtension/OMExtension/Source/UIKit/OMApplication.swift | 1 | 22338 | //
// OMApplication.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if !os(macOS) && !os(watchOS)
import UIKit
import AudioToolbox
// MARK: - Authentication
#if !os(tvOS)
import LocalAuthentication
public enum OMAuthenticationTouchID: Int {
case success
case error
case authenticationFailed
case userCancel
case userFallback
case systemCancel
case passcodeNotSet
case touchIDNotAvailable
case touchIDNotEnrolled
}
#endif
public enum OMBaseURLType: String {
case release, develop, test, custom
public var currentType: OMBaseURLType {
if let type = UserDefaults.standard.object(forKey: UIApplication.OM.release.defaultBaseURLTypeKey) as? String, !UIApplication.OM.release.isAppstore {
return OMBaseURLType(rawValue: type) ?? OMBaseURLType.release
} else {
return self
}
}
public var currentURL: String {
return UIApplication.OM.release.module(type: currentType)
}
}
public extension UIApplication {
struct OM {
// MARK: - Audio
/**
http://iphonedevwiki.net/index.php/AudioServices
*/
public enum SoundID: Int {
case newMail = 1000
case mailSent = 1001
case voiceMail = 1002
case recivedMessage = 1003
case sentMessage = 1004
case alarm = 1005
case lowPower = 1006
case smsReceived1 = 1007
case smsReceived2 = 1008
case smsReceived3 = 1009
case smsReceived4 = 1010
case smsReceived5 = 1013
case smsReceived6 = 1014
case tweetSent = 1016
case anticipate = 1020
case bloom = 1021
case calypso = 1022
case chooChoo = 1023
case descent = 1024
case fanfare = 1025
case ladder = 1026
case minuet = 1027
case newsFlash = 1028
case noir = 1029
case sherwoodForest = 1030
case spell = 1031
case suspence = 1032
case telegraph = 1033
case tiptoes = 1034
case typewriters = 1035
case update = 1036
case ussdAlert = 1050
case simToolkitCallDropped = 1051
case simToolkitGeneralBeep = 1052
case simToolkitNegativeACK = 1053
case simToolkitPositiveACK = 1054
case simToolkitSMS = 1055
case tink = 1057
case ctBusy = 1070
case ctCongestion = 1071
case ctPathACK = 1072
case ctError = 1073
case ctCallWaiting = 1074
case ctKeytone = 1075
case lock = 1100
case unlock = 1101
case failedUnlock = 1102
case keypressedTink = 1103
case keypressedTock = 1104
case tock = 1105
case beepBeep = 1106
case ringerCharged = 1107
case photoShutter = 1108
case shake = 1109
case jblBegin = 1110
case jblConfirm = 1111
case jblCancel = 1112
case beginRecording = 1113
case endRecording = 1114
case jblAmbiguous = 1115
case jblNoMatch = 1116
case beginVideoRecord = 1117
case endVideoRecord = 1118
case vcInvitationAccepted = 1150
case vcRinging = 1151
case vcEnded = 1152
case vcCallWaiting = 1153
case vcCallUpgrade = 1154
case touchTone1 = 1200
case touchTone2 = 1201
case touchTone3 = 1202
case touchTone4 = 1203
case touchTone5 = 1204
case touchTone6 = 1205
case touchTone7 = 1206
case touchTone8 = 1207
case touchTone9 = 1208
case touchTone10 = 1209
case touchToneStar = 1210
case touchTonePound = 1211
case headsetStartCall = 1254
case headsetRedial = 1255
case headsetAnswerCall = 1256
case headsetEndCall = 1257
case headsetCallWaitingActions = 1258
case headsetTransitionEnd = 1259
case voicemail = 1300
case receivedMessage = 1301
case newMail2 = 1302
case mailSent2 = 1303
case alarm2 = 1304
case lock2 = 1305
case tock2 = 1306
case smsReceived1_2 = 1307
case smsReceived2_2 = 1308
case smsReceived3_2 = 1309
case smsReceived4_2 = 1310
case smsReceivedVibrate = 1311
case smsReceived1_3 = 1312
case smsReceived5_3 = 1313
case smsReceived6_3 = 1314
case voicemail2 = 1315
case anticipate2 = 1320
case bloom2 = 1321
case calypso2 = 1322
case chooChoo2 = 1323
case descent2 = 1324
case fanfare2 = 1325
case ladder2 = 1326
case minuet2 = 1327
case newsFlash2 = 1328
case noir2 = 1329
case sherwoodForest2 = 1330
case spell2 = 1331
case suspence2 = 1332
case telegraph2 = 1333
case tiptoes2 = 1334
case typewriters2 = 1335
case update2 = 1336
case ringerVibeChanged = 1350
case silentVibeChanged = 1351
case vibrate = 4095
}
// MARK: - App
/// 获取单例delegate
public static var appDelegate: UIApplicationDelegate { return UIApplication.shared.delegate! }
// 获取当前UIViewController
public static var currentVC: UIViewController? {
var top = UIApplication.shared.keyWindow?.rootViewController
if top?.presentedViewController != nil {
top = top?.presentedViewController
} else if top?.isKind(of: UITabBarController.classForCoder()) == true {
top = (top as! UITabBarController).selectedViewController
if (top?.isKind(of: UINavigationController.classForCoder()) == true) && (top as! UINavigationController).topViewController != nil {
top = (top as! UINavigationController).topViewController
}
} else if (top?.isKind(of: UINavigationController.classForCoder()) == true) && (top as! UINavigationController).topViewController != nil {
top = (top as! UINavigationController).topViewController
}
return top
}
// 获取当前UINavigationController
public static var currentNC: UINavigationController? {
if let current = OM.currentVC {
return current.navigationController
}
return nil
}
// 获取当前UITabBarController
public static var currentTBC: UITabBarController? {
if let top = UIApplication.shared.keyWindow?.rootViewController, top.isKind(of: UITabBarController.classForCoder()) == true {
return (top as! UITabBarController)
}
return nil
}
/// 获取应用名称
public static var appName: String {
if let name = Bundle.main.infoDictionary!["CFBundleDisplayName"] as? String {
return name
}
return Bundle.main.infoDictionary!["CFBundleName"] as? String ?? ""
}
/// 获取应用唯一标识
public static var appIdentifier: String { return Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String }
/// 获取应用内部版本号
public static var appBuild: String { return Bundle.main.infoDictionary!["CFBundleVersion"] as! String }
/// 获取应用外部版本号
public static var appVersion: String { return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String }
/// 是否存在一个以应用唯一标识为标记的key
public static var isFirstStart: Bool { return OM.isFirstStartForKey(OM.appIdentifier) }
/// 是否存在一个以内部版本号为标记的key
public static var isFirstStartForCurrentBuild: Bool { return OM.isFirstStartForKey(OM.appBuild) }
/// 是否存在一个以外部版本号为标记的key
public static var isFirstStartForCurrentVersion: Bool { return OM.isFirstStartForKey(OM.appVersion) }
/**
是否存在标记key,并保存key
- parameter key: 标记key是否存在
- returns: 是否存在标记key
*/
public static func isFirstStartForKey(_ key: String) -> (Bool) {
let defaults = UserDefaults.standard
let isFirstStart: Bool = defaults.bool(forKey: key)
defaults.set(true, forKey: key)
defaults.synchronize()
if isFirstStart != true {
return true
} else {
return false
}
}
/**
是否可以打开URL (判断手机是否安装微信 需要在“Info.plist”中将要使用的URL Schemes列为白名单)
- parameter string: e.g. weixin://
- returns: 成功/失败
*/
public static func canOpenURL(string: String) -> Bool {
if let url = URL(string: string) {
return shared.canOpenURL(url)
}
return false
}
/**
在浏览器中打开URL (跳转微信 需要在“Info.plist”中将要使用的URL Schemes列为白名单)
- parameter string: e.g. weixin://
- returns: 成功/失败
*/
@discardableResult
public static func openURL(string: String) -> Bool {
if let url = URL(string: string) {
return shared.openURL(url)
}
return false
}
/// 打电话
///
/// - Parameter telephone: 电话号码
/// - Returns: 成功/失败
@discardableResult
public static func call(telephone: String) -> Bool {
guard telephone.count > 0 else {
return false
}
return openURL(string: "telprompt:\(telephone)")
}
/// 跳转到appStore应用详情
///
/// - Parameter id: 应该id
/// - Returns: 成功/失败
@discardableResult
public static func openAppStoreDetails(id: Int) -> Bool {
return openURL(string: "itms-apps://itunes.apple.com/app/id\(id)")
}
/// 跳转到appStore应用评价
///
/// - Parameter id: 应该id
/// - Returns: 成功/失败
@discardableResult
public static func openAppStoreReviews(id: Int) -> Bool {
return openURL(string: "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=\(id)")
}
/// 应用在appStore中的下载地址
///
/// - Parameter id: 应该id
/// - Returns: 成功/失败
public static func getAppStoreURL(id: Int) -> String { return "https://itunes.apple.com/app/id\(id)" }
/// 应用在appStore中的详情json的请求地址
///
/// - Parameter id: 应该id
/// - Returns: 成功/失败
public static func getAppStoreLookupURL(id: Int) -> String { return "https://itunes.apple.com/US/lookup?id=\(id)" }
/**
跳转到应用设置
- returns: 成功/失败
*/
@discardableResult
public static func openAppSettings() -> Bool { return openURL(string: UIApplicationOpenSettingsURLString) }
// MARK: - Audio
public static func playSystemSound(soundID: OM.SoundID) {
AudioServicesPlaySystemSound(SystemSoundID(soundID.rawValue))
}
public static func playVibrate() {
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
}
public static func playSound(forResource: String) {
guard let soundPath = Bundle.main.path(forResource: forResource, ofType: nil) else { return }
guard let soundUrl = URL(string: soundPath) else { return }
var soundID: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundUrl as CFURL, &soundID)
AudioServicesPlaySystemSound(soundID)
}
// MARK: - Authentication
#if !os(tvOS)
public static func authenticationTouchID(reason: String, handler: @escaping (Bool, LAError?) -> Void) {
let context: LAContext = LAContext()
var error: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (success, error) in
handler(success, error as? LAError)
})
} else {
handler(false, error as? LAError)
}
}
#endif
// MARK: - Release
public struct release {
/* Must first in AppDelegate didFinishLaunchingWithOptions configure the environment
#if DEBUG
let isDebug = true
#else
let isDebug = false
#endif
#if APPSTORE
let isAppstore = true
#else
let isAppstore = false
#endif
#if BETA
let isBeta = true
#else
let isBeta = false
#endif
UIApplication.OM.release.isDebug = isDebug
UIApplication.OM.release.isAppstore = isAppstore
UIApplication.OM.release.isBeta = isBeta
UIApplication.OM.release.configURLRelease = "https://release.example.com"
UIApplication.OM.release.configURLDeveloper = "https://developer.example.com"
UIApplication.OM.release.configURLTest = "https://test.example.com"
*/
public static var isDebug = true
public static var isAppstore = false
public static var isBeta = false
public static var defaultBaseURLTypeKey = "OM_BaseURLTypeKey"
public static var defaultCustomModuleKey = "OM_CustomModuleKey"
/// 默认BaseURLType
public static var baseURL: OMBaseURLType = baseURLType
private static var baseURLType: OMBaseURLType {
if isAppstore {
return .release
} else if isDebug {
return .develop
}
return .test
}
private static func showCustomBaseURL(currentURL: String = baseURL.currentURL, viewController: UIViewController? = UIApplication.OM.currentVC, completionHandler: ((OMBaseURLType) -> Void)? = nil) {
let alert = UIAlertController(title: "custom BaseURL", message: nil, preferredStyle: .alert)
alert.addTextField { (textField) in
textField.text = currentURL
textField.keyboardType = .URL
}
alert.addAction(UIAlertAction(title: "ok", style: .default, handler: { (_) in
let url = alert.textFields?.first?.text
if let url = url, url.omIsURL {
UserDefaults.standard.set(url, forKey: defaultCustomModuleKey)
UserDefaults.standard.synchronize()
saveBaseURL(URLType: .custom)
completionHandler?(.custom)
} else {
let alert = UIAlertController(title: "address validation fails", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .cancel, handler: { _ in
showCustomBaseURL(currentURL: url ?? baseURL.currentURL, viewController: viewController, completionHandler: completionHandler)
}))
viewController?.om.presentViewController(alert)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
viewController?.om.presentViewController(alert)
}
public static func showBaseURL(viewController: UIViewController? = UIApplication.OM.currentVC, completionHandler: ((OMBaseURLType) -> Void)? = nil) {
let current = UserDefaults.standard.object(forKey: defaultBaseURLTypeKey) as? String ?? baseURL.rawValue
let alert = UIAlertController(title: "current BaseURL: [" + current + "]", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: OMBaseURLType.release.rawValue, style: .default, handler: { (_) in
saveBaseURL(URLType: .release)
completionHandler?(.release)
}))
alert.addAction(UIAlertAction(title: OMBaseURLType.develop.rawValue, style: .default, handler: { (_) in
saveBaseURL(URLType: .develop)
completionHandler?(.develop)
}))
alert.addAction(UIAlertAction(title: OMBaseURLType.test.rawValue, style: .default, handler: { (_) in
saveBaseURL(URLType: .test)
completionHandler?(.test)
}))
alert.addAction(UIAlertAction(title: OMBaseURLType.custom.rawValue, style: .destructive, handler: { (_) in
showCustomBaseURL(viewController: viewController, completionHandler: completionHandler)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
guard let viewController = viewController else {
print("viewController is nil")
return
}
viewController.om.presentViewController(alert)
}
public static func saveBaseURL(URLType: OMBaseURLType) {
UserDefaults.standard.set(URLType.rawValue, forKey: defaultBaseURLTypeKey)
UserDefaults.standard.synchronize()
}
public static var configURLRelease = "https://release.example.com"
public static var configURLDeveloper = "https://developer.example.com"
public static var configURLTest = "https://test.example.com"
fileprivate
static func module(type: OMBaseURLType) -> String {
switch type {
case .release:
return configURLRelease
case .develop:
return configURLDeveloper
case .test:
return configURLTest
case .custom:
if let url = UserDefaults.standard.object(forKey: defaultCustomModuleKey) as? String {
return url
}
return module(type: .develop)
}
}
}
}
}
#endif
| mit | 7ec41bd2978c91c15249d6b89f76e620 | 34.620915 | 209 | 0.526009 | 5.495337 | false | false | false | false |
someoneAnyone/Nightscouter | NightscouterNow Extension/SiteDetailInterfaceController.swift | 1 | 5713 | //
// SiteDetailInterfaceController.swift
// Nightscouter
//
// Created by Peter Ina on 11/8/15.
// Copyright © 2015 Peter Ina. All rights reserved.
//
import WatchKit
import Foundation
import NightscouterWatchOSKit
//protocol SiteDetailViewDidUpdateItemDelegate {
// func didUpdateItem(_ model: WatchModel)
// func didSetItemAsDefault(_ model: WatchModel)
//}
class SiteDetailInterfaceController: WKInterfaceController {
@IBOutlet var compassGroup: WKInterfaceGroup!
@IBOutlet var detailGroup: WKInterfaceGroup!
@IBOutlet var lastUpdateLabel: WKInterfaceLabel!
@IBOutlet var lastUpdateHeader: WKInterfaceLabel!
@IBOutlet var batteryLabel: WKInterfaceLabel!
@IBOutlet var batteryHeader: WKInterfaceLabel!
@IBOutlet var compassImage: WKInterfaceImage!
@IBOutlet var siteUpdateTimer: WKInterfaceTimer!
var site: Site? {
didSet {
self.configureView()
}
}
override func willActivate() {
super.willActivate()
print("willActivate")
self.configureView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: Interface Builder Actions
@IBAction func updateButton() {
print(">>> Entering \(#function) <<<")
guard let site = site else { return }
refreshDataFor(site)
}
func refreshDataFor(_ site: Site, index: Int = 0) {
print(">>> Entering \(#function) <<<")
/// Tie into networking code.
site.fetchDataFromNetwork() { (updatedSite, err) in
if let _ = err {
return
}
SitesDataSource.sharedInstance.updateSite(updatedSite)
}
}
@IBAction func setAsComplication() {
// TODO: Create icon and function that sets current site as the watch complication.
SitesDataSource.sharedInstance.primarySite = site
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
if let context = context as? [String: AnyObject],let index = context[DefaultKey.lastViewedSiteIndex.rawValue] as? Int {
self.site = SitesDataSource.sharedInstance.sites[index]
}
setupNotifications()
}
fileprivate func setupNotifications() {
NotificationCenter.default.addObserver(forName: .nightscoutDataStaleNotification, object: nil, queue: .main) { (notif) in
print(">>> Entering \(#function) <<<")
self.configureView()
}
}
func configureView() {
guard let site = self.site else {
let image = NSAssetKitWatchOS.imageOfWatchFace()
compassImage.setImage(image)
compassImage.setAlpha(0.5)
return
}
let dataSource = SiteSummaryModelViewModel(withSite: site)
let compassAlpha: CGFloat = dataSource.lookStale ? 0.5 : 1.0
//let timerHidden: Bool = dataSource.lookStale
let image = self.createImage(dataSource: dataSource, delegate: dataSource, frame: calculateFrameForImage())
//OperationQueue.main.addOperation {
self.setTitle(dataSource.nameLabel)
// Compass Image
self.compassImage.setAlpha(compassAlpha)
self.compassImage.setImage(image)
// Battery label
self.batteryLabel.setText(dataSource.batteryLabel)
self.batteryLabel.setTextColor(dataSource.batteryColor)
self.batteryHeader.setText(LocalizedString.batteryLabel.localized)
self.batteryHeader.setHidden(dataSource.batteryHidden)
self.batteryLabel.setHidden(dataSource.batteryHidden)
// Last reading label
self.lastUpdateLabel.setText(PlaceHolderStrings.date)
self.lastUpdateLabel.setTextColor(PlaceHolderStrings.defaultColor.colorValue)
self.lastUpdateLabel.setHidden(true)
self.siteUpdateTimer.setDate(dataSource.lastReadingDate)
self.siteUpdateTimer.setTextColor(dataSource.lastReadingColor)
self.siteUpdateTimer.setHidden(false)
//}
}
func calculateFrameForImage() -> CGRect {
let frame = self.contentFrame
let smallest = min(min(frame.height, frame.width), 134)
let groupFrame = CGRect(x: 0, y: 0, width: smallest, height: smallest)
return groupFrame
}
func createImage(dataSource:CompassViewDataSource, delegate:CompassViewDelegate, frame: CGRect) -> UIImage {
let sgvColor = delegate.sgvColor
let rawColor = delegate.rawColor
let image = NSAssetKitWatchOS.imageOfWatchFace(frame, arrowTintColor: sgvColor, rawColor: rawColor , isDoubleUp: dataSource.direction.isDoubleRingVisible, isArrowVisible: dataSource.direction.isArrowVisible, isRawEnabled: !dataSource.rawHidden, deltaString: dataSource.deltaLabel, sgvString: dataSource.sgvLabel, rawString: dataSource.rawLabel , angle: CGFloat(dataSource.direction.angleForCompass))
return image
}
override func handleUserActivity(_ userInfo: [AnyHashable: Any]?) {
print(">>> Entering \(#function) <<<")
guard let indexOfSite = userInfo?[DefaultKey.lastViewedSiteIndex] as? Int else {
return
}
SitesDataSource.sharedInstance.lastViewedSiteIndex = indexOfSite
DispatchQueue.main.async {
self.site = SitesDataSource.sharedInstance.sites[indexOfSite]
}
}
}
| mit | 23f50ab1e2df05f537db8e5232605636 | 33.618182 | 407 | 0.63848 | 5.159892 | false | false | false | false |
inamiy/VTree | Sources/Apply.swift | 1 | 7714 | #if os(iOS) || os(tvOS)
import UIKit
private let _scale = UIScreen.main.scale
#elseif os(macOS)
import AppKit
private let _scale = NSScreen.main()!.backingScaleFactor
#endif
/// Apply `Patch` (generated from `diff()`) to the existing real `View`.
///
/// - Returns:
/// - Same view (reused) if `view` itself is not replaced by new view or removed.
/// This reuse also occurs when `view`'s property changed or it's childrens are changed.
/// - New view (replaced)
/// - `nil` (removed)
public func apply<Msg: Message>(patch: Patch<Msg>, to view: View) -> View?
{
let patchIndexes = patch.steps.map { $0.key }.sorted()
let indexedViews = _indexViews(view, patchIndexes)
var newView: View? = view
for index in patchIndexes {
let steps = patch.steps[index]!
for step in steps {
if let indexedView = indexedViews[index] {
let appliedView = _applyStep(step, to: indexedView)
if index == 0, let appliedView = appliedView {
newView = appliedView
}
}
}
}
if let newView = newView {
if patch.flexboxFrames.isEmpty == false {
let flexboxFrames = patch.flexboxFrames.map { _roundFrame($0) }
applyFlexbox(frames: flexboxFrames, to: newView)
}
}
return newView
}
/// - Returns:
/// - new view, i.e. `.some(.some(newView))`
/// - removed, i.e. `.some(.none)`
/// - same view (reused), i.e. `.none`
private func _applyStep<Msg: Message>(_ step: PatchStep<Msg>, to view: View) -> View??
{
switch step {
case let .replace(newTree):
let newView = newTree.createView()
if let parentView = view.superview {
parentView.replaceSubview(view, with: newView)
}
return newView
case let .props(removes, updates, inserts):
for removeKey in removes {
view.setValue(nil, forKey: removeKey)
}
for update in updates {
view.setValue(_toOptionalAny(update.value), forKey: update.key)
}
for insert in inserts {
view.setValue(_toOptionalAny(insert.value), forKey: insert.key)
}
return nil
case let .handlers(removes, updates, inserts):
for removeEvent in removes {
_removeHandler(for: removeEvent, in: view)
}
for update in updates {
_updateHandler(msg: update.value, for: update.key, in: view)
}
for insert in inserts {
_insertHandler(msg: insert.value, for: insert.key, in: view)
}
return nil
case let .gestures(removes, inserts):
for removeEvent in removes {
_removeGesture(for: removeEvent, in: view)
}
for insert in inserts {
_insertGesture(for: insert, in: view)
}
return nil
case .removeChild:
view.removeFromSuperview()
return .some(nil)
case let .insertChild(newTree):
let newChildView = newTree.createView()
view.addSubview(newChildView)
return nil
case let .reorderChildren(reorder):
_applyReorder(to: view, reorder: reorder)
return nil
}
}
internal func applyFlexbox(frames: [CGRect], to view: View)
{
func flatten(_ view: View) -> [View]
{
var views = [view]
let subviews = view.subviews.filter { $0.isVTreeView }.flatMap { flatten($0) }
views.append(contentsOf: subviews)
return views
}
for (frame, view) in zip(frames, flatten(view)) {
view.frame = frame
}
}
// MARK: remove/insert handlers
private func _removeHandler(for event: SimpleEvent, in view: View)
{
#if os(iOS) || os(tvOS)
if case let (.control(controlEvents), view as UIControl) = (event, view) {
view.vtree.removeHandler(for: controlEvents)
return
}
#endif
}
private func _insertHandler<Msg: Message>(msg: Msg, for event: SimpleEvent, in view: View)
{
#if os(iOS) || os(tvOS)
if case let (.control(controlEvents), view as UIControl) = (event, view) {
view.vtree.addHandler(for: controlEvents) { _ in
Messenger.shared.send(AnyMsg(msg))
}
return
}
#endif
}
private func _updateHandler<Msg: Message>(msg: Msg, for event: SimpleEvent, in view: View)
{
_removeHandler(for: event, in: view)
_insertHandler(msg: msg, for: event, in: view)
}
// MARK: remove/insert gestures
private func _removeGesture<Msg: Message>(for event: GestureEvent<Msg>, in view: View)
{
#if os(iOS) || os(tvOS)
view.vtree.removeGesture(for: event)
#endif
}
private func _insertGesture<Msg: Message>(for event: GestureEvent<Msg>, in view: View)
{
#if os(iOS) || os(tvOS)
view.vtree.addGesture(for: event) { msg in
Messenger.shared.send(AnyMsg(msg))
}
#endif
}
// MARK: Reorder
private func _applyReorder(to view: View, reorder: Reorder)
{
var keyViews = [ObjectIdentifier: View]()
for remove in reorder.removes {
let removingView = view.subviews[remove.fromIndex]
if let removingKey = remove.key {
keyViews[ObjectIdentifier(removingKey)] = removingView
}
removingView.removeFromSuperview()
}
for insert in reorder.inserts {
if let insertingKey = insert.key, let insertingView = keyViews[ObjectIdentifier(insertingKey)] {
view.insertSubview(insertingView, at: insert.toIndex)
}
}
}
// MARK: _indexViews
/// Create index-view-table.
private func _indexViews(_ rootView: View, _ patchIndexes: [Int]) -> [Int: View]
{
var indexedViews = [Int: View]()
_accumulateRecursively(
rootView: rootView,
rootIndex: 0,
patchIndexes: patchIndexes,
indexedViews: &indexedViews
)
return indexedViews
}
private func _accumulateRecursively(rootView: View, rootIndex: Int, patchIndexes: [Int], indexedViews: inout [Int: View])
{
if patchIndexes.contains(rootIndex) {
indexedViews[rootIndex] = rootView
}
// Early exit if subviews are not created via VTree.
// For example, UIButton has internal UIImageView and UIButtonLabel,
// but VTree only handles `VButton`.
guard let firstSubview = rootView.subviews.first, firstSubview.isVTreeView == true else {
return
}
var childIndex = rootIndex
for (i, childView) in rootView.subviews.enumerated() {
childIndex += 1
func descendantCount(for view: View) -> Int
{
return view.subviews
.filter { $0.isVTreeView }
.reduce(0) { $0 + 1 + descendantCount(for: $1) }
}
let nextChildIndex = childIndex + descendantCount(for: childView)
if _indexInRange(patchIndexes, childIndex, nextChildIndex) {
_accumulateRecursively(
rootView: childView,
rootIndex: childIndex,
patchIndexes: patchIndexes,
indexedViews: &indexedViews
)
}
childIndex = nextChildIndex
}
}
// MARK: Helper
private func _roundFrame(_ frame: CGRect) -> CGRect
{
func roundPixel(_ value: CGFloat) -> CGFloat
{
return round(value * _scale) / _scale
}
return CGRect(
x: roundPixel(frame.origin.x),
y: roundPixel(frame.origin.y),
width: roundPixel(frame.size.width),
height: roundPixel(frame.size.height)
)
}
| mit | d16acea2b73a6ab2b90c306449d8ce4f | 28.669231 | 121 | 0.590096 | 4.103191 | false | false | false | false |
stripe/stripe-ios | StripeIdentity/StripeIdentity/Source/NativeComponents/Coordinators/ImageUploaders/DocumentUploader.swift | 1 | 8387 | //
// DocumentUploader.swift
// StripeIdentity
//
// Created by Mel Ludowise on 12/8/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import Foundation
@_spi(STP) import StripeCameraCore
@_spi(STP) import StripeCore
import UIKit
protocol DocumentUploaderDelegate: AnyObject {
func documentUploaderDidUpdateStatus(_ documentUploader: DocumentUploader)
func documentUploaderDidUploadFront(_ documentUploader: DocumentUploaderProtocol)
func documentUploaderDidUploadBack(_ documentUploader: DocumentUploaderProtocol)
}
protocol DocumentUploaderProtocol: AnyObject {
/// Tuple of front and back document file data
typealias CombinedFileData = (
front: StripeAPI.VerificationPageDataDocumentFileData?,
back: StripeAPI.VerificationPageDataDocumentFileData?
)
var delegate: DocumentUploaderDelegate? { get set }
var frontUploadStatus: DocumentUploader.UploadStatus { get }
var backUploadStatus: DocumentUploader.UploadStatus { get }
var frontUploadFuture: Future<StripeAPI.VerificationPageDataDocumentFileData>? { get }
var backUploadFuture: Future<StripeAPI.VerificationPageDataDocumentFileData>? { get }
func uploadImages(
for side: DocumentSide,
originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: StripeAPI.VerificationPageDataDocumentFileData.FileUploadMethod
)
func reset()
}
final class DocumentUploader: DocumentUploaderProtocol {
enum UploadStatus {
case notStarted
case inProgress
case complete
case error(Error)
}
weak var delegate: DocumentUploaderDelegate?
let imageUploader: IdentityImageUploader
/// Future that is fulfilled when front images are uploaded to the server.
/// Value is nil if upload has not been requested.
private(set) var frontUploadFuture: Future<StripeAPI.VerificationPageDataDocumentFileData>? {
didSet {
guard oldValue !== frontUploadFuture else {
return
}
frontUploadStatus = (frontUploadFuture == nil) ? .notStarted : .inProgress
frontUploadFuture?.observe { [weak self, weak frontUploadFuture] result in
// Only update `frontUploadStatus` if `frontUploadFuture` has not been reassigned
guard let self = self,
frontUploadFuture === self.frontUploadFuture
else {
return
}
switch result {
case .success:
self.frontUploadStatus = .complete
case .failure(let error):
self.frontUploadStatus = .error(error)
}
}
}
}
/// Future that is fulfilled when back images are uploaded to the server.
/// Value is nil if upload has not been requested.
private(set) var backUploadFuture: Future<StripeAPI.VerificationPageDataDocumentFileData>? {
didSet {
guard oldValue !== backUploadFuture else {
return
}
backUploadStatus = (backUploadFuture == nil) ? .notStarted : .inProgress
backUploadFuture?.observe { [weak self, weak backUploadFuture] result in
// Only update `backUploadStatus` if `backUploadFuture` has not been reassigned
guard let self = self,
backUploadFuture === self.backUploadFuture
else {
return
}
switch result {
case .success:
self.backUploadStatus = .complete
case .failure(let error):
self.backUploadStatus = .error(error)
}
}
}
}
/// Status of whether the front images have finished uploading
private(set) var frontUploadStatus: UploadStatus = .notStarted {
didSet {
delegate?.documentUploaderDidUpdateStatus(self)
if case .complete = frontUploadStatus {
delegate?.documentUploaderDidUploadFront(self)
}
}
}
/// Status of whether the back images have finished uploading
private(set) var backUploadStatus: UploadStatus = .notStarted {
didSet {
delegate?.documentUploaderDidUpdateStatus(self)
if case .complete = backUploadStatus {
delegate?.documentUploaderDidUploadBack(self)
}
}
}
init(
imageUploader: IdentityImageUploader
) {
self.imageUploader = imageUploader
}
/// Uploads a high and low resolution image for a specific side of the
/// document and updates either `frontUploadFuture` or `backUploadFuture`.
/// - Note: If `idDetectorOutput` is non-nil, the high-res image will be
/// cropped and an un-cropped image will be uploaded as the low-res image.
/// If `idDetectorOutput` is nil, then only a high-res image will be
/// uploaded and it will not be cropped.
/// - Parameters:
/// - side: The side of the image (front or back) to upload.
/// - originalImage: The original image captured or uploaded by the user.
/// - idDetectorOutput: The output from the IDDetector model
/// - method: The method the image was obtained.
func uploadImages(
for side: DocumentSide,
originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: StripeAPI.VerificationPageDataDocumentFileData.FileUploadMethod
) {
let uploadFuture = uploadImages(
originalImage,
documentScannerOutput: documentScannerOutput,
exifMetadata: exifMetadata,
method: method,
fileNamePrefix: "\(imageUploader.apiClient.verificationSessionId)_\(side.rawValue)"
)
switch side {
case .front:
self.frontUploadFuture = uploadFuture
case .back:
self.backUploadFuture = uploadFuture
}
}
/// Uploads both a high and low resolution image
func uploadImages(
_ originalImage: CGImage,
documentScannerOutput: DocumentScannerOutput?,
exifMetadata: CameraExifMetadata?,
method: StripeAPI.VerificationPageDataDocumentFileData.FileUploadMethod,
fileNamePrefix: String
) -> Future<StripeAPI.VerificationPageDataDocumentFileData> {
// Only upload a low res image if the high res image will be cropped
if let documentBounds = documentScannerOutput?.idDetectorOutput.documentBounds {
return imageUploader.uploadLowAndHighResImages(
originalImage,
highResRegionOfInterest: documentBounds,
cropPaddingComputationMethod: .maxImageWidthOrHeight,
lowResFileName: "\(fileNamePrefix)_full_frame",
highResFileName: fileNamePrefix
).chained { (lowResFile, highResFile) in
return Promise(
value: StripeAPI.VerificationPageDataDocumentFileData(
documentScannerOutput: documentScannerOutput,
highResImage: highResFile.id,
lowResImage: lowResFile.id,
exifMetadata: exifMetadata,
uploadMethod: method
)
)
}
} else {
return imageUploader.uploadHighResImage(
originalImage,
regionOfInterest: nil,
cropPaddingComputationMethod: .maxImageWidthOrHeight,
fileName: fileNamePrefix
).chained { highResFile in
return Promise(
value: StripeAPI.VerificationPageDataDocumentFileData(
documentScannerOutput: documentScannerOutput,
highResImage: highResFile.id,
lowResImage: nil,
exifMetadata: exifMetadata,
uploadMethod: method
)
)
}
}
}
/// Resets the status of the uploader
func reset() {
frontUploadFuture = nil
backUploadFuture = nil
}
}
| mit | f74561d262fdbc74828e0eb3039a91ad | 36.106195 | 97 | 0.61865 | 5.650943 | false | false | false | false |
macemmi/HBCI4Swift | HBCI4Swift/HBCI4Swift/Source/RIPEMD160.swift | 1 | 5035 | //
// RIPEMD160.swift
// HBCISmartCard
//
// Created by Frank Emminghaus on 09.08.15.
// Copyright (c) 2015 Frank Emminghaus. All rights reserved.
//
import Foundation
class RIPEMD160 {
var h0:UInt32 = 0x67452301;
var h1:UInt32 = 0xefcdab89;
var h2:UInt32 = 0x98badcfe;
var h3:UInt32 = 0x10325476;
var h4:UInt32 = 0xc3d2e1f0;
var paddedData:Data!
let r = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ];
let r´ = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ];
let s = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ];
let s´ = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ];
let K:[UInt32] = [ 0x00000000,
0x5a827999,
0x6ed9eba1,
0x8f1bbcdc,
0xa953fd4e ];
let K´:[UInt32] = [ 0x50a28be6,
0x5c4dd124,
0x6d703ef3,
0x7a6d76e9,
0x00000000 ];
init(data: Data) {
self.paddedData = pad(data);
}
func pad(_ data:Data) ->Data {
var paddedData = NSData(data: data) as Data;
var paddingData = [UInt8](repeating: 0, count: 72);
paddingData[0] = 0x80;
let zeros = (64 - ((data.count+9) % 64)) % 64;
var n = data.count * 8;
paddedData.append(paddingData, count: zeros+1);
let p = UnsafeMutablePointer<Int>.allocate(capacity: 1)
memcpy(p, &n,MemoryLayout.size(ofValue: n))
paddedData.append(UnsafeBufferPointer<Int>(start: &n, count: 1));
return paddedData;
}
func f(_ j:Int, x:UInt32, y:UInt32, z:UInt32) ->UInt32 {
if j<=15 {
return x ^ y ^ z;
} else if j <= 31 {
return (x & y) | (~x & z);
} else if j <= 47 {
return (x | ~y) ^ z;
} else if j <= 63 {
return (x & z) | (y & ~z);
} else if j <= 79 {
return x ^ (y | ~z);
} else {
assertionFailure("RIPEMD160: wrong index for function f");
}
return 0;
}
func rol(_ x:UInt32, n:Int) -> UInt32 {
return (x << UInt32(n)) | (x >> UInt32(32 - n));
}
func hash(_ X:UnsafePointer<UInt32>) {
var A = h0;
var B = h1;
var C = h2;
var D = h3;
var E = h4;
var A´ = h0;
var B´ = h1;
var C´ = h2;
var D´ = h3;
var E´ = h4;
var T:UInt32;
for j in 0...79 {
T = rol(A &+ f(j, x:B, y:C, z:D) &+ X[r[j]] &+ K[j>>4], n: s[j]) &+ E;
A = E;
E = D;
D = rol(C, n: 10);
C = B;
B = T;
T = rol(A´ &+ f(79-j, x:B´, y:C´, z:D´) &+ X[r´[j]] &+ K´[j>>4], n: s´[j]) &+ E´;
A´ = E´;
E´ = D´;
D´ = rol(C´, n: 10);
C´ = B´;
B´ = T;
}
T = h1 &+ C &+ D´;
h1 = h2 &+ D &+ E´;
h2 = h3 &+ E &+ A´;
h3 = h4 &+ A &+ B´;
h4 = h0 &+ B &+ C´;
h0 = T;
}
func digest() ->Data {
let blocks = paddedData.count / 64;
paddedData.withUnsafeBytes { (p:UnsafeRawBufferPointer) in
let q = p.bindMemory(to: UInt32.self)
var x = q.baseAddress!
for _ in 0 ..< blocks {
hash(x);
x = x.advanced(by: 16);
}
}
let digest = NSMutableData();
digest.append(&h0, length: 4);
digest.append(&h1, length: 4);
digest.append(&h2, length: 4);
digest.append(&h3, length: 4);
digest.append(&h4, length: 4);
return digest as Data;
}
}
| gpl-2.0 | 49f7f56d0c1bdbd7377eecf8b9eca2ad | 31.083333 | 93 | 0.392807 | 2.792969 | false | false | false | false |
johnpatrickmorgan/wtfautolayout | Sources/App/Parsing/ConstraintsParser+EquationConstraint.swift | 1 | 1281 | import Foundation
import Sparse
// MARK: - Equation Constraint
// (e.g. "UIImageView:0x7fd382f50.top == UITableViewCell:0x7fd39b20.top")
extension ConstraintsParser {
static let equationConstraint = layoutItemAttribute.thenSkip(wss).then(relation)
.thenSkip(wss).then(preMultiplier).then(optional(layoutItemAttribute))
.thenSkip(wss).then(postMultiplier).then(anyConstant).then(optionalInfo)
.map {
try AnonymousConstraint(
first: $0.0.0.0.0.0,
relation: $0.0.0.0.0.1,
multiplier: $0.0.0.0.1 ?? $0.0.1 ?? Multiplier(),
second: $0.0.0.1,
constant: $0.1,
names: $1
)
}
}
private extension ConstraintsParser {
static let layoutItemAttribute = partialInstance.then(dotAttribute)
static let anyConstant = extent.map { Constant($1) }.otherwise(constant)
static let constant = number.map(Constant.init).otherwise(pure(Constant()))
static let preMultiplier = optional(number.thenSkip(string("*")).map(Multiplier.init))
.named("prefixed multiplier")
static let postMultiplier = optional(string("*").skipThen(wss).skipThen(number).map(Multiplier.init))
.named("postfixed multiplier")
}
| mit | d75236d17d390e98a85ab331dd6bae25 | 37.818182 | 105 | 0.641686 | 3.846847 | false | false | false | false |
wbaumann/SmartReceiptsiOS | SmartReceipts/Common/Utils/RecentCurrenciesCache.swift | 2 | 2246 | //
// RecentCurrenciesCache.swift
// SmartReceipts
//
// Created by Victor on 4/12/17.
// Copyright © 2017 Will Baumann. All rights reserved.
//
import Foundation
import FMDB
/// Recently used currencies cache
class RecentCurrenciesCache: NSObject {
static let shared = RecentCurrenciesCache()
/// Recent currencies (codes)
var cachedCurrencyCodes: [String] {
return cachedCurrencies.map{ $0.code }
}
/// Recent currencies
private(set) var cachedCurrencies: [Currency] {
get {
var cached: [Currency]?
if let unarchivedData = cache.object(forKey: currenciesKey) {
cached = NSKeyedUnarchiver.unarchiveObject(with: unarchivedData as Data) as? Array<Currency>
}
return cached ?? []
}
set {
let archivedData = NSKeyedArchiver.archivedData(withRootObject: newValue) as NSData
cache.setObject(archivedData, forKey: currenciesKey)
}
}
private let cache = NSCache<NSString, NSData>()
private let currenciesKey: NSString = "RecentCurrenciesCache_cachedCurrencies"
private override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(update), name: NSNotification.Name.DatabaseDidInsertModel, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(update), name: NSNotification.Name.DatabaseDidDeleteModel, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(update), name: NSNotification.Name.DatabaseDidUpdateModel, object: nil)
}
/// Force reload
@objc func update() {
/// read FMDB queue from global_dispatch queue
DispatchQueue.global(qos: .default).async {
let fetched = Database.sharedInstance().recentCurrencies()
DispatchQueue.main.async {
self.cachedCurrencies = fetched ?? [Currency]()
}
}
}
// MARK: - Test
/// For unit tests only (as we don't want to expose cachedCurrencies setter)
func updateInDatabase(database: Database) {
self.cachedCurrencies = database.recentCurrencies()
}
}
| agpl-3.0 | 7cc69113d84e40ed54e8848556da275e | 33.015152 | 144 | 0.649443 | 4.923246 | false | false | false | false |
cuzv/EasySwift | Sources/UIScreen+Extension.swift | 1 | 2595 | //
// UIScreen+Extension.swift
// EasySwift
//
// Created by Shaw on 7/20/18.
// Copyright © 2018 Shaw. All rights reserved.
//
import UIKit
public enum ScreenSize: Int, CaseIterable {
case unknown
/// iPhone 4, iPhone 4S
case inch3_5
/// iPhone 5, iPhone 5S, iPhone 5C, iPhone SE
case inch4_0
/// iPhone 6, iPhone 6S, iPhone 7, iPhone 8
case inch4_7
/// iPhone 6 Plus, iPhone 6S Plus, iPhone 7 Plus, iPhone 8 Plus
case inch5_5
/// iPhone X, iPhone XS
case inch5_8
/// iPhone XR
case inch6_1
/// iPhone XS Max
case inch6_5
/// iPad 3, iPad 4, iPad Air, iPad Air 2, iPad Pro 9.7-inch, iPad 5th, iPad 6th
/// iPad 1st and 2nd Generation
/// iPad Mini Retina 2nd, 3rd, 4th Generation
/// iPad Mini 1st Generation
case inch7_9_or_9_7
/// iPad Pro 10.5
case inch10_5
/// iPad Pro 12.9 1st and iPad Pro 12.9 2nd
case inch_12_9
}
extension ScreenSize: Equatable, Comparable {
public static func ==(lhs: ScreenSize, rhs: ScreenSize) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (lhs: ScreenSize, rhs: ScreenSize) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: ScreenSize, rhs: ScreenSize) -> Bool {
return lhs.rawValue <= rhs.rawValue
}
public static func >= (lhs: ScreenSize, rhs: ScreenSize) -> Bool {
return lhs.rawValue >= rhs.rawValue
}
public static func > (lhs: ScreenSize, rhs: ScreenSize) -> Bool {
return lhs.rawValue > rhs.rawValue
}
}
public extension UIScreen {
public var size: ScreenSize {
switch nativeBounds.size {
case CGSize(width: 640, height: 960): return .inch3_5
case CGSize(width: 640, height: 1136): return .inch4_0
case CGSize(width: 750, height: 1334): return .inch4_7
case CGSize(width: 1242, height: 2208): return .inch5_5
case CGSize(width: 1125, height: 2436): return .inch5_8
case CGSize(width: 828, height: 1792): return .inch6_1
case CGSize(width: 1242, height: 2688): return .inch6_5
case CGSize(width: 1536, height: 2048), CGSize(width: 768, height: 1024): return .inch7_9_or_9_7
case CGSize(width: 1668, height: 2224): return .inch10_5
case CGSize(width: 2048, height: 2732): return .inch_12_9
default: return .unknown
}
}
public var isNotchExist: Bool {
switch size {
case .inch6_5, .inch6_1, .inch5_8:
return true
default:
return false
}
}
}
| mit | ceef836e0cb66abb4e0a1056b5508edc | 28.146067 | 104 | 0.611411 | 3.602778 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/GMPalette.swift | 1 | 11398 | //
// GMPalette.swift
// GMColor
//
// Created by Todsaporn Banjerdkit (katopz) on 12/22/14.
// Copyright (c) 2014 Debokeh. All rights reserved.
//
import UIKit
class GMPalette {
static func all() -> [[UIColor]] {
return [red(), pink(), purple(),
deepPurple(), indigo(), blue(),
lightBlue(), cyan(), teal(),
green(), lightGreen(), lime(),
yellow(), amber(), orange(),
deepOrange(), brown(), grey(),
blueGrey(), blackAndWhite(),
]
}
static func allNoBlack() -> [[UIColor]] {
return [red(), pink(), purple(),
deepPurple(), indigo(), blue(),
lightBlue(), cyan(), teal(),
green(), lightGreen(), lime(),
yellow(), amber(), orange(),
deepOrange(), brown(), grey(),
[GMColor.blueGrey300Color(),
GMColor.blueGrey400Color(),
GMColor.blueGrey500Color(),
],
]
}
static func allAccent() -> [[UIColor]] {
return [redA(), pinkA(), purpleA(),
deepPurpleA(), indigoA(), blueA(),
lightBlueA(), cyanA(), tealA(),
greenA(), lightGreenA(), limeA(),
yellowA(), amberA(), orangeA(),
deepOrangeA(), ]
}
static func toCGC(colors: [UIColor]) -> [CGColor] {
var toReturn: [CGColor] = []
var i = 0
for color in colors {
if i < 3 {
i += 1
} else {
toReturn.append(color.cgColor)
}
}
return toReturn
}
static func allColor() -> [UIColor] {
var toReturn: [UIColor] = []
for i in all() {
toReturn.append(contentsOf: i)
}
return toReturn
}
static func allColorNoBlack() -> [UIColor] {
return allNoBlack().flatMap({ return $0 })
}
static func allColorAccent() -> [UIColor] {
var toReturn: [UIColor] = []
for i in allAccent() {
toReturn.append(contentsOf: i)
}
toReturn.append(UIColor.black)
return toReturn
}
static func allCGColor() -> [CGColor] {
var toReturn: [CGColor] = []
for a in all() {
toReturn.append(contentsOf: toCGC(colors: a))
}
return toReturn
}
static func allAccentCGColor() -> [CGColor] {
var toReturn: [CGColor] = []
for a in allAccent() {
toReturn.append(contentsOf: toCGC(colors: a))
}
return toReturn
}
class func red() -> [UIColor] {
return [GMColor.red200Color(), GMColor.red300Color(),
GMColor.red400Color(), GMColor.red500Color(),
GMColor.red600Color(), GMColor.red700Color(),
GMColor.red800Color(), GMColor.red900Color(),
]
}
class func redA() -> [UIColor] {
return [GMColor.redA200Color(),
GMColor.redA400Color(), GMColor.redA700Color(), ]
}
class func pink() -> [UIColor] {
return [GMColor.pink200Color(), GMColor.pink300Color(),
GMColor.pink400Color(), GMColor.pink500Color(),
GMColor.pink600Color(), GMColor.pink700Color(),
GMColor.pink800Color(), GMColor.pink900Color(),
]
}
class func pinkA() -> [UIColor] {
return [GMColor.pinkA200Color(),
GMColor.pinkA400Color(), GMColor.pinkA700Color(), ]
}
class func purple() -> [UIColor] {
return [GMColor.purple200Color(), GMColor.purple300Color(),
GMColor.purple400Color(), GMColor.purple500Color(),
GMColor.purple600Color(), GMColor.purple700Color(),
GMColor.purple800Color(), GMColor.purple900Color(),
]
}
class func purpleA() -> [UIColor] {
return [GMColor.purpleA200Color(),
GMColor.purpleA400Color(), GMColor.purpleA700Color(), ]
}
class func deepPurple() -> [UIColor] {
return [GMColor.deepPurple200Color(), GMColor.deepPurple300Color(),
GMColor.deepPurple400Color(), GMColor.deepPurple500Color(),
GMColor.deepPurple600Color(), GMColor.deepPurple700Color(),
GMColor.deepPurple800Color(), GMColor.deepPurple900Color(),
]
}
class func deepPurpleA() -> [UIColor] {
return [GMColor.deepPurpleA200Color(),
GMColor.deepPurpleA400Color(), GMColor.deepPurpleA700Color(), ]
}
class func indigo() -> [UIColor] {
return [GMColor.indigo200Color(), GMColor.indigo300Color(),
GMColor.indigo400Color(), GMColor.indigo500Color(),
GMColor.indigo600Color(), GMColor.indigo700Color(),
GMColor.indigo800Color(), GMColor.indigo900Color(),
]
}
class func indigoA() -> [UIColor] {
return [GMColor.indigoA200Color(),
GMColor.indigoA400Color(), GMColor.indigoA700Color(), ]
}
class func blue() -> [UIColor] {
return [GMColor.blue200Color(), GMColor.blue300Color(),
GMColor.blue400Color(), GMColor.blue500Color(),
GMColor.blue600Color(), GMColor.blue700Color(),
GMColor.blue800Color(), GMColor.blue900Color(),
]
}
class func blueA() -> [UIColor] {
return [GMColor.blueA200Color(),
GMColor.blueA400Color(), GMColor.blueA700Color(), ]
}
class func lightBlue() -> [UIColor] {
return [GMColor.lightBlue200Color(), GMColor.lightBlue300Color(),
GMColor.lightBlue400Color(), GMColor.lightBlue500Color(),
GMColor.lightBlue600Color(), GMColor.lightBlue700Color(),
GMColor.lightBlue800Color(), GMColor.lightBlue900Color(),
]
}
class func lightBlueA() -> [UIColor] {
return [GMColor.lightBlueA200Color(),
GMColor.lightBlueA400Color(), GMColor.lightBlueA700Color(), ]
}
class func cyan() -> [UIColor] {
return [GMColor.cyan200Color(), GMColor.cyan300Color(),
GMColor.cyan400Color(), GMColor.cyan500Color(),
GMColor.cyan600Color(), GMColor.cyan700Color(),
GMColor.cyan800Color(), GMColor.cyan900Color(),
]
}
class func cyanA() -> [UIColor] {
return [GMColor.cyanA200Color(),
GMColor.cyanA400Color(), GMColor.cyanA700Color(), ]
}
class func teal() -> [UIColor] {
return [GMColor.teal200Color(), GMColor.teal300Color(),
GMColor.teal400Color(), GMColor.teal500Color(),
GMColor.teal600Color(), GMColor.teal700Color(),
GMColor.teal800Color(), GMColor.teal900Color(),
]
}
class func tealA() -> [UIColor] {
return [GMColor.tealA200Color(),
GMColor.tealA400Color(), GMColor.tealA700Color(), ]
}
class func green() -> [UIColor] {
return [GMColor.green200Color(), GMColor.green300Color(),
GMColor.green400Color(), GMColor.green500Color(),
GMColor.green600Color(), GMColor.green700Color(),
GMColor.green800Color(), GMColor.green900Color(),
]
}
class func greenA() -> [UIColor] {
return [GMColor.greenA200Color(),
GMColor.greenA400Color(), GMColor.greenA700Color(), ]
}
class func lightGreen() -> [UIColor] {
return [GMColor.lightGreen200Color(), GMColor.lightGreen300Color(),
GMColor.lightGreen400Color(), GMColor.lightGreen500Color(),
GMColor.lightGreen600Color(), GMColor.lightGreen700Color(),
GMColor.lightGreen800Color(), GMColor.lightGreen900Color(),
]
}
class func lightGreenA() -> [UIColor] {
return [GMColor.lightGreenA200Color(),
GMColor.lightGreenA400Color(), GMColor.lightGreenA700Color(), ]
}
class func lime() -> [UIColor] {
return [GMColor.lime200Color(), GMColor.lime300Color(),
GMColor.lime400Color(), GMColor.lime500Color(),
GMColor.lime600Color(), GMColor.lime700Color(),
GMColor.lime800Color(), GMColor.lime900Color(),
]
}
class func limeA() -> [UIColor] {
return [GMColor.limeA200Color(),
GMColor.limeA400Color(), GMColor.limeA700Color(), ]
}
class func yellow() -> [UIColor] {
return [GMColor.yellow400Color(), GMColor.yellow500Color(),
GMColor.yellow600Color(), GMColor.yellow700Color(),
GMColor.yellow800Color(), GMColor.yellow900Color(),
]
}
class func yellowA() -> [UIColor] {
return [GMColor.yellowA200Color(),
GMColor.yellowA400Color(), GMColor.yellowA700Color(), ]
}
class func amber() -> [UIColor] {
return [GMColor.amber200Color(), GMColor.amber300Color(),
GMColor.amber400Color(), GMColor.amber500Color(),
GMColor.amber600Color(), GMColor.amber700Color(),
GMColor.amber800Color(), GMColor.amber900Color(),
]
}
class func amberA() -> [UIColor] {
return [GMColor.amberA200Color(),
GMColor.amberA400Color(), GMColor.amberA700Color(), ]
}
class func orange() -> [UIColor] {
return [GMColor.orange200Color(), GMColor.orange300Color(),
GMColor.orange400Color(), GMColor.orange500Color(),
GMColor.orange600Color(), GMColor.orange700Color(),
GMColor.orange800Color(), GMColor.orange900Color(),
]
}
class func orangeA() -> [UIColor] {
return [GMColor.orangeA200Color(),
GMColor.orangeA400Color(), GMColor.orangeA700Color(), ]
}
class func deepOrange() -> [UIColor] {
return [GMColor.deepOrange200Color(), GMColor.deepOrange300Color(),
GMColor.deepOrange400Color(), GMColor.deepOrange500Color(),
GMColor.deepOrange600Color(), GMColor.deepOrange700Color(),
GMColor.deepOrange800Color(), GMColor.deepOrange900Color(),
]
}
class func deepOrangeA() -> [UIColor] {
return [GMColor.deepOrangeA200Color(),
GMColor.deepOrangeA400Color(), GMColor.deepOrangeA700Color(), ]
}
class func brown() -> [UIColor] {
return [GMColor.brown200Color(), GMColor.brown300Color(),
GMColor.brown400Color(), GMColor.brown500Color(),
GMColor.brown600Color(), GMColor.brown700Color(),
GMColor.brown800Color(), GMColor.brown900Color(),
]
}
class func grey() -> [UIColor] {
return [GMColor.grey400Color(), GMColor.grey500Color(),
GMColor.grey600Color(), GMColor.grey700Color(),
GMColor.grey800Color(), GMColor.grey900Color(),
]
}
class func blueGrey() -> [UIColor] {
return [GMColor.blueGrey300Color(),
GMColor.blueGrey400Color(), GMColor.blueGrey500Color(),
GMColor.blueGrey600Color(), GMColor.blueGrey700Color(),
GMColor.blueGrey800Color(), GMColor.blueGrey900Color(),
]
}
class func blackAndWhite() -> [UIColor] {
return [GMColor.blackColor()]
}
}
| apache-2.0 | 4f562f61cde8a711e1f71425245e8e55 | 33.539394 | 79 | 0.564924 | 4.457567 | false | false | false | false |
Ceroce/SwiftRay | SwiftRay/SwiftRay/Hitable.swift | 1 | 1210 | //
// Hitable.swift
// SwiftRay
//
// Created by Renaud Pradenc on 23/11/2016.
// Copyright © 2016 Céroce. All rights reserved.
//
struct HitIntersection {
let distance: Float // Distance from the origin of the ray
let position: Vec3
let normal: Vec3
let material: Material
}
protocol Hitable {
func hit(ray: Ray, distMin: Float, distMax: Float) -> HitIntersection?
func boundingBox(startTime: Float, endTime: Float) -> BoundingBox
}
func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? {
var closerIntersection: HitIntersection? = nil
var closestSoFar: Float = Float.infinity
for hitable in hitables {
if let intersection = hitable.hit(ray: ray, distMin: 0.001, distMax: closestSoFar) {
if intersection.distance < closestSoFar {
closestSoFar = intersection.distance
closerIntersection = intersection
}
}
}
return closerIntersection
}
/*func closestHit(ray: Ray, hitables: [Hitable]) -> HitIntersection? {
for hitable in hitables { // There is only one
return hitable.hit(ray: ray, distMin: 0.001, distMax: Float.infinity)
}
return nil
}*/
| mit | df7796f5090971f038a21b15024d9136 | 27.761905 | 92 | 0.654801 | 3.909385 | false | false | false | false |
haranicle/RealmSample | RealmSample/Task.swift | 1 | 1226 | //
// Task.swift
// RealmSample
//
// Copyright (c) 2015年 haranicle. All rights reserved.
//
import UIKit
import Realm
/**
タスクを表すクラス。
*/
class Task: RLMObject {
/// UUID
dynamic var uuid = NSUUID().UUIDString
/// タイトル
dynamic var title = ""
/// 完了しているか
dynamic var isDone = false
/// 保存したDate
dynamic var savedDate = NSDate()
override class func primaryKey() -> String {
return "uuid"
}
/// isDoneを文字列で表現する
func isDoneAsString() -> String {
if isDone {
return "Done🍣"
}
return "Doing🚀"
}
// MARK: - DB関連
/**
タスクをDBに記録する。
*/
func save() {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.addObject(self)
realm.commitWriteTransaction()
}
/**
isDoneを変更してDBを更新する。
*/
func updateIsDone(isDone:Bool) {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
self.isDone = isDone
realm.commitWriteTransaction()
}
} | mit | a45faba3df88bd950a3d0462415c40f4 | 16.539683 | 55 | 0.54529 | 4.119403 | false | false | false | false |
drewag/Swiftlier | Sources/Swiftlier/Model/Observable/ObservableReference.swift | 1 | 5655 | //
// ObservableReference.swift
// Swiftlier
//
// Created by Andrew J Wagner on 1/29/17.
// Copyright © 2017 Drewag. All rights reserved.
// Copyright (c) 2014 Drewag LLC. 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.
/**
Store a value that can be observed by external objects
*/
public protocol Referenceable: class {}
public final class ObservableReference<T: Referenceable> {
public typealias Handler = () -> ()
typealias HandlerSpec = (options: ObservationOptions, handler: Handler)
// MARK: Properties
/**
The current value
*/
public let value : T
public func signalChanged() {
var handlersToCall: [Handler] = []
for observerIndex in Array((0..<self.observers.count).reversed()) {
let observer = self.observers[observerIndex].observer
var handlers = self.observers[observerIndex].handlers
if observer.value != nil {
for handlerIndex in Array((0..<handlers.count).reversed()) {
let handlerSpec = handlers[handlerIndex]
handlersToCall.append(handlerSpec.handler)
if handlerSpec.options.contains(.onlyOnce) {
handlers.remove(at: handlerIndex)
}
}
if handlers.count == 0 {
self.observers.remove(at: observerIndex)
}
else {
self.observers[observerIndex] = (observer: observer, handlers: handlers)
}
}
else {
if let index = self.indexOfObserver(observer) {
self.observers.remove(at: index)
}
}
}
for handler in handlersToCall {
handler()
}
}
/**
Whether there is at least 1 current observer
*/
public var hasObserver: Bool {
return observers.count > 0
}
// MARK: Initializers
public init(_ value: T, onHasObserversChanged: ((Bool) -> ())? = nil) {
self.value = value
self.onHasObserverChanged = onHasObserversChanged
}
// MARK: Methods
/**
Add handler for when the value has changed
- parameter observer: observing object to be referenced later to remove the hundler
- parameter handler: callback to be called when value is changed
*/
public func addObserver(_ observer: AnyObject, handler: @escaping Handler) {
self.addObserver(observer, options: [], handler: handler)
}
/**
Add handler for when the value has changed
- parameter observer: observing object to be referenced later to remove the hundler
- parameter options: observation options
- parameter handler: callback to be called when value is changed
*/
public func addObserver(_ observer: AnyObject, options: ObservationOptions, handler: @escaping Handler) {
if let index = self.indexOfObserver(observer) {
// since the observer exists, add the handler to the existing array
self.observers[index].handlers.append((options: options, handler: handler))
}
else {
// since the observer does not already exist, add a new tuple with the
// observer and an array with the handler
let oldCount = self.observers.count
self.observers.append((observer: WeakWrapper(observer), handlers: [(options: options, handler: handler)]))
if oldCount == 0 {
self.onHasObserverChanged?(true)
}
}
if options.contains(.initial) {
handler()
}
}
/**
Remove all handlers for the given observer
- parameter observer: the observer to remove handlers from
*/
public func removeObserver(_ observer: AnyObject) {
if let index = self.indexOfObserver(observer) {
self.observers.remove(at: index)
if self.observers.count == 0 {
self.onHasObserverChanged?(false)
}
}
}
// MARK: Private Properties
fileprivate var observers: [(observer: WeakWrapper<AnyObject>, handlers: [HandlerSpec])] = []
fileprivate var onHasObserverChanged: ((Bool) -> ())?
}
private extension ObservableReference {
func indexOfObserver(_ observer: AnyObject) -> Int? {
var index: Int = 0
for (possibleObserver, _) in self.observers {
if possibleObserver.value === observer {
return index
}
index += 1
}
return nil
}
}
| mit | 65ef5d1fb45d219201f1c31b76ad8236 | 34.118012 | 118 | 0.623276 | 4.903729 | false | false | false | false |
codePrincess/playgrounds | PlayWithYourSmile.playground/Sources/Ext.swift | 2 | 1294 | import Foundation
import UIKit
public extension Array {
func randomElement() -> Element {
let index = Int(arc4random_uniform(UInt32(self.count)))
return self[index]
}
}
extension UIColor {
convenience init(hexString:String) {
let hexString = hexString.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color:UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:1)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return NSString(format:"#%06x", rgb) as String
}
}
| mit | a769868934bb82f255a6f5522920fd61 | 25.958333 | 95 | 0.530912 | 3.957187 | false | false | false | false |
xilosada/BitcoinFinder | BitcoinFinder/CoreDataStackManager.swift | 1 | 5917 | //
// Copyright 2015 X.I. Losada.
//
// 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 CoreData
private let SQLITE_FILE_NAME = "BitcoinFinder.sqlite"
class CoreDataStackManager {
// MARK: - Shared Instance
/**
* This class variable provides an easy way to get access
*/
static let sharedInstance = CoreDataStackManager()
private init(){}
// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory: NSURL = {
print("Instantiating the applicationDocumentsDirectory property")
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
// MARK: The app contains a correctly configured managed object context backed by a local SQLite store
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
print("Instantiating the managedObjectModel property")
// MARK: The app uses a managed object model created in the Xcode Model Editor. A .xcdatamodeld model file is present.
let modelURL = NSBundle.mainBundle().URLForResource("VirtualTourist", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
/**
* The Persistent Store Coordinator is an object that the Context uses to interact with the underlying file system. Usually
* the persistent store coordinator object uses an SQLite database file to save the managed objects. But it is possible to
* configure it to use XML or other formats.
*
* Typically you will construct your persistent store manager exactly like this. It needs two pieces of information in order
* to be set up:
*
* - The path to the sqlite file that will be used. Usually in the documents directory
* - A configured Managed Object Model. See the next property for details.
*/
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
print("Instantiating the persistentStoreCoordinator property")
let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME)
print("sqlite path: \(url.path!)")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
} | apache-2.0 | 482626a3a6aca00ac3e0c59f7f065012 | 44.875969 | 290 | 0.684806 | 5.689423 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.