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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tofergregg/IBM-Wheelwriter-Hack | software/IBM Wheelwriter Word Processor/IBM Wheelwriter Word Processor/ViewController.swift | 1 | 17887 | //
// ViewController.swift
// IBM Wheelwriter Word Processor
//
// Created by Chris Gregg on 2/2/17.
// Copyright © 2017 Chris Gregg. All rights reserved.
//
import Cocoa
import ORSSerial
// implement resize function
// source (slightly modified): http://stackoverflow.com/a/30422317/561677
extension NSImage {
func resizeImage(width: CGFloat, _ height: CGFloat) -> NSImage {
let img = NSImage(size: CGSize(width:width, height:height))
img.lockFocus()
let ctx = NSGraphicsContext.current()
ctx?.imageInterpolation = .high
self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: .copy, fraction: 1)
img.unlockFocus()
return img
}
}
struct ImageAndPosition {
var location : Int;
var data : Data
init(location: Int, data: Data) {
self.location = location
self.data = data
}
}
enum TypeOfPrintData {
case text
case image
}
struct DataToPrint {
var typeOfData : TypeOfPrintData
var data : Data
}
class ViewController: NSViewController, ORSSerialPortDelegate {
// class variables for sending data
var printData : Data!
var header : Data!
var runData : [[UInt8]]!
var allPrintData : [DataToPrint]!
var serialPort: ORSSerialPort?
var sendingText = false
var sendingImage = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@IBOutlet var fullTextView: NSTextView!
@IBAction func bold(sender : Any) {
print("User pressed bold");
let fm = NSFontManager.shared()
let fakeBoldButton = NSButton()
fakeBoldButton.tag = 2 // tag of 2 tells the fontmanager we want to change bold
let fontName = fm.selectedFont?.fontName ?? "None"
print(fontName)
if (fontName.contains("Bold")) {
fm.removeFontTrait(fakeBoldButton)
} else {
fm.addFontTrait(fakeBoldButton)
}
}
@IBAction func printDoc(sender: Any) {
// handle embedded images
let attribText = fullTextView.attributedString()
print("attribs:")
print(attribText)
print("about to print attribs")
var lastAttribWasAttachment = false;
var currentString = ""
attribText.enumerateAttributes(in: NSMakeRange(0,attribText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0), using: {(value, range, stop) in
// options:
if let attachment = value["NSAttachment"] as? NSTextAttachment,
let fileWrapper = attachment.fileWrapper,
let data = fileWrapper.regularFileContents {
// 1. It is an attachment (image)
if (currentString != "") {
print("current string:'\(currentString)'")
}
print("attachment")
lastAttribWasAttachment = true;
} else if let bold = value["NSFont"] as? NSFont {
var partialString = ""
if (bold.fontName.contains("Bold")) {
// 2. It is bold
if value["NSUnderline"] != nil {
// 2a. It is also underlined
partialString = "BU"+attribText.attributedSubstring(from: range).string+"UB"
//print("bold and underlined:'\(text)'")
} else {
// 2b. It is bold but not underlined
partialString = "B"+attribText.attributedSubstring(from: range).string+"B"
//print("bold:'\(text)'")
}
} else {
if value["NSUnderline"] != nil {
// 3. It is underlined but not bold
partialString = "U"+attribText.attributedSubstring(from: range).string+"U"
//print("underlined:'\(text)'")
} else {
// 4. It is neither bold nor underlined
partialString = attribText.attributedSubstring(from: range).string
//print("regular:'\(text)'")
}
}
if lastAttribWasAttachment {
currentString = partialString
} else {
currentString += partialString
}
lastAttribWasAttachment = false;
}
//print("value:\(value), range:\(range.location), length:\(range.length)")
})
if !lastAttribWasAttachment {
print("current string:'\(currentString)'")
}
//print(attribText)
var imageArray : [ImageAndPosition] = []
if (attribText.containsAttachments) {
// keep track of all the attachments as data for later printing
attribText.enumerateAttribute(NSAttachmentAttributeName, in: NSMakeRange(0,attribText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0), using: {(value, range, stop) in
if let attachment: Any = value {
if let attachment = attachment as? NSTextAttachment,
let fileWrapper = attachment.fileWrapper,
let data = fileWrapper.regularFileContents {
print("\(range.location),\(range.length)")
imageArray.append(ImageAndPosition(location: range.location, data: data))
sendingImage = true
sendingText = false
printImageToTypewriter(data: data)
}
}
})
}
/*let typewriterString = parseTextFromView()
print(typewriterString)
do {
try sendTextToIBM(typewriterText: typewriterString)
}
catch {
print("Too much data (limit: 64KB)")
}*/
}
func sendNextPartToTypewriter() {
//
}
func printImageToTypewriter(data: Data) {
let maxDimension : CGFloat = 50
let img = NSImage(data:data)?.resizeImage(width: maxDimension, maxDimension)
print (img ?? "<no image>")
let raw_img : NSBitmapImageRep! = NSBitmapImageRep(data: (img?.tiffRepresentation)!)
let height = raw_img.pixelsHigh
let width = raw_img.pixelsWide
// the following was borrowed from: https://gist.github.com/bpercevic/b5b193c3379b3f048210
var bitmapData: UnsafeMutablePointer<UInt8> = raw_img.bitmapData!
var r, g, b: UInt8
// convert all pixels to black & white
var bw_pixels : [UInt8] = []
for _ in 0 ..< height { // rows
for _ in 0 ..< width { // cols
r = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
g = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 1)
b = bitmapData.pointee
bitmapData = bitmapData.advanced(by: 2) // ignore alpha
// a = bitmapData.pointee
//bitmapData = bitmapData.advanced(by: 1)
// from here: http://stackoverflow.com/a/14331/561677
let grayscalePixel = (0.2125 * Double(r)) + (0.7154 * Double(g)) + (0.0721 * Double(b))
// convert to b&w:
// from here: http://stackoverflow.com/a/18778280/561677
let finalPixel : UInt8
if (grayscalePixel < 128) {
finalPixel = 0
} else {
finalPixel = 255
}
bw_pixels.append(finalPixel)
//print("\(grayscalePixel),\(finalPixel)")
}
}
// determine runs for printing
var runs : [[UInt8]] = [[1]] // initial command to print an image is 1
for row in 0 ..< height { // rows
var prevBit = bw_pixels[row * width] // start at the first bit on the row
var bitCount = 0
var lineBits = 0
for col in 0 ..< width { // cols
let currentBit = bw_pixels[row * width + col]
if currentBit != prevBit {
if prevBit == 0 {
runs.append([UInt8(bitCount & 0xff), UInt8(bitCount >> 8), 46])
} else {
runs.append([UInt8(bitCount & 0xff), UInt8(bitCount >> 8), 32])
}
lineBits += bitCount
bitCount = 0
prevBit = currentBit
}
bitCount += 1
}
if prevBit == 0 { // 0 is black
// don't bother printing a string of spaces at the end, just dots
runs.append([UInt8(bitCount & 0xff), UInt8(bitCount >> 8), 46])
lineBits += bitCount
}
runs.append([UInt8(lineBits & 0xff), UInt8(lineBits >> 8), 10])
}
runs.append([0, 0, 0]) // end of image
runData = runs
print(runData)
sendImageToIBM(runs: runs)
}
func processImage(runs : [[UInt8]]) {
for run in runs {
if run == [1,0,0] || run == [0, 0, 0] {
continue; // skip first and last
}
let runLength = Int(run[0]) + (Int(run[1]) << 8)
if (run[2] == 10) {
// just print a newline
print()
} else {
for _ in 0..<runLength {
print(Character(UnicodeScalar(run[2])), terminator:"")
}
}
}
}
func parseTextFromView() -> String {
let attribText = fullTextView.attributedString()
let plainText = fullTextView.string ?? ""
// find underlined and bolded text
var charCount = 0
var printable = CharacterSet.letters
printable.formUnion(CharacterSet.decimalDigits)
printable.formUnion(CharacterSet.whitespacesAndNewlines)
printable.formUnion(CharacterSet.punctuationCharacters)
var bolded_attr : Bool
var underlined_attr : Bool
// current state
var bolded = false;
var underlined = false;
// typewriter_string
var typewriterString = ""
for char in plainText.characters {
if (!printable.contains(UnicodeScalar("\(char)")!)) {
continue // skip non-printable characters
}
var rng = NSRange()
let fontAttribName : NSFont? = attribText.attribute(NSFontAttributeName, at: charCount, effectiveRange: &rng) as! NSFont?
if (fontAttribName != nil) {
bolded_attr = (fontAttribName?.fontName.contains("Bold"))!
} else {
bolded_attr = false
}
underlined_attr = !(attribText.attribute(NSUnderlineStyleAttributeName, at: charCount, effectiveRange: &rng) == nil)
print(char, terminator: ", underlined: ")
print(underlined_attr, terminator: ", bold: ")
print(bolded_attr)
if (bolded_attr) {
if (!bolded) {
bolded = true
typewriterString += "\(Character(UnicodeScalar(2)))" // bold control character for typewriter
}
} else {
if (bolded) {
bolded = false;
typewriterString += "\(Character(UnicodeScalar(2)))"
}
}
if (underlined_attr) {
if (!underlined) {
underlined = true
typewriterString += "\(Character(UnicodeScalar(3)))" // underline control character
}
} else {
if (underlined) {
underlined = false;
typewriterString += "\(Character(UnicodeScalar(3)))"
}
}
typewriterString += "\(char)"
charCount+=1
}
typewriterString += "\n" // just to be sure we end with a newline
return typewriterString
}
func sendTextToIBM(typewriterText : String) throws {
// max size, 64KB
if (typewriterText.characters.count > (1 << 16)) {
throw NSError(domain: "Cannot send more than 64KB to device.", code: -1, userInfo: nil)
}
// convert string to data
printData = typewriterText.data(using: .utf8)! as Data
// set up header to tell typewriter we are printing a bunch of text
// first, convert the size of the text into two bytes
// as binary: 0000 0001 1010 0101 (421)
let textLength = typewriterText.characters.count
let lowByte = UInt8(textLength & 0xff)
let highByte = UInt8(textLength >> 8)
header = Data(bytes: [0x0, lowByte, highByte])
self.serialPort = ORSSerialPort(path: "/dev/tty.wchusbserial1410")
serialPort?.baudRate = 115200
self.serialPort?.delegate = self
sendingText = true
serialPort?.open()
}
func sendImageToIBM(runs : [[UInt8]]) {
self.serialPort = ORSSerialPort(path: "/dev/tty.wchusbserial1420")
serialPort?.baudRate = 115200
self.serialPort?.delegate = self
sendingImage = true
serialPort?.open()
}
func sendTextToArduino() {
let MAX_DATA = 40 // only 40 characters at once so the arudino buffer doesn't overflow
if (printData.count > 0) {
let endIndex = min(MAX_DATA,printData.endIndex)
let textToSend = printData.subdata(in: 0..<endIndex)
printData = printData.subdata(in: endIndex..<printData.endIndex)
serialPort?.send(textToSend)
} else {
serialPort?.close()
sendingText = false
sendNextPartToTypewriter()
}
}
func sendImageToArduino() {
let MAX_DATA = 20 // 3 * 3 bytes = 60 at a time
if (runData.count > 0) {
let endIndex = min(MAX_DATA, runData.endIndex)
let runDataToSend = runData[0..<endIndex]
let newRunData = runData[endIndex..<runData.endIndex]
// manually copy newRunData into runData, because it is just an ArraySlice now
runData = []
for d in newRunData {
runData.append(d)
}
// create an actual data to send
var dataToSend : Data = Data()
for d in runDataToSend {
dataToSend.append(d[0])
if (d.count > 1) { // the first element is a single value
dataToSend.append(d[1])
dataToSend.append(d[2])
}
}
//for d in dataToSend {
// print (d)
//}
serialPort?.send(dataToSend)
} else {
serialPort?.close()
sendingImage = false
sendNextPartToTypewriter()
}
}
@IBAction func setupMargins(sender: NSButton) {
print("setting up...")
}
// ORSSerialDelegate methods
func serialPort(_ serialPort: ORSSerialPort, didReceive data: Data) {
if let string = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) {
print("\(string)")
if (string.contains("\n")) {
if sendingText {
sendTextToArduino()
} else if sendingImage {
sendImageToArduino()
}
}
}
}
func serialPort(_ serialPort: ORSSerialPort, didEncounterError error: Error) {
print("Serial port (\(serialPort)) encountered error: \(error)")
}
func serialPortWasOpened(_ serialPort: ORSSerialPort) {
print("Serial port \(serialPort) was opened")
// delay a bit more before sending data, so that the
// Arduino can start the sketch (it gets reset every time
// the serial port is opened...)
let delayInSeconds = 1.5
//sendingText = false // remove later
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {
//serialPort.send(Data(bytes: [0x04])) // reset typewriter
if self.sendingText {
serialPort.send(self.header)
self.sendTextToArduino()
} else if (self.sendingImage) {
self.sendImageToArduino()
}
}
}
/**
* Called when a serial port is removed from the system, e.g. the user unplugs
* the USB to serial adapter for the port.
*
* In this method, you should discard any strong references you have maintained for the
* passed in `serialPort` object. The behavior of `ORSSerialPort` instances whose underlying
* serial port has been removed from the system is undefined.
*
* @param serialPort The `ORSSerialPort` instance representing the port that was removed.
*/
public func serialPortWasRemoved(fromSystem serialPort: ORSSerialPort) {
self.serialPort = nil
}
}
| mit | 2183ae2c03a9cf2683ec75f3d3f883bb | 35.576687 | 199 | 0.525774 | 4.89625 | false | false | false | false |
SwiftOnEdge/Edge | Sources/HTTP/Routing/ErrorEndpoint.swift | 1 | 3292 | //
// ErrorEndpoint.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 12/18/17.
//
import Foundation
import StreamKit
import Regex
import PathToRegex
struct ErrorEndpoint: HandlerNode {
let handler: ErrorHandler
weak var parent: Router?
let method: Method?
func setParameters(on request: Request, match: Match) {
request.parameters = [:]
}
func shouldHandleAndAddParams(request: Request, error: Error) -> Bool {
if let method = method, request.method != method {
return false
}
return true
}
func handle(
requests: Signal<Request>,
errors: Signal<(Request, Error)>,
responses: Signal<Response>
) -> (
handled: Signal<Response>,
errored: Signal<(Request, Error)>,
unhandled: Signal<Request>
) {
let (shouldHandle, unhandled) = errors.partition(self.shouldHandleAndAddParams)
let (handled, errored) = handle(errors: shouldHandle)
let (mergedResponses, responsesInput) = Signal<Response>.pipe()
responses.add(observer: responsesInput)
handled.add(observer: responsesInput)
let (mergedErrored, erroredInput) = Signal<(Request, Error)>.pipe()
unhandled.add(observer: erroredInput)
errored.add(observer: erroredInput)
return (mergedResponses, mergedErrored, requests)
}
init(parent: Router? = nil, method: Method? = nil, _ handler: ErrorHandler) {
self.handler = handler
self.method = method
self.parent = parent
}
}
extension ErrorEndpoint {
func handle(errors: Signal<(Request, Error)>) -> (Signal<Response>, Signal<(Request, Error)>) {
let responses: Signal<Response>
let (newErrors, newErrorsInput) = Signal<(Request, Error)>.pipe()
switch handler {
case .sync(let syncTransform):
responses = errors.flatMap { (request, error) -> Response? in
do {
let response = try syncTransform(request, error)
response.request = request
return response
} catch {
newErrorsInput.sendNext((request, error))
return nil
}
}
case .async(let asyncTransform):
responses = errors.flatMap { (request, error) -> Signal<Response?> in
return Signal { observer in
asyncTransform(request, error).then {
$0.request = request
observer.sendNext($0)
observer.sendCompleted()
}.catch { error in
newErrorsInput.sendNext((request, error))
observer.sendNext(nil)
observer.sendCompleted()
}
return nil
}
}.flatMap { (response: Response?) in response }
}
return (responses, newErrors)
}
}
extension ErrorEndpoint: CustomStringConvertible {
var description: String {
if let method = method {
return "\(method) '\(routePath)'"
}
return "ERROR '\(routePath)'"
}
}
| mit | e8cabee32eaf59ae4e501c5b128ed483 | 29.766355 | 99 | 0.555286 | 4.935532 | false | false | false | false |
wj2061/ios7ptl-swift3.0 | ch21-Text/SimpleLayout/SimpleLayout/ViewController.swift | 1 | 2278 | //
// ViewController.swift
// SimpleLayout
//
// Created by wj on 15/11/28.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let string = "Here is some simple text that includes bold and italics.\n \n We can even include some color."
let attrString = CFAttributedStringCreateMutable(nil, 0)
CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), string as CFString)
let baseFont = CTFontCreateUIFontForLanguage(.system, 16, nil)
let length = CFStringGetLength(string as CFString)
CFAttributedStringSetAttribute(attrString, CFRangeMake(0, length), kCTFontAttributeName, baseFont)
let boldFont = CTFontCreateCopyWithSymbolicTraits(baseFont!, 0, nil, .boldTrait, .boldTrait)
CFAttributedStringSetAttribute(attrString, CFStringFind(string as CFString, "bold" as CFString, []), kCTFontAttributeName, boldFont)
let italicFont = CTFontCreateCopyWithSymbolicTraits(baseFont!, 0, nil, .italicTrait, .italicTrait)
CFAttributedStringSetAttribute(attrString, CFStringFind(string as CFString, "italics" as CFString, []), kCTFontAttributeName, italicFont)
let color = UIColor.red.cgColor
CFAttributedStringSetAttribute(attrString, CFStringFind(string as CFString, "color" as CFString, []), kCTForegroundColorAttributeName, color)
var alignment = CTTextAlignment.justified
var setting = CTParagraphStyleSetting(spec: .alignment, valueSize: MemoryLayout<CTTextAlignment>.size, value: &alignment)
let style = CTParagraphStyleCreate(&setting, 1)
var lastLineRange = CFStringFind(string as CFString, "\n" as CFString, .compareBackwards)
lastLineRange.location += 1
lastLineRange.length = CFStringGetLength(string as CFString) - lastLineRange.location
CFAttributedStringSetAttribute(attrString, lastLineRange, kCTParagraphStyleAttributeName, style)
let label = CoreTextLabel(frame: self.view.bounds.insetBy(dx: 10, dy: 10))
label.attributedString = attrString!
view.addSubview(label)
}
}
| mit | 9bfb8b9bd30bc1b229e33880069a51bb | 45.428571 | 149 | 0.705495 | 5.194064 | false | false | false | false |
Mars182838/WJCycleScrollView | WJCycleScrollView/Extentions/NSAttributedStringExtensions.swift | 1 | 2291 | //
// NSAttributedStringExtensions.swift
// EZSwiftExtensions
//
// Created by Lucas Farah on 18/02/16.
// Copyright (c) 2016 Lucas Farah. All rights reserved.
//
import UIKit
extension NSAttributedString {
/// EZSE: Adds bold attribute to NSAttributedString and returns it
#if os(iOS)
public func bold() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(UIFont.systemFontSize())], range: range)
return copy
}
#endif
/// EZSE: Adds underline attribute to NSAttributedString and returns it
public func underline() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue], range: range)
return copy
}
#if os(iOS)
/// EZSE: Adds italic attribute to NSAttributedString and returns it
public func italic() -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSFontAttributeName: UIFont.italicSystemFontOfSize(UIFont.systemFontSize())], range: range)
return copy
}
#endif
/// EZSE: Adds color attribute to NSAttributedString and returns it
public func color(color: UIColor) -> NSAttributedString {
guard let copy = self.mutableCopy() as? NSMutableAttributedString else { return self }
let range = (self.string as NSString).rangeOfString(self.string)
copy.addAttributes([NSForegroundColorAttributeName: color], range: range)
return copy
}
}
/// EZSE: Appends one NSAttributedString to another NSAttributedString and returns it
public func += (inout left: NSAttributedString, right: NSAttributedString) {
let ns = NSMutableAttributedString(attributedString: left)
ns.appendAttributedString(right)
left = ns
}
| mit | 38d118b2a40feb88704f54815d669882 | 35.951613 | 119 | 0.706678 | 5.206818 | false | false | false | false |
ben-ng/swift | stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift | 1 | 4084 | //===--- SwiftPrivateLibcExtras.swift -------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
#if !os(Windows) || CYGWIN
public func _stdlib_mkstemps(_ template: inout String, _ suffixlen: CInt) -> CInt {
#if os(Android)
preconditionFailure("mkstemps doesn't work on Android")
#else
var utf8CStr = template.utf8CString
let (fd, fileName) = utf8CStr.withUnsafeMutableBufferPointer {
(utf8CStr) -> (CInt, String) in
let fd = mkstemps(utf8CStr.baseAddress!, suffixlen)
let fileName = String(cString: utf8CStr.baseAddress!)
return (fd, fileName)
}
template = fileName
return fd
#endif
}
#endif
public var _stdlib_FD_SETSIZE: CInt {
return 1024
}
public struct _stdlib_fd_set {
var _data: [UInt]
static var _wordBits: Int {
return MemoryLayout<UInt>.size * 8
}
public init() {
_data = [UInt](
repeating: 0,
count: Int(_stdlib_FD_SETSIZE) / _stdlib_fd_set._wordBits)
}
public func isset(_ fd: CInt) -> Bool {
let fdInt = Int(fd)
return (
_data[fdInt / _stdlib_fd_set._wordBits] &
UInt(1 << (fdInt % _stdlib_fd_set._wordBits))
) != 0
}
public mutating func set(_ fd: CInt) {
let fdInt = Int(fd)
_data[fdInt / _stdlib_fd_set._wordBits] |=
UInt(1 << (fdInt % _stdlib_fd_set._wordBits))
}
public mutating func clear(_ fd: CInt) {
let fdInt = Int(fd)
_data[fdInt / _stdlib_fd_set._wordBits] &=
~UInt(1 << (fdInt % _stdlib_fd_set._wordBits))
}
public mutating func zero() {
let count = _data.count
return _data.withUnsafeMutableBufferPointer {
(_data) in
for i in 0..<count {
_data[i] = 0
}
return
}
}
}
#if !os(Windows) || CYGWIN
public func _stdlib_select(
_ readfds: inout _stdlib_fd_set, _ writefds: inout _stdlib_fd_set,
_ errorfds: inout _stdlib_fd_set, _ timeout: UnsafeMutablePointer<timeval>?
) -> CInt {
return readfds._data.withUnsafeMutableBufferPointer {
(readfds) in
writefds._data.withUnsafeMutableBufferPointer {
(writefds) in
errorfds._data.withUnsafeMutableBufferPointer {
(errorfds) in
let readAddr = readfds.baseAddress
let writeAddr = writefds.baseAddress
let errorAddr = errorfds.baseAddress
func asFdSetPtr(
_ p: UnsafeMutablePointer<UInt>?
) -> UnsafeMutablePointer<fd_set>? {
return UnsafeMutableRawPointer(p)?
.assumingMemoryBound(to: fd_set.self)
}
return select(
_stdlib_FD_SETSIZE,
asFdSetPtr(readAddr),
asFdSetPtr(writeAddr),
asFdSetPtr(errorAddr),
timeout)
}
}
}
}
#endif
/// Swift-y wrapper around pipe(2)
public func _stdlib_pipe() -> (readEnd: CInt, writeEnd: CInt, error: CInt) {
var fds: [CInt] = [0, 0]
let ret = fds.withUnsafeMutableBufferPointer { unsafeFds -> CInt in
pipe(unsafeFds.baseAddress)
}
return (readEnd: fds[0], writeEnd: fds[1], error: ret)
}
//
// Functions missing in `Darwin` module.
//
public func _WSTATUS(_ status: CInt) -> CInt {
return status & 0x7f
}
public var _WSTOPPED: CInt {
return 0x7f
}
public func WIFEXITED(_ status: CInt) -> Bool {
return _WSTATUS(status) == 0
}
public func WIFSIGNALED(_ status: CInt) -> Bool {
return _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0
}
public func WEXITSTATUS(_ status: CInt) -> CInt {
return (status >> 8) & 0xff
}
public func WTERMSIG(_ status: CInt) -> CInt {
return _WSTATUS(status)
}
| apache-2.0 | cb9866032e3277c773051c9c30cc616a | 25.519481 | 83 | 0.61998 | 3.557491 | false | false | false | false |
ayushgoel/SAHistoryNavigationViewController | SAHistoryNavigationViewController/SAHistoryViewAnimatedTransitioning.swift | 1 | 4120 | //
// SAHistoryViewAnimatedTransitioning.swift
// SAHistoryNavigationViewController
//
// Created by 鈴木大貴 on 2015/10/26.
// Copyright (c) 2015年 鈴木大貴. All rights reserved.
//
import UIKit
class SAHistoryViewAnimatedTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
//MARK: - Static Constants
static private let Duration: NSTimeInterval = 0.25
static private let Scale: CGFloat = 0.7
//MARK: - Properties
private var isPresenting = true
//MARK: - Initializers
init(isPresenting: Bool) {
super.init()
self.isPresenting = isPresenting
}
//MARK - Life cycle
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return SAHistoryViewAnimatedTransitioning.Duration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
guard let containerView = transitionContext.containerView() else {
return
}
guard let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) else {
return
}
guard let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) else {
return
}
if isPresenting {
pushAniamtion(transitionContext, containerView: containerView, toVC: toVC, fromVC: fromVC)
} else {
popAniamtion(transitionContext, containerView: containerView, toVC: toVC, fromVC: fromVC)
}
}
}
//MARK: - Animations
extension SAHistoryViewAnimatedTransitioning {
private func pushAniamtion(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, toVC: UIViewController, fromVC: UIViewController) {
guard let hvc = toVC as? SAHistoryViewController else {
return
}
containerView.addSubview(toVC.view)
fromVC.view.hidden = true
hvc.view.frame = containerView.bounds
hvc.collectionView.transform = CGAffineTransformIdentity
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: .CurveEaseOut, animations: {
hvc.collectionView.transform = CGAffineTransformMakeScale(SAHistoryViewAnimatedTransitioning.Scale, SAHistoryViewAnimatedTransitioning.Scale)
}) { finished in
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
fromVC.view.hidden = false
hvc.collectionView.transform = CGAffineTransformIdentity
hvc.view.removeFromSuperview()
} else {
hvc.view.hidden = false
fromVC.view.removeFromSuperview()
}
transitionContext.completeTransition(!cancelled)
}
}
private func popAniamtion(transitionContext: UIViewControllerContextTransitioning, containerView: UIView, toVC: UIViewController, fromVC: UIViewController) {
guard let hvc = fromVC as? SAHistoryViewController else {
return
}
containerView.addSubview(toVC.view)
toVC.view.hidden = true
hvc.view.frame = containerView.bounds
hvc.collectionView.transform = CGAffineTransformMakeScale(SAHistoryViewAnimatedTransitioning.Scale, SAHistoryViewAnimatedTransitioning.Scale)
UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, options: .CurveEaseOut, animations: {
hvc.collectionView.transform = CGAffineTransformIdentity
hvc.scrollToSelectedIndex(false)
}) { finished in
let cancelled = transitionContext.transitionWasCancelled()
if cancelled {
hvc.collectionView.transform = CGAffineTransformIdentity
toVC.view.removeFromSuperview()
} else {
toVC.view.hidden = false
hvc.view.removeFromSuperview()
}
transitionContext.completeTransition(!cancelled)
}
}
}
| mit | 1e72c53a3b4521bd6865ae7b20747a04 | 38.442308 | 162 | 0.674305 | 6.177711 | false | false | false | false |
mapsme/omim | iphone/Maps/UI/PlacePage/Components/PlacePageHeader/PlacePageHeaderPresenter.swift | 5 | 1382 | protocol PlacePageHeaderPresenterProtocol: class {
func configure()
func onClosePress()
func onExpandPress()
}
protocol PlacePageHeaderViewControllerDelegate: AnyObject {
func previewDidPressClose()
func previewDidPressExpand()
}
class PlacePageHeaderPresenter {
enum HeaderType {
case flexible
case fixed
}
private weak var view: PlacePageHeaderViewProtocol?
private let placePagePreviewData: PlacePagePreviewData
private weak var delegate: PlacePageHeaderViewControllerDelegate?
private let headerType: HeaderType
init(view: PlacePageHeaderViewProtocol,
placePagePreviewData: PlacePagePreviewData,
delegate: PlacePageHeaderViewControllerDelegate?,
headerType: HeaderType) {
self.view = view
self.delegate = delegate
self.placePagePreviewData = placePagePreviewData
self.headerType = headerType
}
}
extension PlacePageHeaderPresenter: PlacePageHeaderPresenterProtocol {
func configure() {
view?.setTitle(placePagePreviewData.title ?? "")
switch headerType {
case .flexible:
view?.isExpandViewHidden = false
view?.isShadowViewHidden = true
case .fixed:
view?.isExpandViewHidden = true
view?.isShadowViewHidden = false
}
}
func onClosePress() {
delegate?.previewDidPressClose()
}
func onExpandPress() {
delegate?.previewDidPressExpand()
}
}
| apache-2.0 | cc5d0ade7c381dbb8b5fb107ad3431b4 | 24.592593 | 70 | 0.745297 | 4.866197 | false | false | false | false |
DanijelHuis/HDAugmentedReality | HDAugmentedReality/Classes/Main/Presenter/ARPresenter.swift | 1 | 18953 | //
// ARPresenter.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 16/12/2016.
// Copyright © 2016 Danijel Huis. All rights reserved.
//
import UIKit
import CoreLocation
/**
Handles visual presentation of annotations.
Adds ARAnnotationViews on the screen and calculates its screen positions. Before anything
is done, it first filters annotations by distance and count for improved performance. This
class is also responsible for vertical stacking of the annotation views.
It can be subclassed if custom positioning is needed, e.g. if you wan't to position
annotations relative to its altitudes you would subclass ARPresenter and override
xPositionForAnnotationView and yPositionForAnnotationView.
*/
open class ARPresenter: UIView
{
/**
How much to vertically offset annotations by distance, in pixels per meter. Use it if distanceOffsetMode is manual or automaticOffsetMinDistance.
Also look at distanceOffsetMinThreshold and distanceOffsetMode.
*/
open var distanceOffsetMultiplier: Double?
/**
All annotations farther(from user) than this value will be offset using distanceOffsetMultiplier. Use it if distanceOffsetMode is manual.
Also look at distanceOffsetMultiplier and distanceOffsetMode.
*/
open var distanceOffsetMinThreshold: Double = 0
/**
Distance offset mode, it affects vertical offset of annotations by distance.
*/
open var distanceOffsetMode = DistanceOffsetMode.automatic
/**
If set, it will be used instead of distanceOffsetMultiplier and distanceOffsetMinThreshold if distanceOffsetMode != none
Use it to calculate vartical offset by given distance.
*/
open var distanceOffsetFunction: ((_ distance: Double) -> Double)?
/**
How low on the screen is nearest annotation. 0 = top, 1 = bottom.
*/
open var bottomBorder: Double = 0.55
/**
Distance offset mode, it affects vertical offset of annotations by distance.
*/
public enum DistanceOffsetMode
{
/// Annotations are not offset vertically with distance.
case none
/// Use distanceOffsetMultiplier and distanceOffsetMinThreshold to control offset.
case manual
/// distanceOffsetMinThreshold is set to closest annotation, distanceOffsetMultiplier must be set by user.
case automaticOffsetMinDistance
/**
distanceOffsetMinThreshold is set to closest annotation and distanceOffsetMultiplier
is set to fit all annotations on screen vertically(before stacking)
*/
case automatic
}
@IBOutlet open weak var arViewController: ARViewController!
/// All annotations
open var annotations: [ARAnnotation] = []
/// Annotations filtered by distance/maxVisibleAnnotations. Look at activeAnnotationsFromAnnotations.
open var activeAnnotations: [ARAnnotation] = []
/// AnnotionViews for all active annotations, this is set in createAnnotationViews.
open var annotationViews: [ARAnnotationView] = []
/// AnnotationViews that are on visible part of the screen or near its border.
open var visibleAnnotationViews: [ARAnnotationView] = []
/// Responsible for transform/layout of annotations after they have been layouted by ARPresenter. e.g. used for stacking.
open var presenterTransform: ARPresenterTransform?
{
didSet
{
self.presenterTransform?.arPresenter = self
}
}
public init(arViewController: ARViewController)
{
self.arViewController = arViewController
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
// When changing ARPresenter it might be usefull to let AnnotationViews deinit.
for annotation in self.annotations
{
annotation.annotationView = nil
}
}
open override func awakeFromNib()
{
super.awakeFromNib()
if self.arViewController == nil
{
fatalError("Set arViewController outlet from xib.")
}
}
/**
Total maximum number of visible annotation views. Default value is 100. Max value is 500.
This will affect performance, especially if stacking is involved.
*/
open var maxVisibleAnnotations = 100
{
didSet
{
if(maxVisibleAnnotations > MAX_VISIBLE_ANNOTATIONS)
{
maxVisibleAnnotations = MAX_VISIBLE_ANNOTATIONS
}
}
}
/**
Maximum distance(in meters) for annotation to be shown.
Default value is 0 meters, which means that distances of annotations don't affect their visiblity.
This can be used to increase performance.
*/
open var maxDistance: Double = 0
//==========================================================================================================================================================
// MARK: Reload - main logic
//==========================================================================================================================================================
/**
This is called from ARViewController, it handles main logic, what is called and when.
*/
open func reload(annotations: [ARAnnotation], reloadType: ARViewController.ReloadType)
{
guard self.arViewController.arStatus.ready else { return }
// Detecting some rare cases, e.g. if clear was called then we need to recreate everything.
let changeDetected = self.annotations.count != annotations.count
// needsRelayout indicates that position of user or positions of annotations have changed. e.g. user moved, annotations moved/changed.
// This means that positions of annotations on the screen must be recalculated.
let needsRelayout = reloadType == .annotationsChanged || reloadType == .reloadLocationChanged || reloadType == .userLocationChanged || changeDetected
// Doing heavier stuff here
if needsRelayout
{
self.annotations = annotations
// Filtering annotations and creating annotation views. Doing this only on big location changes, not on any user location change.
if reloadType != .userLocationChanged || changeDetected
{
self.activeAnnotations = self.activeAnnotationsFromAnnotations(annotations: annotations)
self.createAnnotationViews()
}
self.adjustDistanceOffsetParameters()
for annotationView in self.annotationViews
{
annotationView.bindUi()
}
// This must be done before layout
self.resetLayoutParameters()
}
self.addRemoveAnnotationViews(arStatus: self.arViewController.arStatus)
self.preLayout(arStatus: self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
self.layout(arStatus: self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
self.postLayout(arStatus:self.arViewController.arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
//==========================================================================================================================================================
// MARK: Filtering(Active annotations)
//==========================================================================================================================================================
/**
Gives opportunity to the presenter to filter annotations and reduce number of items it is working with.
Default implementation filters by maxVisibleAnnotations and maxDistance.
*/
open func activeAnnotationsFromAnnotations(annotations: [ARAnnotation]) -> [ARAnnotation]
{
var activeAnnotations: [ARAnnotation] = []
for annotation in annotations
{
// maxVisibleAnnotations filter
if activeAnnotations.count >= self.maxVisibleAnnotations
{
annotation.active = false
continue
}
// maxDistance filter
if self.maxDistance != 0 && annotation.distanceFromUser > self.maxDistance
{
annotation.active = false
continue
}
annotation.active = true
activeAnnotations.append(annotation)
}
return activeAnnotations
}
//==========================================================================================================================================================
// MARK: Creating annotation views
//==========================================================================================================================================================
/**
Creates views for active annotations and removes views from inactive annotations.
@IMPROVEMENT: Add reuse logic
*/
open func createAnnotationViews()
{
var annotationViews: [ARAnnotationView] = []
let activeAnnotations = self.activeAnnotations
// Removing existing annotation views and reseting some properties
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
// Destroy views for inactive anntotations
for annotation in self.annotations
{
if(!annotation.active)
{
annotation.annotationView = nil
}
}
// Create views for active annotations
for annotation in activeAnnotations
{
var annotationView: ARAnnotationView? = nil
if annotation.annotationView != nil
{
annotationView = annotation.annotationView
}
else
{
annotationView = self.arViewController.dataSource?.ar(self.arViewController, viewForAnnotation: annotation)
}
annotation.annotationView = annotationView
if let annotationView = annotationView
{
annotationView.annotation = annotation
annotationViews.append(annotationView)
}
}
self.annotationViews = annotationViews
}
/// Removes all annotation views from screen and resets annotations
open func clear()
{
for annotation in self.annotations
{
annotation.active = false
annotation.annotationView = nil
}
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
self.annotations = []
self.activeAnnotations = []
self.annotationViews = []
self.visibleAnnotationViews = []
}
//==========================================================================================================================================================
// MARK: Add/Remove
//==========================================================================================================================================================
/**
Adds/removes annotation views to/from superview depending if view is on visible part of the screen.
Also, if annotation view is on visible part, it is added to visibleAnnotationViews.
*/
open func addRemoveAnnotationViews(arStatus: ARStatus)
{
let degreesDeltaH = arStatus.hFov
let heading = arStatus.heading
self.visibleAnnotationViews.removeAll()
for annotation in self.activeAnnotations
{
guard let annotationView = annotation.annotationView else { continue }
// This is distance of center of annotation to the center of screen, measured in degrees
let delta = ARMath.deltaAngle(heading, annotation.azimuth)
if fabs(delta) < degreesDeltaH
{
if annotationView.superview == nil
{
// insertSubview at 0 so that farther ones are beneath nearer ones
self.insertSubview(annotationView, at: 0)
}
self.visibleAnnotationViews.append(annotationView)
}
else
{
if annotationView.superview != nil
{
annotationView.removeFromSuperview()
}
}
}
}
//==========================================================================================================================================================
// MARK: Layout
//==========================================================================================================================================================
/**
Layouts annotation views.
- Parameter relayoutAll: If true it will call xPositionForAnnotationView/yPositionForAnnotationView for each annotation view, else
it will only take previously calculated x/y positions and add heading/pitch offsets to visible annotation views.
*/
open func layout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
let pitchYOffset = CGFloat(arStatus.pitch * arStatus.vPixelsPerDegree)
let annotationViews = needsRelayout ? self.annotationViews : self.visibleAnnotationViews
for annotationView in annotationViews
{
guard let annotation = annotationView.annotation else { continue }
if(needsRelayout)
{
let x = self.xPositionForAnnotationView(annotationView, arStatus: arStatus)
let y = self.yPositionForAnnotationView(annotationView, arStatus: arStatus)
annotationView.arPosition = CGPoint(x: x, y: y)
}
let headingXOffset = CGFloat(ARMath.deltaAngle(annotation.azimuth, arStatus.heading)) * CGFloat(arStatus.hPixelsPerDegree)
let x: CGFloat = annotationView.arPosition.x + headingXOffset
let y: CGFloat = annotationView.arPosition.y + pitchYOffset + annotationView.arPositionOffset.y
// Final position of annotation
annotationView.frame = CGRect(x: x, y: y, width: annotationView.bounds.size.width, height: annotationView.bounds.size.height)
}
}
/**
x position without the heading, heading offset is added in layoutAnnotationViews due to performance.
*/
open func xPositionForAnnotationView(_ annotationView: ARAnnotationView, arStatus: ARStatus) -> CGFloat
{
let centerX = self.bounds.size.width * 0.5
let x = centerX - (annotationView.bounds.size.width * annotationView.centerOffset.x)
return x
}
/**
y position without the pitch, pitch offset is added in layoutAnnotationViews due to performance.
*/
open func yPositionForAnnotationView(_ annotationView: ARAnnotationView, arStatus: ARStatus) -> CGFloat
{
guard let annotation = annotationView.annotation else { return 0}
let bottomY = self.bounds.size.height * CGFloat(self.bottomBorder)
let distance = annotation.distanceFromUser
// Offset by distance
var distanceOffset: Double = 0
if self.distanceOffsetMode != .none
{
if let function = self.distanceOffsetFunction
{
distanceOffset = function(distance)
}
else if distance > self.distanceOffsetMinThreshold, let distanceOffsetMultiplier = self.distanceOffsetMultiplier
{
let distanceForOffsetCalculation = distance - self.distanceOffsetMinThreshold
distanceOffset = -(distanceForOffsetCalculation * distanceOffsetMultiplier)
}
}
// y
let y = bottomY - (annotationView.bounds.size.height * annotationView.centerOffset.y) + CGFloat(distanceOffset)
return y
}
/**
Resets temporary stacking fields. This must be called before stacking and before layout.
*/
open func resetLayoutParameters()
{
for annotationView in self.annotationViews
{
annotationView.arPositionOffset = CGPoint.zero
annotationView.arAlternateFrame = CGRect.zero
}
}
open func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
self.presenterTransform?.preLayout(arStatus: arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
open func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
self.presenterTransform?.postLayout(arStatus: arStatus, reloadType: reloadType, needsRelayout: needsRelayout)
}
//==========================================================================================================================================================
// MARK: DistanceOffset
//==========================================================================================================================================================
open func adjustDistanceOffsetParameters()
{
guard var minDistance = self.activeAnnotations.first?.distanceFromUser else { return }
guard let maxDistance = self.activeAnnotations.last?.distanceFromUser else { return }
if minDistance > maxDistance { minDistance = maxDistance }
let deltaDistance = maxDistance - minDistance
let availableHeight = Double(self.bounds.size.height) * self.bottomBorder - 30 // 30 because we don't want them to be on top but little bit below
if self.distanceOffsetMode == .automatic
{
self.distanceOffsetMinThreshold = minDistance
self.distanceOffsetMultiplier = deltaDistance > 0 ? availableHeight / deltaDistance : 0
}
else if self.distanceOffsetMode == .automaticOffsetMinDistance
{
self.distanceOffsetMinThreshold = minDistance
}
}
}
| mit | a1ec3e6e61c8bbd7f8f6f0e6724324fa | 39.844828 | 160 | 0.56469 | 6.183361 | false | false | false | false |
touchopia/HackingWithSwift | project39/Project39/ViewController.swift | 1 | 1510 | //
// ViewController.swift
// Project39
//
// Created by TwoStraws on 26/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var playData = PlayData()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .search, target: self, action: #selector(searchTapped))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return playData.filteredWords.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let word = playData.filteredWords[indexPath.row]
cell.textLabel!.text = word
cell.detailTextLabel!.text = "\(playData.wordCounts.count(for: word))"
return cell
}
func searchTapped() {
let ac = UIAlertController(title: "Filter…", message: nil, preferredStyle: .alert)
ac.addTextField()
ac.addAction(UIAlertAction(title: "Filter", style: .default) { [unowned self] _ in
let userInput = ac.textFields?[0].text ?? "0"
self.playData.applyUserFilter(userInput)
self.tableView.reloadData()
})
ac.addAction(UIAlertAction(title: "Cancel", style: .cancel))
present(ac, animated: true)
}
}
| unlicense | ffeda431a7ba1a5de7db4a0ffb65e1c4 | 26.907407 | 134 | 0.733245 | 3.934726 | false | false | false | false |
thinkaboutiter/Transitions | SideTransitions/SideTransitions/source/UILayer/SideTransitions/SidePresentationController.swift | 1 | 6126 | //
// SidePresentationController.swift
// SideTransitions
//
// Created by Boyan Yankov on 2020-W14-05-Apr-Sun.
// Copyright © 2020 [email protected]. All rights reserved.
//
import UIKit
import SimpleLogger
class SidePresentationController: UIPresentationController {
// MARK: - Properties
private let direction: SideTransitionDirection
private lazy var dimmingView: UIView = {
// let effect: UIBlurEffect = UIBlurEffect.init(style: .dark)
// let result: UIVisualEffectView = UIVisualEffectView(effect: effect)
let result: UIView = UIView()
let color: UIColor = UIColor.AppColor.dimmingViewBackgroundColor
result.backgroundColor = color
result.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tapGestureRecognizer: UITapGestureRecognizer =
UITapGestureRecognizer(target: self,
action: #selector(self.handleTap(recognizer:)))
result.addGestureRecognizer(tapGestureRecognizer)
result.isUserInteractionEnabled = true
result.alpha = 0.0
return result
}()
override var frameOfPresentedViewInContainerView: CGRect {
var result: CGRect = .zero
guard let containerView: UIView = self.containerView else {
assert(false, "Invalid containerView object!")
return result
}
result.size = self.size(forChildContentContainer: self.presentedViewController,
withParentContainerSize: containerView.bounds.size)
switch self.direction {
case .right(let coverage):
result.origin.x = containerView.frame.width * (1.0 - CGFloat(coverage.rawValue))
case .bottom(let coverage):
result.origin.y = containerView.frame.height * (1.0 - CGFloat(coverage.rawValue))
default:
break
}
return result
}
// MARK: - Initialization
init(presentedViewController: UIViewController,
presenting presentingViewController: UIViewController?,
direction: SideTransitionDirection)
{
self.direction = direction
super.init(presentedViewController: presentedViewController,
presenting: presentingViewController)
Logger.success.message("direction=\(self.direction)")
}
deinit {
Logger.fatal.message("direction=\(self.direction)")
}
// MARK: - Life cycle
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
let color: UIColor = UIColor.AppColor.dimmingViewBackgroundColor
self.dimmingView.backgroundColor = color
}
// MARK: - Customization
override func size(forChildContentContainer container: UIContentContainer,
withParentContainerSize parentSize: CGSize) -> CGSize
{
let result: CGSize
switch self.direction {
case .left(let coverage):
result = CGSize(width: parentSize.width * CGFloat(coverage.rawValue),
height: parentSize.height)
case .right(let coverage):
result = CGSize(width: parentSize.width * CGFloat(coverage.rawValue),
height: parentSize.height)
case .top(let coverage):
result = CGSize(width: parentSize.width,
height: parentSize.height * CGFloat(coverage.rawValue))
case .bottom(let coverage):
result = CGSize(width: parentSize.width,
height: parentSize.height * CGFloat(coverage.rawValue))
}
return result
}
override func presentationTransitionWillBegin() {
guard let containerView: UIView = self.containerView else {
assert(false, "Invalid containerView object!")
return
}
self.dimmingView.frame = containerView.bounds
containerView.insertSubview(self.dimmingView, at: 0)
let reveal: (UIView) -> Void = { view in
view.alpha = 1.0
}
let round: (UIView?) -> Void = { view in
let corners: UIView.Corners = UIView.Corners.for(self.direction)
view?.round(corners,
cornerRadius: Constants.presentedViewCornerRadius)
}
guard let coordinator: UIViewControllerTransitionCoordinator = self.presentedViewController.transitionCoordinator else {
reveal(self.dimmingView)
round(self.presentedView)
return
}
coordinator.animate(
alongsideTransition: { _ in
reveal(self.dimmingView)
round(self.presentedView)
},
completion: nil)
}
override func dismissalTransitionWillBegin() {
let conceal: (UIView) -> Void = { view in
view.alpha = 0.0
}
let corner: (UIView?) -> Void = { view in
let corners: UIView.Corners = UIView.Corners.for(self.direction)
view?.round(corners,
cornerRadius: 0)
}
guard let coordinator: UIViewControllerTransitionCoordinator = self.presentedViewController.transitionCoordinator else {
conceal(self.dimmingView)
corner(self.presentedView)
return
}
coordinator.animate(
alongsideTransition: { _ in
conceal(self.dimmingView)
corner(self.presentedView)
},
completion: nil)
}
override func containerViewWillLayoutSubviews() {
self.presentedView?.frame = self.frameOfPresentedViewInContainerView
self.presentedView?.layer.masksToBounds = true
}
// MARK: - Gestures
@objc
func handleTap(recognizer: UITapGestureRecognizer) {
self.presentingViewController.dismiss(animated: true,
completion: nil)
}
}
// MARK: - Constants
private extension SidePresentationController {
enum Constants {
static let presentedViewCornerRadius: CGFloat = 20
}
}
| mit | dba3f3fdf6baa9603eb35efe89a20a16 | 37.043478 | 128 | 0.621061 | 5.624426 | false | false | false | false |
tkremenek/swift | test/Index/index_keypath_member_lookup.swift | 10 | 9214 | // RUN: %target-swift-ide-test -print-indexed-symbols -source-filename %s | %FileCheck %s
struct Point {
// CHECK: [[@LINE-1]]:8 | struct/Swift | Point | {{.*}} | Def | rel: 0
var x: Int
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | x | [[PX_USR:s:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:x | [[PX_GET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-3]]:7 | instance-method/acc-set/Swift | setter:x | [[PX_SET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
var y: Int
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | y | [[PY_USR:s:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:y | [[PY_GET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-3]]:7 | instance-method/acc-set/Swift | setter:y | [[PY_SET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
}
struct Rectangle {
// CHECK: [[@LINE-1]]:8 | struct/Swift | Rectangle | {{.*}} | Def | rel: 0
var topLeft: Point
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | topLeft | [[TL_USR:s:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:topLeft | [[TL_GET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-3]]:7 | instance-method/acc-set/Swift | setter:topLeft | [[TL_SET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
var bottomRight: Point
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | bottomRight | [[BR_USR:s:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:7 | instance-method/acc-get/Swift | getter:bottomRight | [[BR_GET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
// CHECK: [[@LINE-3]]:7 | instance-method/acc-set/Swift | setter:bottomRight | [[BR_SET_USR:s:.*]] | Def,Impl,RelChild,RelAcc | rel: 1
}
@dynamicMemberLookup
struct Lens<T> {
// CHECK: [[@LINE-1]]:8 | struct/Swift | Lens | {{.*}} | Def | rel: 0
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
// CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR:s:.*]] | Def,RelChild | rel: 1
get { return Lens<U>(obj[keyPath: member]) }
// CHECK: [[@LINE-1]]:5 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR:s:.*]] | Def,RelChild,RelAcc | rel: 1
set { obj[keyPath: member] = newValue.obj }
// CHECK: [[@LINE-1]]:5 | instance-method/acc-set/Swift | setter:subscript(dynamicMember:) | [[SUB_SET_USR:s:.*]] | Def,RelChild,RelAcc | rel: 1
}
}
func testRead1(r: Lens<Rectangle>, a: Lens<[Int]>) {
_ = r.topLeft
// CHECK: [[TL_LINE:[0-9]+]]:7 | param/Swift | r
// => implicit dynamicMember subscript (topLeft)
// CHECK: [[TL_LINE]]:8 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,Impl,RelCont | rel: 1
// CHECK: [[TL_LINE]]:8 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR]] | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// => property topLeft
// CHECK: [[TL_LINE]]:9 | instance-property/Swift | topLeft | [[TL_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[TL_LINE]]:9 | instance-method/acc-get/Swift | getter:topLeft | [[TL_GET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
_ = r.bottomRight.y
// CHECK: [[BR_LINE:[0-9]+]]:7 | param/Swift | r
// => implicit dynamicMember subscript (bottomRight)
// CHECK: [[BR_LINE]]:8 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,Impl,RelCont | rel: 1
// CHECK: [[BR_LINE]]:8 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR]] | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// => property bottomRight
// CHECK: [[BR_LINE]]:9 | instance-property/Swift | bottomRight | [[BR_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[BR_LINE]]:9 | instance-method/acc-get/Swift | getter:bottomRight | [[BR_GET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// => implicit dynamicMember subscript (y)
// CHECK: [[BR_LINE]]:20 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,Impl,RelCont | rel: 1
// CHECK: [[BR_LINE]]:20 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR]] | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// => property y
// CHECK: [[BR_LINE]]:21 | instance-property/Swift | y | [[PY_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[BR_LINE]]:21 | instance-method/acc-get/Swift | getter:y | [[PY_GET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
_ = a[0]
// CHECK: [[A_LINE:[0-9]+]]:7 | param/Swift | a
// => implicit dynamicMember subscript
// CHECK: [[A_LINE]]:8 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,Impl,RelCont | rel: 1
// CHECK: [[A_LINE]]:8 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR]] | Ref,Call,Impl,RelRec,RelCall,RelCont | rel: 2
// => subscript [Int]
// CHECK: [[A_LINE]]:8 | instance-property/subscript/Swift | subscript(_:) | s:SayxSicip | Ref,Read,RelCont | rel: 1
// CHECK: [[A_LINE]]:8 | instance-method/acc-get/Swift | getter:subscript(_:) | s:SayxSicig | Ref,Call,Impl,RelCall,RelCont | rel: 1
}
func testWrite1(r: inout Lens<Rectangle>, p: Lens<Point>, a: inout Lens<[Int]>) {
r.topLeft = p
// CHECK: [[WTL_LINE:[0-9]+]]:3 | param/Swift | r
// => implicit dynamicMember subscript (topLeft)
// CHECK: [[WTL_LINE]]:4 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Writ,Impl,RelCont | rel: 1
// CHECK: [[WTL_LINE]]:4 | instance-method/acc-set/Swift | setter:subscript(dynamicMember:) | [[SUB_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// => property topLeft
// CHECK: [[WTL_LINE]]:5 | instance-property/Swift | topLeft | [[TL_USR]] | Ref,Writ,RelCont | rel: 1
// CHECK: [[WTL_LINE]]:5 | instance-method/acc-set/Swift | setter:topLeft | [[TL_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
r.bottomRight.y = Lens(3)
// CHECK: [[WBR_LINE:[0-9]+]]:3 | param/Swift | r
// => implicit dynamicMember subscript (bottomRight)
// CHECK: [[WBR_LINE:[0-9]+]]:4 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,Writ,Impl,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:4 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | [[SUB_GET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:4 | instance-method/acc-set/Swift | setter:subscript(dynamicMember:) | [[SUB_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// => property bottomRight
// CHECK: [[WBR_LINE:[0-9]+]]:5 | instance-property/Swift | bottomRight | [[BR_USR]] | Ref,Read,Writ,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:5 | instance-method/acc-get/Swift | getter:bottomRight | [[BR_GET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:5 | instance-method/acc-set/Swift | setter:bottomRight | [[BR_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// => implicit dynamicMember subscript (y)
// CHECK: [[WBR_LINE:[0-9]+]]:16 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Writ,Impl,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:16 | instance-method/acc-set/Swift | setter:subscript(dynamicMember:) | [[SUB_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// => property y
// CHECK: [[WBR_LINE:[0-9]+]]:17 | instance-property/Swift | y | [[PY_USR]] | Ref,Writ,RelCont | rel: 1
// CHECK: [[WBR_LINE:[0-9]+]]:17 | instance-method/acc-set/Swift | setter:y | [[PY_SET_USR]] | Ref,Call,Impl,RelCall,RelCont | rel: 1
// FIXME: crashes typechecker rdar://problem/49533404
// a[0] = Lens(1)
}
func testExplicit(r: Lens<Rectangle>, a: Lens<[Int]>) {
_ = r[dynamicMember: \.topLeft]
// CHECK: [[ETL_LINE:[0-9]+]]:7 | param/Swift | r
// Not implicit.
// CHECK: [[ETL_LINE]]:8 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[ETL_LINE]]:26 | instance-property/Swift | topLeft | [[TL_USR]] | Ref,Read,RelCont | rel: 1
_ = a[dynamicMember: \.[0]]
// CHECK: [[EA_LINE:[0-9]+]]:7 | param/Swift | a
// Not implicit.
// CHECK: [[EA_LINE]]:8 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB_USR]] | Ref,Read,RelCont | rel: 1
// CHECK: [[EA_LINE]]:26 | instance-property/subscript/Swift | subscript(_:) | s:SayxSicip | Ref,Read,RelCont | rel: 1
}
// Don't crash: rdar63558609
//
@dynamicMemberLookup
protocol Foo {
var prop: Bar {get}
// CHECK: [[@LINE-1]]:7 | instance-property/Swift | prop | [[PROP_USR:.*]] | Def,RelChild | rel: 1
}
struct Bar {
let enabled = false
}
extension Foo {
subscript<T>(dynamicMember keyPath: KeyPath<Bar,T>) -> T {
// CHECK: [[@LINE-1]]:3 | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB2_USR:.*]] | Def,RelChild | rel: 1
// CHECK: [[@LINE-2]]:60 | instance-method/acc-get/Swift | getter:subscript(dynamicMember:) | {{.*}} | Def,Dyn,RelChild,RelAcc | rel: 1
// CHECK-NEXT: RelChild,RelAcc | instance-property/subscript/Swift | subscript(dynamicMember:) | [[SUB2_USR]]
prop[keyPath: keyPath]
// CHECK: [[@LINE-1]]:5 | instance-property/Swift | prop | [[PROP_USR]] | Ref,Read,RelCont | rel: 1
}
}
| apache-2.0 | 2d5a23913b958dcb1eecd9dc83ba2f79 | 56.5875 | 158 | 0.642718 | 2.938138 | false | false | false | false |
tkremenek/swift | test/SILOptimizer/infinite_recursion.swift | 2 | 6833 | // RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify
func a() {
a() // expected-warning {{function call causes an infinite recursion}}
}
func throwing_func() throws {
try throwing_func() // expected-warning {{function call causes an infinite recursion}}
}
func b(_ x : Int) {
if x != 0 {
b(x) // expected-warning {{function call causes an infinite recursion}}
} else {
b(x+1) // expected-warning {{function call causes an infinite recursion}}
}
}
func noInvariantArgs(_ x : Int) {
if x != 0 {
noInvariantArgs(x-1) // expected-warning {{function call causes an infinite recursion}}
} else {
noInvariantArgs(x+1) // expected-warning {{function call causes an infinite recursion}}
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func invariantArgCondition(_ x : Int) {
if x != 0 {
invariantArgCondition(x) // expected-warning {{function call causes an infinite recursion}}
}
}
func invariantLoopCondition(_ x : Int) {
while x != 0 {
invariantLoopCondition(x) // expected-warning {{function call causes an infinite recursion}}
}
}
final class ClassWithInt {
var i: Int = 0
}
func invariantMemCondition(_ c: ClassWithInt) {
if c.i > 0 {
invariantMemCondition(c) // expected-warning {{function call causes an infinite recursion}}
}
}
func variantMemCondition(_ c: ClassWithInt) {
if c.i > 0 {
c.i -= 1
invariantMemCondition(c) // no warning
}
}
func nestedInvariantCondition(_ x : Int, _ y: Int) {
if x > 0 {
if y != 0 {
if x == 0 {
nestedInvariantCondition(x, y) // expected-warning {{function call causes an infinite recursion}}
}
}
}
}
func nestedVariantCondition(_ x : Int, _ y: Int) {
if x > 0 {
if y != 0 {
if x == 0 {
nestedVariantCondition(x, y - 1) // no warning
}
}
}
}
func multipleArgs1(_ x : Int, _ y : Int) {
if y > 0 {
multipleArgs1(x - 1, y) // expected-warning {{function call causes an infinite recursion}}
} else if x > 10 {
multipleArgs1(x - 2, y)
}
}
func multipleArgs2(_ x : Int, _ y : Int) {
if y > 0 {
multipleArgs2(x, y - 1) // expected-warning {{function call causes an infinite recursion}}
} else if x > 10 {
multipleArgs2(x, y - 2) // expected-warning {{function call causes an infinite recursion}}
}
}
func multipleArgsNoWarning(_ x : Int, _ y : Int) {
if y > 0 {
multipleArgsNoWarning(x, y - 1)
} else if x > 10 {
multipleArgsNoWarning(x - 1, y)
}
}
struct Str {
var x = 27
mutating func writesMemory() {
if x > 0 {
x -= 1
writesMemory() // no warning
}
}
mutating func doesNotWriteMem() {
if x > 0 {
doesNotWriteMem() // expected-warning {{function call causes an infinite recursion}}
}
}
func nonMutating() {
if x > 0 {
nonMutating() // expected-warning {{function call causes an infinite recursion}}
}
}
}
func d(_ x : Int) {
var x = x
if x != 0 {
x += 1
}
return d(x) // expected-warning {{function call causes an infinite recursion}}
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() {
while true { // expected-note {{condition always evaluates to true}}
g() // expected-warning {{function call causes an infinite recursion}}
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) {
var x = x
while (x < 5) {
x -= 1
}
i(0) // expected-warning {{function call causes an infinite recursion}}
}
func j() -> Int {
return 5 + j() // expected-warning {{function call causes an infinite recursion}}
}
func k() -> Any {
return type(of: k()) // expected-warning {{function call causes an infinite recursion}}
}
@_silgen_name("exit") func exit(_: Int32) -> Never
func l() {
guard Bool.random() else {
exit(0) // no warning; calling 'exit' terminates the program
}
l()
}
func m() {
guard Bool.random() else {
fatalError() // we _do_ warn here, because fatalError is a programtermination_point
}
m() // expected-warning {{function call causes an infinite recursion}}
}
enum MyNever {}
func blackHole() -> MyNever {
blackHole() // expected-warning {{function call causes an infinite recursion}}
}
@_semantics("programtermination_point")
func terminateMe() -> MyNever {
terminateMe() // no warning; terminateMe is a programtermination_point
}
func n() -> MyNever {
if Bool.random() {
blackHole() // no warning; blackHole() will terminate the program
}
n()
}
func o() -> MyNever {
if Bool.random() {
o()
}
blackHole() // no warning; blackHole() will terminate the program
}
func mayHaveSideEffects() {}
func p() {
if Bool.random() {
mayHaveSideEffects() // presence of side-effects doesn't alter the check for the programtermination_point apply
fatalError()
}
p() // expected-warning {{function call causes an infinite recursion}}
}
class S {
convenience init(a: Int) {
self.init(a: a) // expected-warning {{function call causes an infinite recursion}}
}
init(a: Int?) {}
static func a() {
return a() // expected-warning {{function call causes an infinite recursion}}
}
func b() { // No warning - has a known override.
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
var bar: String = "hi!"
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
override var bar: String {
get {
return super.bar
}
set {
self.bar = newValue // expected-warning {{function call causes an infinite recursion}}
}
}
}
func == (l: S?, r: S?) -> Bool {
if l == nil && r == nil { return true } // expected-warning {{function call causes an infinite recursion}}
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool {
return lhs == rhs // expected-warning {{function call causes an infinite recursion}}
}
func factorial(_ n : UInt) -> UInt {
return (n != 0) ? factorial(n - 1) * n : factorial(1) // expected-warning {{function call causes an infinite recursion}}
// expected-warning @-1 {{function call causes an infinite recursion}}
}
func tr(_ key: String) -> String {
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
// expected-warning @-1 {{function call causes an infinite recursion}}
}
class Node {
var parent: Node?
var rootNode: RootNode {
return parent!.rootNode // No warning - has an override.
}
}
class RootNode: Node {
override var rootNode: RootNode { return self }
}
| apache-2.0 | d7418e246944f32a6cb3153b36bffae4 | 22.241497 | 126 | 0.610566 | 3.545926 | false | false | false | false |
ValeryLanin/InstagramFirebase | InstagramFirebase/Extensions.swift | 1 | 1494 | //
// Extensions.swift
// InstagramFirebase
//
// Created by Admin on 03.10.17.
// Copyright © 2017 Valery Lanin. All rights reserved.
//
import UIKit
extension UIColor {
static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor {
return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: 1)
}
// func someRandomeMethod() {
//
// }
}
extension UIView {
func anchor(top: NSLayoutYAxisAnchor?, left: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, right: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true
}
if let left = left {
self.leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true
}
if let right = right {
rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true
}
if width != 0 {
widthAnchor.constraint(equalToConstant: width).isActive = true
}
if height != 0 {
heightAnchor.constraint(equalToConstant: height).isActive = true
}
}
}
| mit | 90a5872ff3eabcd7e2f9df1f41850c7a | 25.660714 | 255 | 0.639652 | 4.524242 | false | false | false | false |
thebnich/firefox-ios | Client/Frontend/Browser/Browser.swift | 1 | 13704 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
protocol BrowserHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol BrowserDelegate {
func browser(browser: Browser, didAddSnackbar bar: SnackBar)
func browser(browser: Browser, didRemoveSnackbar bar: SnackBar)
optional func browser(browser: Browser, didCreateWebView webView: WKWebView)
optional func browser(browser: Browser, willDeleteWebView webView: WKWebView)
}
class Browser: NSObject {
private var _isPrivate: Bool = false
internal private(set) var isPrivate: Bool {
get {
if #available(iOS 9, *) {
return _isPrivate
} else {
return false
}
}
set {
_isPrivate = newValue
}
}
var webView: WKWebView? = nil
var browserDelegate: BrowserDelegate? = nil
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
var lastRequest: NSURLRequest? = nil
var restoring: Bool = false
var pendingScreenshot = false
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
private(set) var screenshot: UIImage?
var screenshotUUID: NSUUID?
private var helperManager: HelperManager? = nil
private var configuration: WKWebViewConfiguration? = nil
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
@available(iOS 9, *)
init(configuration: WKWebViewConfiguration, isPrivate: Bool) {
self.configuration = configuration
super.init()
self.isPrivate = isPrivate
}
class func toTab(browser: Browser) -> RemoteTab? {
if let displayURL = browser.displayURL {
let history = Array(browser.historyList.filter(RemoteTab.shouldIncludeURL).reverse())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: browser.displayTitle,
history: history,
lastUsed: NSDate.now(),
icon: nil)
} else if let sessionData = browser.sessionData where !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.reverse())
return RemoteTab(clientGUID: nil,
URL: history[0],
title: browser.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
return nil
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = WKWebView(frame: CGRectZero, configuration: configuration!)
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGrayColor()
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
restore(webView)
self.webView = webView
browserDelegate?.browser?(self, didCreateWebView: webView)
// lastTitle is used only when showing zombie tabs after a session restore.
// Since we now have a web view, lastTitle is no longer useful.
lastTitle = nil
}
}
func restore(webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Browser. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var updatedURLs = [String]()
for url in sessionData.urls {
let updatedURL = WebServer.sharedInstance.updateLocalURL(url)!.absoluteString
updatedURLs.append(updatedURL)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = updatedURLs
jsonDict["currentPage"] = currentPage
let escapedJSON = JSON.stringify(jsonDict, pretty: false).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let restoreURL = NSURL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
lastRequest = NSURLRequest(URL: restoreURL!)
webView.loadRequest(lastRequest!)
} else if let request = lastRequest {
webView.loadRequest(request)
} else {
log.error("creating webview with no lastRequest and no session data: \(self.url)")
}
}
deinit {
if let webView = webView {
browserDelegate?.browser?(self, willDeleteWebView: webView)
}
}
var loading: Bool {
return webView?.loading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [NSURL] {
func listToUrl(item: WKBackForwardListItem) -> NSURL { return item.URL }
var tabs = self.backList?.map(listToUrl) ?? [NSURL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
return displayURL?.absoluteString ?? lastTitle ?? ""
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width > width {
width = icon.width!
largest = icon
}
}
return largest
}
var url: NSURL? {
return webView?.URL ?? lastRequest?.URL
}
var displayURL: NSURL? {
if let url = url {
if ReaderModeUtils.isReaderModeURL(url) {
return ReaderModeUtils.decodeURL(url)
}
if ErrorPageHelper.isErrorPageURL(url) {
let decodedURL = ErrorPageHelper.decodeURL(url)
if !AboutUtils.isAboutURL(decodedURL) {
return decodedURL
} else {
return nil
}
}
if !AboutUtils.isAboutURL(url) {
return url
}
}
return nil
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
func goToBackForwardListItem(item: WKBackForwardListItem) {
webView?.goToBackForwardListItem(item)
}
func loadRequest(request: NSURLRequest) -> WKNavigation? {
if let webView = webView {
lastRequest = request
return webView.loadRequest(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
if let _ = webView?.reloadFromOrigin() {
log.info("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
log.info("restoring webView from scratch")
restore(webView)
}
}
func addHelper(helper: BrowserHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(name name: String) -> BrowserHelper? {
return helperManager?.getHelper(name: name)
}
func hideContent(animated: Bool = false) {
webView?.userInteractionEnabled = false
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(animated: Bool = false) {
webView?.userInteractionEnabled = true
if animated {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(bar: SnackBar) {
bars.append(bar)
browserDelegate?.browser(self, didAddSnackbar: bar)
}
func removeSnackbar(bar: SnackBar) {
if let index = bars.indexOf(bar) {
bars.removeAtIndex(index)
browserDelegate?.browser(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for var i = bars.count-1; i >= 0; i-- {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = NSUUID()
}
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
private var helpers = [String: BrowserHelper]()
private weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(helper: BrowserHelper, name: String) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right BrowserHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.addScriptMessageHandler(self, name: scriptMessageHandlerName)
}
}
func getHelper(name name: String) -> BrowserHelper? {
return helpers[name]
}
}
extension WKWebView {
func runScriptFunction(function: String, fromScript: String, callback: (AnyObject?) -> Void) {
if let path = NSBundle.mainBundle().pathForResource(fromScript, ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String {
evaluateJavaScript(source, completionHandler: { (obj, err) -> Void in
if let err = err {
print("Error injecting \(err)")
return
}
self.evaluateJavaScript("__firefox__.\(fromScript).\(function)", completionHandler: { (obj, err) -> Void in
self.evaluateJavaScript("delete window.__firefox__.\(fromScript)", completionHandler: { (obj, err) -> Void in })
if let err = err {
print("Error running \(err)")
return
}
callback(obj)
})
})
}
}
}
}
| mpl-2.0 | 8d7ab08545adbbadad9d27bfe4a3601b | 32.101449 | 167 | 0.597271 | 5.416601 | false | false | false | false |
terietor/GTSegmentedControl | Source/SegmentedControl.swift | 1 | 8944 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
/**
A multiline segmented control
*/
public class SegmentedControl: UIView {
/**
The items of the segmented control
*/
public var items: [Any] = [Any]() {
didSet {
createSegmentedControls()
}
}
/**
Items per row
*/
public var itemsPerRow = 3 {
didSet {
createSegmentedControls()
}
}
/**
Spacing between the rows
*/
public var spacing: Double = 0 {
didSet {
createSegmentedControls()
}
}
private var _value: String?
/**
The value for the current selected segment
*/
public var value: String? {
get {
return self._value
}
set(newValue) {
// we will start an expensive operation
// so we must do it only if there is difference
// in the UI.
if self.value == newValue {
return
}
self._value = newValue
changeCurrentIndex()
}
}
/**
It is called when value changes
*/
public var valueDidChange: ((String) -> ())?
/**
This color will be used as the color of the
UISegmentedControl's text
*/
public var textColor: UIColor? {
didSet {
guard let textColor = self.textColor else {
return
}
let attributes = [
NSForegroundColorAttributeName: textColor,
NSFontAttributeName: UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
]
UISegmentedControl
.appearance(whenContainedInInstancesOf: [type(of: self)])
.setTitleTextAttributes(attributes, for: .selected)
}
}
public override func tintColorDidChange() {
for control in self.segmentedControls {
control.tintColor = self.tintColor
}
}
private var segmentedControls: [UISegmentedControl] = [UISegmentedControl]()
private var kvoContext = UInt8()
deinit {
for control in self.segmentedControls {
removeObserverForSegmentedControl(control)
}
}
private func createSegmentedControls() {
removeSegmentedControlsFromView()
var currentSegmentedControl = UISegmentedControl()
self.segmentedControls.append(currentSegmentedControl)
for item in self.items {
if !addSegment(currentSegmentedControl, item: item) {
currentSegmentedControl = UISegmentedControl()
self.segmentedControls.append(currentSegmentedControl)
currentSegmentedControl.translatesAutoresizingMaskIntoConstraints = false
addSegment(currentSegmentedControl, item: item)
}
}
addSegmentedControlsToView()
}
@discardableResult
private func addSegment(
_ segmentedControl: UISegmentedControl,
item: Any
) -> Bool {
guard
segmentedControl.numberOfSegments < self.itemsPerRow
else { return false }
let segmentIndex = segmentedControl.numberOfSegments
segmentedControl.insertSegment(
withTitle: item as? String,
at: segmentIndex,
animated: false
)
return true
}
private func addSegmentedControlsToView() {
var previousControl: UISegmentedControl!
for (index, control) in self.segmentedControls.enumerated() {
addObserverForSegmentedControl(control)
addSubview(control)
if index == 0 {
control.snp.makeConstraints() { make in
make.left.right.equalTo(self)
make.top.equalTo(self)
}
} else {
control.snp.makeConstraints() { make in
make.left.right.equalTo(self)
make.top.equalTo(previousControl.snp.bottom)
.offset(self.spacing).priority(UILayoutPriorityDefaultLow)
}
}
previousControl = control
}
}
private func removeSegmentedControlsFromView() {
for segment in self.segmentedControls {
segment.removeFromSuperview()
removeObserverForSegmentedControl(segment)
}
self.segmentedControls.removeAll()
}
private func changeCurrentIndex() {
guard let
value = self.value
else { return }
for control in self.segmentedControls {
for index in 0...control.numberOfSegments - 1 {
let title = control.titleForSegment(at: index)
guard value == title else { continue }
// yes KVO sucks, but we don't have another
// way to do this
removeObserverForSegmentedControl(control)
control.selectedSegmentIndex = index
addObserverForSegmentedControl(control)
} // end for index
} // end for
}
// MARK: KVO
open override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?)
{
if keyPath != "selectedSegmentIndex" &&
context != &self.kvoContext
{
return
}
guard let segmentedControl = object as? UISegmentedControl else { return }
if let
value = segmentedControl
.titleForSegment(at: segmentedControl.selectedSegmentIndex)
{
self._value = value
self.valueDidChange?(value)
}
for control in self.segmentedControls {
guard control != segmentedControl else { continue }
// If we don't remove the observer and call the selectedSegmentIndex
// then the KVO will be triggered again. And then the selectedSegmentIndex
// will call the KVO. In simple words we will trigger an infinite loop.
// We can't use UIControlEvents.ValueChanged because
// in iOS 9 if the keyboard is active the .ValueChanged target won't
// be called.
removeObserverForSegmentedControl(control)
control.selectedSegmentIndex = -1
addObserverForSegmentedControl(control)
}
}
private func removeObserverForSegmentedControl(_ control: UISegmentedControl) {
control.removeObserver(
self,
forKeyPath: "selectedSegmentIndex",
context: &self.kvoContext
)
}
private func addObserverForSegmentedControl(_ control: UISegmentedControl) {
control.addObserver(
self,
forKeyPath: "selectedSegmentIndex",
options: [.old, .new],
context: &self.kvoContext
)
}
open override var intrinsicContentSize : CGSize {
var height: CGFloat = 0
for (index, control) in self.segmentedControls.enumerated() {
if index != 0 {
height += CGFloat(self.spacing)
}
height += control.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
return CGSize(width: UIViewNoIntrinsicMetric, height: height)
}
}
| mit | c2907330ddd787ee1f77f33878838777 | 30.382456 | 97 | 0.577147 | 5.857236 | false | false | false | false |
akaralar/siesta | Tests/Functional/ProgressSpec.swift | 1 | 12053 | //
// ProgressSpec.swift
// Siesta
//
// Created by Paul on 2015/10/4.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
@testable import Siesta
import Quick
import Nimble
import Nocilla
class ProgressSpec: ResourceSpecBase
{
override func resourceSpec(_ service: @escaping () -> Service, _ resource: @escaping () -> Resource)
{
describe("always reaches 1")
{
it("on success")
{
_ = stubRequest(resource, "GET").andReturn(200)
let req = resource().load()
awaitNewData(req)
expect(req.progress) == 1.0
}
it("on request error")
{
let req = resource().request(.post, text: "𐀯𐀁𐀱𐀲", encoding: String.Encoding.ascii)
awaitFailure(req, alreadyCompleted: true)
expect(req.progress) == 1.0
}
it("on server error")
{
_ = stubRequest(resource, "GET").andReturn(500)
let req = resource().load()
awaitFailure(req)
expect(req.progress) == 1.0
}
it("on connection error")
{
_ = stubRequest(resource, "GET").andFailWithError(NSError(domain: "foo", code: 1, userInfo: nil))
let req = resource().load()
awaitFailure(req)
expect(req.progress) == 1.0
}
it("on cancellation")
{
let reqStub = stubRequest(resource, "GET").andReturn(200).delay()
let req = resource().load()
req.cancel()
expect(req.progress) == 1.0
_ = reqStub.go()
awaitFailure(req, alreadyCompleted: true)
}
}
// Exact progress values are subjective, and subject to change. These specs only examine
// what affects the progress computation.
describe("computation")
{
var getRequest: Bool!
var metrics: RequestTransferMetrics!
var progress: RequestProgressComputation?
beforeEach
{
progress = nil
metrics = RequestTransferMetrics(
requestBytesSent: 0,
requestBytesTotal: nil,
responseBytesReceived: 0,
responseBytesTotal: nil)
setResourceTime(100)
}
func progressComparison(_ closure: (Void) -> Void) -> (before: Double, after: Double)
{
progress = progress ?? RequestProgressComputation(isGet: getRequest)
progress!.update(from: metrics)
let before = progress!.fractionDone
closure()
progress!.update(from: metrics)
let after = progress!.fractionDone
return (before, after)
}
func expectProgressToIncrease(_ closure: (Void) -> Void)
{
let result = progressComparison(closure)
expect(result.after) > result.before
}
func expectProgressToRemainUnchanged(_ closure: (Void) -> Void)
{
let result = progressComparison(closure)
expect(result.after) == result.before
}
func expectProgressToRemainAlmostUnchanged(_ closure: (Void) -> Void)
{
let result = progressComparison(closure)
expect(result.after) ≈ result.before ± 0.01
}
context("for request with no body")
{
beforeEach { getRequest = true }
it("increases while waiting for request to start")
{
expectProgressToIncrease
{ setResourceTime(101) }
}
it("is stable when response arrives")
{
expectProgressToIncrease { setResourceTime(101) }
expectProgressToRemainAlmostUnchanged
{
setResourceTime(1000)
metrics.responseBytesReceived = 1
metrics.responseBytesTotal = 1000
}
}
it("tracks download")
{
metrics.requestBytesSent = 0
metrics.requestBytesTotal = 0
metrics.responseBytesReceived = 1
metrics.responseBytesTotal = 1000
expectProgressToIncrease
{ metrics.responseBytesReceived = 2 }
}
it("tracks download even when size is unknown")
{
metrics.requestBytesSent = 0
metrics.requestBytesTotal = 0
metrics.responseBytesReceived = 1
expectProgressToIncrease
{ metrics.responseBytesReceived = 2 }
}
it("never reaches 1 if response size is unknown")
{
metrics.requestBytesSent = 0
metrics.requestBytesTotal = 0
metrics.responseBytesReceived = 1
metrics.responseBytesTotal = -1
expectProgressToIncrease
{ metrics.responseBytesReceived = 1000000 }
expect(progress?.rawFractionDone) < 1
}
it("is stable when estimated download size becomes precise")
{
metrics.requestBytesSent = 0
metrics.requestBytesTotal = 0
metrics.responseBytesReceived = 10
expectProgressToRemainUnchanged
{ metrics.responseBytesTotal = 20 }
}
it("does not exceed 1 even if bytes downloaded exceed total")
{
metrics.responseBytesReceived = 10000
metrics.responseBytesTotal = 2
expectProgressToRemainUnchanged
{ metrics.responseBytesReceived = 20000 }
expect(progress?.rawFractionDone) == 1
}
}
context("for request with a body")
{
beforeEach { getRequest = false }
it("is stable when request starts uploading after a delay")
{
expectProgressToIncrease { setResourceTime(101) }
expectProgressToRemainAlmostUnchanged
{
setResourceTime(1000)
metrics.requestBytesSent = 1
metrics.requestBytesTotal = 1000
}
}
it("tracks upload")
{
metrics.requestBytesSent = 1
metrics.requestBytesTotal = 1000
expectProgressToIncrease
{ metrics.requestBytesSent = 2 }
}
it("tracks upload even if upload size is unknown")
{
metrics.requestBytesSent = 10
metrics.requestBytesTotal = -1
expectProgressToIncrease
{ metrics.requestBytesSent = 11 }
}
it("is stable when estimated upload size becomes precise")
{
metrics.requestBytesSent = 10
metrics.requestBytesTotal = -1
expectProgressToRemainUnchanged
{ metrics.requestBytesTotal = 100 }
}
it("does not track time while uploading")
{
metrics.requestBytesSent = 1
metrics.requestBytesTotal = 1000
expectProgressToRemainUnchanged
{ setResourceTime(120) }
}
it("increases while waiting for response after upload")
{
metrics.requestBytesSent = 1000
metrics.requestBytesTotal = 1000
expectProgressToIncrease
{ setResourceTime(110) }
}
it("is stable when response arrives")
{
metrics.requestBytesSent = 1000
metrics.requestBytesTotal = 1000
expectProgressToIncrease { setResourceTime(110) }
expectProgressToRemainAlmostUnchanged
{
setResourceTime(110)
metrics.responseBytesReceived = 1
metrics.responseBytesTotal = 1000
}
}
it("tracks download")
{
metrics.requestBytesSent = 1000
metrics.requestBytesTotal = 1000
metrics.responseBytesReceived = 1
metrics.responseBytesTotal = 1000
expectProgressToIncrease
{ metrics.responseBytesReceived = 2 }
}
}
}
describe("callback")
{
@discardableResult
func recordProgress(
setup: (Request) -> Void = { _ in },
until stopCondition: @escaping ([Double]) -> Bool)
-> [Double]
{
var progressReports: [Double] = []
let expectation = QuickSpec.current().expectation(description: "recordProgressUntil")
var fulfilled = false
let reqStub = stubRequest(resource, "GET").andReturn(200).delay()
let req = resource().load().onProgress
{
progressReports.append($0)
if !fulfilled && stopCondition(progressReports)
{
fulfilled = true
expectation.fulfill()
}
}
setup(req)
QuickSpec.current().waitForExpectations(timeout: 1, handler: nil)
_ = reqStub.go()
awaitNewData(req)
return progressReports
}
it("receives periodic updates during request")
{
let progressReports = recordProgress(until: { $0.count >= 4 })
// The mere passage of time should increase latency, and thus make progress increase beyond 0
expect(progressReports.any { $0 > 0 }) == true
expect(progressReports.sorted()) == progressReports
}
describe("last notification")
{
it("is 1")
{
let progressReports = recordProgress(until: { _ in true })
expect(progressReports.last) == 1
}
it("comes before the completion callback")
{
var completionCalled = false
recordProgress(
setup:
{
$0.onProgress { _ in expect(completionCalled) == false }
.onCompletion { _ in completionCalled = true }
},
until: { _ in true })
}
}
}
}
}
| mit | a5505d4b2842a46e53760cec1fa3d004 | 35.698171 | 113 | 0.453601 | 6.135066 | false | true | false | false |
WalterCreazyBear/Swifter30 | PhoneHistory/PhoneHistory/ViewController.swift | 1 | 3103 | //
// ViewController.swift
// PhoneHistory
//
// Created by Bear on 2017/6/15.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
fileprivate var products: [Product]?
fileprivate let identifer = "productCell"
fileprivate var navigationTitle :String
fileprivate lazy var tableView :UITableView = {
let table = UITableView.init()
table.backgroundColor = UIColor.white
table.register(UITableViewCell.self, forCellReuseIdentifier: self.identifer)
table.frame = self.view.bounds
table.delegate = self
table.dataSource = self
return table
}()
init() {
navigationTitle = "PhoneList"
super.init(nibName: nil, bundle: nil)
}
convenience init(title:String)
{
//未初始化时,属性是不被赋值的,因为其内存空间不存在
//so,下面两行代码不能对调
self.init()
navigationTitle = title
}
required init?(coder aDecoder: NSCoder) {
navigationTitle = "PhoneList"
super.init(coder: aDecoder);
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.white
self.title = navigationTitle
self.view.addSubview(self.tableView)
products = [
Product(name: "1907 Wall Set", cellImageName: "image-cell1", fullscreenImageName: "phone-fullscreen1"),
Product(name: "1921 Dial Phone", cellImageName: "image-cell2", fullscreenImageName: "phone-fullscreen2"),
Product(name: "1937 Desk Set", cellImageName: "image-cell3", fullscreenImageName: "phone-fullscreen3"),
Product(name: "1984 Moto Portable", cellImageName: "image-cell4", fullscreenImageName: "phone-fullscreen4")
]
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return products?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: self.identifer)!
guard let products = products else { return cell }
cell.textLabel?.text = products[(indexPath as NSIndexPath).row].name
if let imageName = products[(indexPath as NSIndexPath).row].cellImageName {
cell.imageView?.image = UIImage(named: imageName)
}
return cell;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 94.0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detailViewController = PhoneDetail()
self.navigationController?.pushViewController(detailViewController, animated: true)
}
}
| mit | f0b5327330e6e15149c9d10fe4cc3fb2 | 33.827586 | 119 | 0.653465 | 4.855769 | false | false | false | false |
JakeLin/SwiftWeather | SwiftWeatherUITests/SwiftWeatherUITests.swift | 1 | 2224 | //
// Created by Jake Lin on 8/18/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import XCTest
import Quick
import Nimble
class SwiftWeatherUITests: QuickSpec {
override func spec() {
let app = XCUIApplication()
beforeSuite {
self.continueAfterFailure = false
app.launch()
}
describe("a wheather viewcontroller") {
context("location service is enabled") {
context("when in portrait") {
beforeEach {
XCUIDevice.shared.orientation = .portrait
}
itBehavesLike("a properly laidout wheather viewcontroller")
}
context("when in landscape") {
beforeEach {
XCUIDevice.shared.orientation = .landscapeLeft
}
itBehavesLike("a properly laidout wheather viewcontroller")
}
}
}
}
}
class RegularWheatherViewControllerConfiguration: QuickConfiguration {
override class func configure(_ configuration: Configuration) {
let app = XCUIApplication()
let window = app.windows.element(boundBy: 0)
sharedExamples("a properly laidout wheather viewcontroller") { (context: SharedExampleContext) in
it("shows city") {
let cityLabel = app.staticTexts["a11y_current_city"]
expect(cityLabel.exists).to(beTruthy())
expect(window.frame.contains(cityLabel.frame)).to(beTruthy())
}
it("shows wheather icon") {
let wheatherIconLabel = app.staticTexts["a11y_wheather_icon"]
expect(wheatherIconLabel.exists).to(beTruthy())
expect(window.frame.contains(wheatherIconLabel.frame)).to(beTruthy())
}
it("shows wheather temperature") {
let wheatherTemperatureLabel = app.staticTexts["a11y_wheather_temperature"]
expect(wheatherTemperatureLabel.exists).to(beTruthy())
expect(window.frame.contains(wheatherTemperatureLabel.frame)).to(beTruthy())
}
}
}
}
| mit | b042872060bbe3781218c86495c9780d | 30.757143 | 105 | 0.569501 | 5.145833 | false | true | false | false |
ccdeccdecc/ccemoticon | 表情键盘/表情键盘/Emoticon/CCEmoticonViewController.swift | 1 | 5301 | //
// CCEmoticonViewController.swift
// 表情键盘
//
// Created by apple on 15/11/8.
// Copyright © 2015年 eason. All rights reserved.
//
import UIKit
class CCEmoticonViewController: UIViewController {
//MARK: -属性
private var collectionViewCellIdentifier = "collectionViewCellIdentifier"
override func viewDidLoad() {
super.viewDidLoad()
// view.backgroundColor = UIColor.cyanColor()
prepareUI()
}
//MARK: - 准备UI
func prepareUI() {
//添加子控件
view.addSubview(collectionView)
view.addSubview(toolbarView)
//添加约束
collectionView.translatesAutoresizingMaskIntoConstraints = false
toolbarView.translatesAutoresizingMaskIntoConstraints = false
let views = ["cv" : collectionView, "tb" : toolbarView]
//conllectionView水平方向
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
//toolbarView
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
//垂直方向
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
setupToolBar()
setupCollectionView()
}
///设置toolBar
private func setupToolBar() {
var items = [UIBarButtonItem]()
for name in ["最近", "默认", "emoji", "浪小花"] {
let button = UIButton()
//设置标题
button.setTitle(name, forState: UIControlState.Normal)
//设置颜色
button.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Normal)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Highlighted)
button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
button.sizeToFit()
//创建barbuttonitem
let item = UIBarButtonItem(customView: button)
items.append(item)
//添加弹簧
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
}
//移除最后一个多有的弹簧
items.removeLast()
toolbarView.items = items
}
///设置collectionView
private func setupCollectionView() {
collectionView.dataSource = self
//注册cell
collectionView.registerClass(CCEmoticonCell.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
}
//MARK: -懒加载
private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CCCollectionViewFlowLayout())
private lazy var toolbarView = UIToolbar()
}
//MARK: - 扩展CCEmoticonViewController 实现 UICollectionViewDataSource 协议
extension CCEmoticonViewController: UICollectionViewDataSource {
//返回cell的数量
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 21 * 2
}
//返回cell
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewCellIdentifier, forIndexPath: indexPath) as! CCEmoticonCell
cell.backgroundColor = UIColor.randomColor()
return cell
}
}
//MARK: - 自定义表情cell
class CCEmoticonCell: UICollectionViewCell {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
//MARK: - 准备UI
private func prepareUI() {
//添加子控件
contentView.addSubview(emoticonButton)
//设置frame
emoticonButton.frame = CGRectInset(bounds, 4, 4)
emoticonButton.backgroundColor = UIColor.cyanColor()
}
//MARK: - 懒加载
///表情按钮
private lazy var emoticonButton: UIButton = UIButton()
}
//MARK: - 继承流水布局
///在collectionView布局之前设置layout的参数
class CCCollectionViewFlowLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
//item宽度
let width = collectionView!.frame.width / 7.0
let height = collectionView!.frame.height / 3.0
itemSize = CGSize(width: width, height: height)
//滚动方向
scrollDirection = UICollectionViewScrollDirection.Horizontal
//间距
minimumLineSpacing = 0
minimumInteritemSpacing = 0
//取消弹簧效果
collectionView?.bounces = false
collectionView?.alwaysBounceHorizontal = false
collectionView?.showsHorizontalScrollIndicator = false
//分页显示
collectionView?.pagingEnabled = true
}
}
| apache-2.0 | 3de1773c26232addb21bf44bc31cde64 | 32.311258 | 175 | 0.659841 | 5.414424 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/Media+Blog.swift | 1 | 2780 | import Foundation
extension Media {
/// Inserts and returns a new managed Media object, in the context.
///
@objc class func makeMedia(in context: NSManagedObjectContext) -> Media {
let media = NSEntityDescription.insertNewObject(forEntityName: "Media", into: context) as! Media
media.creationDate = Date()
media.mediaID = 0
media.remoteStatus = .local
return media
}
/// Inserts and returns a new managed Media object, with a blog.
///
@objc class func makeMedia(blog: Blog) -> Media {
let media = makeMedia(in: blog.managedObjectContext!)
media.blog = blog
return media
}
/// Inserts and returns a new managed Media object, with a post.
///
@objc class func makeMedia(post: AbstractPost) -> Media {
let media = makeMedia(blog: post.blog)
media.addPostsObject(post)
return media
}
/// Returns an existing Media object that matches the mediaID if it exists, or nil.
///
@objc class func existingMediaWith(mediaID: NSNumber, inBlog blog: Blog) -> Media? {
guard let blogMedia = blog.media as? Set<Media> else {
return nil
}
return blogMedia.first(where: ({ $0.mediaID == mediaID }))
}
/// Returns an existing Media object that matches the remoteURL if it exists, or nil.
///
@objc class func existingMediaWith(remoteURL: String, inBlog blog: Blog) -> Media? {
guard let blogMedia = blog.media as? Set<Media> else {
return nil
}
return blogMedia.first(where: ({ $0.remoteURL == remoteURL }))
}
/// Returns an existing Media object that matches the mediaID if it exists, or creates a stub if not.
///
@objc class func existingOrStubMediaWith(mediaID: NSNumber, inBlog blog: Blog) -> Media? {
if let media = Media.existingMediaWith(mediaID: mediaID, inBlog: blog) {
return media
}
let media = Media.makeMedia(blog: blog)
media.mediaID = mediaID
media.remoteStatus = .stub
return media
}
/// Returns a list of Media objects from a post, that should be autoUploaded on the next attempt.
///
/// - Parameters:
/// - post: the post to look auto-uploadable media for.
/// - automatedRetry: whether the media to upload is the result of an automated retry.
///
/// - Returns: the Media objects that should be autoUploaded.
///
class func failedForUpload(in post: AbstractPost, automatedRetry: Bool) -> [Media] {
post.media.filter { media in
media.remoteStatus == .failed
&& (!automatedRetry || media.autoUploadFailureCount.intValue < Media.maxAutoUploadFailureCount)
}
}
}
| gpl-2.0 | ec209f34b2d9ac87e5106a6ad08e5988 | 35.103896 | 111 | 0.629137 | 4.476651 | false | false | false | false |
adamcumiskey/BlockDataSource | Example/BlockDataSource/ExampleCollectionViewController.swift | 1 | 1921 | //
// ExampleCollectionViewController.swift
// BlockDataSource_Example
//
// Created by Adam on 6/25/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import BlockDataSource
import UIKit
class ExampleCollectionViewController: BlockCollectionViewController {
lazy var items: [UIImage] = {
return (0..<30).map { _ in
let rand = arc4random_uniform(100)
if rand % 2 == 0 {
return #imageLiteral(resourceName: "king_burger")
} else {
return #imageLiteral(resourceName: "lego_burger")
}
}
}()
init() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = .init(width: 100, height: 100)
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.sectionInset = .init(top: 10, left: 10, bottom: 10, right: 10)
layout.headerReferenceSize = .init(width: UIScreen.main.bounds.width, height: 100)
super.init(collectionViewLayout: layout)
self.title = "Reordering"
self.collectionView?.backgroundColor = .white
self.dataSource = DataSource(
sections: [
Section(
header: Reusable { (view: InformationCollectionReusableView) in
view.textLabel?.text = "Press and hold on a cell for a few moments, then drag and drop to reorder."
},
items: items.map { item in
return Item(reorderable: true) { (cell: ImageCollectionViewCell) in
cell.imageView.image = item
}
}
)
],
onReorder: { [unowned self] origin, destination in
self.items.moveObjectAtIndex(origin.item, toIndex: destination.item)
}
)
}
}
| mit | 6d947917dfc752afbc1f30265f1d1bbd | 33.909091 | 123 | 0.552604 | 4.987013 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Logging/LogReader.swift | 1 | 10876 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 13/02/16.
*/
import Foundation
import CleanroomLogger
import RegexUtil
final class LogReader {
var stopped = true
var offset: UInt64 = 0
var startingPoint: LogDate = LogDate(date: Date.distantPast)
var fileHandle: FileHandle?
var path: String
let fileManager = FileManager()
private var info: LogReaderInfo
private var logReaderManager: LogReaderManager?
private var queue: DispatchQueue?
private var _lines = [ConcurrentQueue<LogLine>]()
init(info: LogReaderInfo, logPath: String, removeLogfile: Bool = true) {
self.info = info
self.path = "\(logPath)/Logs/\(info.name).log"
Log.info?.message("Init reader for \(info.name) at path \(self.path)")
if fileManager.fileExists(atPath: self.path)
&& !FileUtils.isFileOpen(byHearthstone: self.path)
&& removeLogfile {
do {
Log.info?.message("Removing log file at \(self.path)")
try fileManager.removeItem(atPath: self.path)
} catch {
Log.error?.message("\(error)")
}
}
_lines.removeAll()
for _ in 1...max(1, max(info.startsWithFiltersGroup.count, info.containsFiltersGroup.count) ) {
_lines.append(ConcurrentQueue<LogLine>())
}
}
func findEntryPoint(choice: String) -> LogDate {
return findEntryPoint(choices: [choice])
}
func findEntryPoint(choices: [String]) -> LogDate {
guard fileManager.fileExists(atPath: path) else {
return LogDate(date: Date.distantPast)
}
var fileContent: String
do {
fileContent = try String(contentsOfFile: path)
} catch {
return LogDate(date: Date.distantPast)
}
let lines: [String] = fileContent
.components(separatedBy: "\n")
.filter({ !$0.isBlank }).reversed()
for line in lines {
if choices.any({ line.range(of: $0) != nil }) {
Log.verbose?.message("Found \(line)")
return LogLine(namespace: .power, line: line).time
}
}
return LogDate(date: Date.distantPast)
}
func start(manager logReaderManager: LogReaderManager, entryPoint: LogDate) {
stopped = false
self.logReaderManager = logReaderManager
startingPoint = entryPoint
var queueName = "be.michotte.hstracker.readers.\(info.name)"
if info.startsWithFiltersGroup.count > 0, let filter = info.startsWithFiltersGroup[0].first {
queueName += ".\(filter.lowercased())"
}
queue = DispatchQueue(label: queueName, attributes: [])
if let queue = queue {
Log.info?.message("Starting to track \(info.name)")
let sp = LogReaderManager.fullDateStringFormatter.string(from: startingPoint)
Log.verbose?.message("\(info.name) has queue \(queueName) starting at \(sp)")
queue.async {
self.readFile()
}
}
}
func readFile() {
Log.verbose?.message("reading \(path)")
self.offset = findInitialOffset()
while !stopped {
if fileHandle == nil && fileManager.fileExists(atPath: path) {
fileHandle = FileHandle(forReadingAtPath: path)
let sp = LogReaderManager.fullDateStringFormatter.string(from: startingPoint)
Log.verbose?.message("file exists \(path), offset for \(sp) is \(offset),"
+ " queue: be.michotte.hstracker.readers.\(info.name)")
}
fileHandle?.seek(toFileOffset: offset)
if let data = fileHandle?.readDataToEndOfFile() {
autoreleasepool {
if let linesStr = String(data: data, encoding: .utf8) {
let lines = linesStr
.components(separatedBy: CharacterSet.newlines)
.filter {
!$0.isEmpty && $0.hasPrefix("D ") && $0.characters.count > 20
}
if !lines.isEmpty {
var loglinesBuffer = Array(repeating: [LogLine](), count: _lines.count)
for line in lines {
offset += UInt64((line + "\n")
.lengthOfBytes(using: .utf8))
let cutted = line.substring(from:
line.characters.index(line.startIndex, offsetBy: 19))
if !info.hasFilters {
let logLine = LogLine(namespace: info.name,
line: line)
if logLine.time >= startingPoint {
loglinesBuffer[0].append(logLine)
}
} else {
for i in 0..<info.startsWithFiltersGroup.count {
if (info.startsWithFiltersGroup.count > i
&& info.startsWithFiltersGroup[i].any({
cutted.hasPrefix($0) || cutted.match(RegexPattern(stringLiteral: $0))
}))
|| (info.containsFiltersGroup.count > i &&
info.containsFiltersGroup[i].any({ cutted.contains($0) })) {
let logLine = LogLine(namespace: info.name,
line: line)
if logLine.time >= startingPoint {
loglinesBuffer[i].append(logLine)
}
}
}
}
}
// enqueue all buffers
for i in 0..<loglinesBuffer.count {
_lines[i].enqueueAll(collection: loglinesBuffer[i])
}
}
} else {
Log.warning?.message("Can not read \(path) as utf8, resetting")
fileHandle = nil
}
if !fileManager.fileExists(atPath: path) {
Log.verbose?.message("setting \(path) handle to nil \(offset))")
fileHandle = nil
}
if fileHandle == nil {
offset = 0
}
}
} else {
fileHandle = nil
}
Thread.sleep(forTimeInterval: LogReaderManager.updateDelay)
}
}
func findInitialOffset() -> UInt64 {
guard fileManager.fileExists(atPath: path) else {
return 0
}
return autoreleasepool {
var offset: UInt64 = 0
guard let fileHandle = FileHandle(forReadingAtPath: path) else {
return 0
}
fileHandle.seekToEndOfFile()
let fileLength = fileHandle.offsetInFile
fileHandle.seek(toFileOffset: 0)
while offset < fileLength {
let sizeDiff = 4096 - min(fileLength - offset, UInt64(4096))
offset += 4096
let fileOffset: UInt64 = UInt64(max(Int64(fileLength) - Int64(offset), Int64(0)))
fileHandle.seek(toFileOffset: fileOffset)
let data = fileHandle.readData(ofLength: 4096)
if let string = String(data: data, encoding: .ascii) {
var skip: UInt64 = 0
for i in 0 ... 4096 {
skip += 1
if i >= string.characters.count || string.char(at: i) == "\n" {
break
}
}
offset -= skip
let lines = String(string.characters.dropFirst(Int(skip)))
.components(separatedBy: "\n")
for i in 0 ... (lines.count - 1) {
if lines[i].isBlank {
continue
}
let logLine = LogLine(namespace: info.name, line: lines[i])
if logLine.time < startingPoint {
let negativeOffset = lines.take(i + 1)
.map({ UInt64(($0 + "\n").characters.count) })
.reduce(0, +)
let current = Int64(fileLength) - Int64(offset)
+ Int64(negativeOffset) + Int64(sizeDiff)
return UInt64(max(current, Int64(0)))
}
}
}
}
return 0
}
}
func stop(eraseLogFile: Bool) {
Log.info?.message("Stopping tracker \(info.name)")
fileHandle?.closeFile()
fileHandle = nil
for lines in _lines {
lines.clear()
}
// try to truncate log file when stopping
if fileManager.fileExists(atPath: path) && eraseLogFile {
let file = FileHandle(forWritingAtPath: path)
file?.truncateFile(atOffset: UInt64(0))
file?.closeFile()
offset = 0
}
stopped = true
}
func collect(index: Int) -> [LogLine] {
var items = [LogLine]()
let size = _lines[index].count
if size == 0 {
return items
}
for _ in 0..<size {
if let elem = _lines[index].dequeue() {
items.append(elem)
} else {
break
}
}
return items
}
}
| mit | 74577b505b7d9c8319158e8abb094789 | 37.704626 | 113 | 0.447867 | 5.566018 | false | false | false | false |
kelvin13/noise | sources/noise/noise.swift | 1 | 12572 | public
protocol Noise
{
func evaluate(_ x:Double, _ y:Double) -> Double
func evaluate(_ x:Double, _ y:Double, _ z:Double) -> Double
func evaluate(_ x:Double, _ y:Double, _ z:Double, _ w:Double) -> Double
func amplitude_scaled(by factor:Double) -> Self
func frequency_scaled(by factor:Double) -> Self
func reseeded() -> Self
}
public
extension Noise
{
@available(*, deprecated, message: "area sampling is deprecated, iterate over a Domain2D.Iterator iterator and sample directly instead.")
func sample_area(width:Int, height:Int) -> [(Double, Double, Double)]
{
var samples:[(Double, Double, Double)] = []
samples.reserveCapacity(width * height)
for i in 0 ..< height
{
for j in 0 ..< width
{
let x:Double = Double(j) + 0.5,
y:Double = Double(i) + 0.5
samples.append((x, y, self.evaluate(x, y)))
}
}
return samples
}
@available(*, deprecated, message: "area sampling is deprecated, iterate over a Domain2D.Iterator iterator and sample directly instead.")
func sample_area_saturated_to_u8(width:Int, height:Int, offset:Double = 0.5) -> [UInt8]
{
var samples:[UInt8] = []
samples.reserveCapacity(width * height)
for i in 0 ..< height
{
for j in 0 ..< width
{
let x:Double = Double(j) + 0.5,
y:Double = Double(i) + 0.5
samples.append(UInt8(max(0, min(255, self.evaluate(x, y) + offset))))
}
}
return samples
}
@available(*, deprecated, message: "volume sampling is deprecated, iterate over a Domain3D.Iterator iterator and sample directly instead.")
func sample_volume(width:Int, height:Int, depth:Int) -> [(Double, Double, Double, Double)]
{
var samples:[(Double, Double, Double, Double)] = []
samples.reserveCapacity(width * height * depth)
for i in 0 ..< depth
{
for j in 0 ..< height
{
for k in 0 ..< width
{
let x:Double = Double(k) + 0.5,
y:Double = Double(j) + 0.5,
z:Double = Double(i) + 0.5
samples.append((x, y, z, self.evaluate(x, y, z)))
}
}
}
return samples
}
@available(*, deprecated, message: "volume sampling is deprecated, iterate over a Domain3D.Iterator iterator and sample directly instead.")
func sample_volume_saturated_to_u8(width:Int, height:Int, depth:Int, offset:Double = 0.5) -> [UInt8]
{
var samples:[UInt8] = []
samples.reserveCapacity(width * height * depth)
for i in 0 ..< depth
{
for j in 0 ..< height
{
for k in 0 ..< width
{
let x:Double = Double(k) + 0.5,
y:Double = Double(j) + 0.5,
z:Double = Double(i) + 0.5
samples.append(UInt8(max(0, min(255, self.evaluate(x, y, z) + offset))))
}
}
}
return samples
}
}
enum Math
{
typealias IntV2 = (a:Int, b:Int)
typealias IntV3 = (a:Int, b:Int, c:Int)
typealias DoubleV2 = (x:Double, y:Double)
typealias DoubleV3 = (x:Double, y:Double, z:Double)
@inline(__always)
private static
func fraction(_ x:Double) -> (Int, Double)
{
let integer:Int = x > 0 ? Int(x) : Int(x) - 1
return (integer, x - Double(integer))
}
@inline(__always)
static
func fraction(_ v:DoubleV2) -> (IntV2, DoubleV2)
{
let (i1, f1):(Int, Double) = Math.fraction(v.0),
(i2, f2):(Int, Double) = Math.fraction(v.1)
return ((i1, i2), (f1, f2))
}
@inline(__always)
static
func fraction(_ v:DoubleV3) -> (IntV3, DoubleV3)
{
let (i1, f1):(Int, Double) = Math.fraction(v.0),
(i2, f2):(Int, Double) = Math.fraction(v.1),
(i3, f3):(Int, Double) = Math.fraction(v.2)
return ((i1, i2, i3), (f1, f2, f3))
}
@inline(__always)
static
func add(_ v1:IntV2, _ v2:IntV2) -> IntV2
{
return (v1.a + v2.a, v1.b + v2.b)
}
@inline(__always)
static
func add(_ v1:IntV3, _ v2:IntV3) -> IntV3
{
return (v1.a + v2.a, v1.b + v2.b, v1.c + v2.c)
}
@inline(__always)
static
func add(_ v1:DoubleV2, _ v2:DoubleV2) -> DoubleV2
{
return (v1.x + v2.x, v1.y + v2.y)
}
@inline(__always)
static
func add(_ v1:DoubleV3, _ v2:DoubleV3) -> DoubleV3
{
return (v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)
}
@inline(__always)
static
func sub(_ v1:IntV2, _ v2:IntV2) -> IntV2
{
return (v1.a - v2.a, v1.b - v2.b)
}
@inline(__always)
static
func sub(_ v1:IntV3, _ v2:IntV3) -> IntV3
{
return (v1.a - v2.a, v1.b - v2.b, v1.c - v2.c)
}
@inline(__always)
static
func sub(_ v1:DoubleV2, _ v2:DoubleV2) -> DoubleV2
{
return (v1.x - v2.x, v1.y - v2.y)
}
@inline(__always)
static
func sub(_ v1:DoubleV3, _ v2:DoubleV3) -> DoubleV3
{
return (v1.x - v2.x, v1.y - v2.y, v1.z - v2.z)
}
@inline(__always)
static
func mult(_ v1:IntV2, _ v2:IntV2) -> IntV2
{
return (v1.a * v2.a, v1.b * v2.b)
}
@inline(__always)
static
func mult(_ v1:IntV3, _ v2:IntV3) -> IntV3
{
return (v1.a * v2.a, v1.b * v2.b, v1.c * v2.c)
}
@inline(__always)
static
func mult(_ v1:DoubleV2, _ v2:DoubleV2) -> DoubleV2
{
return (v1.x * v2.x, v1.y * v2.y)
}
@inline(__always)
static
func mult(_ v1:DoubleV3, _ v2:DoubleV3) -> DoubleV3
{
return (v1.x * v2.x, v1.y * v2.y, v1.z * v2.z)
}
@inline(__always)
static
func div(_ v1:DoubleV2, _ v2:DoubleV2) -> DoubleV2
{
return (v1.x / v2.x, v1.y / v2.y)
}
@inline(__always)
static
func div(_ v1:DoubleV3, _ v2:DoubleV3) -> DoubleV3
{
return (v1.x / v2.x, v1.y / v2.y, v1.z / v2.z)
}
@inline(__always)
private static
func mod(_ x:Int, _ n:Int) -> Int
{
let remainder = x % n
return remainder >= 0 ? remainder : remainder + n
}
@inline(__always)
static
func mod(_ v1:IntV2, _ v2:IntV2) -> IntV2
{
return (Math.mod(v1.a, v2.a), Math.mod(v1.b, v2.b))
}
@inline(__always)
static
func mod(_ v1:IntV3, _ v2:IntV3) -> IntV3
{
return (Math.mod(v1.a, v2.a), Math.mod(v1.b, v2.b), Math.mod(v1.c, v2.c))
}
@inline(__always)
static
func dot(_ v1:DoubleV2, _ v2:DoubleV2) -> Double
{
return v1.x * v2.x + v1.y * v2.y
}
@inline(__always)
static
func dot(_ v1:DoubleV3, _ v2:DoubleV3) -> Double
{
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
}
@inline(__always)
static
func cast_double(_ v:IntV2) -> DoubleV2
{
return (Double(v.a), Double(v.b))
}
@inline(__always)
static
func cast_double(_ v:IntV3) -> DoubleV3
{
return (Double(v.a), Double(v.b), Double(v.c))
}
@inline(__always)
static
func lerp(_ a:Double, _ b:Double, factor:Double) -> Double
{
return (1 - factor) * a + factor * b
}
@inline(__always)
static
func quintic_ease(_ x:Double) -> Double
{
// 6x^5 - 15x^4 + 10x^3
return x * x * x * (10.addingProduct(x, (-15).addingProduct(x, 6)))
}
@inline(__always)
static
func quintic_ease(_ v:DoubleV2) -> DoubleV2
{
return (Math.quintic_ease(v.x), Math.quintic_ease(v.y))
}
@inline(__always)
static
func quintic_ease(_ v:DoubleV3) -> DoubleV3
{
return (Math.quintic_ease(v.x), Math.quintic_ease(v.y), Math.quintic_ease(v.z))
}
}
/// UNDOCUMENTED
public
struct Domain2D:Sequence
{
private
let sample_lower_bound:Math.DoubleV2,
sample_upper_bound:Math.DoubleV2,
increment:Math.DoubleV2
public
struct Iterator:IteratorProtocol
{
private
var sample:Math.DoubleV2
private
let domain:Domain2D
init(_ domain:Domain2D)
{
self.sample = Math.add(domain.sample_lower_bound, (-0.5, 0.5))
self.domain = domain
}
public mutating
func next() -> (Double, Double)?
{
self.sample.x += 1
if self.sample.x >= self.domain.sample_upper_bound.x
{
self.sample.x = self.domain.sample_lower_bound.x + 0.5
self.sample.y += 1
if self.sample.y >= self.domain.sample_upper_bound.y
{
return nil
}
}
return Math.mult(self.domain.increment, self.sample)
}
}
public
init(samples_x:Int, samples_y:Int)
{
self.increment = (1, 1)
self.sample_lower_bound = (0, 0)
self.sample_upper_bound = Math.cast_double((samples_x, samples_y))
}
public
init(_ x_range:ClosedRange<Double>, _ y_range:ClosedRange<Double>, samples_x:Int, samples_y:Int)
{
let sample_count:Math.DoubleV2 = Math.cast_double((samples_x, samples_y)),
range_lower_bound:Math.DoubleV2 = (x_range.lowerBound, y_range.lowerBound),
range_upper_bound:Math.DoubleV2 = (x_range.upperBound, y_range.upperBound),
range_difference:Math.DoubleV2 = Math.sub(range_upper_bound, range_lower_bound)
self.increment = Math.div(range_difference, sample_count)
self.sample_lower_bound = Math.div(Math.mult(range_lower_bound, sample_count), range_difference)
self.sample_upper_bound = Math.add(self.sample_lower_bound, sample_count)
}
public
func makeIterator() -> Iterator
{
return Iterator(self)
}
}
/// UNDOCUMENTED
public
struct Domain3D:Sequence
{
private
let sample_lower_bound:Math.DoubleV3,
sample_upper_bound:Math.DoubleV3,
increment:Math.DoubleV3
public
struct Iterator:IteratorProtocol
{
private
var sample:Math.DoubleV3
private
let domain:Domain3D
init(_ domain:Domain3D)
{
self.sample = Math.add(domain.sample_lower_bound, (-0.5, 0.5, 0.5))
self.domain = domain
}
public mutating
func next() -> (Double, Double, Double)?
{
self.sample.x += 1
if self.sample.x >= self.domain.sample_upper_bound.x
{
self.sample.x = self.domain.sample_lower_bound.x + 0.5
self.sample.y += 1
if self.sample.y >= self.domain.sample_upper_bound.y
{
self.sample.y = self.domain.sample_lower_bound.y + 0.5
self.sample.z += 1
if self.sample.z >= self.domain.sample_upper_bound.z
{
return nil
}
}
}
return Math.mult(self.domain.increment, self.sample)
}
}
public
init(samples_x:Int, samples_y:Int, samples_z:Int)
{
self.increment = (1, 1, 1)
self.sample_lower_bound = (0, 0, 0)
self.sample_upper_bound = Math.cast_double((samples_x, samples_y, samples_z))
}
public
init(_ x_range:ClosedRange<Double>, _ y_range:ClosedRange<Double>, _ z_range:ClosedRange<Double>,
samples_x:Int, samples_y:Int, samples_z:Int)
{
let sample_count:Math.DoubleV3 = Math.cast_double((samples_x, samples_y, samples_z)),
range_lower_bound:Math.DoubleV3 = (x_range.lowerBound, y_range.lowerBound, z_range.lowerBound),
range_upper_bound:Math.DoubleV3 = (x_range.upperBound, y_range.upperBound, z_range.upperBound),
range_difference:Math.DoubleV3 = Math.sub(range_upper_bound, range_lower_bound)
self.increment = Math.div(range_difference, sample_count)
self.sample_lower_bound = Math.div(Math.mult(range_lower_bound, sample_count), range_difference)
self.sample_upper_bound = Math.add(self.sample_lower_bound, sample_count)
}
public
func makeIterator() -> Iterator
{
return Iterator(self)
}
}
| gpl-3.0 | 44c62da58904a10b373296bbc6db5263 | 27.768879 | 143 | 0.52943 | 3.270552 | false | false | false | false |
zhugejunwei/Algorithms-in-Java-Swift-CPP | Dijkstra & Floyd/Carthage/Checkouts/Charts/Charts/Classes/Charts/PieChartView.swift | 3 | 14304 | //
// PieChartView.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
/// View that represents a pie chart. Draws cake like slices.
public class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHightlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if (_dataNotSet)
{
return
}
let radius = diameter / 2.0
let c = centerOffsets
let dataSets = data?.dataSets as? [PieChartDataSet]
let maxShift = dataSets?.reduce(0.0, combine: { shift, dataSet in
return dataSet.selectionShift > shift ? dataSet.selectionShift : shift
}) ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = (c.x - radius) + (maxShift / 2.0)
_circleBox.origin.y = (c.y - radius) + (maxShift / 2.0)
_circleBox.size.width = diameter - maxShift
_circleBox.size.height = diameter - maxShift
}
internal override func calcMinMax()
{
super.calcMinMax()
calcAngles()
}
public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let center = self.centerCircleBox
var r = self.radius
var off = r / 10.0 * 3.6
if self.isDrawHoleEnabled
{
off = (r - (r * self.holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let i = e.xIndex
// offset needed to center the drawn text in the slice
let offset = drawAngles[i] / 2.0
// calculate the text position
let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x)
let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y)
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
_drawAngles.reserveCapacity(_data.yValCount)
_absoluteAngles.reserveCapacity(_data.yValCount)
var dataSets = _data.dataSets
var cnt = 0
for (var i = 0; i < _data.dataSetCount; i++)
{
let set = dataSets[i]
var entries = set.yVals
for (var j = 0; j < entries.count; j++)
{
_drawAngles.append(calcAngle(abs(entries[j].value)))
if (cnt == 0)
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt++
}
}
}
/// checks if the given index in the given DataSet is set for highlighting or not
public func needsHighlight(xIndex xIndex: Int, dataSetIndex: Int) -> Bool
{
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
{
return false
}
for (var i = 0; i < _indicesToHightlight.count; i++)
{
// check if the xvalue for the given dataset needs highlight
if (_indicesToHightlight[i].xIndex == xIndex
&& _indicesToHightlight[i].dataSetIndex == dataSetIndex)
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for (var i = 0; i < _absoluteAngles.count; i++)
{
if (_absoluteAngles[i] > a)
{
return i
}
}
return -1; // return -1 if no index found
}
/// - returns: the index of the DataSet this x-index belongs to.
public func dataSetIndexForIndex(xIndex: Int) -> Int
{
var dataSets = _data.dataSets
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].entryForXIndex(xIndex) !== nil)
{
return i
}
}
return -1
}
/// - returns: an integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
public var drawAngles: [CGFloat]
{
return _drawAngles
}
/// - returns: the absolute angles of the different chart slices (where the
/// slices end)
public var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// Sets the color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// *Note: Use holeTransparent with holeColor = nil to make the hole transparent.*
public var holeColor: UIColor?
{
get
{
return (renderer as! PieChartRenderer).holeColor!
}
set
{
(renderer as! PieChartRenderer).holeColor = newValue
setNeedsDisplay()
}
}
/// Set the hole in the center of the PieChart transparent
public var holeTransparent: Bool
{
get
{
return (renderer as! PieChartRenderer).holeTransparent
}
set
{
(renderer as! PieChartRenderer).holeTransparent = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the PieChart is transparent, false if not.
public var isHoleTransparent: Bool
{
return (renderer as! PieChartRenderer).holeTransparent
}
/// true if the hole in the center of the pie-chart is set to be visible, false if not
public var drawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
set
{
(renderer as! PieChartRenderer).drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not
public var isDrawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart. By default, the text is "Total value + sum of all values"
public var centerText: String!
{
get
{
return (renderer as! PieChartRenderer).centerText
}
set
{
(renderer as! PieChartRenderer).centerText = newValue
setNeedsDisplay()
}
}
/// true if drawing the center text is enabled
public var drawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
set
{
(renderer as! PieChartRenderer).drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing the center text is enabled
public var isDrawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
public override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// - returns: the circlebox, the boundingbox of the pie-chart slices
public var circleBox: CGRect
{
return _circleBox
}
/// - returns: the center of the circlebox
public var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// Sets the font of the center text of the piechart.
public var centerTextFont: UIFont
{
get
{
return (renderer as! PieChartRenderer).centerTextFont
}
set
{
(renderer as! PieChartRenderer).centerTextFont = newValue
setNeedsDisplay()
}
}
/// Sets the color of the center text of the piechart.
public var centerTextColor: UIColor
{
get
{
return (renderer as! PieChartRenderer).centerTextColor
}
set
{
(renderer as! PieChartRenderer).centerTextColor = newValue
setNeedsDisplay()
}
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
public var holeRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).holeRadiusPercent
}
set
{
(renderer as! PieChartRenderer).holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
public var transparentCircleRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).transparentCircleRadiusPercent
}
set
{
(renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// set this to true to draw the x-value text into the pie slices
public var drawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
set
{
(renderer as! PieChartRenderer).drawXLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isDrawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
public var usePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
set
{
(renderer as! PieChartRenderer).usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isUsePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
}
/// the line break mode for center text.
/// note that different line break modes give different performance results - Clipping being the fastest, WordWrapping being the slowst.
public var centerTextLineBreakMode: NSLineBreakMode
{
get
{
return (renderer as! PieChartRenderer).centerTextLineBreakMode
}
set
{
(renderer as! PieChartRenderer).centerTextLineBreakMode = newValue
setNeedsDisplay()
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
public var centerTextRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).centerTextRadiusPercent
}
set
{
(renderer as! PieChartRenderer).centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
} | mit | 9adee36e4784f35db912504196d320e2 | 27.324752 | 189 | 0.567783 | 5.07919 | false | false | false | false |
blinkinput/blinkinput-ios | Samples/DeepOCR-sample-Swift/DeepOCR-sample-Swift/CustomOverlay.swift | 2 | 2336 | //
// CustomOverlay.swift
// pdf417-sample-Swift
//
// Created by Dino Gustin on 06/03/2018.
// Copyright © 2018 Dino. All rights reserved.
//
import BlinkInput
protocol MBICustomOverlayDelegate {
func customOverlayViewControllerDidFinishScannig(_ customOverlay: CustomOverlay, state: MBIRecognizerResultState)
}
class CustomOverlay: MBICustomOverlayViewController {
var delegate: MBICustomOverlayDelegate?
@IBOutlet var viewFinder: UIView!
@IBOutlet var resultTextView: UITextView!
var dotsSubview: MBIDotsResultSubview?
static func initFromStoryboardWith(_ delegate: MBICustomOverlayDelegate) -> CustomOverlay {
let customOverlay: CustomOverlay = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "CustomOverlay") as! CustomOverlay
customOverlay.delegate = delegate
return customOverlay
}
override func viewDidLoad() {
self.scanningRecognizerRunnerViewControllerDelegate = self;
self.metadataDelegates.detectionRecognizerRunnerViewControllerDelegate = self;
self.dotsSubview = MBIDotsResultSubview(frame: self.viewFinder.bounds)
self.dotsSubview?.shouldIgnoreFastResults = true
self.viewFinder.addSubview(self.dotsSubview!)
}
@IBAction func didTapClose(_ sender: Any) {
self.recognizerRunnerViewController?.overlayViewControllerWillCloseCamera(self);
self.dismiss(animated: true, completion: nil); }
}
extension CustomOverlay: MBIScanningRecognizerRunnerViewControllerDelegate {
func recognizerRunnerViewControllerDidFinishScanning(_ recognizerRunnerViewController: UIViewController & MBIRecognizerRunnerViewController, state: MBIRecognizerResultState) {
self.delegate?.customOverlayViewControllerDidFinishScannig(self, state: state)
}
}
extension CustomOverlay: MBIDetectionRecognizerRunnerViewControllerDelegate {
func recognizerRunnerViewController(_ recognizerRunnerViewController: UIViewController & MBIRecognizerRunnerViewController, didFinishDetectionWithDisplayablePoints displayablePoints: MBIDisplayablePointsDetection) {
DispatchQueue.main.async(execute: {() -> Void in
self.dotsSubview?.detectionFinished(withDisplayablePoints: displayablePoints)
})
}
}
| apache-2.0 | 092be5a721b1b382371c0d6e541a3135 | 37.916667 | 219 | 0.763597 | 5 | false | false | false | false |
Buratti/VaporPayPal | Sources/VaporPayPalAmount.swift | 1 | 1579 | //
// VaporPayPalAmount.swift
// VaporAuthTemplate
//
// Created by Alessio Buratti on 04/03/2017.
//
//
import Foundation
import JSON
/// Describes an amount
public final class VaporPayPalAmount {
/// The PayPal REST API supported currencies. [Source](https://developer.paypal.com/docs/integration/direct/rest-api-payment-country-currency-support/)
public enum Currency: String {
case aud = "AUD"
case brl = "BRL"
case cad = "CAD"
case czk = "CZK"
case dkk = "DKK"
case eur = "EUR"
case hkd = "HKD"
case huf = "HUF"
case ils = "ILS"
case jpy = "JPY"
case myr = "MYR"
case mxn = "MXN"
case twd = "TWD"
case nzd = "NZD"
case nok = "NOK"
case php = "PHP"
case pln = "PLN"
case gbp = "GBP"
case rub = "RUB"
case sgd = "SGD"
case sek = "SEK"
case chf = "CHF"
case thb = "THB"
case usd = "USD"
}
/// The total amount
public var total: Double
/// The selected currency
public var currency: Currency
/// Create an amount
public init(_ total: Double, _ currency: Currency) {
self.total = total
self.currency = currency
}
}
extension VaporPayPalAmount: JSONRepresentable {
public func makeJSON() throws -> JSON {
guard total > 0 else { throw VaporPayPalError.invalidAmount }
return JSON(["total": total.makeNode(),
"currency": currency.rawValue.makeNode()])
}
}
| mit | f8411a7dbef0294366760d327e7fa334 | 23.671875 | 155 | 0.554782 | 3.795673 | false | false | false | false |
naoyashiga/LegendTV | LegendTV/Random.swift | 1 | 1114 | //
// Random.swift
// LegendTV
//
// Created by naoyashiga on 2015/08/13.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
import Darwin
extension Int {
static func random() -> Int {
return Int(arc4random())
}
static func random(range: Range<Int>) -> Int {
return Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex
}
}
extension Double {
static func random() -> Double {
return drand48()
}
}
extension Array {
/**
* Shuffles the array elements.
*/
mutating func shuffle() {
if count > 1 {
let iLast = count - 1
for i in 0..<iLast {
let iRandom = Int.random(i...iLast)
let temp = self[i]
self[i] = self[iRandom]
self[iRandom] = temp
}
}
}
/**
* Returns a copy of the array with the elements shuffled.
*/
func shuffled() -> [Element] {
var newArray = [Element](self)
newArray.shuffle()
return newArray
}
} | mit | 1c01042a49840d3e43a2ed0a6a4e72e9 | 20.403846 | 100 | 0.538669 | 4 | false | false | false | false |
ripplek/KKPhotoBrowser | PhotoBrowser/PhotoCell.swift | 1 | 5940 | //
// PhotoCell.swift
// PhotoBrowser
//
// Created by 张坤 on 2017/6/15.
// Copyright © 2017年 zhangkun. All rights reserved.
//
import UIKit
import SnapKit
import Kingfisher
/// 图像 Cell 布局
struct PhotoCellLayout {
var viewWidth: Float {
return Float(UIScreen.main.bounds.size.width) - Float((count-1)) * margin
}
var itemSize: CGSize {
let itemWidth: CGFloat = CGFloat((viewWidth - Float((count-1)) * itemMargin) / Float(count))
return CGSize(width: itemWidth, height: itemWidth)
}
let margin: Float
let itemMargin: Float
let count: Int
}
protocol PhotoCellDelegate {
func didSelectedImageIndex(cell: PhotoCell, index: Int)
}
class PhotoCell: UITableViewCell {
var delegate: PhotoCellDelegate?
var photos_urls: Array<String>! {
didSet {
updateCell()
}
}
func visibaleImageViews() -> [UIImageView] {
var arrayM = Array<UIImageView>()
for iv in pictureView.subviews {
if !iv.isHidden {
arrayM.append(iv as! UIImageView)
}
}
return arrayM
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
prepareUI()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func updateCell() {
let pictureViewSize = pictureViewSizeWith(count: photos_urls.count)
pictureView.snp.updateConstraints { (make) in
make.height.equalTo(pictureViewSize.height)
}
for iv in pictureView.subviews {
iv.isHidden = true
}
var index = 0
for urlString in photos_urls {
let imageV = pictureView.subviews[index] as! UIImageView
let url = URL(string: urlString)
imageV.kf.setImage(with: url) { (result) in
switch result {
case .success(let res):
// 单图等比例缩放
if index == 0, self.photos_urls.count == 1 {
let height = pictureViewSize.height
let width = res.image.size.width * height / res.image.size.height
imageV.frame = CGRect(x: 0, y: 0, width: width, height: height)
} else if index == 0 {
imageV.frame = CGRect(x: 0, y: 0, width: self.layout.itemSize.width, height: self.layout.itemSize.width)
}
case .failure(let error):
print(error)
}
}
imageV.isHidden = false
index+=1
if index == 2 && photos_urls.count == 4 {
index+=1
}
}
}
@objc private func tapImageView(recognizer: UITapGestureRecognizer) {
var index = recognizer.view!.tag
if photos_urls.count == 4 && index > 2 {
index-=1
}
self.delegate?.didSelectedImageIndex(cell: self, index: index)
}
private func pictureViewSizeWith(count: Int) -> CGSize {
if count == 0 {
return CGSize.zero
}
let row = Int((count-1) / layout.count) + 1
let height = CGFloat(row-1) * CGFloat(layout.itemMargin) + CGFloat(row) * layout.itemSize.width
return CGSize(width: layout.itemSize.width, height: height)
}
/// 设置界面
private func prepareUI() {
backgroundColor = UIColor(white: 0.93, alpha: 1)
contentView.addSubview(pictureView)
pictureView.snp.makeConstraints { (make) in
make.top.equalTo(layout.margin)
make.leading.equalTo(layout.margin)
make.width.equalTo(layout.viewWidth)
make.height.equalTo(layout.viewWidth)
}
contentView.snp.makeConstraints { (make) in
make.top.leading.trailing.equalToSuperview()
make.bottom.equalTo(pictureView).offset(layout.margin)
}
pictureView.backgroundColor = backgroundColor
prepareImageViews()
}
private func prepareImageViews() {
pictureView.clipsToBounds = true
let count = layout.count * layout.count
let rect = CGRect(x: 0, y: 0, width: layout.itemSize.width, height: layout.itemSize.height)
let step = layout.itemSize.width + CGFloat(layout.itemMargin)
for i in 0..<count {
// 添加图像视图
let imageV = UIImageView()
imageV.frame = rect
imageV.contentMode = .scaleAspectFill
imageV.clipsToBounds = true
pictureView.addSubview(imageV)
// 计算图像位置
let col = Int(i % layout.count)
let row = Int(i / layout.count)
imageV.frame = rect.offsetBy(dx: CGFloat(col)*step, dy: CGFloat(row)*step)
imageV.backgroundColor = UIColor.lightGray
// 添加手势
imageV.tag = i
imageV.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView(recognizer:)))
imageV.addGestureRecognizer(tap)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
private let pictureView: UIView = UIView()
private let layout: PhotoCellLayout = PhotoCellLayout(margin: 12, itemMargin: 2, count: 3)
}
| mit | c6a9f3b615e01053249b17b59d6b7a83 | 30.395722 | 128 | 0.562085 | 4.75 | false | false | false | false |
cooliean/CLLKit | XLForm/Examples/Swift/SwiftExample/CustomRows/FloatLabeledTextField/FloatLabeledTextFieldCell.swift | 14 | 5642 | // FloatLabeledTextFieldCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( 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.
//
let XLFormRowDescriptorTypeFloatLabeledTextField = "XLFormRowDescriptorTypeFloatLabeledTextField"
class FloatLabeledTextFieldCell : XLFormBaseCell, UITextFieldDelegate {
static let kFontSize : CGFloat = 16.0
lazy var floatLabeledTextField: JVFloatLabeledTextField = {
let result = JVFloatLabeledTextField(frame: CGRect.zero)
result.translatesAutoresizingMaskIntoConstraints = false
result.font = UIFont.systemFontOfSize(kFontSize)
result.floatingLabel.font = .boldSystemFontOfSize(kFontSize)
result.clearButtonMode = .WhileEditing
return result
}()
//Mark: - XLFormDescriptorCell
override func configure() {
super.configure()
selectionStyle = .None
contentView.addSubview(self.floatLabeledTextField)
floatLabeledTextField.delegate = self
contentView.addConstraints(layoutConstraints())
}
override func update() {
super.update()
if let rowDescriptor = rowDescriptor {
floatLabeledTextField.attributedPlaceholder = NSAttributedString(string: rowDescriptor.title ?? "" , attributes: [NSForegroundColorAttributeName: UIColor.lightGrayColor()])
if let value = rowDescriptor.value {
floatLabeledTextField.text = value.displayText()
}
else {
floatLabeledTextField.text = rowDescriptor.noValueDisplayText
}
floatLabeledTextField.enabled = !rowDescriptor.isDisabled()
floatLabeledTextField.floatingLabelTextColor = .lightGrayColor()
floatLabeledTextField.alpha = rowDescriptor.isDisabled() ? 0.6 : 1.0
}
}
override func formDescriptorCellCanBecomeFirstResponder() -> Bool {
return rowDescriptor?.isDisabled() == false
}
override func formDescriptorCellBecomeFirstResponder() -> Bool {
return self.floatLabeledTextField.becomeFirstResponder()
}
override static func formDescriptorCellHeightForRowDescriptor(rowDescriptor: XLFormRowDescriptor!) -> CGFloat {
return 55.0
}
//MARK: Helpers
func layoutConstraints() -> [NSLayoutConstraint]{
let views = ["floatLabeledTextField" : floatLabeledTextField]
let metrics = ["hMargin": 15.0, "vMargin": 8.0]
var result = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(hMargin)-[floatLabeledTextField]-(hMargin)-|", options:.AlignAllCenterY, metrics:metrics, views:views)
result += NSLayoutConstraint.constraintsWithVisualFormat("V:|-(vMargin)-[floatLabeledTextField]-(vMargin)-|", options:.AlignAllCenterX, metrics:metrics, views:views)
return result
}
func textFieldDidChange(textField : UITextField) {
if floatLabeledTextField == textField {
if let rowDescriptor = rowDescriptor, let text = self.floatLabeledTextField.text {
if text.isEmpty == false {
rowDescriptor.value = self.floatLabeledTextField.text
} else {
rowDescriptor.value = nil
}
}
}
}
//Mark: UITextFieldDelegate
func textFieldShouldClear(textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldClear(textField)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldReturn(textField)
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldBeginEditing(textField)
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
return self.formViewController().textFieldShouldEndEditing(textField)
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
return self.formViewController().textField(textField, shouldChangeCharactersInRange: range, replacementString: string)
}
func textFieldDidBeginEditing(textField: UITextField) {
self.formViewController().textFieldDidBeginEditing(textField)
}
func textFieldDidEndEditing(textField: UITextField) {
self.textFieldDidChange(textField)
self.formViewController().textFieldDidEndEditing(textField)
}
}
| mit | 92030f7f4c7c1179cae314611054d4e6 | 39.3 | 184 | 0.700461 | 5.822497 | false | false | false | false |
MaddTheSane/Nuke | Nuke.playground/Pages/Introduction.xcplaygroundpage/Contents.swift | 1 | 1856 | import Nuke
import UIKit
import XCPlayground
/*:
## Why use Nuke?
Nuke is an advanced pure Swift framework for loading, caching, processing, displaying and preheating images. It takes care of all those things so you don't have to.
Nuke's goal is to provide the simplest possible interface and implementation that solves those complex tasks. Without compromising extensibility.
*/
/*:
### Zero Config
Create and resume `ImageTask` with `NSURL`.
*/
Nuke.taskWithURL(NSURL(string: "https://farm8.staticflickr.com/7315/16455839655_7d6deb1ebf_z_d.jpg")!) {
let image = $0.image
}.resume()
/*:
### Adding Request Options
Create `ImageRequest` with `NSURLRequest`. Configure `ImageRequest` to resize image. Create and resume `ImageTask`.
*/
let URLRequest = NSURLRequest(URL: NSURL(string: "https://farm4.staticflickr.com/3892/14940786229_5b2b48e96c_z_d.jpg")!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 60)
var request = ImageRequest(URLRequest: URLRequest)
// Set target size in pixels
request.targetSize = CGSize(width: 200.0, height: 200.0)
request.contentMode = .AspectFill
Nuke.taskWithRequest(request) {
let image = $0.image
}.resume()
/*:
### Using Image Response
`ImageResponse` is an enum with associated values. If the request is successful `ImageResponse` contains image and some metadata about the response. If request fails `ImageResponse` returns an error.
*/
Nuke.taskWithURL(NSURL(string: "https://farm8.staticflickr.com/7315/16455839655_7d6deb1ebf_z_d.jpg")!) { response in
switch response {
case let .Success(image, info):
if info.fastResponse {
// Image was retrieved synchronously from memory cache
}
let image = image
case let .Failure(error):
// Handle error
break
}
}.resume()
XCPSetExecutionShouldContinueIndefinitely()
//: [Next](@next)
| mit | e3b95e4dbce517e1815866f7adc840ad | 32.745455 | 199 | 0.73222 | 3.882845 | false | false | false | false |
soso1617/iCalendar | Calendar/DataModel/ModelManager/DayMananger.swift | 1 | 4427 | //
// DayMananger.swift
// Calendar
//
// Created by Zhang, Eric X. on 4/30/17.
// Copyright © 2017 ShangHe. All rights reserved.
//
import Foundation
/*********************************************************************
*
* class DayManager -- Singleton
* This class is responsible for controlling the core data model: Day
*
*********************************************************************/
class DayManager {
// MARK: Singleton init
//
// singleton instance
//
static let sharedManager = DayManager()
//
// prevent be init from others
//
private init() {
}
/**
Create Day by Day data dict, will check core data if this object already exsit
- Parameter dict: Day data, must contain primary key value
- Returns: Day obj
*/
func createDayBy(dict: [String : Any]) -> Day? {
var retDay: Day? = nil
//
// make sure the primary key exists
//
if let primaryValue = dict[DayProperties.primaryKey] as? Int32
{
//
// try to fetch the day obj if exist
//
if let day = self.fetchDayByKeyValue(primaryValue)
{
retDay = day
//
// set properties value if it's contained in dict
//
if let valueInWeek = dict[DayProperties.valueInWeek] as? Int16
{
retDay?.valueInWeek = valueInWeek
}
if let valueInMonth = dict[DayProperties.valueInMonth] as? Int16
{
retDay?.valueInMonth = valueInMonth
}
if let nameInWeek = dict[DayProperties.nameInWeek] as? String
{
retDay?.nameInWeek = nameInWeek
}
if let date = dict[DayProperties.date] as? NSDate
{
retDay?.date = date
}
}
else
{
retDay = CalendarModelManager.sharedManager.createObj(entityName: EntityName.day) as? Day
//
// set property value if it's contained in dict
//
retDay?.id = Int32(primaryValue)
if let valueInWeek = dict[DayProperties.valueInWeek] as? Int16
{
retDay?.valueInWeek = valueInWeek
}
if let valueInMonth = dict[DayProperties.valueInMonth] as? Int16
{
retDay?.valueInMonth = valueInMonth
}
if let nameInWeek = dict[DayProperties.nameInWeek] as? String
{
retDay?.nameInWeek = nameInWeek
}
if let date = dict[DayProperties.date] as? NSDate
{
retDay?.date = date
}
}
}
return retDay
}
/**
Fetch Day by Day id
- Parameter value: Day id
- Returns: Specified Day obj
*/
func fetchDayByKeyValue(_ value: Int32) -> Day? {
var retDay: Day? = nil
let predicate = NSPredicate.init(format: "%K = %ld", DayProperties.primaryKey, value)
if let fetchedResult = CalendarModelManager.sharedManager.fetchObj(entityName: EntityName.day, predicate: predicate) as? Array<Day>, fetchedResult.count > 0
{
retDay = fetchedResult.last
}
return retDay
}
/**
Fetch today's Day obj
- Returns: Today Day obj
*/
func today() -> Day? {
let calendar = Calendar.init(identifier: .gregorian)
let dateComponents = calendar.dateComponents([.day, .month, .year], from: Date())
if let today = self.fetchDayByKeyValue(dayId(year: dateComponents.year!, month: dateComponents.month!, day: dateComponents.day!))
{
//
// set is-today
//
today.isToday = true
return today
}
return nil
}
}
| mit | 03ffcdc012b589438184d45aad37de96 | 26.320988 | 164 | 0.456846 | 5.170561 | false | false | false | false |
Knyazik/Dark-Chat | Dark Chat/LoginViewController.swift | 1 | 3635 | //
// LoginViewController.swift
// Dark Chat
//
// Created by elusive on 8/27/17.
// Copyright © 2017 Knyazik. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var bottomLayoutGuideConstraint: NSLayoutConstraint!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
hideKeyboard()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow(_:)),
name: .UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide(_:)),
name: .UIKeyboardWillHide,
object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self,
name: .UIKeyboardWillShow,
object: nil)
NotificationCenter.default.removeObserver(self,
name: .UIKeyboardWillHide,
object: nil)
}
// MARK: - Private
private func setup() {
loginButton.layer.cornerRadius = 3.0
}
// MARK: - Actions
@IBAction func loginDidTouch(_ sender: AnyObject) {
guard
let name = nameTextField.text
else {
UIUtils.showAlert("Error", message: "Please enter your name")
return
}
if !name.isEmpty {
Auth.auth().signInAnonymously(completion: { (user, error) in
if let error = error {
print(error.localizedDescription)
return
}
self.performSegue(withIdentifier: "LoginToChat", sender: nil)
})
} else {
UIUtils.showAlert("Error", message: "Please enter your name")
}
}
// MARK: - Notifications
func keyboardWillShow(_ notification: Notification) {
let keyboardEndFrame = ((notification as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let convertedKeyboardEndFrame = view.convert(keyboardEndFrame, from: view.window)
bottomLayoutGuideConstraint
.constant = view.bounds.maxY - convertedKeyboardEndFrame.minY + 10
layoutView()
}
func keyboardWillHide(_ notification: Notification) {
bottomLayoutGuideConstraint.constant = 48
layoutView()
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard
let navVC = segue.destination as? UINavigationController,
let channelVC = navVC.viewControllers.first as? ChannelListViewController
else {
return
}
channelVC.senderDisplayName = nameTextField?.text
}
}
| mit | 2b09fc4e466e9aae46071f799040003d | 30.877193 | 130 | 0.531921 | 6.233276 | false | false | false | false |
malonguwa/PostHelper | PostHelper/PostHelper/Home/HAHomeTableController.swift | 1 | 2117 | //
// HAHomeTableController.swift
// PostHelper
//
// Created by LONG MA on 21/11/16.
// Copyright © 2016 HnA. All rights reserved.
//
import UIKit
import FacebookLogin
class HAHomeTableController: UITableViewController {
private var flag = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
self.performSegue(withIdentifier: "homeToPost", sender: nil)
// let loginManager = LoginManager()
// loginManager.logIn([.publishActions], viewController: self) { loginResult in
// switch loginResult {
// case .failed(let error):
// print(error)
// case .cancelled:
// print("User cancelled login.")
// case .success(let grantedPermissions, let declinedPermissions, let accessToken):
//
// print("Logged in with publish permisson!, \n grantedPermissions: \(grantedPermissions), \n declinedPermissions: \(declinedPermissions),\n accessToken: \(accessToken)")
//
// self.flag = 1
//// guard let navi = self.navigationController else{
//// return
//// }
//
//
// self.performSegue(withIdentifier: "homeToPost", sender: nil)
//
// }
// }
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
return flag == 1 ? true : false
}
}
| apache-2.0 | 2f3d9851ac474004a26b0d0cb94126d4 | 32.587302 | 189 | 0.575142 | 5.014218 | false | false | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/Library/BookmarkDetailPanel.swift | 1 | 16730 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
private let BookmarkDetailFieldCellIdentifier = "BookmarkDetailFieldCellIdentifier"
private let BookmarkDetailFolderCellIdentifier = "BookmarkDetailFolderCellIdentifier"
private struct BookmarkDetailPanelUX {
static let FieldRowHeight: CGFloat = 58
static let FolderIconSize = CGSize(width: 20, height: 20)
static let IndentationWidth: CGFloat = 20
static let MinIndentedContentWidth: CGFloat = 100
}
class BookmarkDetailPanelError: MaybeErrorType {
public var description = "Unable to save BookmarkNode."
}
class BookmarkDetailPanel: SiteTableViewController {
enum BookmarkDetailSection: Int, CaseIterable {
case fields
case folder
}
enum BookmarkDetailFieldsRow: Int {
case title
case url
}
// Non-editable field(s) that all BookmarkNodes have.
let bookmarkNodeGUID: GUID? // `nil` when creating new.
let bookmarkNodeType: BookmarkNodeType
// Editable field(s) that all BookmarkNodes have.
var parentBookmarkFolder: BookmarkFolder
// Sort position for the BookmarkItem. If editing, this
// value remains the same as it was prior to the edit
// unless the parent folder gets changed. In that case,
// and in the case of adding a new BookmarkItem, this
// value becomes `nil` which causes it to be re-positioned
// to the bottom of the parent folder upon saving.
var bookmarkItemPosition: UInt32?
// Editable field(s) that only BookmarkItems and
// BookmarkFolders have.
var bookmarkItemOrFolderTitle: String?
// Editable field(s) that only BookmarkItems have.
var bookmarkItemURL: String?
var isNew: Bool {
return bookmarkNodeGUID == nil
}
var isFolderListExpanded = false
// Array of tuples containing all of the BookmarkFolders
// along with their indentation depth.
var bookmarkFolders: [(folder: BookmarkFolder, indent: Int)] = []
private var maxIndentationLevel: Int {
return Int(floor((view.frame.width - BookmarkDetailPanelUX.MinIndentedContentWidth) / BookmarkDetailPanelUX.IndentationWidth))
}
convenience init(profile: Profile, bookmarkNode: BookmarkNode, parentBookmarkFolder: BookmarkFolder) {
self.init(profile: profile, bookmarkNodeGUID: bookmarkNode.guid, bookmarkNodeType: bookmarkNode.type, parentBookmarkFolder: parentBookmarkFolder)
self.bookmarkItemPosition = bookmarkNode.position
if let bookmarkItem = bookmarkNode as? BookmarkItem {
self.bookmarkItemOrFolderTitle = bookmarkItem.title
self.bookmarkItemURL = bookmarkItem.url
self.title = Strings.BookmarksEditBookmark
} else if let bookmarkFolder = bookmarkNode as? BookmarkFolder {
self.bookmarkItemOrFolderTitle = bookmarkFolder.title
self.title = Strings.BookmarksEditFolder
}
}
convenience init(profile: Profile, withNewBookmarkNodeType bookmarkNodeType: BookmarkNodeType, parentBookmarkFolder: BookmarkFolder) {
self.init(profile: profile, bookmarkNodeGUID: nil, bookmarkNodeType: bookmarkNodeType, parentBookmarkFolder: parentBookmarkFolder)
if bookmarkNodeType == .bookmark {
self.bookmarkItemOrFolderTitle = ""
self.bookmarkItemURL = ""
self.title = Strings.BookmarksNewBookmark
} else if bookmarkNodeType == .folder {
self.bookmarkItemOrFolderTitle = ""
self.title = Strings.BookmarksNewFolder
}
}
private init(profile: Profile, bookmarkNodeGUID: GUID?, bookmarkNodeType: BookmarkNodeType, parentBookmarkFolder: BookmarkFolder) {
self.bookmarkNodeGUID = bookmarkNodeGUID
self.bookmarkNodeType = bookmarkNodeType
self.parentBookmarkFolder = parentBookmarkFolder
super.init(profile: profile)
self.tableView.accessibilityIdentifier = "Bookmark Detail"
self.tableView.keyboardDismissMode = .onDrag
self.tableView.register(TextFieldTableViewCell.self, forCellReuseIdentifier: BookmarkDetailFieldCellIdentifier)
self.tableView.register(OneLineTableViewCell.self, forCellReuseIdentifier: BookmarkDetailFolderCellIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel) { _ in
self.navigationController?.popViewController(animated: true)
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save) { _ in
self.save().uponQueue(.main) { _ in
self.navigationController?.popViewController(animated: true)
if self.isNew, let bookmarksPanel = self.navigationController?.visibleViewController as? BookmarksPanel {
bookmarksPanel.didAddBookmarkNode()
}
}
}
if isNew, bookmarkNodeType == .bookmark {
bookmarkItemURL = "https://"
}
updateSaveButton()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Focus the keyboard on the first text field.
if let firstTextFieldCell = tableView.visibleCells.first(where: { $0 is TextFieldTableViewCell }) as? TextFieldTableViewCell {
firstTextFieldCell.textField.becomeFirstResponder()
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
DispatchQueue.main.async {
self.tableView.reloadSections(IndexSet(integer: BookmarkDetailSection.folder.rawValue), with: .automatic)
}
}
override func applyTheme() {
super.applyTheme()
if let current = navigationController?.visibleViewController as? Themeable, current !== self {
current.applyTheme()
}
tableView.backgroundColor = UIColor.theme.tableView.headerBackground
}
override func reloadData() {
// Can be called while app backgrounded and the db closed, don't try to reload the data source in this case
if profile.isShutdown { return }
profile.places.getBookmarksTree(rootGUID: BookmarkRoots.RootGUID, recursive: true).uponQueue(.main) { result in
guard let rootFolder = result.successValue as? BookmarkFolder else {
// TODO: Handle error case?
self.bookmarkFolders = []
self.tableView.reloadData()
return
}
var bookmarkFolders: [(folder: BookmarkFolder, indent: Int)] = []
func addFolder(_ folder: BookmarkFolder, indent: Int = 0) {
// Do not append itself and the top "root" folder to this list as
// bookmarks cannot be stored directly within it.
if folder.guid != BookmarkRoots.RootGUID && folder.guid != self.bookmarkNodeGUID {
bookmarkFolders.append((folder, indent))
}
var folderChildren: [BookmarkNode]? = nil
// Suitable to be appended
if folder.guid != self.bookmarkNodeGUID {
folderChildren = folder.children
}
for case let childFolder as BookmarkFolder in folderChildren ?? [] {
// Any "root" folders (i.e. "Mobile Bookmarks") should
// have an indentation of 0.
if childFolder.isRoot {
addFolder(childFolder)
}
// Otherwise, all non-root folder should increase the
// indentation by 1.
else {
addFolder(childFolder, indent: indent + 1)
}
}
}
addFolder(rootFolder)
self.bookmarkFolders = bookmarkFolders
self.tableView.reloadData()
}
}
func updateSaveButton() {
guard bookmarkNodeType == .bookmark else {
return
}
let url = URL(string: bookmarkItemURL ?? "")
navigationItem.rightBarButtonItem?.isEnabled = url?.schemeIsValid == true && url?.host != nil
}
func save() -> Success {
if isNew {
if bookmarkNodeType == .bookmark {
guard let bookmarkItemURL = self.bookmarkItemURL else {
return deferMaybe(BookmarkDetailPanelError())
}
return profile.places.createBookmark(parentGUID: parentBookmarkFolder.guid, url: bookmarkItemURL, title: bookmarkItemOrFolderTitle).bind({ result in
return result.isFailure ? deferMaybe(BookmarkDetailPanelError()) : succeed()
})
} else if bookmarkNodeType == .folder {
guard let bookmarkItemOrFolderTitle = self.bookmarkItemOrFolderTitle else {
return deferMaybe(BookmarkDetailPanelError())
}
return profile.places.createFolder(parentGUID: parentBookmarkFolder.guid, title: bookmarkItemOrFolderTitle).bind({ result in
return result.isFailure ? deferMaybe(BookmarkDetailPanelError()) : succeed()
})
}
} else {
guard let bookmarkNodeGUID = self.bookmarkNodeGUID else {
return deferMaybe(BookmarkDetailPanelError())
}
if bookmarkNodeType == .bookmark {
return profile.places.updateBookmarkNode(guid: bookmarkNodeGUID, parentGUID: parentBookmarkFolder.guid, position: bookmarkItemPosition, title: bookmarkItemOrFolderTitle, url: bookmarkItemURL)
} else if bookmarkNodeType == .folder {
return profile.places.updateBookmarkNode(guid: bookmarkNodeGUID, parentGUID: parentBookmarkFolder.guid, position: bookmarkItemPosition, title: bookmarkItemOrFolderTitle)
}
}
return deferMaybe(BookmarkDetailPanelError())
}
// MARK: UITableViewDataSource | UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
guard indexPath.section == BookmarkDetailSection.folder.rawValue else {
return
}
if isFolderListExpanded, let item = bookmarkFolders[safe: indexPath.row], parentBookmarkFolder.guid != item.folder.guid {
parentBookmarkFolder = item.folder
bookmarkItemPosition = nil
}
isFolderListExpanded = !isFolderListExpanded
tableView.reloadSections(IndexSet(integer: indexPath.section), with: .automatic)
}
func numberOfSections(in tableView: UITableView) -> Int {
return BookmarkDetailSection.allCases.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == BookmarkDetailSection.fields.rawValue {
switch bookmarkNodeType {
case .bookmark:
return 2
case .folder:
return 1
default:
return 0
}
} else if section == BookmarkDetailSection.folder.rawValue {
if isFolderListExpanded {
return bookmarkFolders.count
} else {
return 1
}
}
return 0 // Should not happen.
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Handle folder selection cells.
guard indexPath.section == BookmarkDetailSection.fields.rawValue else {
guard let cell = tableView.dequeueReusableCell(withIdentifier: BookmarkDetailFolderCellIdentifier, for: indexPath) as? OneLineTableViewCell else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
// Disable folder selection when creating a new bookmark or folder.
if isNew {
cell.titleLabel.alpha = 0.5
cell.leftImageView.alpha = 0.5
cell.selectionStyle = .none
cell.isUserInteractionEnabled = false
} else {
cell.titleLabel.alpha = 1.0
cell.leftImageView.alpha = 1.0
cell.selectionStyle = .default
cell.isUserInteractionEnabled = true
}
cell.leftImageView.image = UIImage(named: "bookmarkFolder")?.createScaled(BookmarkDetailPanelUX.FolderIconSize)
cell.leftImageView.contentMode = .center
cell.indentationWidth = BookmarkDetailPanelUX.IndentationWidth
if isFolderListExpanded {
guard let item = bookmarkFolders[safe: indexPath.row] else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
if item.folder.isRoot, let localizedString = LocalizedRootBookmarkFolderStrings[item.folder.guid] {
cell.titleLabel.text = localizedString
} else {
cell.titleLabel.text = item.folder.title
}
cell.indentationLevel = min(item.indent, maxIndentationLevel)
if item.folder.guid == parentBookmarkFolder.guid {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
} else {
if parentBookmarkFolder.isRoot, let localizedString = LocalizedRootBookmarkFolderStrings[parentBookmarkFolder.guid] {
cell.titleLabel.text = localizedString
} else {
cell.titleLabel.text = parentBookmarkFolder.title
}
cell.indentationLevel = 0
cell.accessoryType = .none
}
return cell
}
// Handle Title/URL editable field cells.
guard let cell = tableView.dequeueReusableCell(withIdentifier: BookmarkDetailFieldCellIdentifier, for: indexPath) as? TextFieldTableViewCell else {
return super.tableView(tableView, cellForRowAt: indexPath)
}
cell.delegate = self
switch indexPath.row {
case BookmarkDetailFieldsRow.title.rawValue:
cell.titleLabel.text = Strings.BookmarkDetailFieldTitle
cell.textField.text = bookmarkItemOrFolderTitle
cell.textField.autocapitalizationType = .sentences
cell.textField.keyboardType = .default
return cell
case BookmarkDetailFieldsRow.url.rawValue:
cell.titleLabel.text = Strings.BookmarkDetailFieldURL
cell.textField.text = bookmarkItemURL
cell.textField.autocapitalizationType = .none
cell.textField.keyboardType = .URL
return cell
default:
return super.tableView(tableView, cellForRowAt: indexPath) // Should not happen.
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard indexPath.section == BookmarkDetailSection.fields.rawValue else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
return BookmarkDetailPanelUX.FieldRowHeight
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? SiteTableViewHeader
header?.showBorder(for: .top, section != 0)
}
}
extension BookmarkDetailPanel: TextFieldTableViewCellDelegate {
func textFieldTableViewCell(_ textFieldTableViewCell: TextFieldTableViewCell, didChangeText text: String) {
guard let indexPath = tableView.indexPath(for: textFieldTableViewCell) else {
return
}
switch indexPath.row {
case BookmarkDetailFieldsRow.title.rawValue:
bookmarkItemOrFolderTitle = text
case BookmarkDetailFieldsRow.url.rawValue:
bookmarkItemURL = text
updateSaveButton()
default:
log.warning("Received didChangeText: for a cell with an IndexPath that should not exist.")
}
}
}
| mpl-2.0 | 4068315373b4dd4fdc083eb3f01cc7af | 39.119904 | 207 | 0.644591 | 5.492449 | false | false | false | false |
mark644873613/Doctor-lives | Doctor lives/Doctor lives/classes/Common公共/MainTabBarViewController.swift | 1 | 6436 | //
// MainTabBarViewController.swift
// Doctor lives
//
// Created by qianfeng on 16/10/24.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
//继承于UITabBarController
class MainTabBarViewController: UITabBarController {
//tabbar 的背景
private var bgView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
//调用创建视图控制器
createViewControllers()
}
//创建视图控制器
//自定义tabbar
func creatMyTabBar(imageNames: Array<String>, titles: Array<String>){
//创建背景视图
bgView=UIView.creatView()
//设置背景色
bgView?.backgroundColor=UIColor.init(patternImage: UIImage(named: "appproduct_searchbar")!)
//bgView?.backgroundColor=UIColor(white: 0.9, alpha: 1.0)
view.addSubview(bgView!)
//如需修改边框使用以下方法修改边的宽度与颜色
// bgView?.layer.borderColor=UIColor.blackColor().CGColor
// bgView?.layer.borderWidth=1
//使用自动布局第三方库 SnapKit
bgView?.snp_makeConstraints(closure: {[weak self] (make) in
make.left.right.bottom.equalTo((self?.view)!)
make.height.equalTo(44)
})
//视图控制器对象的数组
//tabbarl图片名字
var imagenames=["tab_class","tab_read","nav_jl","button_mine_normal"]
//标题文字
let titles=["首页","药品分类","用药指南","我的"]
//循环创建按钮
let width=kScreenWidth/CGFloat(imagenames.count)
for i in 0..<imagenames.count{
let imageName=imagenames[i]+"_24x24_@2x"
let selectName=imagenames[i]+"_active_24x24_@2x"
//按钮
let btn=UIButton.createBtn(nil, bgImageName: imageName, heighlightImageName: nil, selectImageName: selectName, target: self, action:#selector(ClickBtn(_:)))
bgView?.addSubview(btn)
//tag值
btn.tag=300+i
//设置自动布局第三方库snapKit
btn.snp_makeConstraints(closure: {[weak self] (make) in
make.top.bottom.equalTo((self?.bgView)!)
make.width.equalTo(width)
make.left.equalTo(width*CGFloat(i))
})
//显示标题
let titleLabel=UILabel.createLabel(titles[i], textAlignement:.Center, font: UIFont.systemFontOfSize(12))
btn.addSubview(titleLabel)
//背景
titleLabel.textColor=UIColor.lightGrayColor()
titleLabel.tag=400
//设置位置
titleLabel.snp_makeConstraints(closure: { (make) in
make.left.right.equalTo(btn)
make.bottom.equalTo(-3)
make.height.equalTo(15)
})
//设置当前第一个为显示默认
if i == 0{
btn.selected=true
titleLabel.textColor=UIColor.redColor()
}
}
}
func ClickBtn(curBtn:UIButton){
let index=curBtn.tag-300
//选中当前按钮
let lastBtn=bgView?.viewWithTag(300+selectedIndex) as! UIButton
lastBtn.selected=false
lastBtn.userInteractionEnabled=true
let lastLabel=lastBtn.viewWithTag(400) as! UILabel
lastLabel.textColor=UIColor.lightGrayColor()
//取消选中之前的按钮
curBtn.selected=true
curBtn.userInteractionEnabled=false
let curLabel=curBtn.viewWithTag(400)as! UILabel
curLabel.textColor=UIColor.redColor()
//切换视图控制器
selectedIndex=index
}
func createViewControllers(){
let path=NSBundle.mainBundle().pathForResource("Controllers", ofType: "json")
let data=NSData(contentsOfFile: path!)
var nameArray:[String]=[]
var images:[String]=[]
var titles:[String]=[]
do {
let json=try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
if json.isKindOfClass(NSArray){
let tmpArray=json as! [[String:String]]
for tmpDict in tmpArray{
let name=tmpDict["ctrlname"]
nameArray.append(name!)
//图片
let imageName=tmpDict["image"]
images.append(imageName!)
let title=tmpDict["title"]
titles.append(title!)
}
}
}catch (let error){
print(error)
}
if nameArray.count == 0{
nameArray=["HomeViewController","DurgViewController","GuideViewController","PofileViewController"]
//tabbarl图片名字
_=["tab_class","tab_read","nav_jl","button_mine_normal"]
//标题文字
titles=["首页","药品分类","用药指南","我的"]
}
var ctrlArray:[UINavigationController]=[]
for i in 0..<nameArray.count{
let name="Doctor_lives."+nameArray[i]
//使用类名创建类的对象
let ctrl=NSClassFromString(name) as! UIViewController.Type
let vc = ctrl.init()
//导航
let navCtrl = UINavigationController(rootViewController: vc)
ctrlArray.append(navCtrl)
//更改系统tabbar颜色
//self.tabBar.tintColor=UIColor.orangeColor()
}
viewControllers = ctrlArray
//自定制tabbar
//隐藏系统的tabbar
tabBar.hidden=true
//自定制tabbar
creatMyTabBar(images,titles: titles)
}
//显示tabbar
func showTabBar(){
UIView.animateWithDuration(0.25) {
self.bgView?.hidden = false
}
}
//隐藏tabbar
func hideTabBar() {
UIView.animateWithDuration(0.25) {
self.bgView?.hidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 956a93d111640b465b7a53360af03ff6 | 29.165829 | 168 | 0.534733 | 4.787081 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Extensions/Bundle+ScienceJournal.swift | 1 | 2084 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
extension Bundle {
/// Returns the current bundle, based on the AppDelegate class. For open-source, this will always
/// be equivalent to Bundle.main.
static var currentBundle: Bundle = {
return Bundle(for: AppDelegateOpen.self)
}()
/// Returns the app version string.
static var appVersionString: String {
let dictionary = Bundle.currentBundle.infoDictionary!
// swiftlint:disable force_cast
return dictionary["CFBundleVersion"] as! String
// swiftlint:enable force_cast
}
/// Returns the build number as an integer.
static var buildVersion: Int32 {
#if SCIENCEJOURNAL_DEV_BUILD
// This can be set to arbitrary values in dev as needed.
return 9999
#else
// This assumes the version string is in the format "1.2.3".
let versionParts = appVersionString.components(separatedBy: ".")
let build = versionParts[2]
guard let version = Int32(build) else {
fatalError("Build version string must be three integers separated by periods.")
}
return version
#endif
}
/// Returns the strings sub-bundle or nil if it is not found.
static var stringsBundle: Bundle? = {
// Look for the Strings.bundle sub-bundle.
guard let subBundlePath =
Bundle.currentBundle.path(forResource: "Strings", ofType: "bundle") else {
return nil
}
return Bundle(url: URL(fileURLWithPath: subBundlePath, isDirectory: true))
}()
}
| apache-2.0 | 4936b5020dfe209e0aa1b07e2beee62d | 32.612903 | 99 | 0.697217 | 4.270492 | false | false | false | false |
ldt25290/MyInstaMap | ThirdParty/AlamofireImage/Example/ImageViewController.swift | 4 | 2289 | //
// ImageViewController.swift
//
// Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import AlamofireImage
import Foundation
import UIKit
class ImageViewController : UIViewController {
var gravatar: Gravatar!
var imageView: UIImageView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setUpInstanceProperties()
setUpImageView()
}
// MARK: - Private - Setup Methods
private func setUpInstanceProperties() {
title = gravatar.email
edgesForExtendedLayout = UIRectEdge()
view.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
}
private func setUpImageView() {
imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
let URL = gravatar.url(size: view.bounds.size.width)
imageView.af_setImage(
withURL: URL,
placeholderImage: nil,
filter: CircleFilter(),
imageTransition: .flipFromBottom(0.5)
)
view.addSubview(imageView)
imageView.frame = view.bounds
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
}
| mit | e41f6b0c42005834fed2698933ed2ff0 | 32.661765 | 81 | 0.696811 | 4.719588 | false | false | false | false |
naokits/bluemix-swift-demo-ios | Pods/BMSPush/Source/BMSConstants.swift | 1 | 2424 | /*
* Copyright 2015 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.
*/
internal var DUMP_TRACE:Bool = true
internal let QUERY_PARAM_SUBZONE = "="
internal let STAGE1 = "stage1"
internal let BLUEMIX_DOMAIN = "bluemix.net"
internal let IMFPUSH_ACTION_DELETE = "action=delete"
internal let IMFPUSH_CONTENT_TYPE_JSON = "application/json; charset = UTF-8"
internal let IMFPUSH_CONTENT_TYPE_KEY = "Content-Type"
internal let IMFPUSH_DEVICE_ID = "deviceId"
internal let IMFPUSH_DEVICES = "devices"
internal let IMFPUSH_TOKEN = "token"
internal let IMFPUSH_USER_ID = "userId"
internal let IMFPUSH_PLATFORM = "platform"
internal let IMFPUSH_TAGS = "tags"
internal let IMFPUSH_TAGNAME = "tagName"
internal let IMFPUSH_TAGNAMES = "tagNames"
internal let IMFPUSH_TAGSNOTFOUND = "tagsNotFound"
internal let IMFPUSH_NAME = "name"
internal let IMFPUSH_SUBSCRIPTIONS = "subscriptions"
internal let IMFPUSH_SUBSCRIBED = "subscribed"
internal let IMFPUSH_SUBSCRIPTIONEXISTS = "subscriptionExists"
internal let IMFPUSH_UNSUBSCRIBED = "unsubscribed"
internal let IMFPUSH_UNSUBSCRIPTIONS = "unsubscriptions"
internal let IMFPUSH_SUBSCRIPTIONNOTEXISTS = "subscriptionNotExists"
internal let IMFPUSH_OPEN = "open"
internal let IMFPUSH_RECEIVED = "received"
internal let IMFPUSH_SEEN = "seen"
internal let IMFPUSH_ACKNOWLEDGED = "acknowledged"
internal let IMFPUSH_APP_MANAGER = "IMFPushAppManager"
internal let IMFPUSH_CLIENT = "IMFPushClient"
internal let IMFPUSH_DISPLAYNAME = "displayName"
internal let IMFPUSH_X_REWRITE_DOMAIN = "X-REWRITE-DOMAIN"
internal let IMFPUSH_PUSH_WORKS_SERVER_CONTEXT = "imfpush/v1/apps"
internal let KEY_METADATA_TYPE = "$type";
internal let TAG_CATEGORY_EVENT = "event";
internal let KEY_METADATA_CATEGORY = "$category";
internal let KEY_METADATA_USER_METADATA = "$userMetadata";
| mit | 8cf5e34b19f3998224a4681089b7fbbe | 26.837209 | 78 | 0.748538 | 3.474601 | false | false | false | false |
royratcliffe/Faraday | Sources/Response+Headers.swift | 1 | 2134 | // Faraday Response+Headers.swift
//
// Copyright © 2015, 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import Foundation
extension Response {
/// - returns: Answers the response content type, including the main type and
/// sub-type. Automatically removes any optional parameters, such as the
/// content character set. Trims any white-space from the string. Answers
/// `nil` if the response does not have a content type.
///
/// Splits the content type at the first semi-colon. There is always at least
/// one split, even if no semi-colon. The first split is the entire content
/// type if none.
public var contentType: String? {
guard let contentType = headers["Content-Type"] else { return nil }
let splits = contentType.characters.split(maxSplits: 1) { $0 == ";" }
guard let first = splits.first else { return nil }
return String(first).trimmingCharacters(in: CharacterSet.whitespaces)
}
}
| mit | 0150887cf9915b9020dd9b28e8e9a92e | 47.295455 | 80 | 0.710588 | 4.609544 | false | false | false | false |
stripe/stripe-ios | StripeUICore/StripeUICoreTests/Snapshot/Elements/CheckboxButtonSnapshotTests.swift | 1 | 3847 | //
// CheckboxButtonSnapshotTests.swift
// StripeUICoreTests
//
// Created by Ramon Torres on 12/14/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
import UIKit
import iOSSnapshotTestCase
import StripeCoreTestUtils
@testable @_spi(STP) import StripeUICore
class CheckboxButtonSnapshotTests: FBSnapshotTestCase {
let attributedLinkText: NSAttributedString = {
let attributedText = NSMutableAttributedString(string: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum auctor justo sit amet luctus egestas. Sed id urna dolor.")
attributedText.addAttributes([.link: URL(string: "https://stripe.com")!], range: NSRange(location: 0, length: 26))
return attributedText
}()
override func setUp() {
super.setUp()
// recordMode = true
}
func testShortText() {
let checkbox = CheckboxButton(text: "Save this card for future [Merchant] payments")
verify(checkbox)
}
func testLongText() {
let checkbox = CheckboxButton(
text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum auctor justo sit amet luctus egestas. Sed id urna dolor."
)
verify(checkbox)
}
func testMultiline() {
let checkbox = CheckboxButton(
text: "Save my info for secure 1-click checkout",
description: "Pay faster at [Merchant] and thousands of merchants."
)
verify(checkbox)
}
func testCustomFont() throws {
var theme = ElementsUITheme.default
theme.fonts.footnote = try XCTUnwrap(UIFont(name: "AmericanTypewriter", size: 13.0))
theme.fonts.footnoteEmphasis = try XCTUnwrap(UIFont(name: "AmericanTypewriter-Semibold", size: 13.0))
let checkbox = CheckboxButton(
text: "Save my info for secure 1-click checkout",
description: "Pay faster at [Merchant] and thousands of merchants.",
theme: theme
)
verify(checkbox)
}
func testLocalization() {
let greekCheckbox = CheckboxButton(text: "Αποθηκεύστε αυτή την κάρτα για μελλοντικές [Merchant] πληρωμές")
verify(greekCheckbox, identifier: "Greek")
let chineseCheckbox = CheckboxButton(
text: "保存我的信息以便一键结账",
description: "在[Merchant]及千万商家使用快捷支付")
verify(chineseCheckbox, identifier: "Chinese")
let hindiCheckbox = CheckboxButton(
text: "सुरक्षित 1-क्लिक चेकआउट के लिए मेरी जानकारी सहेजें",
description: "[Merchant] और हज़ारों व्यापारियों पर तेज़ी से भुगतान करें।")
verify(hindiCheckbox, identifier: "Hindi")
}
func testAttributedText() {
let checkbox = CheckboxButton(
attributedText: attributedLinkText
)
verify(checkbox)
}
func testAttributedTextCustomFont() throws {
var theme = ElementsUITheme.default
theme.fonts.footnote = try XCTUnwrap(UIFont(name: "AmericanTypewriter", size: 13.0))
theme.fonts.footnoteEmphasis = try XCTUnwrap(UIFont(name: "AmericanTypewriter-Semibold", size: 13.0))
let checkbox = CheckboxButton(
attributedText: attributedLinkText,
theme: theme
)
verify(checkbox)
}
func verify(
_ view: UIView,
identifier: String? = nil,
file: StaticString = #filePath,
line: UInt = #line
) {
view.autosizeHeight(width: 340)
view.backgroundColor = .white
STPSnapshotVerifyView(view, identifier: identifier, file: file, line: line)
}
}
| mit | e19b617ec35162dc1592fb587f64b90c | 32.560748 | 190 | 0.640769 | 3.853004 | false | true | false | false |
stripe/stripe-ios | StripeCardScan/StripeCardScan/Source/CardVerify/CardVerifyFraudData.swift | 1 | 2997 | import Foundation
class CardVerifyFraudData: CardScanFraudData {
// one subtlety we have is that we might try to get results before the
// model is done running. Thus we record the model results for this object
// and keep track of any callers that try to get a response too early
// and notify them later.
//
// All data access is on the main queue
var verificationFrameDataResults: [VerificationFramesData]?
var resultCallbacks: [((_ response: [VerificationFramesData]) -> Void)] = []
var acceptedImageConfigs: CardImageVerificationAcceptedImageConfigs?
static let maxCompletionLoopFrames = 5
init(
last4: String? = nil,
acceptedImageConfigs: CardImageVerificationAcceptedImageConfigs? = nil
) {
super.init()
self.last4 = last4
self.acceptedImageConfigs = acceptedImageConfigs
}
override func onResultReady(scannedCardImagesData: [ScannedCardImageData]) {
DispatchQueue.main.async {
let imageCompressionTask = TrackableTask()
let processedVerificationFrames = scannedCardImagesData.compactMap {
$0.toVerificationFramesData(imageConfig: self.acceptedImageConfigs)
}
imageCompressionTask.trackResult(
processedVerificationFrames.count > 0 ? .success : .failure
)
let verificationFramesData = processedVerificationFrames.compactMap { $0.0 }
/// Use the image metadata from the most recent frame
let verificationImageMetadata = processedVerificationFrames.compactMap { $0.1 }.last
/// Calculate the compressed and b64 encoded image sizes in bytes
let totalImagePayloadSizeInBytes = verificationFramesData.compactMap { $0.imageData }
.reduce(0) { $0 + $1.count }
/// Log the verification payload info + image compression duration
ScanAnalyticsManager.shared.trackImageCompressionDuration(task: imageCompressionTask)
ScanAnalyticsManager.shared.logPayloadInfo(
with: .init(
imageCompressionType: verificationImageMetadata?.compressionType.rawValue
?? "unknown",
imageCompressionQuality: verificationImageMetadata?.compressionQuality ?? 0.0,
imagePayloadSize: totalImagePayloadSizeInBytes
)
)
self.verificationFrameDataResults = verificationFramesData
for complete in self.resultCallbacks {
complete(verificationFramesData)
}
self.resultCallbacks = []
}
}
func result(complete: @escaping ([VerificationFramesData]) -> Void) {
DispatchQueue.main.async {
guard let results = self.verificationFrameDataResults else {
self.resultCallbacks.append(complete)
return
}
complete(results)
}
}
}
| mit | a00d0d649d9420d2c8003741338719c2 | 38.96 | 98 | 0.64698 | 5.351786 | false | true | false | false |
MA806P/SwiftDemo | SwiftTestDemo/SwiftTestDemo/NestedTypes.swift | 1 | 1232 | //
// NestedTypes.swift
// SwiftTestDemo
//
// Created by MA806P on 2018/8/30.
// Copyright © 2018年 myz. All rights reserved.
//
import Foundation
struct BlackjackCard {
// 嵌套的 Suit 枚举
enum Suit: Character {
case spades = "♠", hearts = "♡", diamonds = "♢", clubs = "♣"
}
// 嵌套的 Rank 枚举
enum Rank: Int {
case two = 2, three, four, five, six, seven, eight, nine, ten
case jack, queen, king, ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .ace:
return Values(first: 1, second: 11)
case .jack, .queen, .king:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}
// BlackjackCard 的属性和方法
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}
| apache-2.0 | c1036f8aad16c26d7be0ca1d9cabd121 | 21.865385 | 69 | 0.50799 | 3.898361 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/RightSide/Search/Controllers/SearchViewController.swift | 1 | 7771 | //
// SearchViewController.swift
// zhuishushenqi
//
// Created by Nory Chao on 2017/3/11.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
import QSNetwork
class SearchViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UISearchBarDelegate {
var hotWords = [String]()
var headerHeight:CGFloat = 0
var searchWords:String = ""
var books = [Book]()
fileprivate var tagColor = [UIColor(red: 0.56, green: 0.77, blue: 0.94, alpha: 1.0),
UIColor(red: 0.75, green: 0.41, blue: 0.82, alpha: 1.0),
UIColor(red: 0.96, green: 0.74, blue: 0.49, alpha: 1.0),
UIColor(red: 0.57, green: 0.81, blue: 0.84, alpha: 1.0),
UIColor(red: 0.40, green: 0.80, blue: 0.72, alpha: 1.0),
UIColor(red: 0.91, green: 0.56, blue: 0.56, alpha: 1.0),
UIColor(red: 0.56, green: 0.77, blue: 0.94, alpha: 1.0),
UIColor(red: 0.75, green: 0.41, blue: 0.82, alpha: 1.0)]
fileprivate lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 114, width: ScreenWidth, height: ScreenHeight - 114), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.sectionFooterHeight = 10
tableView.rowHeight = 44
tableView.backgroundColor = UIColor.white
tableView.qs_registerCellClass(UITableViewCell.self)
return tableView
}()
lazy var searchController:UISearchController = {
let searchVC:UISearchController = UISearchController(searchResultsController: nil)
searchVC.searchBar.placeholder = "输入书名或作者名111"
searchVC.searchResultsUpdater = self
searchVC.delegate = self
searchVC.searchBar.delegate = self
// searchVC.obscuresBackgroundDuringPresentation = true
searchVC.hidesNavigationBarDuringPresentation = true
searchVC.searchBar.sizeToFit()
searchVC.searchBar.backgroundColor = UIColor.darkGray
return searchVC
}()
var headerView:UIView?
var changeIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
title = "搜索"
initSubview()
requestData()
view.backgroundColor = UIColor.red
}
func requestData() -> Void {
// http://api.zhuishushenqi.com/book/hot-word
let urlString = "\(BASEURL)/book/hot-word"
QSNetwork.request(urlString) { (response) in
QSLog(response.json)
if let json = response.json {
self.hotWords = json["hotWords"] as? [String] ?? [""]
// self.tableView.reloadData()
DispatchQueue.main.async {
self.headerView = self.headView()
self.view.addSubview(self.tableView)
self.tableView.reloadData()
}
}
}
}
func initSubview(){
let bgView = UIView()
bgView.frame = CGRect(x: 0, y: 64, width: self.view.bounds.width, height: 50)
bgView.addSubview(self.searchController.searchBar)
view.addSubview(bgView)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.view.removeFromSuperview()
self.removeFromParentViewController()
}// called when keyboard search button pressed
func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar){
}// called when bookmark button pressed
func searchBarCancelButtonClicked(_ searchBar: UISearchBar){
dismiss(animated: false, completion: nil)
}// called when cancel button pressed
fileprivate func headView()->UIView{
let headerView = UIView()
headerView.backgroundColor = UIColor.white
let label = UILabel()
label.frame = CGRect(x: 15, y: 0, width: 200, height: 21)
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.black
label.text = "大家都在搜"
headerView.addSubview(label)
let btn = UIButton(type: .custom)
btn.setImage(UIImage(named:"actionbar_refresh"), for: .normal)
btn.setTitle("换一批", for: .normal)
btn.setTitleColor(UIColor.darkGray, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
btn.contentHorizontalAlignment = .right
btn.addTarget(self, action: #selector(changeHotWord(btn:)), for: .touchUpInside)
btn.frame = CGRect(x: self.view.bounds.width - 90, y: 0, width: 70, height: 21)
headerView.addSubview(btn)
var x:CGFloat = 20
var y:CGFloat = 10 + 21
let spacex:CGFloat = 10
let spacey:CGFloat = 10
let height:CGFloat = 20
var count = 0
for index in changeIndex..<(changeIndex + 6) {
count = index
if count >= hotWords.count {
count = count - hotWords.count
}
let width = widthOfString(hotWords[count], font: UIFont.systemFont(ofSize: 11), height: 21) + 20
if x + width + 20 > ScreenWidth {
x = 20
y = y + spacey + height
}
let btn = UIButton(type: .custom)
btn.frame = CGRect(x: x, y: y, width: width, height: height)
btn.setTitle(hotWords[count], for: UIControlState())
btn.titleLabel?.font = UIFont.systemFont(ofSize: 11)
btn.setTitleColor(UIColor.white, for: UIControlState())
btn.backgroundColor = tagColor[index%tagColor.count]
btn.layer.cornerRadius = 2
headerView.addSubview(btn)
x = x + width + spacex
}
changeIndex = count + 1
headerHeight = y + height + 10
headerView.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: headerHeight)
return headerView
}
@objc func changeHotWord(btn:UIButton){
if changeIndex > self.hotWords.count {
}
let views = self.headerView?.subviews
for index in 0..<(views?.count ?? 0) {
let view = views?[index]
view?.removeFromSuperview()
}
self.headerView = headView()
self.tableView.reloadData()
}
func updateSearchResults(for searchController: UISearchController) {
}
@objc func backAction(item:UIBarButtonItem){
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = tableView.qs_dequeueReusableCell(UITableViewCell.self)
cell.backgroundColor = UIColor.white
cell.selectionStyle = .none
return cell
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return self.headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return headerHeight
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 12ca74f383e150ee3dd9fff5c6d09d43 | 35.471698 | 161 | 0.597775 | 4.708892 | false | false | false | false |
Dagers/macGHCi | HaskellEditor/TerminalViewController.swift | 1 | 18172 | //
// TerminalViewController.swift
// macGHCi
//
// Created by Daniel Strebinger on 20.02.17.
// Copyright © 2017 Daniel Strebinger. All rights reserved.
//
import Cocoa
/**
This class represents the terminal window. It outputs and reads the haskell commands.
- Author: Daniel Strebinger
*/
internal class TerminalViewController: NSViewController, NSTextViewDelegate {
/**
Represents the reference to the source editor.
*/
@IBOutlet var sourceEditor: NSTextView!
/**
Represents the terminal manager object.
*/
private var ghci : TerminalManager = TerminalManager.init()
/**
Represents the command history object.
*/
private var history : CommandHistory = CommandHistory.init()
/**
Represents the user defaults.
*/
private var userDefaults : UserDefaults = UserDefaults.standard
/**
Represents the current save path of the terminal output.
*/
private var savePath : String = ""
/**
Called when the view will appear.
*/
internal override func viewWillAppear() {
self.setupDefaults()
self.sourceEditor.backgroundColor = self.userDefaults.colorForKey(key: "editorBackgroundColor")!
self.view.window?.title = "macGHCi - Untitled.hs (not saved)"
}
/**
Initializes a new instance of the view controller clas.
*/
internal override func viewDidLoad() {
super.viewDidLoad()
self.sourceEditor.delegate = self
self.sourceEditor.isAutomaticQuoteSubstitutionEnabled = false
self.ghci.start("/usr/local/bin/ghci", args: [])
self.registerNotifications()
}
/**
Called when the view will disappear.
*/
internal override func viewWillDisappear() {
self.ghci.stop()
}
/**
Represents the call back method for the command selector notificaiton.
*/
internal func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool
{
// if enter is called
if (commandSelector == #selector(NSResponder.insertNewline(_:))) {
let command : String = self.sourceEditor.getLatestLine()
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.history.Add(command: command)
self.ghci.write(command)
return true
}
if( commandSelector == #selector(NSResponder.moveUp(_:)) ) {
self.sourceEditor.replaceCommand(command: self.history.GetCommand(older: true))
return true
}
if( commandSelector == #selector(NSResponder.moveDown(_:)) ){
self.sourceEditor.replaceCommand(command: self.history.GetCommand(older: false))
return true
}
if (self.savePath != "")
{
self.view.window?.title = "macGHCi - " + (Foundation.URL(string: self.savePath)?.lastPathComponent)! + " (Unsaved changes)"
}
return false
}
/**
Setups the default values.
*/
private func setupDefaults()
{
if (self.userDefaults.value(forKey: "fontSize") == nil)
{
self.userDefaults.set(13, forKey: "fontSize")
}
if (self.userDefaults.value(forKey: "font") == nil)
{
self.userDefaults.set("Consolas", forKey: "font")
}
if (self.userDefaults.value(forKey: "fontColor") == nil)
{
self.userDefaults.setColor(color: NSColor.black, forKey: "fontColor")
}
if (self.userDefaults.value(forKey: "editorBackgroundColor") == nil)
{
self.userDefaults.setColor(color: NSColor.white, forKey: "editorBackgroundColor")
}
}
/**
Registers for the notifications to listen on.
*/
private func registerNotifications()
{
// register on events. OnNewEditorSession, OnOpenEditorSession, OnLoadFile
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnNewDataReceived"),
object:nil, queue:nil,
using:ghci_OnNewDataReceivedCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnErrorDataReceived"),
object:nil, queue:nil,
using:ghci_OnErrorDataReceivedCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnNewEditorSession"),
object:nil, queue:nil,
using:ghci_OnNewEditorSessionCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnLoadFile"),
object:nil, queue:nil,
using:ghci_OnLoadFileCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnAddFile"),
object:nil, queue:nil,
using:ghci_OnAddFileCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnRunMain"),
object:nil, queue:nil,
using:ghci_OnRunMainCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnReload"),
object:nil, queue:nil,
using:ghci_OnReloadCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnClearModules"),
object:nil, queue:nil,
using:ghci_OnClearModulesCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnOpenTextEditor"),
object:nil, queue:nil,
using:ghci_OnOpenTextEditorCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnOpenEditorSession"),
object:nil, queue:nil,
using:ghci_OnOpenEditorSessionCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnSaveEditorSession"),
object:nil, queue:nil,
using:ghci_OnSaveEditorSessionCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnSaveAsEditorSession"),
object:nil, queue:nil,
using:ghci_OnSaveAsEditorSessionCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnDisplayCommands"),
object:nil, queue:nil,
using:ghci_OnDisplayCommandsCallBack)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnRefreshEditor"),
object:nil, queue:nil,
using:onRefreshEditor)
NotificationCenter.default.addObserver(forName:Notification.Name(rawValue:"OnCancelExecution"),
object:nil, queue:nil,
using:ghci_OnCancelExecutionCallBack)
}
/**
Represents the call back method of the on cancel execution notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnCancelExecutionCallBack(notification: Notification)
{
self.ghci.interrupt()
self.ghci.resume()
}
/**
Redraws the content of the source editor.
- Parameter notification: Contains the notification arguments.
*/
private func onRefreshEditor(notification: Notification)
{
self.sourceEditor.backgroundColor = self.userDefaults.colorForKey(key: "editorBackgroundColor")!
let attributes = [NSAttributedStringKey.font: NSFont(name: self.userDefaults.object(forKey: "font") as! String, size: self.userDefaults.object(forKey: "fontSize") as! CGFloat), NSAttributedStringKey.foregroundColor: self.userDefaults.colorForKey(key: "fontColor")]
self.sourceEditor.textStorage?.setAttributedString(NSAttributedString(string: (self.sourceEditor.textStorage?.string)!, attributes: attributes))
}
/**
Represents the call back method of the on new data received notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnNewDataReceivedCallBack(notification: Notification)
{
let userInfo = notification.userInfo
let message = userInfo?["message"] as? String
let attributes = [NSAttributedStringKey.font: NSFont(name: self.userDefaults.object(forKey: "font") as! String, size: self.userDefaults.object(forKey: "fontSize") as! CGFloat), NSAttributedStringKey.foregroundColor: self.userDefaults.colorForKey(key: "fontColor")]
self.sourceEditor.textStorage?.append(NSAttributedString(string: message!, attributes: attributes))
self.sourceEditor.scrollToEndOfDocument(self)
}
/**
Represents the call back method of the on new error received notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnErrorDataReceivedCallBack(notification: Notification)
{
let userInfo = notification.userInfo
let message = userInfo?["message"] as? String
let attributes = [NSAttributedStringKey.font: NSFont(name: self.userDefaults.object(forKey: "font") as! String, size: self.userDefaults.object(forKey: "fontSize") as! CGFloat), NSAttributedStringKey.foregroundColor: self.userDefaults.colorForKey(key: "fontColor")]
self.sourceEditor.textStorage?.setAttributedString(NSAttributedString(string: self.sourceEditor.getPreviousLineAndAppend(message: message!), attributes: attributes))
self.sourceEditor.scrollToEndOfDocument(self)
}
/**
Represents the call back method of the on new editor session notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnNewEditorSessionCallBack(notification: Notification)
{
self.savePath = ""
self.view.window?.title = "macGHCi - Untitled.hs (not saved)"
self.sourceEditor.textStorage?.mutableString.setString("")
self.ghci.write("")
}
/**
Represents the call back method of the on run main notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnRunMainCallBack(notification: Notification)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":main")
}
/**
Represents the call back method of the on reload notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnReloadCallBack(notification: Notification)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":reload")
}
/**
Represents the call back method of the on clear modules notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnClearModulesCallBack(notification: Notification)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":load")
}
/**
Represents the call back method of the on open text editor notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnOpenTextEditorCallBack(notification: Notification)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":edit")
}
/**
Represents the call back method of the on display commands notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnDisplayCommandsCallBack(notification: Notification)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":help")
}
/**
Represents the call back method of the on load file notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnLoadFileCallBack(notification: Notification)
{
let panel : NSOpenPanel = NSOpenPanel()
panel.title = "Select file"
panel.allowedFileTypes = ["hs"]
panel.begin(
completionHandler: {(result : NSApplication.ModalResponse) in
if(result == NSApplication.ModalResponse.OK)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":l " + panel.url!.path)
}
})
}
/**
Represents the call back method of the on open editor session notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnOpenEditorSessionCallBack(notification: Notification)
{
let panel : NSOpenPanel = NSOpenPanel()
panel.title = "Select file"
panel.allowedFileTypes = ["hs"]
panel.begin(
completionHandler: {(result) in
if(result == NSApplication.ModalResponse.OK)
{
self.view.window?.title = "macGHCi - " + (panel.url?.lastPathComponent)!
self.sourceEditor.textStorage?.mutableString.setString("")
var value : String = ""
do
{
try value = NSString(contentsOf: panel.url!, encoding: String.Encoding.utf8.rawValue) as String!
}
catch _
{
value = ""
}
self.sourceEditor.backgroundColor = self.userDefaults.colorForKey(key: "editorBackgroundColor")!
let attributes = [NSAttributedStringKey.font: NSFont(name: self.userDefaults.object(forKey: "font") as! String, size: self.userDefaults.object(forKey: "fontSize") as! CGFloat), NSAttributedStringKey.foregroundColor: self.userDefaults.colorForKey(key: "fontColor")]
self.sourceEditor.textStorage?.setAttributedString(NSAttributedString(string: value, attributes: attributes ))
}
})
}
/**
Represents the call back method of the on save editor session notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnSaveEditorSessionCallBack(notification: Notification)
{
if (self.savePath == "")
{
let panel : NSSavePanel = NSSavePanel()
panel.title = "Save file"
panel.allowedFileTypes = ["hs"]
panel.begin(
completionHandler: {(result : NSApplication.ModalResponse) in
if(result == NSApplication.ModalResponse.OK)
{
self.view.window?.title = "macGHCi - " + (panel.url?.lastPathComponent)!
self.savePath = panel.url!.path
FileManager.default.createFile(atPath: self.savePath, contents: self.sourceEditor.textStorage!.string.data(using: .utf8), attributes: nil)
}
})
return
}
FileManager.default.createFile(atPath: self.savePath, contents: self.sourceEditor.textStorage!.string.data(using: .utf8), attributes: nil)
}
/**
Represents the call back method of the on save editor session notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnSaveAsEditorSessionCallBack(notification: Notification)
{
let panel : NSSavePanel = NSSavePanel()
panel.title = "Save file"
panel.allowedFileTypes = ["hs"]
panel.begin(
completionHandler: {(result : NSApplication.ModalResponse) in
if(result == NSApplication.ModalResponse.OK)
{
self.view.window?.title = "macGHCi - " + (panel.url?.lastPathComponent)!
self.savePath = panel.url!.path
FileManager.default.createFile(atPath: self.savePath, contents: self.sourceEditor.textStorage!.string.data(using: .utf8), attributes: nil)
}
})
}
/**
Represents the call back method of the on add file notification.
- Parameter notification: Contains the notification arguments.
*/
private func ghci_OnAddFileCallBack(notification: Notification)
{
let panel : NSOpenPanel = NSOpenPanel()
panel.title = "Select file"
panel.allowedFileTypes = ["hs"]
panel.begin(
completionHandler: {(result : NSApplication.ModalResponse) in
if(result == NSApplication.ModalResponse.OK)
{
self.sourceEditor.textStorage?.append(NSAttributedString(string: "\n"))
self.ghci.write(":add " + panel.url!.path)
}
})
}
}
| gpl-3.0 | dacd98cad1ec5fc4b4549186c836303d | 39.560268 | 285 | 0.598701 | 5.34127 | false | false | false | false |
parkera/swift | test/Concurrency/Runtime/actor_counters.swift | 1 | 2492 | // RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library)
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.5, *)
actor Counter {
private var value = 0
private let scratchBuffer: UnsafeMutableBufferPointer<Int>
init(maxCount: Int) {
scratchBuffer = .allocate(capacity: maxCount)
scratchBuffer.initialize(repeating: 0)
}
func next() -> Int {
let current = value
// Make sure we haven't produced this value before
assert(scratchBuffer[current] == 0)
scratchBuffer[current] = 1
value = value + 1
return current
}
deinit {
for i in 0..<value {
assert(scratchBuffer[i] == 1)
}
}
}
@available(SwiftStdlib 5.5, *)
func worker(identity: Int, counters: [Counter], numIterations: Int) async {
for i in 0..<numIterations {
let counterIndex = Int.random(in: 0 ..< counters.count)
let counter = counters[counterIndex]
let nextValue = await counter.next()
print("Worker \(identity) calling counter \(counterIndex) produced \(nextValue)")
}
}
@available(SwiftStdlib 5.5, *)
func runTest(numCounters: Int, numWorkers: Int, numIterations: Int) async {
// Create counter actors.
var counters: [Counter] = []
for i in 0..<numCounters {
counters.append(Counter(maxCount: numWorkers * numIterations))
}
// Create a bunch of worker threads.
var workers: [Task.Handle<Void, Error>] = []
for i in 0..<numWorkers {
workers.append(
detach { [counters] in
await Task.sleep(UInt64.random(in: 0..<100) * 1_000_000)
await worker(identity: i, counters: counters, numIterations: numIterations)
}
)
}
// Wait until all of the workers have finished.
for worker in workers {
try! await worker.get()
}
print("DONE!")
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
// Useful for debugging: specify counter/worker/iteration counts
let args = CommandLine.arguments
let counters = args.count >= 2 ? Int(args[1])! : 10
let workers = args.count >= 3 ? Int(args[2])! : 100
let iterations = args.count >= 4 ? Int(args[3])! : 1000
print("counters: \(counters), workers: \(workers), iterations: \(iterations)")
await runTest(numCounters: counters, numWorkers: workers, numIterations: iterations)
}
}
| apache-2.0 | 4d5f5f6851db7994dc28fd241f839e2e | 27.318182 | 114 | 0.668941 | 3.851623 | false | false | false | false |
yokoe/luckybeast-ios | luckybeast/Listener.swift | 1 | 5175 | import UIKit
import Speech
protocol ListenerDelegate: class {
func listener(_ listener: Listener, didUpdateRecognizerAuthorizationStatus status: SFSpeechRecognizerAuthorizationStatus)
func listener(_ listener: Listener, didDetectWordToLookUp word: String)
func listenerDidDetectCaptureRequest(_ listener: Listener)
func listenerDidDetectNameCalled(_ listener: Listener)
func listener(_ listener: Listener, didUpdateBestTranscription transcription: String?)
}
class Listener: NSObject {
private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "ja-JP"))!
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
fileprivate let audioEngine = AVAudioEngine()
weak var delegate: ListenerDelegate?
var bestTranscriptionString: String? {
didSet {
delegate?.listener(self, didUpdateBestTranscription: bestTranscriptionString)
}
}
private var isMonitoring = false
var authorizationStatus: SFSpeechRecognizerAuthorizationStatus = .notDetermined {
didSet {
delegate?.listener(self, didUpdateRecognizerAuthorizationStatus: authorizationStatus)
}
}
override init() {
super.init()
speechRecognizer.delegate = self
}
func requestAuthorization() {
SFSpeechRecognizer.requestAuthorization { authStatus in
OperationQueue.main.addOperation {
self.authorizationStatus = authStatus
}
}
}
private var isNameCalled = false
func startMonitoring() throws {
if isMonitoring { return }
isMonitoring = true
isNameCalled = false
recognitionTask?.cancel()
recognitionTask = nil
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") }
guard let recognitionRequest = recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest) { [weak self] result, error in
guard let `self` = self else { return }
var isFinal = false
if let result = result {
let input = result.bestTranscription.formattedString
isFinal = result.isFinal
self.bestTranscriptionString = input
if !self.isNameCalled && input.lastIndex(of: "ボス") != nil {
self.delegate?.listenerDidDetectNameCalled(self)
self.isNameCalled = true
}
["ってなんですか", "てなんですか", "って何", "ってなに", "わかりますか", "なに", "なんですか"].forEach({ (suffix) in
if input.hasSuffix(suffix) {
isFinal = true
var word = input.replacingOccurrences(of: suffix, with: "")
self.recognitionRequest?.endAudio()
if let index = word.lastIndex(of: "ボス") {
word = word.substring(from: word.index(word.startIndex, offsetBy: index)).replacingOccurrences(of: "ボス", with: "")
}
if word.hasPrefix("これ") {
self.delegate?.listenerDidDetectCaptureRequest(self)
} else {
self.delegate?.listener(self, didDetectWordToLookUp: word)
}
}
})
}
// TODO: 60秒以上経過した場合の処理
if error != nil || isFinal {
self.isMonitoring = false
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
}
}
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
try audioEngine.start()
}
}
extension Listener: SFSpeechRecognizerDelegate {
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
debugPrint("SpeechRecognizer availabile: ", available)
}
}
| mit | 28817c9d677b269fe0423c4aa470ca96 | 38.913386 | 145 | 0.602486 | 5.977594 | false | false | false | false |
petester42/Moya | Source/Plugins/NetworkLoggerPlugin.swift | 2 | 3526 | import Foundation
/// Logs network activity (outgoing requests and incoming responses).
public final class NetworkLoggerPlugin: PluginType {
private let loggerId = "Moya_Logger"
private let dateFormatString = "dd/MM/yyyy HH:mm:ss"
private let dateFormatter = NSDateFormatter()
private let separator = ", "
private let terminator = "\n"
private let output: (items: Any..., separator: String, terminator: String) -> Void
/// If true, also logs response body data.
public let verbose: Bool
public init(verbose: Bool = false, output: (items: Any..., separator: String, terminator: String) -> Void = print) {
self.verbose = verbose
self.output = output
}
public func willSendRequest(request: RequestType, target: TargetType) {
output(items: logNetworkRequest(request.request), separator: separator, terminator: terminator)
}
public func didReceiveResponse(result: Result<Moya.Response, Moya.Error>, target: TargetType) {
if case .Success(let response) = result {
output(items: logNetworkResponse(response.response, data: response.data, target: target), separator: separator, terminator: terminator)
} else {
output(items: logNetworkResponse(nil, data: nil, target: target), separator: separator, terminator: terminator)
}
}
}
private extension NetworkLoggerPlugin {
private var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter.stringFromDate(NSDate())
}
private func format(loggerId: String, date: String, identifier: String, message: String) -> String {
return "\(loggerId): [\(date)] \(identifier): \(message)"
}
func logNetworkRequest(request: NSURLRequest?) -> [String] {
var output = [String]()
output += [format(loggerId, date: date, identifier: "Request", message: request?.description ?? "(invalid request)")]
if let headers = request?.allHTTPHeaderFields {
output += [format(loggerId, date: date, identifier: "Request Headers", message: headers.description)]
}
if let bodyStream = request?.HTTPBodyStream {
output += [format(loggerId, date: date, identifier: "Request Body Stream", message: bodyStream.description)]
}
if let httpMethod = request?.HTTPMethod {
output += [format(loggerId, date: date, identifier: "HTTP Request Method", message: httpMethod)]
}
if let body = request?.HTTPBody where verbose == true {
if let stringOutput = NSString(data: body, encoding: NSUTF8StringEncoding) as? String {
output += [format(loggerId, date: date, identifier: "Request Body", message: stringOutput)]
}
}
return output
}
func logNetworkResponse(response: NSURLResponse?, data: NSData?, target: TargetType) -> [String] {
guard let response = response else {
return [format(loggerId, date: date, identifier: "Response", message: "Received empty network response for \(target).")]
}
var output = [String]()
output += [format(loggerId, date: date, identifier: "Response", message: response.description)]
if let data = data, let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) as? String where verbose == true {
output += [stringData]
}
return output
}
}
| mit | 8c4d5481cd057f58b24753bcd7b468b7 | 39.528736 | 147 | 0.653715 | 4.810368 | false | false | false | false |
exyte/fan-menu | Example/Example/TaskViewController.swift | 1 | 1906 | import Foundation
import UIKit
import Macaw
import FanMenu
class TaskViewController: UIViewController {
@IBOutlet weak var fanMenu: FanMenu!
@IBOutlet weak var colorLabel: UILabel!
let colors = [0x231FE4, 0x00BFB6, 0xFFC43D, 0xFF5F3D, 0xF34766]
override func viewDidLoad() {
super.viewDidLoad()
fanMenu.button = mainButton(colorHex: 0x7C93FE)
fanMenu.items = colors.enumerated().map { arg -> FanMenuButton in
let (index, item) = arg
return FanMenuButton(
id: String(index),
image: .none,
color: Color(val: item)
)
}
fanMenu.menuRadius = 70.0
fanMenu.duration = 0.2
fanMenu.interval = (Double.pi, 2 * Double.pi)
fanMenu.radius = 15.0
fanMenu.onItemWillClick = { button in
self.hideTitle()
if button.id != "main" {
let newColor = self.colors[Int(button.id)!]
let fanGroup = self.fanMenu.node as? Group
let circleGroup = fanGroup?.contents[2] as? Group
let shape = circleGroup?.contents[0] as? Shape
shape?.fill = Color(val: newColor)
}
}
fanMenu.transform = CGAffineTransform(rotationAngle: CGFloat(3 * Double.pi/2.0))
fanMenu.backgroundColor = .clear
}
func hideTitle() {
let newValue = !self.colorLabel.isHidden
UIView.transition(
with: colorLabel, duration: 0.5, options: .transitionCrossDissolve, animations: {
self.colorLabel.isHidden = newValue
}, completion: nil)
}
func mainButton(colorHex: Int) -> FanMenuButton {
return FanMenuButton(
id: "main",
image: .none,
color: Color(val: colorHex)
)
}
}
| mit | d1868f47de49704bdb2328365fec151c | 29.741935 | 93 | 0.555089 | 4.312217 | false | false | false | false |
edx/edx-app-ios | Source/EnrolledCoursesViewController+Banner.swift | 1 | 3916 | //
// EnrolledCoursesViewController+Banner.swift
// edX
//
// Created by Saeed Bashir on 9/29/21.
// Copyright © 2021 edX. All rights reserved.
//
import Foundation
// if the app is open from the deep link, send banner get request after a delay
private let DeeplinkDelayTime: Double = 10
//Notics/Acquisition Banner handling
extension EnrolledCoursesViewController: BannerViewControllerDelegate {
func handleBanner() {
if !handleBannerOnStart || environment.session.currentUser == nil {
return
}
// If the banner is already on screen don't send the banner request
if UIApplication.shared.topMostController() is BannerViewController {
return
}
let delegate = UIApplication.shared.delegate as? OEXAppDelegate
let delay: Double = delegate?.appOpenedFromExternalLink == true ? DeeplinkDelayTime : 0
delegate?.appOpenedFromExternalLink = false
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
self?.fetchBanner()
}
}
private func fetchBanner() {
let request = BannerAPI.unacknowledgedAPI()
environment.networkManager.taskForRequest(request) { [weak self] result in
if let link = result.data?.first {
self?.showBanner(with: link, title: nil, requireAuth: true, showNavbar: false)
}
}
}
private func showBanner(with link: String, title: String?, requireAuth: Bool, modal: Bool = true, showNavbar: Bool) {
guard let topController = UIApplication.shared.topMostController(),
let URL = URL(string: link) else { return }
environment.router?.showBannerViewController(from: topController, url: URL, title: title, delegate: self, alwaysRequireAuth: requireAuth, modal: modal, showNavbar: showNavbar)
}
private func showBrowserViewController(with link: String, title: String? ,requireAuth: Bool) {
guard let topController = UIApplication.shared.topMostController(),
let URL = URL(string: link) else { return }
environment.router?.showBrowserViewController(from: topController, title: title, url: URL)
}
//MARK:- BannerViewControllerDelegate
func navigate(with action: BannerAction, screen: BannerScreen?) {
switch action {
case .continueWithoutDismiss:
if let screen = screen,
let navigationURL = navigationURL(for: screen) {
showBanner(with: navigationURL, title: nil, requireAuth: authRequired(for: screen), modal: false, showNavbar: true)
}
break
case .dismiss:
dismiss(animated: true) { [weak self] in
if let screen = screen,
let navigationURL = self?.navigationURL(for: screen) {
self?.showBrowserViewController(with: navigationURL, title: self?.title(for: screen), requireAuth: self?.authRequired(for: screen) ?? false)
}
}
break
}
}
private func navigationURL(for screen: BannerScreen) -> String? {
switch screen {
case .privacyPolicy:
return environment.config.agreementURLsConfig.privacyPolicyURL?.absoluteString
case .tos:
return environment.config.agreementURLsConfig.tosURL?.absoluteString
case .deleteAccount:
return environment.config.deleteAccountURL
}
}
private func title(for screen: BannerScreen) -> String? {
switch screen {
case .deleteAccount:
return Strings.ProfileOptions.Deleteaccount.webviewTitle
default:
return nil
}
}
private func authRequired(for screen: BannerScreen) -> Bool {
switch screen {
case .deleteAccount:
return true
default:
return false
}
}
}
| apache-2.0 | 0947b9c3e3aa8c79087e128b4f31c130 | 35.933962 | 183 | 0.638825 | 4.906015 | false | false | false | false |
dongjiahao/-2D-3D- | 作死/CeMian.swift | 1 | 2574 | //
// CeMian.swift
// 作死
//
// Created by 董嘉豪 on 2017/8/2.
// Copyright © 2017年 董嘉豪. All rights reserved.
//
import UIKit
import Photos
//获取侧面
class CeMian: SelectTheImageUIViewController {
@objc func theNextStep() {
do {
try isThereAnImage(侧面)
skip("ShowCeMianViewController")
} catch EnrollError.noImageFound {
let a = UIAlertController(title: "错误",
message: "请选择图片后再进入下一步",
preferredStyle: UIAlertControllerStyle.alert)
a.addAction(UIAlertAction(title: "选择图片",
style: UIAlertActionStyle.default,
handler: { (_) -> Void in self.selector()}))
a.addAction(UIAlertAction(title: "关闭",
style: UIAlertActionStyle.default,
handler: nil))
self.present(a, animated: true, completion: nil)
} catch {
print("未知错误")
}
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
侧面 = info[UIImagePickerControllerOriginalImage] as? UIImage
imageView.frame = CGRect(x: 0,
y: (self.view.frame.height / 2) - (侧面!.size.height * self.view.frame.width / 侧面!.size.width) / 2,
width: self.view.frame.width,
height: 侧面!.size.height * self.view.frame.width / 侧面!.size.width)
imageView.image = 侧面
if flag {
SavePicture(侧面!)
flag = false
}
picker.dismiss(animated: true, completion: {
() -> Void in
})
}
override func viewDidLoad() {
super.viewDidLoad()
initButton(title: "选择图片",
x: 16,
y: 20,
width: 100,
height: 30,
function: #selector(CeMian.selector))
initButton(title: "下一步",
x: self.view.frame.width * 0.5 - 50,
y: 20,
width: 100,
height: 30,
function: #selector(CeMian.theNextStep))
self.view.addSubview(imageView)
}
}
| mit | 9300b579e8935be47799081a94a087a4 | 31.276316 | 130 | 0.466368 | 4.717308 | false | false | false | false |
cfm-art/SwiftJsonParser | SwiftJsonParser/Constants/DeparseOptions.swift | 1 | 2265 | //
// DeparseOption.swift
// SwiftJsonParser
//
// Created by あると on 2016/09/19.
// Copyright © 2016年 あると. All rights reserved.
//
import Foundation
/// Json文字列化の際のオプション
@objc
public class DeparseOptions
: NSObject
{
/// 改行の方法
@objc
public enum NewLine : Int
{
case kCrLf
case kCr
case kLf
case kNone
}
/// タブ
private var tab_ : String = " "
/// 改行
private var newline_ : String = ""
/// :の前のスペース
private var beforeColon_ : String = ""
/// :の後のスペース
private var afterColon_ : String = ""
/// タブの指定
/// - parameter tab :
/// - returns : self
public func setTab(tab: String) -> DeparseOptions
{
tab_ = tab
return self
}
/// 改行の指定
/// - parameter newline :
/// - returns : self
public func setNewline(newline : NewLine) -> DeparseOptions
{
switch newline {
case .kCrLf:
newline_ = "\r\n"
break
case .kCr:
newline_ = "\r"
break
case .kLf:
newline_ = "\n"
break
default:
newline_ = ""
break
}
return self
}
/// :の前後のスペース幅の指定
/// - parameter beforeWidth :
/// - parameter afterWidth :
/// - returns :
public func setColonSpace(before beforeWidth: Int, after afterWidth: Int ) -> DeparseOptions
{
let space: Character = " "
beforeColon_ = String(count: beforeWidth, repeatedValue: space)
afterColon_ = String(count: afterWidth, repeatedValue: space)
return self
}
///
/// - returns :
internal func tab() -> String
{
return tab_
}
///
/// - returns :
internal func newline() -> String
{
return newline_
}
///
/// - returns :
internal func beforeColon() -> String
{
return beforeColon_
}
///
/// - returns :
internal func afterColon() -> String
{
return afterColon_
}
}
| mit | 055ce63ea820e8506c1a41e8c980315a | 18.759259 | 96 | 0.490159 | 4.018832 | false | false | false | false |
wireapp/wire-ios-data-model | Tests/Source/Model/Messages/ZMClientMessageTests+Unarchiving.swift | 1 | 4505 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import WireTesting
import WireDataModel
class ZMClientMessageTests_Unarchiving: BaseZMClientMessageTests {
func testThatItUnarchivesAConversationWhenItWasNotCleared() {
// given
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.remoteIdentifier = UUID.create()
conversation.isArchived = true
let genericMessage = GenericMessage(content: Text(content: "bar"))
let event = createUpdateEvent(UUID(), conversationID: conversation.remoteIdentifier!, genericMessage: genericMessage)
// when
performPretendingUiMocIsSyncMoc {
XCTAssertNotNil(ZMOTRMessage.createOrUpdate(from: event, in: self.uiMOC, prefetchResult: nil))
}
// then
XCTAssertFalse(conversation.isArchived)
}
func testThatItDoesNotUnarchiveASilencedConversation() {
// given
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.remoteIdentifier = UUID.create()
conversation.isArchived = true
conversation.mutedMessageTypes = .all
let genericMessage = GenericMessage(content: Text(content: "bar"))
let event = createUpdateEvent(UUID(), conversationID: conversation.remoteIdentifier!, genericMessage: genericMessage)
// when
performPretendingUiMocIsSyncMoc {
ZMOTRMessage.createOrUpdate(from: event, in: self.uiMOC, prefetchResult: nil)
}
// then
XCTAssertTrue(conversation.isArchived)
}
func testThatItDoesNotUnarchiveAClearedConversation_TimestampForMessageIsOlder() {
// given
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.remoteIdentifier = UUID.create()
conversation.isArchived = true
uiMOC.saveOrRollback()
let lastMessage = try! conversation.appendText(content: "foo") as! ZMClientMessage
lastMessage.serverTimestamp = Date().addingTimeInterval(10)
conversation.lastServerTimeStamp = lastMessage.serverTimestamp!
conversation.clearMessageHistory()
let genericMessage = GenericMessage(content: Text(content: "bar"))
let event = createUpdateEvent(UUID(), conversationID: conversation.remoteIdentifier!, genericMessage: genericMessage)
XCTAssertNotNil(event)
XCTAssertGreaterThan(conversation.clearedTimeStamp!.timeIntervalSince1970, event.timestamp!.timeIntervalSince1970)
// when
performPretendingUiMocIsSyncMoc {
ZMOTRMessage.createOrUpdate(from: event, in: self.uiMOC, prefetchResult: nil)
}
// then
XCTAssertTrue(conversation.isArchived)
}
func testThatItUnarchivesAClearedConversation_TimestampForMessageIsNewer() {
// given
let conversation = ZMConversation.insertNewObject(in: uiMOC)
conversation.remoteIdentifier = UUID.create()
conversation.isArchived = true
uiMOC.saveOrRollback()
let lastMessage = try! conversation.appendText(content: "foo") as! ZMClientMessage
lastMessage.serverTimestamp = Date().addingTimeInterval(-10)
conversation.lastServerTimeStamp = lastMessage.serverTimestamp!
conversation.clearMessageHistory()
let genericMessage = GenericMessage(content: Text(content: "bar"))
let event = createUpdateEvent(UUID(), conversationID: conversation.remoteIdentifier!, genericMessage: genericMessage)
XCTAssertLessThan(conversation.clearedTimeStamp!.timeIntervalSince1970, event.timestamp!.timeIntervalSince1970)
// when
performPretendingUiMocIsSyncMoc {
ZMOTRMessage.createOrUpdate(from: event, in: self.uiMOC, prefetchResult: nil)
}
// then
XCTAssertFalse(conversation.isArchived)
}
}
| gpl-3.0 | a007df163826ad06726cb0f35950add8 | 37.504274 | 125 | 0.714317 | 5.275176 | false | true | false | false |
hooman/swift | test/SILGen/Inputs/specialize_attr_module2.swift | 4 | 971 | import A
extension PublicThing {
@_specialize(exported: true, kind: full, target: doStuffWith(_:), where T == Int)
public func specializedoStuff2(_ t: T) {}
}
@_specializeExtension
extension InternalThing {
@_specialize(exported: true, target:doStuffWith(boxed:), where T == Int)
public func specializedDoStuffWith2(_ t: BoxedThing<T>) {}
}
@_specializeExtension
extension InternalThing2 {
public var specializeComputedZ : T {
@_specialize(exported: true, target: computedZ, where T == Int)
_modify {
fatalError("don't call")
}
@_specialize(exported: true, target: computedZ, where T == Int)
_read {
fatalError("don't call")
}
}
public subscript(specialized i: Int) -> T {
@_specialize(exported: true, target: subscript(_:), where T == Int)
get {
fatalError("don't call")
}
@_specialize(exported: true, target: subscript(_:), where T == Int)
set {
fatalError("don't call")
}
}
}
| apache-2.0 | 98e6fa9a2e57c8189d313e58c60fd031 | 25.243243 | 83 | 0.644696 | 3.868526 | false | false | false | false |
codelynx/ShogibanKit | Sources/ShogibanKit/String+Z.swift | 1 | 3062 | //
// String+Z.swift
// ZKit
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Electricwoods LLC, Kaz Yoshikawa.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension String {
func stringByAppendingPathExtension(_ str: String) -> String? {
return (self as NSString).appendingPathExtension(str)
}
func stringByAppendingPathComponent(_ str: String) -> String {
return (self as NSString).appendingPathComponent(str)
}
var stringByDeletingPathExtension: String {
return (self as NSString).deletingPathExtension
}
var stringByDeletingLastPathComponent: String {
return (self as NSString).deletingLastPathComponent
}
var stringByAbbreviatingWithTildeInPath: String {
return (self as NSString).abbreviatingWithTildeInPath;
}
var stringByExpandingTildeInPath: String {
return (self as NSString).expandingTildeInPath;
}
var lastPathComponent: String {
return (self as NSString).lastPathComponent
}
var pathExtension: String {
return (self as NSString).pathExtension
}
var pathComponents: [String] {
return (self as NSString).pathComponents
}
func pathsForResourcesOfType(_ type: String) -> [String] {
let enumerator = FileManager.default.enumerator(atPath: self)
var filePaths = [String]()
while let filePath = enumerator?.nextObject() as? String {
if filePath.pathExtension == type {
filePaths.append(filePath)
}
}
return filePaths
}
var lines: [String] {
var lines = [String]()
self.enumerateLines { (line, stop) -> () in
lines.append(line)
}
return lines
}
func indent() -> String {
return self.lines.map{" " + $0}.joined(separator: "\r")
}
func substringWithRange(_ range: NSRange) -> Substring {
let subindex1 = self.index(self.startIndex, offsetBy: range.location)
let subindex2 = self.index(subindex1, offsetBy: range.length)
return self[subindex1 ..< subindex2]
// return self.substring(with: subindex1 ..< subindex2)
}
var data: Data {
return self.data(using: String.Encoding.utf8)!
}
}
| mit | 10178a55905a5236a9ce7394c6723d8f | 28.728155 | 85 | 0.733834 | 3.866162 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/AggregationResult.swift | 1 | 1731 | /**
* Copyright IBM Corporation 2018
*
* 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
/** AggregationResult. */
public struct AggregationResult: Decodable {
/// Key that matched the aggregation type.
public var key: String?
/// Number of matching results.
public var matchingResults: Int?
/// Aggregations returned in the case of chained aggregations.
public var aggregations: [QueryAggregation]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case key = "key"
case matchingResults = "matching_results"
case aggregations = "aggregations"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let keyAsString = try? container.decode(String.self, forKey: .key) { key = keyAsString }
if let keyAsInt = try? container.decode(Int.self, forKey: .key) { key = "\(keyAsInt)" }
matchingResults = try container.decodeIfPresent(Int.self, forKey: .matchingResults)
aggregations = try container.decodeIfPresent([QueryAggregation].self, forKey: .aggregations)
}
}
| mit | e9bca4e60f54be746ccdcb5b2b37a4df | 36.630435 | 100 | 0.709417 | 4.46134 | false | false | false | false |
Harley-xk/Chrysan | Chrysan/Sources/Views/AnimatedPathView.swift | 1 | 2174 | //
// ShapeView.swift
// Chrysan
//
// Created by Harley-xk on 2020/9/29.
// Copyright © 2020 Harley. All rights reserved.
//
import UIKit
public class AnimatedPathView: UIView {
public typealias Path = [CGPoint]
var paths: [Path] = []
var color: UIColor = .white
/// create an AnimatedPathView from path array
/// - Parameter paths: vector point arrays form 0 ~ 1
public convenience init(paths: [Path], color: UIColor) {
self.init()
backgroundColor = .clear
self.paths = paths
self.color = color
}
public override class var layerClass: AnyClass {
return CAShapeLayer.self
}
var shapeLayer: CAShapeLayer {
return layer as! CAShapeLayer
}
public override func draw(_ rect: CGRect) {
super.draw(rect)
let path = UIBezierPath()
for lines in paths {
guard lines.count > 1 else {
break
}
let first = lines.first!
path.move(to: CGPoint(
x: first.x * bounds.width,
y: first.y * bounds.height
))
for index in 1 ..< lines.count {
let point = lines[index]
path.addLine(
to: CGPoint(
x: point.x * bounds.width,
y: point.y * bounds.height
)
)
}
}
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = 3
shapeLayer.lineCap = .round
shapeLayer.lineJoin = .round
shapeLayer.path = path.cgPath
}
public func startAnimation() {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = 0.0
animation.toValue = 1.0
animation.duration = 0.3
animation.fillMode = .forwards
animation.isRemovedOnCompletion = true
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
shapeLayer.add(animation, forKey: nil)
}
}
| mit | b551676ab1fcb25ac0964508cf9c29fa | 25.82716 | 78 | 0.541647 | 4.905192 | false | false | false | false |
kstaring/swift | benchmark/single-source/Integrate.swift | 4 | 1921 | //===--- Integrate.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
// A micro-benchmark for recursive divide and conquer problems.
// The program performs integration via Gaussian Quadrature
class Integrate {
static let epsilon = 1.0e-9
let fun: (Double) -> Double
init (f: @escaping (Double) -> Double) {
fun = f
}
private func recEval(_ l: Double, fl: Double, r: Double, fr: Double, a: Double) -> Double {
let h = (r - l) / 2
let hh = h / 2
let c = l + h
let fc = fun(c)
let al = (fl + fc) * hh
let ar = (fr + fc) * hh
let alr = al + ar
let error = abs(alr-a)
if (error < Integrate.epsilon) {
return alr
} else {
let a1 = recEval(c, fl:fc, r:r, fr:fr, a:ar)
let a2 = recEval(l, fl:fl, r:c, fr:fc, a:al)
return a1 + a2
}
}
@inline(never)
func computeArea(_ left: Double, right: Double) -> Double {
return recEval(left, fl:fun(left), r:right, fr:fun(right), a:0)
}
}
@inline(never)
public func run_Integrate(_ N: Int) {
let obj = Integrate(f: { x in (x*x + 1.0) * x})
let left = 0.0
let right = 10.0
let ref_result = 2550.0
let bound = 0.0001
var result = 0.0
for _ in 1...N {
result = obj.computeArea(left, right:right)
if abs(result - ref_result) > bound {
break
}
}
CheckResults(abs(result - ref_result) < bound,
"Incorrect results in Integrate: abs(\(result) - \(ref_result)) > \(bound)")
}
| apache-2.0 | a3b792d5aacc3492a893b0954b388d4b | 27.25 | 93 | 0.565331 | 3.412078 | false | false | false | false |
4jchc/4jchc-BaiSiBuDeJie | 4jchc-BaiSiBuDeJie/4jchc-BaiSiBuDeJie/Class/Tool/UITabBarController+Extension.swift | 1 | 1383 | //
// UITabBarController+UITabBar.swift
// 4jchc-BaiSiBuDeJie
//
// Created by 蒋进 on 16/2/15.
// Copyright © 2016年 蒋进. All rights reserved.
//
import Foundation
import UIKit
extension UITabBarController{
//MARK: 添加子控制器+UITabBar封装-UIViewController版
/// 添加子控制器+UITabBar封装-UIViewController版
func addChildVc(title:String ,image:String, selectedImage:String,childVc:UIViewController){
// 设置子控制器的文字
//childVc.title = title // 同时设置tabbar和navigationBar的文字
// 设置tabbar的文字
childVc.tabBarItem.title = title as String
// 设置navigationBar的文字
// childVc.navigationItem.title = title as String
childVc.tabBarItem.image = UIImage(named: image)
// 声明:这张图片按照原始的样子显示出来,不要自动渲染成其他颜色(比如蓝色)
childVc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
// 先给外面传进来的小控制器 包装 一个导航控制器
let nav:XMGNavigationController = XMGNavigationController(rootViewController: childVc)
/// 添加为子控制器
self.addChildViewController(nav)
}
} | apache-2.0 | d93ca90c91c4bc5aa4222784af57f6c5 | 26.5 | 133 | 0.669844 | 4.421456 | false | false | false | false |
natecook1000/WWDC | WWDC/RoundPlayButton.swift | 2 | 1168 | //
// RoundPlayButton.swift
// WWDC
//
// Created by Guilherme Rambo on 05/10/15.
// Copyright © 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ViewUtils
class RoundPlayButton: NSButton {
override func drawRect(dirtyRect: NSRect) {
let bezel = NSBezierPath(ovalInRect: NSInsetRect(bounds, 1.0, 1.0))
bezel.lineWidth = 1.0
if highlighted {
Theme.WWDCTheme.fillColor.darkerColor.set()
} else {
Theme.WWDCTheme.fillColor.set()
}
bezel.stroke()
let playImage = NSImage(named: "play")!
let playMask = playImage.CGImage
let ctx = NSGraphicsContext.currentContext()?.CGContext
let multiplier = CGFloat(0.8)
let imageWidth = playImage.size.width*multiplier
let imageHeight = playImage.size.height*multiplier
let glyphRect = NSMakeRect(floor(bounds.size.width/2-imageWidth/2)+2.0, floor(bounds.size.height/2-imageHeight/2)+1.0, floor(imageWidth), floor(imageHeight))
CGContextClipToMask(ctx, glyphRect, playMask)
CGContextFillRect(ctx, bounds)
}
}
| bsd-2-clause | 9018f3202b458ac2e0658618f383aa18 | 28.923077 | 165 | 0.634961 | 4.306273 | false | false | false | false |
elslooo/hoverboard | Hoverboard/AuthorizationManagerDelegate.swift | 1 | 4114 | /*
* Copyright (c) 2017 Tim van Elsloo
*
* 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 AppKit
import Foundation
import HoverboardKit
extension AppDelegate : AuthorizationManagerDelegate {
/**
* In this function we update our user interface if necessary to reflect
* whether or not Hoverboard is authorized to manage windows of other
* applications.
*/
func authorizationManagerDidGrantAccess(_ manager: AuthorizationManager) {
if self.hasCompletedOnboarding == false {
// If the user has not completed onboarding, we make sure to present
// the onboarding window controller. It will also activate (focus)
// the app and show our icon in the dock.
if self.onboardingWindowController == nil {
self.setupOnboardingController()
}
NSApp.activate(ignoringOtherApps: true)
NSApp.setActivationPolicy(.regular)
} else {
// If the user has already completed onboarding, we don't have to do
// anything other than to make sure that the icon is not shown in
// the dock.
NSApp.setActivationPolicy(.accessory)
}
do {
// Initialize and configure a new window manager.
try self.manager = WindowManager()
self.manager?.delegate = self
try self.manager?.start()
// If we are in the process of onboarding, make sure that the user
// interface reflects the change in authorization.
if let setupController = self.setupController {
if setupController.indexOfSelectedItem < 2 &&
LoginItem.main.isEnabled {
setupController.selectItem(atIndex: 2, animated: true)
} else if setupController.indexOfSelectedItem < 1 {
setupController.selectItem(atIndex: 1, animated: true)
}
}
} catch let error {
// TODO: we need to propagate this error to the user interface.
print("Error: \(error)")
}
}
/**
* In this function we update the user interface state to reflect that
* authorization to Hoverboard for managing windows of other applications
* has been revoked.
*/
func authorizationManagerDidRevokeAccess(_ manager: AuthorizationManager) {
NSApp.setActivationPolicy(.regular)
self.hasCompletedOnboarding = false
if let controller = self.onboardingWindowController,
let setupController = self.setupController {
// We need to show the onboarding window, pop it to the first view
// controller and select the first stage (authorization).
controller.showWindow(nil)
controller.pop(controller: setupController, animated: true)
self.setupController?.selectItem(atIndex: 0, animated: true)
} else {
self.setupOnboardingController()
NSApp.activate(ignoringOtherApps: true)
}
}
}
| mit | 4c49c3447673dd0e7d5a9dae854908da | 42.305263 | 80 | 0.659212 | 5.201011 | false | false | false | false |
MHaroonBaig/MotionKit | Example/Example/AppDelegate.swift | 4 | 6115 | //
// AppDelegate.swift
// Example
//
// Created by Haroon on 19/02/2015.
// Copyright (c) 2015 MotionKit. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.motionkit.Example" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Example", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Example.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 642ec18e393efedcd302432de39b9471 | 54.09009 | 290 | 0.716108 | 5.79072 | false | false | false | false |
juangrt/SwiftImageUploader | SwiftImageUploader/AppDelegate.swift | 1 | 3287 | //
// AppDelegate.swift
// SwiftImageUploader
//
// Created by Juan Carlos Garzon on 6/22/16.
// Copyright © 2016 ZongWare. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[0] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? MediaCollectionViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| gpl-3.0 | d943055b9a66bd7eaa42bb740cb2bab2 | 54.694915 | 285 | 0.765673 | 6.2 | false | false | false | false |
designatednerd/Cat2Cat | SampleSwiftMacApp/Cat2CatExampleSwiftMac/Cat2CatExampleSwiftMacTests/Cat2CatExampleSwiftMacTests.swift | 1 | 2843 | //
// Cat2CatExampleSwiftMacTests.swift
// Cat2CatExampleSwiftMacTests
//
// Created by Isaac Greenspan on 11/3/14.
// Copyright (c) 2014 Vokal. All rights reserved.
//
import Cocoa
import XCTest
class Cat2CatExampleSwiftMacTests: XCTestCase {
/// Tests the assumption that an .appiconset returns an image when using imageNamed:
func testAppIconsDoReturnImages() {
XCTAssertNotNil(NSImage(named:"AppIcon"), "AppIcon is nil!")
}
/// Tests the assumption that an .iconset returns an image when using imageNamed:
func testIconSetsDoReturnImages() {
XCTAssertNotNil(NSImage(named:"Icon"), "Icon is nil!")
}
/// Tests that the image data retrieved from the two different methods is identical.
func testMethodImageAndImageNamedAreEqual() {
guard let imageNamed = NSImage(named:"US Capitol") else {
XCTFail("Named image did not unwrap!")
return
}
let methodRetreived = NSImage.ac_US_Capitol()
let imageNamedData = imageNamed.TIFFRepresentation
let methodReterivedData = methodRetreived.TIFFRepresentation
// Compare the data of the two images. Note that comparing the images directly doesn't work since that tests whether they're the same instance, not whether they have identical data.
XCTAssertTrue(imageNamedData == methodReterivedData, "Capitol images are not equal!")
}
/// Tests that our pipe-seperation of items from seperate catalogs is working by making sure at least one image from each catalog has made it in.
func testAtLeastOneImageFromEachCatalogWorks() {
XCTAssertNotNil(NSImage.ac_No_C(), "No C Image was nil!")
XCTAssertNotNil(NSImage.ac_Golden_Gate_Bridge(), "Golden Gate Bridge image was nil!")
}
/// Tests that all images from the Photos Asset Catalog are working.
func testAllImagesFromPhotosWork() {
XCTAssertNotNil(NSImage.ac_Golden_Gate_Bridge(), "Golden Gate Bridge image was nil!")
XCTAssertNotNil(NSImage.ac_US_Capitol(), "US Capitol image was nil!")
XCTAssertNotNil(NSImage.ac_Venice_Beach(), "Venice Beach image was nil!")
XCTAssertNotNil(NSImage.ac_Wrigley_Field(), "Wrigley Field image was nil!")
}
/// Tests that all images from the Icons Asset Catalog are working.
func testThatAllImagesFromIconsWork() {
XCTAssertNotNil(NSImage.ac_AppIcon(), "App Icon was nil!")
XCTAssertNotNil(NSImage.ac_Icon(), "Icon was nil!")
XCTAssertNotNil(NSImage.ac_No_C(), "No C image was nil!")
XCTAssertNotNil(NSImage.ac_SidewaysC(), "Sideways C was nil!")
XCTAssertNotNil(NSImage.ac_PD_in_circle(), "PD in circle was nil!")
XCTAssertNotNil(NSImage.ac_PDe_Darka_Circle(), "PD in dark circle was nil")
}
}
| mit | a027a60446df5ca831b9ab9413ca1dbe | 43.421875 | 189 | 0.687302 | 4.387346 | false | true | false | false |
auth0/Auth0.swift | Auth0Tests/WebAuthenticationSpec.swift | 1 | 840 | import Foundation
import Quick
import Nimble
@testable import Auth0
class WebAuthenticationSpec: QuickSpec {
override func spec() {
let storage = TransactionStore.shared
var transaction: SpyTransaction!
beforeEach {
transaction = SpyTransaction()
storage.clear()
storage.store(transaction)
}
describe("current transaction") {
let url = URL(string: "https://auth0.com")!
it("should resume current transaction") {
transaction.isResumed = true
expect(WebAuthentication.resume(with: url)) == true
}
it("should cancel current transaction") {
WebAuthentication.cancel()
expect(transaction.isCancelled) == true
}
}
}
}
| mit | c13f5f0f61d708983cadd97f18fd4fd9 | 21.105263 | 67 | 0.566667 | 5.350318 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/infinite_recursion.swift | 11 | 4044 | // RUN: %target-swift-frontend -emit-sil -primary-file %s -o /dev/null -verify
func a() { // expected-warning {{all paths through this function will call itself}}
a()
}
func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
if x != 0 {
b(x)
} else {
b(x+1)
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
if x != 0 {
x += 1
}
return d(x)
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() { // expected-warning {{all paths through this function will call itself}}
while true { // expected-note {{condition always evaluates to true}}
g()
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
while (x < 5) {
x -= 1
}
i(0)
}
func j() -> Int { // expected-warning {{all paths through this function will call itself}}
return 5 + j()
}
func k() -> Any { // expected-warning {{all paths through this function will call itself}}
return type(of: k())
}
@_silgen_name("exit") func exit(_: Int32) -> Never
func l() {
guard Bool.random() else {
exit(0) // no warning; calling 'exit' terminates the program
}
l()
}
func m() { // expected-warning {{all paths through this function will call itself}}
guard Bool.random() else {
fatalError() // we _do_ warn here, because fatalError is a programtermination_point
}
m()
}
enum MyNever {}
func blackHole() -> MyNever { // expected-warning {{all paths through this function will call itself}}
blackHole()
}
@_semantics("programtermination_point")
func terminateMe() -> MyNever {
terminateMe() // no warning; terminateMe is a programtermination_point
}
func n() -> MyNever {
if Bool.random() {
blackHole() // no warning; blackHole() will terminate the program
}
n()
}
func o() -> MyNever {
if Bool.random() {
o()
}
blackHole() // no warning; blackHole() will terminate the program
}
func mayHaveSideEffects() {}
func p() { // expected-warning {{all paths through this function will call itself}}
if Bool.random() {
mayHaveSideEffects() // presence of side-effects doesn't alter the check for the programtermination_point apply
fatalError()
}
p()
}
class S {
convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}}
self.init(a: a)
}
init(a: Int?) {}
static func a() { // expected-warning {{all paths through this function will call itself}}
return a()
}
func b() { // expected-warning {{all paths through this function will call itself}}
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
var bar: String = "hi!"
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
override var bar: String {
get {
return super.bar
}
set { // expected-warning {{all paths through this function will call itself}}
self.bar = newValue
}
}
}
func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}}
if l == nil && r == nil { return true }
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}}
return lhs == rhs
}
func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}}
return (n != 0) ? factorial(n - 1) * n : factorial(1)
}
func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}}
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
}
| apache-2.0 | 2acb9279a5ec548928eb2fdb2ab7ae4e | 22.511628 | 149 | 0.617458 | 3.504333 | false | false | false | false |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/codegen/Killmails.swift | 1 | 11932 | import Foundation
import Alamofire
import Futures
public extension ESI {
var killmails: Killmails {
return Killmails(esi: self)
}
struct Killmails {
let esi: ESI
@discardableResult
public func getSingleKillmail(ifNoneMatch: String? = nil, killmailHash: String, killmailID: Int, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<Killmails.Killmail>> {
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
let url = esi.baseURL + "/killmails/\(killmailID)/\(killmailHash)/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<Killmails.Killmail>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<Killmails.Killmail>) in
promise.set(response: response, cached: 1209600.0)
}
return promise.future
}
@discardableResult
public func getCorporationsRecentKillsAndLosses(corporationID: Int, ifNoneMatch: String? = nil, page: Int? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Killmails.GetCorporationsCorporationIDKillmailsRecentOk]>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-killmails.read_corporation_killmails.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
if let v = page?.httpQuery {
query.append(URLQueryItem(name: "page", value: v))
}
let url = esi.baseURL + "/corporations/\(corporationID)/killmails/recent/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<[Killmails.GetCorporationsCorporationIDKillmailsRecentOk]>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Killmails.GetCorporationsCorporationIDKillmailsRecentOk]>) in
promise.set(response: response, cached: 300.0)
}
return promise.future
}
@discardableResult
public func getCharactersRecentKillsAndLosses(characterID: Int, ifNoneMatch: String? = nil, page: Int? = nil, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> Future<ESI.Result<[Killmails.Recent]>> {
let scopes = esi.token?.scopes ?? []
guard scopes.contains("esi-killmails.read_killmails.v1") else {return .init(.failure(ESIError.forbidden))}
let body: Data? = nil
var headers = HTTPHeaders()
headers["Accept"] = "application/json"
if let v = ifNoneMatch?.httpQuery {
headers["If-None-Match"] = v
}
var query = [URLQueryItem]()
query.append(URLQueryItem(name: "datasource", value: esi.server.rawValue))
if let v = page?.httpQuery {
query.append(URLQueryItem(name: "page", value: v))
}
let url = esi.baseURL + "/characters/\(characterID)/killmails/recent/"
let components = NSURLComponents(string: url)!
components.queryItems = query
let promise = Promise<ESI.Result<[Killmails.Recent]>>()
esi.request(components.url!, method: .get, encoding: body ?? URLEncoding.default, headers: headers, cachePolicy: cachePolicy).validateESI().responseESI { (response: DataResponse<[Killmails.Recent]>) in
promise.set(response: response, cached: 300.0)
}
return promise.future
}
public struct GetKillmailsKillmailIDKillmailHashUnprocessableEntity: Codable, Hashable {
public var error: String?
public init(error: String?) {
self.error = error
}
enum CodingKeys: String, CodingKey, DateFormatted {
case error
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct GetCorporationsCorporationIDKillmailsRecentOk: Codable, Hashable {
public var killmailHash: String
public var killmailID: Int
public init(killmailHash: String, killmailID: Int) {
self.killmailHash = killmailHash
self.killmailID = killmailID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case killmailHash = "killmail_hash"
case killmailID = "killmail_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Recent: Codable, Hashable {
public var killmailHash: String
public var killmailID: Int
public init(killmailHash: String, killmailID: Int) {
self.killmailHash = killmailHash
self.killmailID = killmailID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case killmailHash = "killmail_hash"
case killmailID = "killmail_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Killmail: Codable, Hashable {
public struct Victim: Codable, Hashable {
public struct GetKillmailsKillmailIDKillmailHashPosition: Codable, Hashable {
public var x: Double
public var y: Double
public var z: Double
public init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
enum CodingKeys: String, CodingKey, DateFormatted {
case x
case y
case z
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Items: Codable, Hashable {
public struct Item: Codable, Hashable {
public var flag: Int
public var itemTypeID: Int
public var quantityDestroyed: Int64?
public var quantityDropped: Int64?
public var singleton: Int
public init(flag: Int, itemTypeID: Int, quantityDestroyed: Int64?, quantityDropped: Int64?, singleton: Int) {
self.flag = flag
self.itemTypeID = itemTypeID
self.quantityDestroyed = quantityDestroyed
self.quantityDropped = quantityDropped
self.singleton = singleton
}
enum CodingKeys: String, CodingKey, DateFormatted {
case flag
case itemTypeID = "item_type_id"
case quantityDestroyed = "quantity_destroyed"
case quantityDropped = "quantity_dropped"
case singleton
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public var flag: Int
public var itemTypeID: Int
public var items: [Killmails.Killmail.Victim.Items.Item]?
public var quantityDestroyed: Int64?
public var quantityDropped: Int64?
public var singleton: Int
public init(flag: Int, itemTypeID: Int, items: [Killmails.Killmail.Victim.Items.Item]?, quantityDestroyed: Int64?, quantityDropped: Int64?, singleton: Int) {
self.flag = flag
self.itemTypeID = itemTypeID
self.items = items
self.quantityDestroyed = quantityDestroyed
self.quantityDropped = quantityDropped
self.singleton = singleton
}
enum CodingKeys: String, CodingKey, DateFormatted {
case flag
case itemTypeID = "item_type_id"
case items
case quantityDestroyed = "quantity_destroyed"
case quantityDropped = "quantity_dropped"
case singleton
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public var allianceID: Int?
public var characterID: Int?
public var corporationID: Int?
public var damageTaken: Int
public var factionID: Int?
public var items: [Killmails.Killmail.Victim.Items]?
public var position: Killmails.Killmail.Victim.GetKillmailsKillmailIDKillmailHashPosition?
public var shipTypeID: Int
public init(allianceID: Int?, characterID: Int?, corporationID: Int?, damageTaken: Int, factionID: Int?, items: [Killmails.Killmail.Victim.Items]?, position: Killmails.Killmail.Victim.GetKillmailsKillmailIDKillmailHashPosition?, shipTypeID: Int) {
self.allianceID = allianceID
self.characterID = characterID
self.corporationID = corporationID
self.damageTaken = damageTaken
self.factionID = factionID
self.items = items
self.position = position
self.shipTypeID = shipTypeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case allianceID = "alliance_id"
case characterID = "character_id"
case corporationID = "corporation_id"
case damageTaken = "damage_taken"
case factionID = "faction_id"
case items
case position
case shipTypeID = "ship_type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public struct Attacker: Codable, Hashable {
public var allianceID: Int?
public var characterID: Int?
public var corporationID: Int?
public var damageDone: Int
public var factionID: Int?
public var finalBlow: Bool
public var securityStatus: Float
public var shipTypeID: Int?
public var weaponTypeID: Int?
public init(allianceID: Int?, characterID: Int?, corporationID: Int?, damageDone: Int, factionID: Int?, finalBlow: Bool, securityStatus: Float, shipTypeID: Int?, weaponTypeID: Int?) {
self.allianceID = allianceID
self.characterID = characterID
self.corporationID = corporationID
self.damageDone = damageDone
self.factionID = factionID
self.finalBlow = finalBlow
self.securityStatus = securityStatus
self.shipTypeID = shipTypeID
self.weaponTypeID = weaponTypeID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case allianceID = "alliance_id"
case characterID = "character_id"
case corporationID = "corporation_id"
case damageDone = "damage_done"
case factionID = "faction_id"
case finalBlow = "final_blow"
case securityStatus = "security_status"
case shipTypeID = "ship_type_id"
case weaponTypeID = "weapon_type_id"
var dateFormatter: DateFormatter? {
switch self {
default: return nil
}
}
}
}
public var attackers: [Killmails.Killmail.Attacker]
public var killmailID: Int
public var killmailTime: Date
public var moonID: Int?
public var solarSystemID: Int
public var victim: Killmails.Killmail.Victim
public var warID: Int?
public init(attackers: [Killmails.Killmail.Attacker], killmailID: Int, killmailTime: Date, moonID: Int?, solarSystemID: Int, victim: Killmails.Killmail.Victim, warID: Int?) {
self.attackers = attackers
self.killmailID = killmailID
self.killmailTime = killmailTime
self.moonID = moonID
self.solarSystemID = solarSystemID
self.victim = victim
self.warID = warID
}
enum CodingKeys: String, CodingKey, DateFormatted {
case attackers
case killmailID = "killmail_id"
case killmailTime = "killmail_time"
case moonID = "moon_id"
case solarSystemID = "solar_system_id"
case victim
case warID = "war_id"
var dateFormatter: DateFormatter? {
switch self {
case .killmailTime: return DateFormatter.esiDateTimeFormatter
default: return nil
}
}
}
}
}
}
| mit | cbeaa64c15e0cb6518185a142c028bd2 | 29.131313 | 261 | 0.6677 | 3.777145 | false | false | false | false |
visenze/visearch-widget-swift | ViSearchWidgets/ViSearchWidgets/ViColorPickerModalViewController.swift | 2 | 9630 | //
// ViColorPickerModalViewController.swift
// ViSearchWidgets
//
// Created by Hung on 25/11/16.
// Copyright © 2016 Visenze. All rights reserved.
//
import UIKit
private let reuseIdentifier = "ViColorCell"
private let headerCollectionViewCellReuseIdentifier = "ViHeaderCell"
public protocol ViColorPickerDelegate: class {
func didPickColor(sender: ViColorPickerModalViewController, color: String)
}
/// Color picker view controller
/// Present colors in a grid (collection view). Implement ViColorPickerDelegate to receive notification for selected color
/// List of colors are configurable
open class ViColorPickerModalViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
/// list of color strings in hex format e.g. #123456 or 123456. The hex is optional
open var colorList: [String] = []
/// current selector color.. will be indicated with a tick
open var selectedColor : String? = nil
/// built in collection view
public var collectionView : UICollectionView? {
let resultsView = self.view as! ViSearchResultsView
return resultsView.collectionView
}
/// collection view layout
public var collectionViewLayout: UICollectionViewLayout {
let resultsView = self.view as! ViSearchResultsView
return resultsView.collectionViewLayout
}
/// title label
public var titleLabel : UILabel?
/// show/hide title
public var showTitleHeader: Bool = true
/// delegate notify when a color is picked
public weak var delegate: ViColorPickerDelegate?
/// size for a color item. Default to 44 x 44
public var itemSize: CGSize = CGSize(width: 44, height: 44) {
didSet {
reloadLayout()
}
}
/// spacing between items on same row.. item size may need to be re-calculated if this change
public var itemSpacing : CGFloat = 4.0 {
didSet{
reloadLayout()
}
}
/// background color
public var backgroundColor : UIColor = UIColor.white
/// left padding
public var paddingLeft: CGFloat = 0 {
didSet{
reloadLayout()
}
}
/// right padding
public var paddingRight: CGFloat = 0 {
didSet{
reloadLayout()
}
}
/// show/hide Power by Visenze logo
public var showPowerByViSenze : Bool = true
// MARK: init methods
public init() {
super.init(nibName: nil, bundle: nil)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// MARK : setup method, can be override by subclass to do init
open func setup(){
self.titleLabel = UILabel()
self.titleLabel?.textAlignment = .left
self.titleLabel?.font = ViTheme.sharedInstance.default_widget_title_font
self.title = "Pick a color:"
self.titleLabel?.text = self.title
// Important: without this the header above collection view will appear behind the navigation bar
self.edgesForExtendedLayout = []
}
open override func loadView() {
let searchResultsView = ViSearchResultsView(frame: .zero)
self.view = searchResultsView
}
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.collectionView!.delegate = self
self.collectionView!.dataSource = self
// Register cell classes
self.collectionView!.register(ViProductCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.collectionView!.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerCollectionViewCellReuseIdentifier)
reloadLayout()
}
// MARK: collectionView delegate
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize{
return .zero
}
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return colorList.count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
let color = colorList[indexPath.row]
cell.contentView.backgroundColor = UIColor.colorWithHexString(color, alpha: 1.0)
var tickView = cell.contentView.viewWithTag(99) as? UIImageView
if(tickView == nil){
// create
tickView = UIImageView(image: ViIcon.tick)
tickView?.clipsToBounds = true
// center the image
tickView?.frame = CGRect(x: ( (self.itemSize.width - 36) / 2 ) , y: ( (self.itemSize.height - 36) / 2 ) , width: 36, height: 36)
cell.contentView.addSubview(tickView!)
}
tickView?.isHidden = true
tickView?.tintColor = UIColor.white
/// if selected view, then we need to add in the tick
if let selectedColor = self.selectedColor {
if selectedColor == color {
tickView?.isHidden = false
// if white then need to change tick to black
if selectedColor == "ffffff" || selectedColor == "#ffffff" {
tickView?.tintColor = UIColor.black
}
}
}
cell.contentView.addBorder(width: 0.5, color: UIColor.lightGray)
return cell
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let delegate = delegate {
let color = colorList[indexPath.row]
self.selectedColor = color
delegate.didPickColor(sender: self, color: color)
}
}
// MARK: Reload Layout
open func reloadLayout(){
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumLineSpacing = itemSpacing
layout.minimumInteritemSpacing = itemSpacing
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.footerReferenceSize = .zero
layout.scrollDirection = .vertical
self.collectionView?.backgroundColor = backgroundColor
self.view.backgroundColor = backgroundColor
layout.itemSize = itemSize
let searchResultsView = self.view as! ViSearchResultsView
searchResultsView.paddingLeft = paddingLeft
searchResultsView.paddingRight = paddingRight
// static header
if self.headerSize.height > 0 {
if let headerView = self.headerView() {
searchResultsView.setHeader(headerView)
}
}
searchResultsView.headerHeight = self.headerSize.height
// static footer
if self.footerSize.height > 0 {
if let footerView = self.footerView() {
searchResultsView.setFooter(footerView)
}
}
searchResultsView.footerHeight = self.footerSize.height
searchResultsView.setNeedsLayout()
searchResultsView.layoutIfNeeded()
}
// MARK: header
open var headerSize : CGSize {
if !showTitleHeader {
return .zero
}
if self.title != nil {
return CGSize(width: self.view.bounds.width, height: ViTheme.sharedInstance.default_widget_title_font.lineHeight + 16)
}
return .zero
}
open func headerView() -> UIView? {
if !showTitleHeader {
return nil
}
if let title = self.title, let label = self.titleLabel {
label.text = title
label.sizeToFit()
var labelFrame = label.frame
labelFrame.origin.y = labelFrame.origin.y + 3
label.frame = labelFrame
return label
}
return nil
}
// MARK: footer - Power by ViSenze
open func footerView() -> UIView? {
if !showPowerByViSenze {
return nil
}
let powerImgView = UIImageView(image: ViIcon.power_visenze)
var width = footerSize.width
var height = footerSize.height
if let img = ViIcon.power_visenze {
width = min(width, img.size.width)
height = min(height, img.size.height)
}
powerImgView.frame = CGRect(x: (self.view.bounds.width - width - 2), y: 4 , width: width, height: height )
powerImgView.backgroundColor = ViTheme.sharedInstance.default_btn_background_color
return powerImgView
}
open var footerSize : CGSize {
if !showPowerByViSenze {
return CGSize.zero
}
// hide footer if there is no color
if self.colorList.count == 0 {
return CGSize.zero
}
return CGSize(width: 100, height: 25)
}
}
| mit | 27ae10f7a62041217ed1b7997e9b6b64 | 30.990033 | 196 | 0.612525 | 5.361359 | false | false | false | false |
tmandry/AXSwift | AXSwiftExample/AppDelegate.swift | 1 | 2524 | import Cocoa
import AXSwift
class ApplicationDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Check that we have permission
guard UIElement.isProcessTrusted(withPrompt: true) else {
NSLog("No accessibility API permission, exiting")
NSRunningApplication.current.terminate()
return
}
// Get Active Application
if let application = NSWorkspace.shared.frontmostApplication {
NSLog("localizedName: \(String(describing: application.localizedName)), processIdentifier: \(application.processIdentifier)")
let uiApp = Application(application)!
NSLog("windows: \(String(describing: try! uiApp.windows()))")
NSLog("attributes: \(try! uiApp.attributes())")
NSLog("at 0,0: \(String(describing: try! uiApp.elementAtPosition(0, 0)))")
if let bundleIdentifier = application.bundleIdentifier {
NSLog("bundleIdentifier: \(bundleIdentifier)")
let windows = try! Application.allForBundleID(bundleIdentifier).first!.windows()
NSLog("windows: \(String(describing: windows))")
}
}
// Get Application by bundleIdentifier
let app = Application.allForBundleID("com.apple.finder").first!
NSLog("finder: \(app)")
NSLog("role: \(try! app.role()!)")
NSLog("windows: \(try! app.windows()!)")
NSLog("attributes: \(try! app.attributes())")
if let title: String = try! app.attribute(.title) {
NSLog("title: \(title)")
}
NSLog("multi: \(try! app.getMultipleAttributes(["AXRole", "asdf", "AXTitle"]))")
NSLog("multi: \(try! app.getMultipleAttributes(.role, .title))")
// Try to set an unsettable attribute
if let window = try! app.windows()?.first {
do {
try window.setAttribute(.title, value: "my title")
let newTitle: String? = try! window.attribute(.title)
NSLog("title set; result = \(newTitle ?? "<none>")")
} catch {
NSLog("error caught trying to set title of window: \(error)")
}
}
NSLog("system wide:")
NSLog("role: \(try! systemWideElement.role()!)")
// NSLog("windows: \(try! sys.windows())")
NSLog("attributes: \(try! systemWideElement.attributes())")
NSRunningApplication.current.terminate()
}
}
| mit | fab60cf2948a87ccd001a7a4a5012f47 | 43.280702 | 137 | 0.596276 | 4.958743 | false | false | false | false |
MateuszKarwat/Napi | Napi/Models/Subtitle Format/Supported Subtitle Formats/MicroDVDSubtitleFormat.swift | 1 | 2226 | //
// Created by Mateusz Karwat on 07/02/16.
// Copyright © 2016 Mateusz Karwat. All rights reserved.
//
import Foundation
/// Represents MicroDVD Subtitle Format.
/// MicroDVD Subtitle Format looks like this:
///
/// {111}{222}First line of a text.|Seconds line of a text.
struct MicroDVDSubtitleFormat: SubtitleFormat {
static let fileExtension = "sub"
static let isTimeBased = false
static let regexPattern = "\\{(\\d+)\\}\\{(\\d+)\\}(.+)"
static func decode(_ aString: String) -> [Subtitle] {
return MicroDVDSubtitleFormat.decode(aString, frameRate: 1.0)
}
static func decode(_ aString: String, frameRate: Double) -> [Subtitle] {
var decodedSubtitles = [Subtitle]()
self.enumerateMatches(in: aString) { match in
let startNumber = Int(match.capturedSubstrings[0])
let stopNumber = Int(match.capturedSubstrings[1])
let newSubtitle = Subtitle(startTimestamp: startNumber!.frames(frameRate: frameRate),
stopTimestamp: stopNumber!.frames(frameRate: frameRate),
text: match.capturedSubstrings[2])
decodedSubtitles.append(newSubtitle)
}
return decodedSubtitles
}
static func encode(_ subtitles: [Subtitle]) -> [String] {
var encodedSubtitles = [String]()
for subtitle in subtitles {
let startTimestamp = subtitle.startTimestamp
let stopTimestamp = subtitle.stopTimestamp
var startValue: Int
var stopValue: Int
if startTimestamp.isFrameBased {
startValue = startTimestamp.roundedValue(in: subtitle.startTimestamp.unit)
} else {
startValue = startTimestamp.numberOfFull(.frames(frameRate: 1.0))
}
if stopTimestamp.isFrameBased {
stopValue = stopTimestamp.roundedValue(in: subtitle.stopTimestamp.unit)
} else {
stopValue = stopTimestamp.numberOfFull(.frames(frameRate: 1.0))
}
encodedSubtitles.append("{\(startValue)}{\(stopValue)}\(subtitle.text)")
}
return encodedSubtitles
}
}
| mit | 23dddc8727ca58633a6c54f36abf726b | 33.230769 | 97 | 0.609888 | 5.011261 | false | false | false | false |
dasdom/Swiftandpainless | SwiftAndPainless_3.playground/Pages/Encapsulation Example - Inline Mock.xcplaygroundpage/Contents.swift | 1 | 581 | import XCTest
/*:
[⬅️](@previous) [➡️](@next)
# Encapsulation Example: Inline Mock
*/
class DataSource {
lazy var tableView = UITableView()
var data = [String]()
}
func testSettingData_ReloadsTableView() {
class MockTableView: UITableView {
var reloadDataGotCalled = false
private override func reloadData() {
reloadDataGotCalled = true
super.reloadData()
}
}
let sut = DataSource()
let mockTableView = MockTableView()
sut.tableView = mockTableView
sut.data = ["Foo"]
XCTAssertTrue(mockTableView.reloadDataGotCalled)
} | mit | 3df56f385c40c730a00c75539b228cff | 20.259259 | 50 | 0.684119 | 4.340909 | false | true | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Post/Revisions/Browser/Diffs/RevisionDiffsPageManager.swift | 2 | 3254 | import Foundation
protocol RevisionDiffsPageManagerDelegate: AnyObject {
func currentIndex() -> Int
func pageWillScroll(to direction: UIPageViewController.NavigationDirection)
func pageDidFinishAnimating(completed: Bool)
}
// Delegate and data source of the page view controller used
// by the RevisionDiffsBrowserViewController
//
class RevisionDiffsPageManager: NSObject {
var viewControllers: [RevisionDiffViewController] = []
private unowned var delegate: RevisionDiffsPageManagerDelegate
init(delegate: RevisionDiffsPageManagerDelegate) {
self.delegate = delegate
}
private func index(of viewController: UIViewController?) -> Int? {
return viewControllers.lazy.firstIndex { $0 === viewController }
}
}
extension RevisionDiffsPageManager: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let index = index(of: viewController) else {
return nil
}
return getViewController(at: index, direction: .reverse)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let index = index(of: viewController) else {
return nil
}
return getViewController(at: index, direction: .forward)
}
private func getViewController(at index: Int, direction: UIPageViewController.NavigationDirection) -> UIViewController? {
var nextIndex = 0
let count = viewControllers.count
switch direction {
case .forward:
nextIndex = index + 1
if count == nextIndex || count < nextIndex {
return nil
}
case .reverse:
nextIndex = index - 1
if nextIndex < 0 || count < nextIndex {
return nil
}
@unknown default:
fatalError()
}
return viewControllers[nextIndex]
}
}
extension RevisionDiffsPageManager: UIPageViewControllerDelegate {
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return viewControllers.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return delegate.currentIndex()
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
delegate.pageDidFinishAnimating(completed: completed)
}
func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
let currentIndex = delegate.currentIndex()
guard let viewControllerIndex = index(of: pendingViewControllers.first),
currentIndex != viewControllerIndex else {
return
}
let direction: UIPageViewController.NavigationDirection = currentIndex > viewControllerIndex ? .reverse : .forward
delegate.pageWillScroll(to: direction)
}
}
| gpl-2.0 | 628fd238e84d9a7752253ee85516ea5a | 35.155556 | 190 | 0.702827 | 6.151229 | false | false | false | false |
BenziAhamed/Tracery | CommonTesting/CandidateSelector.swift | 1 | 2711 | //
// CandidateSelector.swift
// Tracery
//
// Created by Benzi on 11/03/17.
// Copyright © 2017 Benzi Ahamed. All rights reserved.
//
import XCTest
@testable import Tracery
class CandidateSelector : XCTestCase {
func testRuleCandidateSelectorIsInvoked() {
let t = Tracery {[
"msg" : ["hello", "world"]
]}
let selector = AlwaysPickFirst()
t.setCandidateSelector(rule: "msg", selector: selector)
for _ in 0..<20 {
XCTAssertEqual(t.expand("#msg#"), "hello")
}
}
func testRuleCandidateSelectorBogusSelectionsAreIgnored() {
let t = Tracery {[
"msg" : ["hello", "world"]
]}
let selector = BogusSelector()
t.setCandidateSelector(rule: "msg", selector: selector)
XCTAssertEqual(t.expand("#msg#"), "{msg}")
}
func testRuleCandidateSelectorReturnValueIsAlwaysHonoured() {
let t = Tracery {[
"msg" : ["hello", "world"]
]}
let selector = PickSpecificItem(offset: .fromEnd(0))
t.setCandidateSelector(rule: "msg", selector: selector)
var tracker = [
"hello": 0,
"world": 0,
]
t.add(modifier: "track") {
let count = tracker[$0] ?? 0
tracker[$0] = count + 1
return $0
}
let target = 10
for _ in 0..<target {
XCTAssertEqual(t.expand("#msg.track#"), "world")
}
XCTAssertEqual(tracker["hello"], 0)
XCTAssertEqual(tracker["world"], target)
}
func testDefaultRuleCandidateSelectorIsUniformlyDistributed() {
let animals = ["unicorn","raven","sparrow","scorpion","coyote","eagle","owl","lizard","zebra","duck","kitten"]
var tracker = [String: Int]()
animals.forEach { tracker[$0] = 0 }
let t = Tracery { ["animal" : animals] }
t.add(modifier: "track") {
let count = tracker[$0] ?? 0
tracker[$0] = count + 1
return $0
}
let invokesPerItem = 10
for _ in 0..<(invokesPerItem * animals.count) {
XCTAssertItemInArray(item: t.expand("#animal.track#"), array: animals)
}
for key in tracker.keys {
XCTAssertEqual(tracker[key], invokesPerItem)
}
}
func testSettingSelectorForNonExistentRuleHasNoEffectAndGeneratesAWarning() {
let t = Tracery()
t.setCandidateSelector(rule: "where", selector: SequentialSelector())
}
}
| mit | 5939f3860c0b11c3c8dd404a8306903d | 25.057692 | 118 | 0.519926 | 4.479339 | false | true | false | false |
stsievert/swix | swix/swix/swix/matrix/m-operators.swift | 2 | 5816 | //
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(_ lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
let lhsM = lhs.flat
let rhsM = rhs.flat
var resM:vector = zeros_like(lhsM) // flat vector
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
let lhsM = lhs.flat
var resM:vector = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(_ lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
let rhsM = rhs.flat
var resM:vector = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOUBLE ASSIGNMENT
func <- (lhs:inout matrix, rhs:Double){
let assign = ones((lhs.shape)) * rhs
lhs = assign
}
// SOLVE
infix operator !/ : Multiplicative
func !/ (lhs: matrix, rhs: vector) -> vector{
return solve(lhs, b: rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == : ComparisonPrecedence
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== : ComparisonPrecedence
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + : Additive
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
// MINUS
infix operator - : Additive
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
// TIMES
infix operator * : Multiplicative
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
// DIVIDE
infix operator / : Multiplicative
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
// LESS THAN
infix operator < : ComparisonPrecedence
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
// GREATER THAN
infix operator > : ComparisonPrecedence
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
// GREATER THAN OR EQUAL
infix operator >= : ComparisonPrecedence
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">=", rhs: rhs)}
// LESS THAN OR EQUAL
infix operator <= : ComparisonPrecedence
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<=", rhs: rhs)}
| mit | a6b3d9cbafefc0d9ef9acee5ab9fd990 | 37.263158 | 74 | 0.627235 | 3.321531 | false | false | false | false |
powerytg/Accented | Accented/UI/Search/Sections/SearchPhotoResultViewController.swift | 1 | 4281 | //
// SearchPhotoResultViewController.swift
// Accented
//
// Photo search result card
//
// Created by Tiangong You on 5/21/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class SearchPhotoResultViewController: CardViewController, SearchResultFilterViewControllerDelegate, SheetMenuDelegate {
var streamViewController : PhotoSearchResultStreamViewController!
var sortingOptionsViewController : SearchResultFilterViewController!
var keyword : String?
var tag : String?
private var sortingModel = PhotoSearchFilterModel()
private let sortingBarHeight : CGFloat = 40
private let streamTopMargin : CGFloat = 44
init(keyword : String) {
self.keyword = keyword
super.init(nibName: nil, bundle: nil)
}
init(tag : String) {
self.tag = tag
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "PHOTOS"
let sortingOption = sortingModel.selectedItem as! SortingOptionMenuItem
var stream : PhotoSearchStreamModel
if let keyword = self.keyword {
stream = StorageService.sharedInstance.getPhotoSearchResult(keyword: keyword, sort : sortingOption.option)
} else if let tag = self.tag {
stream = StorageService.sharedInstance.getPhotoSearchResult(tag: tag, sort : sortingOption.option)
} else {
fatalError("Neither tag nor keyword is specified")
}
// Initialize sorting options
sortingOptionsViewController = SearchResultFilterViewController(sortingModel: sortingModel)
sortingOptionsViewController.delegate = self
addChildViewController(sortingOptionsViewController)
self.view.addSubview(sortingOptionsViewController.view)
sortingOptionsViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: sortingBarHeight)
sortingOptionsViewController.didMove(toParentViewController: self)
// Initialize stream
streamViewController = PhotoSearchResultStreamViewController(stream)
addChildViewController(streamViewController)
self.view.addSubview(streamViewController.view)
streamViewController.view.frame = CGRect(x: 0, y: streamTopMargin, width: view.bounds.size.width, height: view.bounds.size.height - streamTopMargin)
streamViewController.didMove(toParentViewController: self)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
sortingOptionsViewController.view.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width, height: sortingBarHeight)
}
// MARK: - SearchResultFilterViewControllerDelegate
func sortingButtonDidTap() {
guard let topVC = NavigationService.sharedInstance.topViewController() else { return }
let bottomSheet = SearchResultSortingBottomSheetViewController(model: sortingModel)
bottomSheet.delegate = self
let animationContext = DrawerAnimationContext(content: bottomSheet)
animationContext.anchor = .bottom
animationContext.container = topVC
animationContext.drawerSize = CGSize(width: UIScreen.main.bounds.size.width, height: 266)
DrawerService.sharedInstance.presentDrawer(animationContext)
}
// MARK: - SheetMenuDelegate
func sheetMenuSelectedOptionDidChange(menuSheet: SheetMenuViewController, selectedIndex: Int) {
menuSheet.dismiss(animated: true, completion: nil)
if sortingModel.selectedItem == nil || sortingModel.items.index(of: sortingModel.selectedItem!) != selectedIndex {
let selectedOption = sortingModel.items[selectedIndex] as! SortingOptionMenuItem
sortingModel.selectedItem = selectedOption
StorageService.sharedInstance.currentPhotoSearchSortingOption = selectedOption.option
sortingOptionsViewController.view.setNeedsLayout()
// Notify the steam to update
streamViewController.sortConditionDidChange(sort : selectedOption.option)
}
}
}
| mit | 3937521985f0584bf5f282e558d2d9d3 | 42.232323 | 156 | 0.710047 | 5.336658 | false | false | false | false |
raphaelhanneken/icnscomposer | Icns Composer/MainWindowController.swift | 1 | 2177 | //
// MainWindowController.swift
// Icns Composer
// https://github.com/raphaelhanneken/icnscomposer
//
import Cocoa
/// Manages the MainWindow.xib.
class MainWindowController: NSWindowController, NSWindowDelegate {
/// Handles creation of the .icns file.
var iconset = Iconset()
override var windowNibName: NSNib.Name {
return "MainWindow"
}
/// Starts the export process for the current iconset.
///
/// - parameter sender: NSToolbarItem that sent the export message.
@IBAction func export(_: NSToolbarItem) {
guard let window = window else {
return
}
let dialog = NSSavePanel()
dialog.allowedFileTypes = ["icns"]
dialog.allowsOtherFileTypes = false
dialog.beginSheetModal(for: window) { (result: NSApplication.ModalResponse) -> Void in
if result != NSApplication.ModalResponse.OK {
return
}
do {
try self.iconset.writeToURL(dialog.url)
} catch {
let alert = NSAlert()
alert.messageText = "Oh snap!"
alert.informativeText = "Something went somewhere terribly wrong."
alert.beginSheetModal(for: window, completionHandler: nil)
}
}
}
/// Gets called everytime a user drops an image onto a connected NSImageView.
/// Resizes the dropped images to the appropriate size and adds them to the icon object.
///
/// - parameter sender: The NSImageView that the images have been assigned to.
@IBAction func resize(_ sender: NSImageView) {
let img = IconImage(sender.image,
withSize: NSSize(width: Int(sender.tag / 2), height: Int(sender.tag / 2)),
andScale: .scale1x)
let img2x = IconImage(sender.image,
withSize: NSSize(width: sender.tag, height: sender.tag),
andScale: .scale2x)
if let filename1x = img?.filename, let filename2x = img2x?.filename {
iconset[filename1x] = img
iconset[filename2x] = img2x
}
}
}
| mit | 902aa3bc79ac3552c606b18621da834b | 33.015625 | 102 | 0.590262 | 4.795154 | false | false | false | false |
gaelfoppolo/handicarparking | HandiParking/HandiParking/ParkingSpace.swift | 1 | 5317 | //
// ParkingSpace.swift
// HandiCarParking
//
// Created by Gaël on 12/03/2015.
// Copyright (c) 2015 KeepCore. All rights reserved.
//
/// Emplacements récupérés grâce à OpenStreetMap
class ParkingSpace {
// MARK: Attributs
/// l'id de la node récupérée
var id_node: String
/// la latitude de l'emplacement
var latitude: String
/// la longitude de l'emplacement
var longitude: String
/// l'adresse approximative de l'emplacement (reverseGoogle)
var address: String?
/// distance (à vol d'oiseau) jusqu'à l'emplacement
var distance: CLLocationDistance!
/// distance (estimée) de parcours jusqu'à l'emplacement
var distanceETA: CLLocationDistance!
/// temps (estimé) de parcours jusqu'à l'emplacement
var durationETA: NSTimeInterval?
/// emplacement payant/gratuit
var fee: String?
/// nombre de places
var capacity: String?
/// nom du lieu associé à l'emplacement
var name: String?
// MARK: Initialisateurs
/**
Initialise un nouvel emplacement avec les informations suivantes :
:param: id L'id de la node
:param: lat La latitude de l'emplacement
:param: lon La longitude de l'emplacment
:returns: Un emplacement tout neuf, prêt à être utilisé
*/
init(id: String?, lat: String?, lon: String?, name: String?, fee: String?, capacity: String?, distance: CLLocationDistance) {
self.id_node = id ?? ""
self.latitude = lat ?? ""
self.longitude = lon ?? ""
self.distance = distance
self.name = name
if let feee = fee {
switch feee {
case "yes":
self.fee = NSLocalizedString("FEE",comment:"Fee")
case "no":
self.fee = NSLocalizedString("NO_FEE",comment:"No fee")
default:
break
}
} else {
self.fee = NSLocalizedString("NA",comment:"Not available")
}
if let capa = capacity {
if let capa2 = capa.toInt() {
if capa2 > 1 {
self.capacity = NSString(format: NSLocalizedString("NB_SPACES", comment: "nb spaces"), String(capa2)) as String
} else if capa2 == 1 {
self.capacity = NSString(format: NSLocalizedString("NB_SPACE", comment: "nb space"), String(capa2)) as String
} else {
self.capacity = NSLocalizedString("NA",comment:"Not available")
}
} else {
self.capacity = NSString(format: NSLocalizedString("NB_SPACE", comment: "nb space"), String(1)) as String
}
} else {
self.capacity = NSLocalizedString("NA",comment:"Not available")
}
}
// MARK: Fonctions
/**
Met à jour l'adresse d'un emplacement ou défaut si aucune adresse
:param: adr l'adresse à mettre à jour
*/
func setAddress(adr: String?) {
self.address = adr ?? NSLocalizedString("NO_ADDRESS",comment:"No adresse found")
}
/**
Met à jour la distance et la durée estimée de parcours jusqu'à la place ou défaut si aucune estimation
:param: distETA distance de parcours estimée
:param: durETA durée de parcours estimée
*/
func setDistanceAndDurationETA(distETA: CLLocationDistance?, durETA: NSTimeInterval?) {
self.distanceETA = distETA ?? -1
self.durationETA = durETA ?? -1
}
/**
Génère sous une forme plus lisible par l'utilisateur, la distance
:returns: la distance sous forme lisible
*/
func getDistance() -> NSString {
var distance:CLLocationDistance
if self.distanceETA != -1 {
distance = self.distanceETA
} else {
distance = self.distance!
}
var distanceTexte:String
if distance < 1000 {
distanceTexte = "\(Int(distance)) m"
} else {
distanceTexte = String(format: "%.2f", (distance/1000)) + " km"
}
return distanceTexte
}
/**
Génère sous une forme plus lisible par l'utilisateur, la durée ou défaut si pas de durée
:returns: la durée sous forme lisible
*/
func getDuration() -> NSString {
if self.durationETA != -1 {
let tii = NSInteger(self.durationETA!)
var seconds = tii % 60
var minutes = (tii / 60) % 60
var hours = (tii / 3600)
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Abbreviated
let components = NSDateComponents()
if minutes == 0 && hours == 0 {
components.second = seconds
} else {
components.hour = hours
components.minute = minutes
}
let string = formatter.stringFromDateComponents(components)
return NSString(string: string!)
} else {
return NSLocalizedString("NA",comment:"Not available")
}
}
} | gpl-3.0 | d8daf5117b980ca39bcf72e7cc57efb3 | 30.224852 | 131 | 0.554208 | 4.317512 | false | false | false | false |
alecgorge/AGAudioPlayer | AGAudioPlayer/UI/RemoteCommandManager.swift | 1 | 10674 | //
// RemoteCommandManager.swift
// AGAudioPlayer
//
// Created by Alec Gorge on 9/25/17.
// Copyright © 2017 Alec Gorge. All rights reserved.
//
/*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
`RemoteCommandManager` contains all the APIs calls to MPRemoteCommandCenter to enable and disable various remote control events.
*/
import Foundation
import MediaPlayer
@objc class RemoteCommandManager: NSObject {
// MARK: Properties
/// Reference of `MPRemoteCommandCenter` used to configure and setup remote control events in the application.
fileprivate let remoteCommandCenter = MPRemoteCommandCenter.shared()
/// The instance of `AssetPlaybackManager` to use for responding to remote command events.
weak var player: AGAudioPlayer?
// MARK: Initialization.
init(player: AGAudioPlayer) {
self.player = player
}
deinit {
#if os(tvOS)
activatePlaybackCommands(false)
#endif
activatePlaybackCommands(false)
toggleNextTrackCommand(false)
togglePreviousTrackCommand(false)
toggleSkipForwardCommand(false)
toggleSkipBackwardCommand(false)
toggleChangePlaybackPositionCommand(false)
toggleLikeCommand(false)
toggleDislikeCommand(false)
toggleBookmarkCommand(false)
}
// MARK: MPRemoteCommand Activation/Deactivation Methods
#if os(tvOS)
func activateRemoteCommands(_ enable: Bool) {
activatePlaybackCommands(enable)
// To support Siri's "What did they say?" command you have to support the appropriate skip commands. See the README for more information.
toggleSkipForwardCommand(enable, interval: 15)
toggleSkipBackwardCommand(enable, interval: 20)
}
#endif
func activatePlaybackCommands(_ enable: Bool) {
if enable {
remoteCommandCenter.playCommand.addTarget(self, action: #selector(RemoteCommandManager.handlePlayCommandEvent(_:)))
remoteCommandCenter.pauseCommand.addTarget(self, action: #selector(RemoteCommandManager.handlePauseCommandEvent(_:)))
remoteCommandCenter.stopCommand.addTarget(self, action: #selector(RemoteCommandManager.handleStopCommandEvent(_:)))
remoteCommandCenter.togglePlayPauseCommand.addTarget(self, action: #selector(RemoteCommandManager.handleTogglePlayPauseCommandEvent(_:)))
}
else {
remoteCommandCenter.playCommand.removeTarget(self, action: #selector(RemoteCommandManager.handlePlayCommandEvent(_:)))
remoteCommandCenter.pauseCommand.removeTarget(self, action: #selector(RemoteCommandManager.handlePauseCommandEvent(_:)))
remoteCommandCenter.stopCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleStopCommandEvent(_:)))
remoteCommandCenter.togglePlayPauseCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleTogglePlayPauseCommandEvent(_:)))
}
remoteCommandCenter.playCommand.isEnabled = enable
remoteCommandCenter.pauseCommand.isEnabled = enable
remoteCommandCenter.stopCommand.isEnabled = enable
remoteCommandCenter.togglePlayPauseCommand.isEnabled = enable
toggleChangePlaybackPositionCommand(enable)
toggleNextTrackCommand(enable)
togglePreviousTrackCommand(enable)
}
func toggleNextTrackCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.nextTrackCommand.addTarget(self, action: #selector(RemoteCommandManager.handleNextTrackCommandEvent(_:)))
}
else {
remoteCommandCenter.nextTrackCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleNextTrackCommandEvent(_:)))
}
remoteCommandCenter.nextTrackCommand.isEnabled = enable
}
func togglePreviousTrackCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.previousTrackCommand.addTarget(self, action: #selector(RemoteCommandManager.handlePreviousTrackCommandEvent(event:)))
}
else {
remoteCommandCenter.previousTrackCommand.removeTarget(self, action: #selector(RemoteCommandManager.handlePreviousTrackCommandEvent(event:)))
}
remoteCommandCenter.previousTrackCommand.isEnabled = enable
}
func toggleSkipForwardCommand(_ enable: Bool, interval: Int = 0) {
if enable {
remoteCommandCenter.skipForwardCommand.preferredIntervals = [NSNumber(value: interval)]
remoteCommandCenter.skipForwardCommand.addTarget(self, action: #selector(RemoteCommandManager.handleSkipForwardCommandEvent(event:)))
}
else {
remoteCommandCenter.skipForwardCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleSkipForwardCommandEvent(event:)))
}
remoteCommandCenter.skipForwardCommand.isEnabled = enable
}
func toggleSkipBackwardCommand(_ enable: Bool, interval: Int = 0) {
if enable {
remoteCommandCenter.skipBackwardCommand.preferredIntervals = [NSNumber(value: interval)]
remoteCommandCenter.skipBackwardCommand.addTarget(self, action: #selector(RemoteCommandManager.handleSkipBackwardCommandEvent(event:)))
}
else {
remoteCommandCenter.skipBackwardCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleSkipBackwardCommandEvent(event:)))
}
remoteCommandCenter.skipBackwardCommand.isEnabled = enable
}
func toggleChangePlaybackPositionCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.changePlaybackPositionCommand.addTarget(self, action: #selector(RemoteCommandManager.handleChangePlaybackPositionCommandEvent(event:)))
}
else {
remoteCommandCenter.changePlaybackPositionCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleChangePlaybackPositionCommandEvent(event:)))
}
remoteCommandCenter.changePlaybackPositionCommand.isEnabled = enable
}
func toggleLikeCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.likeCommand.addTarget(self, action: #selector(RemoteCommandManager.handleLikeCommandEvent(event:)))
}
else {
remoteCommandCenter.likeCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleLikeCommandEvent(event:)))
}
remoteCommandCenter.likeCommand.isEnabled = enable
}
func toggleDislikeCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.dislikeCommand.addTarget(self, action: #selector(RemoteCommandManager.handleDislikeCommandEvent(event:)))
}
else {
remoteCommandCenter.dislikeCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleDislikeCommandEvent(event:)))
}
remoteCommandCenter.dislikeCommand.isEnabled = enable
}
func toggleBookmarkCommand(_ enable: Bool) {
if enable {
remoteCommandCenter.bookmarkCommand.addTarget(self, action: #selector(RemoteCommandManager.handleBookmarkCommandEvent(event:)))
}
else {
remoteCommandCenter.bookmarkCommand.removeTarget(self, action: #selector(RemoteCommandManager.handleBookmarkCommandEvent(event:)))
}
remoteCommandCenter.bookmarkCommand.isEnabled = enable
}
// MARK: MPRemoteCommand handler methods.
// MARK: Playback Command Handlers
@objc func handlePauseCommandEvent(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
player?.pause()
return .success
}
@objc func handlePlayCommandEvent(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
player?.resume()
return .success
}
@objc func handleStopCommandEvent(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
player?.stop()
return .success
}
@objc func handleTogglePlayPauseCommandEvent(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
if let b = player?.isPlaying, b {
player?.pause()
}
else {
player?.resume()
}
return .success
}
// MARK: Track Changing Command Handlers
@objc func handleNextTrackCommandEvent(_ event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
if let p = player, p.forward() {
return .success
}
return .noSuchContent
}
@objc func handlePreviousTrackCommandEvent(event: MPRemoteCommandEvent) -> MPRemoteCommandHandlerStatus {
if let p = player, p.backward() {
return .success
}
return .noSuchContent
}
// MARK: Skip Interval Command Handlers
@objc func handleSkipForwardCommandEvent(event: MPSkipIntervalCommandEvent) -> MPRemoteCommandHandlerStatus {
if let p = player {
p.seek(to: p.elapsed + event.interval)
}
return .success
}
@objc func handleSkipBackwardCommandEvent(event: MPSkipIntervalCommandEvent) -> MPRemoteCommandHandlerStatus {
if let p = player {
p.seek(to: p.elapsed - event.interval)
}
return .success
}
@objc func handleChangePlaybackPositionCommandEvent(event: MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus {
if let p = player {
p.seek(to: event.positionTime)
}
return .success
}
// MARK: Feedback Command Handlers
@objc func handleLikeCommandEvent(event: MPFeedbackCommandEvent) -> MPRemoteCommandHandlerStatus {
print("Did recieve likeCommand for")
return .noSuchContent
}
@objc func handleDislikeCommandEvent(event: MPFeedbackCommandEvent) -> MPRemoteCommandHandlerStatus {
print("Did recieve dislikeCommand for")
return .noSuchContent
}
@objc func handleBookmarkCommandEvent(event: MPFeedbackCommandEvent) -> MPRemoteCommandHandlerStatus {
print("Did recieve bookmarkCommand for")
return .noSuchContent
}
}
// MARK: Convienence Category to make it easier to expose different types of remote command groups as the UITableViewDataSource in RemoteCommandListTableViewController.
extension RemoteCommandManager {
}
| mit | 8ecb512beefd958fd1199f2ad4e3c902 | 37.803636 | 170 | 0.689626 | 5.560709 | false | false | false | false |
vl4298/mah-income | Mah Income/Mah Income/Scenes/Category/Add & Update Category/AddUpdateCategoryModelController.swift | 1 | 1137 | //
// AddUpdateCategoryModelController.swift
// Mah Income
//
// Created by Van Luu on 4/28/17.
// Copyright © 2017 Van Luu. All rights reserved.
//
import Foundation
import RealmSwift
class AddUpdateCategoryModelController {
weak var viewController: AddUpdateCategoryViewController!
fileprivate lazy var categoryWorker: CategoryWorker? = {
return CategoryWorker()
}()
func addCategory(name: String) {
guard let worker = categoryWorker else {
viewController.presentError(des: MahError.cannotInit.textMsg)
return
}
if let err = worker.insertCategory(name: name) {
viewController.presentError(des: err.textMsg)
} else {
viewController.didAddNewCategory()
}
}
func update(category: CategoryModel, updateName: String) {
guard let worker = categoryWorker else {
viewController.presentError(des: MahError.cannotInit.textMsg)
return
}
if let err = worker.updateCategory(category: category, name: updateName) {
viewController.presentError(des: err.textMsg)
} else {
viewController.didAddNewCategory()
}
}
}
| mit | 91b9d8173f7201b9142204739e31c546 | 23.695652 | 78 | 0.694542 | 4.286792 | false | false | false | false |
johnnysay/GoodAccountsMakeGoodFriends | Pods/SwiftHEXColors/Sources/SwiftHEXColors.swift | 1 | 4589 | // SwiftHEXColors.swift
//
// Copyright (c) 2014 SwiftHEXColors contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
typealias SWColor = UIColor
#else
import Cocoa
typealias SWColor = NSColor
#endif
private extension Int {
func duplicate4bits() -> Int {
return (self << 4) + self
}
}
/// An extension of UIColor (on iOS) or NSColor (on OSX) providing HEX color handling.
public extension SWColor {
/**
Create non-autoreleased color with in the given hex string. Alpha will be set as 1 by default.
- parameter hexString: The hex string, with or without the hash character.
- returns: A color with the given hex string.
*/
public convenience init?(hexString: String) {
self.init(hexString: hexString, alpha: 1.0)
}
private convenience init?(hex3: Int, alpha: Float) {
self.init(red: CGFloat( ((hex3 & 0xF00) >> 8).duplicate4bits() ) / 255.0,
green: CGFloat( ((hex3 & 0x0F0) >> 4).duplicate4bits() ) / 255.0,
blue: CGFloat( ((hex3 & 0x00F) >> 0).duplicate4bits() ) / 255.0,
alpha: CGFloat(alpha))
}
private convenience init?(hex6: Int, alpha: Float) {
self.init(red: CGFloat( (hex6 & 0xFF0000) >> 16 ) / 255.0,
green: CGFloat( (hex6 & 0x00FF00) >> 8 ) / 255.0,
blue: CGFloat( (hex6 & 0x0000FF) >> 0 ) / 255.0, alpha: CGFloat(alpha))
}
/**
Create non-autoreleased color with in the given hex string and alpha.
- parameter hexString: The hex string, with or without the hash character.
- parameter alpha: The alpha value, a floating value between 0 and 1.
- returns: A color with the given hex string and alpha.
*/
public convenience init?(hexString: String, alpha: Float) {
var hex = hexString
// Check for hash and remove the hash
if hex.hasPrefix("#") {
hex = String(hex[hex.index(after: hex.startIndex)...])
}
guard let hexVal = Int(hex, radix: 16) else {
self.init()
return nil
}
switch hex.count {
case 3:
self.init(hex3: hexVal, alpha: alpha)
case 6:
self.init(hex6: hexVal, alpha: alpha)
default:
// Note:
// The swift 1.1 compiler is currently unable to destroy partially initialized classes in all cases,
// so it disallows formation of a situation where it would have to. We consider this a bug to be fixed
// in future releases, not a feature. -- Apple Forum
self.init()
return nil
}
}
/**
Create non-autoreleased color with in the given hex value. Alpha will be set as 1 by default.
- parameter hex: The hex value. For example: 0xff8942 (no quotation).
- returns: A color with the given hex value
*/
public convenience init?(hex: Int) {
self.init(hex: hex, alpha: 1.0)
}
/**
Create non-autoreleased color with in the given hex value and alpha
- parameter hex: The hex value. For example: 0xff8942 (no quotation).
- parameter alpha: The alpha value, a floating value between 0 and 1.
- returns: color with the given hex value and alpha
*/
public convenience init?(hex: Int, alpha: Float) {
if (0x000000 ... 0xFFFFFF) ~= hex {
self.init(hex6: hex, alpha: alpha)
} else {
self.init()
return nil
}
}
}
| mit | c2f869a309b3e3c1a2ddc828245a2489 | 36.614754 | 115 | 0.631946 | 4.175614 | false | false | false | false |
Fluffcorn/ios-sticker-packs-app | MessagesExtension/WAStickers code files/ImageData.swift | 1 | 4806 | //
// Copyright (c) WhatsApp Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
//
import UIKit
extension CGSize {
public static func ==(left: CGSize, right: CGSize) -> Bool {
return left.width.isEqual(to: right.width) && left.height.isEqual(to: right.height)
}
public static func <(left: CGSize, right: CGSize) -> Bool {
return left.width.isLess(than: right.width) && left.height.isLess(than: right.height)
}
public static func >(left: CGSize, right: CGSize) -> Bool {
return !left.width.isLessThanOrEqualTo(right.width) && !left.height.isLessThanOrEqualTo(right.height)
}
public static func <=(left: CGSize, right: CGSize) -> Bool {
return left.width.isLessThanOrEqualTo(right.width) && left.height.isLessThanOrEqualTo(right.height)
}
public static func >=(left: CGSize, right: CGSize) -> Bool {
return !left.width.isLess(than: right.width) && !left.height.isLess(than: right.height)
}
}
/**
* Represents the two supported extensions for sticker images: png and webp.
*/
enum ImageDataExtension: String {
case png = "png"
case webp = "webp"
}
/**
* Stores sticker image data along with its supported extension.
*/
class ImageData {
let data: Data
let type: ImageDataExtension
var bytesSize: Int64 {
return Int64(data.count)
}
/**
* Returns whether or not the data represents an animated image.
* It will always return false if the image is png.
*/
lazy var animated: Bool = {
if type == .webp {
return WebPManager.shared.isAnimated(webPData: data)
} else {
return false
}
}()
/**
* Returns the webp data representation of the current image. If the current image is already webp,
* the data is simply returned. If it's png, it will returned the webp converted equivalent data.
*/
lazy var webpData: Data? = {
if type == .webp {
return data
} else {
return WebPManager.shared.encode(pngData: data)
}
}()
/**
* Returns a UIImage of the current image data. If data is corrupt, nil will be returned.
*/
lazy var image: UIImage? = {
if type == .webp {
return WebPManager.shared.decode(webPData: data)
} else {
return UIImage(data: data)
}
}()
/**
* Returns an image with the new size.
*/
func image(withSize size: CGSize) -> UIImage? {
guard let image = image else { return nil }
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
image.draw(in: CGRect(origin: .zero, size: size))
let resizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return resizedImage
}
init(data: Data, type: ImageDataExtension) {
self.data = data
self.type = type
}
static func imageDataIfCompliant(contentsOfFile filename: String, isTray: Bool) throws -> ImageData {
let fileExtension: String = (filename as NSString).pathExtension
guard let imageURL = Bundle.main.url(forResource: filename, withExtension: "") else {
throw StickerPackError.fileNotFound
}
let data = try Data(contentsOf: imageURL)
guard let imageType = ImageDataExtension(rawValue: fileExtension) else {
throw StickerPackError.unsupportedImageFormat(fileExtension)
}
return try ImageData.imageDataIfCompliant(rawData: data, extensionType: imageType, isTray: isTray)
}
static func imageDataIfCompliant(rawData: Data, extensionType: ImageDataExtension, isTray: Bool) throws -> ImageData {
let imageData = ImageData(data: rawData, type: extensionType)
guard !imageData.animated else {
throw StickerPackError.animatedImagesNotSupported
}
if isTray {
guard imageData.bytesSize <= Limits.MaxTrayImageFileSize else {
throw StickerPackError.imageTooBig(imageData.bytesSize)
}
guard imageData.image!.size == Limits.TrayImageDimensions else {
throw StickerPackError.incorrectImageSize(imageData.image!.size)
}
} else {
guard imageData.bytesSize <= Limits.MaxStickerFileSize else {
throw StickerPackError.imageTooBig(imageData.bytesSize)
}
guard imageData.image!.size == Limits.ImageDimensions else {
throw StickerPackError.incorrectImageSize(imageData.image!.size)
}
}
return imageData
}
}
| mit | ba497e8a22dc70a93d64a4d2313de6fb | 31.255034 | 122 | 0.637536 | 4.55545 | false | false | false | false |
ShiWeiCN/Goku | Goku/Source/AlertExtensions/AlertView+Extension.swift | 1 | 6520 | // AlertView+Extension.swift
// Goku (https://github.com/ShiWeiCN/Goku)
//
//
// Copyright (c) 2017 shiwei (http://shiweicn.github.io/)
//
// 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
private extension Selector {
static let viewAction = #selector(UIView.tapped(_:))
}
internal class GokuAction: NSObject {
var actionDictionary: Dictionary<NSValue, () -> ()> = Dictionary()
static let shared = GokuAction()
override fileprivate init() { }
}
public extension UIView {
func action(_ f: @escaping () -> ()) {
let tap = UITapGestureRecognizer(target: self, action: .viewAction)
self.addGestureRecognizer(tap)
GokuAction.shared.actionDictionary[NSValue(nonretainedObject: self)] = f
}
@objc fileprivate func tapped(_ tap: UITapGestureRecognizer) {
if let closure = GokuAction.shared.actionDictionary[NSValue(nonretainedObject: tap.view)] {
closure()
} else { }
}
}
internal extension String {
func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [NSAttributedStringKey: AnyObject] = [NSAttributedStringKey.font: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle();
paragraphStyle.lineBreakMode = lineBreakMode!;
attrib.updateValue(paragraphStyle, forKey: NSAttributedStringKey.paragraphStyle);
}
let size = CGSize(width: width, height: CGFloat(Double.greatestFiniteMagnitude));
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
}
internal extension UIView {
@discardableResult
func addBorder(edges: UIRectEdge, color: UIColor = UIColor(hex: 0xCBCBCB), thickness: CGFloat = 0.5) -> [UIView] {
var borders = [UIView]()
func border() -> UIView {
let border = UIView(frame: CGRect.zero)
border.backgroundColor = color
border.translatesAutoresizingMaskIntoConstraints = false
return border
}
if edges.contains(.top) || edges.contains(.all) {
let top = border()
addSubview(top)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[top(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["top": top]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[top]-(0)-|",
options: [],
metrics: nil,
views: ["top": top]))
borders.append(top)
}
if edges.contains(.left) || edges.contains(.all) {
let left = border()
addSubview(left)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[left(==thickness)]",
options: [],
metrics: ["thickness": thickness],
views: ["left": left]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[left]-(0)-|",
options: [],
metrics: nil,
views: ["left": left]))
borders.append(left)
}
if edges.contains(.right) || edges.contains(.all) {
let right = border()
addSubview(right)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:[right(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["right": right]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(0)-[right]-(0)-|",
options: [],
metrics: nil,
views: ["right": right]))
borders.append(right)
}
if edges.contains(.bottom) || edges.contains(.all) {
let bottom = border()
addSubview(bottom)
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:[bottom(==thickness)]-(0)-|",
options: [],
metrics: ["thickness": thickness],
views: ["bottom": bottom]))
addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(0)-[bottom]-(0)-|",
options: [],
metrics: nil,
views: ["bottom": bottom]))
borders.append(bottom)
}
return borders
}
}
| mit | 42c1064e37680a27c0ad80584634801c | 44.915493 | 160 | 0.527454 | 5.719298 | false | false | false | false |
goloveychuk/SwiftPQ | Sources/Buffer.swift | 1 | 4598 | //
// Buffer.swift
// PurePostgres
//
// Created by badim on 10/29/16.
//
//
import Foundation
#if os(Linux)
import Glibc
#else
import Darwin
#endif
public typealias Buffer = Array<Byte>
extension Array {
public func copyBytes(to pointer: UnsafeMutableBufferPointer<Byte>) {
guard pointer.count > 0 else {
return
}
precondition(self.endIndex >= 0)
precondition(self.endIndex <= pointer.count, "The pointer is not large enough")
_ = self.withUnsafeBufferPointer {
memcpy(pointer.baseAddress!, $0.baseAddress!, self.count)
}
}
public func copyBytes(to pointer: UnsafeMutablePointer<Byte>, count: Int) {
copyBytes(to: UnsafeMutableBufferPointer(start: pointer, count: count))
}
}
//extension Buffer {
// public mutating func append(_ byte: Byte) {
// self.bytes.append(byte)
// }
// mutating func replaceSubrange(_ range: Range<Int>, with: Buffer) {
// self.bytes.replaceSubrange(range, with: with)
// }
//}
struct WriteBuffer {
fileprivate var buffer: Buffer
fileprivate var lengthInd: Int = 0
init(_ type: FrontendMessageTypes?) {
buffer = Buffer()
if let type = type {
buffer.append(Byte(type.rawValue.value))
lengthInd = 1
}
self.addInt32(0) //preserve for len
}
func pack() -> Buffer {
var buf = self
buf.buffer.replaceSubrange(lengthInd..<lengthInd+MemoryLayout<Int32>.size, with: Int32(self.buffer.count-lengthInd).toBuffer)//should be faster
return buf.buffer
}
mutating func addInt32(_ v : Int32) {
self.buffer.append(contentsOf: v.toBuffer)
}
mutating func addInt16(_ v: Int16) {
self.buffer.append(contentsOf: v.toBuffer)
}
mutating func addLen() {
lengthInd = self.buffer.count
addInt32(0)
}
mutating func addByte1(_ v: Byte) {
buffer.append(v)
}
mutating func addBuffer(_ v: Buffer) {
buffer.append(contentsOf: v)
}
mutating func addString(_ v : String) {
self.buffer.append(contentsOf: v.toBuffer)
addNull()
}
mutating func addNull() {
self.buffer.append(0)
}
}
enum BufferErrors: Error {
case NotEnough
}
let MSG_HEAD_LEN = 1+MemoryLayout<Int32>.size
struct ReadBuffer {
fileprivate var buffer: Buffer
fileprivate var cursor: Int = 0
init() {
buffer = Buffer()
}
mutating func add(_ d: Buffer) {
if left > 0 {
self.buffer = Buffer(self.buffer[cursor..<buffer.count])
self.buffer.append(contentsOf: d)
} else {
self.buffer = d
}
print(self.buffer.count)
cursor = 0
}
mutating func skip(_ bytes: Int = 1) {
cursor += bytes
}
var left: Int { return buffer.count - cursor }
var isEmpty: Bool {
return left == 0
}
// func clean() {
// cursor = 0
// buffer = Data()
// }
mutating func unpack() throws -> BackendMsgTypes? {
let bytesLeft = buffer.count - cursor
guard bytesLeft >= MSG_HEAD_LEN else {
return nil
}
let msgTypeByte = getByte1()
let msgType = BackendMsgTypes(rawValue: UnicodeScalar(msgTypeByte))!
let len = Int(getInt32())
guard bytesLeft >= len else {
cursor -= MSG_HEAD_LEN
return nil
}
return msgType
}
mutating func getByte1() -> Byte {
cursor += 1
return buffer[cursor-1]
}
mutating func getBytes(_ count: Int) -> Buffer {
let d = buffer[cursor..<cursor+count]
cursor += count
return Buffer(d)
}
mutating func getInt32() -> Int32 {
let newC = cursor+MemoryLayout<Int32>.size
defer { cursor = newC }
return Int32(psBuffer: Buffer(buffer[cursor..<newC]))
}
mutating func getInt16() -> Int16 {
let newC = cursor+MemoryLayout<Int16>.size
defer { cursor = newC }
return Int16(psBuffer: Buffer(buffer[cursor..<newC]))
}
mutating func getString() -> String {
var newCursor = cursor
while buffer[newCursor] != 0 {
newCursor += 1
}
let strData = buffer[cursor..<newCursor]
let str = String(psBuffer: Buffer(strData))
cursor = newCursor + 1
return str
}
var isNull: Bool {
return self.buffer[cursor] == 0
}
}
| mit | f69b80d3e6992fb968678eef9ebb47fb | 24.687151 | 151 | 0.569595 | 4.105357 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/API/ChinachuAPI.swift | 1 | 17414 | /**
*
* ChinachuAPI.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/07/10.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* 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.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import APIKit
import ObjectMapper
import Kingfisher
import KeychainAccess
// TODO: tvOS support
#if os(iOS)
import Crashlytics
#endif
// MARK: - Chinachu API DataParserType
class ChinachuDataParser: DataParser {
var contentType: String? {
return "application/json"
}
func parse(data: Data) throws -> Any {
guard !data.isEmpty else {
return [:]
}
guard let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else {
throw ResponseError.unexpectedObject(data)
}
do {
return try JSONSerialization.jsonObject(with: data, options: [])
} catch let error as NSError {
// TODO: tvOS support
#if os(iOS)
Answers.logCustomEvent(withName: "JSON Serialization error", customAttributes: ["error": error])
#endif
return ["data": string, "parseError": error.description]
}
}
}
class ChinachuPNGImageParser: DataParser {
var contentType: String? {
return "image/png"
}
func parse(data: Data) throws -> Any {
return data
}
}
protocol ChinachuRequestType: Request {
}
// MARK: - Chinachu API RequestType
extension ChinachuRequestType {
// MARK: - Basic Authorization setting
var headerFields: [String: String] {
if ChinachuAPI.username == "" && ChinachuAPI.password == "" {
return [:]
}
if let auth = "\(ChinachuAPI.username):\(ChinachuAPI.password)".data(using: String.Encoding.utf8) {
return ["Authorization": "Basic \(auth.base64EncodedString(options: []))"]
}
return [:]
}
// MARK: - API endpoint definition
var baseURL: URL {
return URL(string: "\(ChinachuAPI.wuiAddress)/api/")!
}
// MARK: - Response check
func interceptObject(_ object: AnyObject, URLResponse: HTTPURLResponse) throws -> AnyObject {
guard (200..<300).contains(URLResponse.statusCode) else {
// TODO: tvOS support
#if os(iOS)
Answers.logCustomEvent(withName: "HTTP Status Code out-of-range", customAttributes: ["status_code": URLResponse.statusCode])
#endif
throw ResponseError.unacceptableStatusCode(URLResponse.statusCode)
}
return object
}
// MARK: - Timeout set
func interceptURLRequest(_ URLRequest: NSMutableURLRequest) throws -> NSMutableURLRequest {
URLRequest.timeoutInterval = ChinachuAPI.timeout
return URLRequest
}
// MARK: - Data parser
var dataParser: DataParser {
return ChinachuDataParser()
}
}
final class ChinachuAPI {
// MARK: - Chinachu WUI configurations
private struct Configuration {
static var timeout: TimeInterval = 10
}
static var wuiAddress: String {
get {
return UserDefaults().string(forKey: "ChinachuWUIAddress") ?? ""
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "ChinachuWUIAddress")
userDefaults.synchronize()
}
}
static var username: String {
get {
return UserDefaults().string(forKey: "ChinachuWUIUsername") ?? ""
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "ChinachuWUIUsername")
userDefaults.synchronize()
}
}
// TODO: Support encryption in tvOS
static var password: String {
get {
#if os(iOS)
if wuiAddress.isEmpty {
return ""
}
let keychain: Keychain
if wuiAddress.range(of: "^https://", options: .regularExpression) != nil {
keychain = Keychain(server: wuiAddress, protocolType: .https, authenticationType: .httpBasic)
} else {
keychain = Keychain(server: wuiAddress, protocolType: .http, authenticationType: .httpBasic)
}
return keychain[username] ?? ""
#elseif os(tvOS)
return UserDefaults.standard.string(forKey: "ChinachuWUIPassword") ?? ""
#endif
}
set {
#if os(iOS)
if wuiAddress.isEmpty {
return
}
let keychain: Keychain
if wuiAddress.range(of: "^https://", options: .regularExpression) != nil {
keychain = Keychain(server: wuiAddress, protocolType: .https, authenticationType: .httpBasic)
} else {
keychain = Keychain(server: wuiAddress, protocolType: .http, authenticationType: .httpBasic)
}
keychain[username] = newValue
keychain.setSharedPassword(newValue, account: username)
#elseif os(tvOS)
let userDefaults = UserDefaults.standard
userDefaults.set(newValue, forKey: "ChinachuWUIPassword")
userDefaults.synchronize()
#endif
}
}
static var timeout: TimeInterval {
get { return Configuration.timeout }
set { Configuration.timeout = newValue }
}
static var transcode: Bool {
get {
return UserDefaults().bool(forKey: "PlaybackTranscoding")
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "PlaybackTranscoding")
userDefaults.synchronize()
}
}
static var videoResolution: String {
get {
return UserDefaults().string(forKey: "TranscodeResolution") ?? "1280x720"
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "TranscodeResolution")
userDefaults.synchronize()
}
}
static var videoBitrate: Int {
get {
let value = UserDefaults().value(forKey: "VideoBitrate") ?? 1024
switch value {
case let intVal as Int:
return intVal
default:
return 0
}
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "VideoBitrate")
userDefaults.synchronize()
}
}
static var audioBitrate: Int {
get {
let value = UserDefaults().value(forKey: "AudioBitrate") ?? 256
switch value {
case let intVal as Int:
return intVal
default:
return 0
}
}
set {
let userDefaults = UserDefaults()
userDefaults.set(newValue, forKey: "AudioBitrate")
userDefaults.synchronize()
}
}
static func lastTime(id: String) -> Int? {
guard let value = UserDefaults().value(forKey: "LastTimes") else {
return nil
}
guard let lastTimes = value as? [String] else {
return nil
}
return lastTimes
.map { $0.components(separatedBy: ":") }
.filter { $0[0] == id }
.map { Int($0[1])! }
.first
}
static func setLastTime(id: String, time: Int?) {
var lastTimes: [String] = []
let userDefaults = UserDefaults()
if let value = userDefaults.value(forKey: "LastTimes") {
if let value = value as? [String] {
lastTimes = value.filter { !$0.hasPrefix("\(id):") }
}
}
if let time = time {
lastTimes.append("\(id):\(time)")
}
lastTimes = Array(lastTimes.suffix(5))
userDefaults.set(lastTimes, forKey: "LastTimes")
userDefaults.synchronize()
}
}
// MARK: - API request types
extension ChinachuAPI {
// MARK: - Recording API
struct RecordingRequest: ChinachuRequestType {
typealias Response = [Program]
var method: HTTPMethod {
return .get
}
var path: String {
return "recorded.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [[String: AnyObject]] else {
return []
}
return dict.map { Mapper<Program>().map(JSON: $0) }.filter { $0 != nil }.map { $0! }
}
}
struct RecordingDetailRequest: ChinachuRequestType {
typealias Response = Program!
var method: HTTPMethod {
return .get
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "recorded/\(self.id).json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return nil
}
return Mapper<Program>().map(JSON: dict)
}
}
struct RecordingFileInfoRequest: ChinachuRequestType {
typealias Response = [String: AnyObject]
var method: HTTPMethod {
return .get
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "recorded/\(self.id)/file.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return [:]
}
return dict
}
}
// MARK: - Timer API
struct TimerRequest: ChinachuRequestType {
typealias Response = [Timer]
var method: HTTPMethod {
return .get
}
var path: String {
return "reserves.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [[String: AnyObject]] else {
return []
}
return dict.map { Mapper<Timer>().map(JSON: $0) }.filter { $0 != nil }.map { $0! }
}
}
struct TimerSkipRequest: ChinachuRequestType {
typealias Response = [String: AnyObject]
var method: HTTPMethod {
return .put
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "reserves/\(self.id)/skip.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return [:]
}
return dict
}
}
struct TimerUnskipRequest: ChinachuRequestType {
typealias Response = [String: AnyObject]
var method: HTTPMethod {
return .put
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "reserves/\(self.id)/unskip.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return [:]
}
return dict
}
}
struct TimerAddRequest: ChinachuRequestType {
typealias Response = [String: AnyObject]
var method: HTTPMethod {
return .put
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "program/\(self.id).json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return [:]
}
return dict
}
}
struct TimerDeleteRequest: ChinachuRequestType {
typealias Response = [String: AnyObject]
var method: HTTPMethod {
return .delete
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "reserves/\(self.id).json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let dict = object as? [String: AnyObject] else {
return [:]
}
return dict
}
}
// MARK: - Guide API
struct GuideRequest: ChinachuRequestType {
typealias Response = [(channel: Channel, programs: [Program])]
var method: HTTPMethod {
return .get
}
var path: String {
return "schedule.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let array = object as? [[String: AnyObject]] else {
// TODO: エラーコードを設定
throw NSError(domain: "", code: 0, userInfo: nil)
}
var response: Response = []
for dict in array {
// Map Channel
guard let channel: Channel = Mapper<Channel>().map(JSON: dict) else {
// TODO: エラーコードを設定
throw NSError(domain: "", code: 0, userInfo: nil)
}
// Map Programs
var programs: [Program] = []
if let progs = dict["programs"] as? [[String: AnyObject]] {
programs = try progs.map {
guard let prog = Mapper<Program>().map(JSON: $0) else {
// TODO: エラーコードを設定
throw NSError(domain: "", code: 0, userInfo: nil)
}
return prog
}
}
// Append
response.append((channel, programs))
}
return response
}
}
// MARK: - Thumbnail API
struct PreviewImageRequest: ChinachuRequestType {
typealias Response = UIImage
var method: HTTPMethod {
return .get
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "recorded/\(self.id)/preview.png"
}
var parameters: Any? {
return ["width": 1280, "height": 720, "pos": 36]
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let data = object as? Data else {
throw ResponseError.unexpectedObject(object)
}
guard let image = UIImage(data: data) else {
throw ResponseError.unexpectedObject(object)
}
return image
}
// MARK: - Data parser
var dataParser: DataParser {
return ChinachuPNGImageParser()
}
}
// MARK: - Data operation API
struct DeleteProgramRequest: ChinachuRequestType {
typealias Response = Bool
var method: HTTPMethod {
return .delete
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "recorded/\(self.id).json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
return true
}
}
struct DeleteProgramFileRequest: ChinachuRequestType {
typealias Response = Bool
var method: HTTPMethod {
return .delete
}
var id: String
init(id: String) {
self.id = id
}
var path: String {
return "recorded/\(self.id)/file.json"
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
return true
}
}
// MARK: - Streaming API
struct StreamingMediaRequest: ChinachuRequestType {
typealias Response = Data
var method: HTTPMethod {
return .get
}
let id: String
let time: Int? /// In seconds
init(id: String, time: Int? = nil) {
self.id = id
self.time = time
}
var path: String {
// Disable mp4 container because time of video streaming is not available
// TODO: Implement alternative method to get time of mp4 container
/*
if ChinachuAPI.transcode {
return "recorded/\(self.id)/watch.mp4"
}
*/
return "recorded/\(self.id)/watch.m2ts"
}
var parameters: Any? {
var p: [String : String]
if ChinachuAPI.transcode {
p = ["ext": "mp4", "c:v": "libx264", "c:a": "aac", "b:v": "\(ChinachuAPI.videoBitrate)k", "size": ChinachuAPI.videoResolution, "b:a": "\(ChinachuAPI.audioBitrate)k"]
} else {
p = ["ext": "m2ts", "c:v": "copy", "c:a": "copy"]
}
if let time = time, time > 0 {
p["ss"] = "\(time)"
}
return p
}
func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Response {
guard let data = object as? Data else {
throw ResponseError.unexpectedObject(object)
}
return data
}
}
}
// MARK: - Error string parser
extension ChinachuAPI {
static func parseErrorMessage(_ error: SessionTaskError) -> String {
switch error {
case .connectionError(let error as NSError):
return error.localizedDescription
case .requestError(let error as RequestError):
switch error {
case .invalidBaseURL(_):
return "Request URL is invalid."
case .unexpectedURLRequest(_):
return "Request URL is unexpected."
}
case .responseError(let error as ResponseError):
switch error {
case .nonHTTPURLResponse(_), .unexpectedObject(_):
return (error as NSError).localizedDescription
case .unacceptableStatusCode(let statusCode):
switch statusCode {
case 401:
return "Authentication failed."
default:
return "HTTP \(statusCode) " + (error as NSError).localizedDescription
}
}
case .connectionError:
return "Connection error."
case .requestError:
return "Request error."
case .responseError:
return "Response error."
}
}
}
| bsd-3-clause | 48d639254ca80c051a69994a10431409 | 23.87106 | 169 | 0.643894 | 3.789566 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Network/NWPath.swift | 3 | 9657 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 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
//
//===----------------------------------------------------------------------===//
import Foundation
import _SwiftNetworkOverlayShims
/// An NWInterface object represents an instance of a network interface of a specific
/// type, such as a Wi-Fi or Cellular interface.
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public struct NWInterface : Hashable, CustomDebugStringConvertible {
public var debugDescription: String {
return self.name
}
public static func ==(lhs: NWInterface, rhs: NWInterface) -> Bool {
return lhs.index == rhs.index && lhs.name == rhs.name
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.index)
hasher.combine(self.name)
}
/// Interface types represent the underlying media for a network link
public enum InterfaceType {
/// A virtual or otherwise unknown interface type
case other
/// A Wi-Fi link
case wifi
/// A Cellular link
case cellular
/// A Wired Ethernet link
case wiredEthernet
/// The Loopback Interface
case loopback
internal var nw : nw_interface_type_t {
switch self {
case .wifi:
return Network.nw_interface_type_wifi
case .cellular:
return Network.nw_interface_type_cellular
case .wiredEthernet:
return Network.nw_interface_type_wired
case .loopback:
return Network.nw_interface_type_loopback
case .other:
return Network.nw_interface_type_other
}
}
internal init(_ nw: nw_interface_type_t) {
switch nw {
case Network.nw_interface_type_wifi:
self = .wifi
case Network.nw_interface_type_cellular:
self = .cellular
case Network.nw_interface_type_wired:
self = .wiredEthernet
case Network.nw_interface_type_loopback:
self = .loopback
default:
self = .other
}
}
}
public let type: InterfaceType
/// The name of the interface, such as "en0"
public let name: String
/// The kernel index of the interface
public let index: Int
internal let nw: nw_interface_t
internal init(_ nw: nw_interface_t) {
self.nw = nw
self.type = NWInterface.InterfaceType(nw_interface_get_type(nw))
self.name = String(cString: nw_interface_get_name(nw))
self.index = Int(nw_interface_get_index(nw))
}
internal init?(_ index: Int) {
guard let nw = nw_interface_create_with_index(UInt32(index)) else {
return nil
}
self.init(nw)
}
internal init?(_ name: String) {
guard let nw = nw_interface_create_with_name(name) else {
return nil
}
self.init(nw)
}
}
/// An NWPath object represents a snapshot of network path state. This state
/// represents the known information about the local interface and routes that may
/// be used to send and receive data. If the network path for a connection changes
/// due to interface characteristics, addresses, or other attributes, a new NWPath
/// object will be generated. Note that the differences in the path attributes may not
/// be visible through public accessors, and these changes should be treated merely
/// as an indication that something about the network has changed.
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public struct NWPath : Equatable, CustomDebugStringConvertible {
public var debugDescription: String {
return String(describing: self.nw)
}
/// An NWPath status indicates if there is a usable route available upon which to send and receive data.
public enum Status {
/// The path has a usable route upon which to send and receive data
case satisfied
/// The path does not have a usable route. This may be due to a network interface being down, or due to system policy.
case unsatisfied
/// The path does not currently have a usable route, but a connection attempt will trigger network attachment.
case requiresConnection
}
public let status: NWPath.Status
/// A list of all interfaces currently available to this path
public let availableInterfaces: [NWInterface]
/// Checks if the path uses an NWInterface that is considered to be expensive
///
/// Cellular interfaces are considered expensive. WiFi hotspots from an iOS device are considered expensive. Other
/// interfaces may appear as expensive in the future.
public let isExpensive : Bool
public let supportsIPv4 : Bool
public let supportsIPv6 : Bool
public let supportsDNS : Bool
/// Check the local endpoint set on a path. This will be nil for paths
/// from an NWPathMonitor. For paths from an NWConnection, this will
/// be set to the local address and port in use by the connection.
public let localEndpoint: NWEndpoint?
/// Check the remote endpoint set on a path. This will be nil for paths
/// from an NWPathMonitor. For paths from an NWConnection, this will
/// be set to the remote address and port in use by the connection.
public let remoteEndpoint: NWEndpoint?
/// Checks if the path uses an NWInterface with the specified type
public func usesInterfaceType(_ type: NWInterface.InterfaceType) -> Bool {
if let path = self.nw {
return nw_path_uses_interface_type(path, type.nw)
}
return false
}
internal let nw: nw_path_t?
internal init(_ path: nw_path_t?) {
var interfaces = [NWInterface]()
var local: NWEndpoint? = nil
var remote: NWEndpoint? = nil
if let path = path {
let nwstatus = nw_path_get_status(path)
switch (nwstatus) {
case Network.nw_path_status_satisfied:
self.status = .satisfied
case Network.nw_path_status_satisfiable:
self.status = .requiresConnection
default:
self.status = .unsatisfied
}
self.isExpensive = nw_path_is_expensive(path)
self.supportsDNS = nw_path_has_dns(path)
self.supportsIPv4 = nw_path_has_ipv4(path)
self.supportsIPv6 = nw_path_has_ipv6(path)
nw_path_enumerate_interfaces(path, { (interface) in
interfaces.append(NWInterface(interface))
return true
})
if let nwlocal = nw_path_copy_effective_local_endpoint(path) {
local = NWEndpoint(nwlocal)
}
if let nwremote = nw_path_copy_effective_remote_endpoint(path) {
remote = NWEndpoint(nwremote)
}
} else {
self.status = .unsatisfied
self.isExpensive = false
self.supportsDNS = false
self.supportsIPv4 = false
self.supportsIPv6 = false
}
self.availableInterfaces = interfaces
self.nw = path
self.localEndpoint = local
self.remoteEndpoint = remote
}
public static func ==(lhs: NWPath, rhs: NWPath) -> Bool {
if let lnw = lhs.nw, let rnw = rhs.nw {
return nw_path_is_equal(lnw, rnw)
}
return lhs.nw == nil && rhs.nw == nil
}
}
/// The NWPathMonitor allows the caller to fetch the current global path (or
/// a path restricted to a specific network interface type). The path for the monitor
/// is an observable property that will be updated upon each network change.
/// Paths generated by a path monitor are not specific to a given endpoint, and
/// will not have the localEndpoint or remoteEndpoint properties set.
/// The paths will watch the state of multiple interfaces, and allows the
/// application to enumerate the available interfaces for use in creating connections
/// or listeners bound to specific interfaces.
@available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
public final class NWPathMonitor {
/// Access the current network path tracked by the monitor
public var currentPath = NWPath(nil)
fileprivate let nw : nw_path_monitor_t
/// Set a block to be called when the network path changes
private var _pathUpdateHandler: ((_ newPath: NWPath) -> Void)?
public var pathUpdateHandler: ((_ newPath: NWPath) -> Void)? {
set {
self._pathUpdateHandler = newValue
}
get {
return self._pathUpdateHandler
}
}
/// Start the path monitor and set a queue on which path updates
/// will be delivered.
/// Start should only be called once on a monitor, and multiple calls to start will
/// be ignored.
public func start(queue: DispatchQueue) {
self._queue = queue
nw_path_monitor_set_queue(self.nw, queue)
nw_path_monitor_start(self.nw)
}
/// Cancel the path monitor, after which point no more path updates will
/// be delivered.
public func cancel() {
nw_path_monitor_cancel(self.nw)
}
private var _queue: DispatchQueue?
/// Get queue used for delivering the pathUpdateHandler block.
/// If the path monitor has not yet been started, the queue will be nil. Once the
/// path monitor has been started, the queue will be valid.
public var queue: DispatchQueue? {
get {
return self._queue
}
}
/// Create a network path monitor to monitor overall network state for the
/// system. This allows enumeration of all interfaces that are available for
/// general use by the application.
public init() {
self.nw = nw_path_monitor_create()
nw_path_monitor_set_update_handler(self.nw) { (newPath) in
self.currentPath = NWPath(newPath)
if let handler = self._pathUpdateHandler {
handler(self.currentPath)
}
}
}
/// Create a network path monitor that watches a single interface type.
public init(requiredInterfaceType: NWInterface.InterfaceType) {
self.nw = nw_path_monitor_create_with_type(requiredInterfaceType.nw)
nw_path_monitor_set_update_handler(self.nw) { (newPath) in
self.currentPath = NWPath(newPath)
if let handler = self._pathUpdateHandler {
handler(self.currentPath)
}
}
}
}
| apache-2.0 | 21185c535502fb534dc88b42b8e20a02 | 31.625 | 120 | 0.709226 | 3.65104 | false | false | false | false |
remlostime/one | one/Pods/SwiftDate/Sources/SwiftDate/DateInRegion+Math.swift | 7 | 5427 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
// MARK: - DateInRegion Private Extension
extension DateInRegion {
/// Return a `DateComponent` object from a given set of `Calendar.Component` object with associated values and a specific region
///
/// - parameter values: calendar components to set (with their values)
/// - parameter multipler: optional multipler (by default is nil; to make an inverse component value it should be multipled by -1)
/// - parameter region: optional region to set
///
/// - returns: a `DateComponents` object
internal static func componentsFrom(values: [Calendar.Component : Int], multipler: Int? = nil, setRegion region: Region? = nil) -> DateComponents {
var cmps = DateComponents()
if region != nil {
cmps.calendar = region!.calendar
cmps.calendar!.locale = region!.locale
cmps.timeZone = region!.timeZone
}
values.forEach { key,value in
if key != .timeZone && key != .calendar {
cmps.setValue( (multipler == nil ? value : value * multipler!), for: key)
}
}
return cmps
}
/// Create a new DateInRegion by adding specified DateComponents to self
///
/// - Parameter dateComponents: date components to add
/// - Returns: a new instance of DateInRegion expressed in same region
/// - Throws: throw `.FailedToCalculate` if new date cannot be evaluated due to wrong components passed
public func add(components dateComponents: DateComponents) throws -> DateInRegion {
let newDate = self.region.calendar.date(byAdding: dateComponents, to: self.absoluteDate)
if newDate == nil { throw DateError.FailedToCalculate }
return DateInRegion(absoluteDate: newDate!, in: self.region)
}
/// Enumerate dates between two intervals by adding specified time components and return an array of dates.
/// `startDate` interval will be the first item of the resulting array. The last item of the array is evaluated automatically.
///
/// - throws: throw `.DifferentCalendar` if dates are expressed in a different calendar,
///
/// - Parameters:
/// - startDate: starting date
/// - endDate: ending date
/// - components: components to add
/// - normalize: normalize both start and end date at the start of the specified component (if nil, normalization is skipped)
/// - Returns: an array of DateInRegion objects
public static func dates(between startDate: DateInRegion, and endDate: DateInRegion, increment components: DateComponents) throws -> [DateInRegion] {
guard startDate.region.calendar == endDate.region.calendar else {
throw DateError.DifferentCalendar
}
var dates = [startDate]
var currentDate = startDate
repeat {
currentDate = try currentDate.add(components: components)
dates.append(currentDate)
} while (currentDate <= endDate)
return dates
}
}
// MARK: - DateInRegion Support for math operation
// These functions allows us to make something like
// `let newDate = (date - 3.days + 3.months)`
// We can sum algebrically a `DateInRegion` object with a calendar component.
public func + (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
let nextDate = lhs.region.calendar.date(byAdding: rhs, to: lhs.absoluteDate)
return DateInRegion(absoluteDate: nextDate!, in: lhs.region)
}
public func - (lhs: DateInRegion, rhs: DateComponents) -> DateInRegion {
return lhs + (-rhs)
}
public func + (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
let cmps = DateInRegion.componentsFrom(values: rhs)
return lhs + cmps
}
public func - (lhs: DateInRegion, rhs: [Calendar.Component : Int]) -> DateInRegion {
var invertedCmps: [Calendar.Component : Int] = [:]
rhs.forEach { invertedCmps[$0] = -$1 }
return lhs + invertedCmps
}
public func - (lhs: DateInRegion, rhs: DateInRegion) -> TimeInterval {
var interval: TimeInterval = 0
if #available(iOS 10.0, *) {
if lhs.absoluteDate < rhs.absoluteDate {
interval = -(DateTimeInterval(start: lhs.absoluteDate, end: rhs.absoluteDate)).duration
} else {
interval = (DateTimeInterval(start: rhs.absoluteDate, end: lhs.absoluteDate)).duration
}
} else {
interval = rhs.absoluteDate.timeIntervalSince(lhs.absoluteDate)
}
return interval
}
| gpl-3.0 | cfbc16c3f4cbc7cb8a9239a9d1d35c3b | 39.5 | 150 | 0.731896 | 4.080451 | false | false | false | false |
hejunbinlan/BRYXBanner | Pod/Classes/Banner.swift | 1 | 15001 | //
// Banner.swift
//
// Created by Harlan Haskins on 7/27/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import UIKit
private enum BannerState {
case Showing, Hidden, Gone
}
/// A level of 'springiness' for Banners.
///
/// - None: The banner will slide in and not bounce.
/// - Slight: The banner will bounce a little.
/// - Heavy: The banner will bounce a lot.
public enum BannerSpringiness {
case None, Slight, Heavy
private var springValues: (damping: CGFloat, velocity: CGFloat) {
switch self {
case .None: return (damping: 1.0, velocity: 1.0)
case .Slight: return (damping: 0.7, velocity: 1.5)
case .Heavy: return (damping: 0.6, velocity: 2.0)
}
}
}
/// Banner is a dropdown notification view that presents above the main view controller, but below the status bar.
public class Banner: UIView {
private class func topWindow() -> UIWindow? {
for window in UIApplication.sharedApplication().windows.reverse() {
if window.windowLevel == UIWindowLevelNormal && !window.hidden { return window }
}
return nil
}
private let contentView = UIView()
private let labelView = UIView()
private let backgroundView = UIView()
/// How long the slide down animation should last.
public var animationDuration: NSTimeInterval = 0.4
/// The preferred style of the status bar during display of the banner. Defaults to `.LightContent`.
///
/// If the banner's `adjustsStatusBarStyle` is false, this property does nothing.
public var preferredStatusBarStyle = UIStatusBarStyle.LightContent
/// Whether or not this banner should adjust the status bar style during its presentation. Defaults to `false`.
public var adjustsStatusBarStyle = false
/// How 'springy' the banner should display. Defaults to `.Slight`
public var springiness = BannerSpringiness.Slight
/// The color of the text as well as the image tint color if `shouldTintImage` is `true`.
public var textColor = UIColor.whiteColor() {
didSet {
resetTintColor()
}
}
/// Whether or not the banner should show a shadow when presented.
public var hasShadows = true {
didSet {
resetShadows()
}
}
/// The color of the background view. Defaults to `nil`.
override public var backgroundColor: UIColor? {
get { return backgroundView.backgroundColor }
set { backgroundView.backgroundColor = newValue }
}
/// The opacity of the background view. Defaults to 0.95.
override public var alpha: CGFloat {
get { return backgroundView.alpha }
set { backgroundView.alpha = newValue }
}
/// A block to call when the uer taps on the banner.
public var didTapBlock: (() -> ())?
/// A block to call after the banner has finished dismissing and is off screen.
public var didDismissBlock: (() -> ())?
/// Whether or not the banner should dismiss itself when the user taps. Defaults to `true`.
public var dismissesOnTap = true
/// Whether or not the banner should dismiss itself when the user swipes up. Defaults to `true`.
public var dismissesOnSwipe = true
/// Whether or not the banner should tint the associated image to the provided `textColor`. Defaults to `true`.
public var shouldTintImage = true {
didSet {
resetTintColor()
}
}
/// The label that displays the banner's title.
public let titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The label that displays the banner's subtitle.
public let detailLabel: UILabel = {
let label = UILabel()
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
/// The image on the left of the banner.
let image: UIImage?
/// The image view that displays the `image`.
public let imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .ScaleAspectFit
return imageView
}()
private var bannerState = BannerState.Hidden {
didSet {
if bannerState != oldValue {
forceUpdates()
}
}
}
/// A Banner with the provided `title`, `subtitle`, and optional `image`, ready to be presented with `show()`.
///
/// - parameter title: The title of the banner. Optional. Defaults to nil.
/// - parameter subtitle: The subtitle of the banner. Optional. Defaults to nil.
/// - parameter image: The image on the left of the banner. Optional. Defaults to nil.
/// - parameter backgroundColor: The color of the banner's background view. Defaults to `UIColor.blackColor()`.
/// - parameter didTapBlock: An action to be called when the user taps on the banner. Optional. Defaults to `nil`.
public required init(title: String? = nil, subtitle: String? = nil, image: UIImage? = nil, backgroundColor: UIColor = UIColor.blackColor(), didTapBlock: (() -> ())? = nil) {
self.didTapBlock = didTapBlock
self.image = image
super.init(frame: CGRectZero)
resetShadows()
addGestureRecognizers()
initializeSubviews()
resetTintColor()
titleLabel.text = title
detailLabel.text = subtitle
backgroundView.backgroundColor = backgroundColor
backgroundView.alpha = 0.95
}
private func forceUpdates() {
guard let superview = superview, showingConstraint = showingConstraint, hiddenConstraint = hiddenConstraint else { return }
switch bannerState {
case .Hidden:
superview.removeConstraint(showingConstraint)
superview.addConstraint(hiddenConstraint)
case .Showing:
superview.removeConstraint(hiddenConstraint)
superview.addConstraint(showingConstraint)
case .Gone:
superview.removeConstraint(hiddenConstraint)
superview.removeConstraint(showingConstraint)
superview.removeConstraints(commonConstraints)
}
setNeedsLayout()
setNeedsUpdateConstraints()
layoutIfNeeded()
updateConstraintsIfNeeded()
}
internal func didTap(recognizer: UITapGestureRecognizer) {
if dismissesOnTap {
dismiss()
}
didTapBlock?()
}
internal func didSwipe(recognizer: UISwipeGestureRecognizer) {
if dismissesOnSwipe {
dismiss()
}
}
private func addGestureRecognizers() {
addGestureRecognizer(UITapGestureRecognizer(target: self, action: "didTap:"))
let swipe = UISwipeGestureRecognizer(target: self, action: "didSwipe:")
swipe.direction = .Up
addGestureRecognizer(swipe)
}
private func resetTintColor() {
titleLabel.textColor = textColor
detailLabel.textColor = textColor
imageView.image = shouldTintImage ? image?.imageWithRenderingMode(.AlwaysTemplate) : image
imageView.tintColor = shouldTintImage ? textColor : nil
}
private func resetShadows() {
layer.shadowColor = UIColor.blackColor().CGColor
layer.shadowOpacity = self.hasShadows ? 0.5 : 0.0
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 4
}
private func initializeSubviews() {
let views = [
"backgroundView": backgroundView,
"contentView": contentView,
"imageView": imageView,
"labelView": labelView,
"titleLabel": titleLabel,
"detailLabel": detailLabel
]
translatesAutoresizingMaskIntoConstraints = false
addSubview(backgroundView)
backgroundView.translatesAutoresizingMaskIntoConstraints = false
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundView]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView(>=80)]|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.backgroundColor = backgroundColor
contentView.translatesAutoresizingMaskIntoConstraints = false
backgroundView.addSubview(contentView)
labelView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(labelView)
labelView.addSubview(titleLabel)
labelView.addSubview(detailLabel)
let statusBarSize = UIApplication.sharedApplication().statusBarFrame.size
let heightOffset = min(statusBarSize.height, statusBarSize.width) // Arbitrary, but looks nice.
for format in ["H:|[contentView]|", "V:|-(\(heightOffset))-[contentView]|"] {
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
let leftConstraintText: String
if image == nil {
leftConstraintText = "|"
} else {
contentView.addSubview(imageView)
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(15)-[imageView]", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 25.0))
imageView.addConstraint(NSLayoutConstraint(item: imageView, attribute: .Height, relatedBy: .Equal, toItem: imageView, attribute: .Width, multiplier: 1.0, constant: 0.0))
leftConstraintText = "[imageView]"
}
let constraintFormat = "H:\(leftConstraintText)-(15)-[labelView]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(>=1)-[labelView]-(>=1)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
backgroundView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]-(<=1)-[labelView]", options: .AlignAllCenterY, metrics: nil, views: views))
for view in [titleLabel, detailLabel] {
let constraintFormat = "H:|-(15)-[label]-(8)-|"
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(constraintFormat, options: .DirectionLeadingToTrailing, metrics: nil, views: ["label": view]))
}
labelView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(10)-[titleLabel][detailLabel]-(10)-|", options: .DirectionLeadingToTrailing, metrics: nil, views: views))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var showingConstraint: NSLayoutConstraint?
private var hiddenConstraint: NSLayoutConstraint?
private var commonConstraints = [NSLayoutConstraint]()
override public func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = superview where bannerState != .Gone else { return }
commonConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[banner]|", options: .DirectionLeadingToTrailing, metrics: nil, views: ["banner": self])
superview.addConstraints(commonConstraints)
let yOffset: CGFloat = -7.0 // Offset the bottom constraint to make room for the shadow to animate off screen.
showingConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
hiddenConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1.0, constant: yOffset)
}
/// Shows the banner. If a view is specified, the banner will be displayed at the top of that view, otherwise at top of the top window. If a `duration` is specified, the banner dismisses itself automatically after that duration elapses.
/// - parameter view: A view the banner will be shown in. Optional. Defaults to 'nil', which in turn means it will be shown in the top window. duration A time interval, after which the banner will dismiss itself. Optional. Defaults to `nil`.
public func show(view: UIView? = Banner.topWindow(), duration: NSTimeInterval? = nil) {
guard let view = view else {
print("[Banner]: Could not find view. Aborting.")
return
}
view.addSubview(self)
forceUpdates()
let (damping, velocity) = self.springiness.springValues
let oldStatusBarStyle = UIApplication.sharedApplication().statusBarStyle
if adjustsStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(preferredStatusBarStyle, animated: true)
}
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Showing
}, completion: { finished in
guard let duration = duration else { return }
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(duration * NSTimeInterval(NSEC_PER_SEC))), dispatch_get_main_queue()) {
self.dismiss(self.adjustsStatusBarStyle ? oldStatusBarStyle : nil)
}
})
}
/// Dismisses the banner.
public func dismiss(oldStatusBarStyle: UIStatusBarStyle? = nil) {
let (damping, velocity) = self.springiness.springValues
UIView.animateWithDuration(animationDuration, delay: 0.0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: .AllowUserInteraction, animations: {
self.bannerState = .Hidden
if let oldStatusBarStyle = oldStatusBarStyle {
UIApplication.sharedApplication().setStatusBarStyle(oldStatusBarStyle, animated: true)
}
}, completion: { finished in
self.bannerState = .Gone
self.removeFromSuperview()
self.didDismissBlock?()
})
}
}
| mit | bbf8b21e0de2c72d0ce06f5d742120ad | 46.025078 | 245 | 0.672755 | 5.355587 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructure/Array/SecondLargestElements.swift | 1 | 818 | //
// SecondLargestElements.swift
// DataStructure
//
// Created by Jigs Sheth on 4/26/16.
// Copyright © 2016 jigneshsheth.com. All rights reserved.
//
import Foundation
public func findSecondLargestElement(input:[Int]) throws -> Int {
if input.count < 2 {
throw NSError(domain: "Invalid Input", code: 1, userInfo: nil)
}
var secondLargestNum = input[1]
var firstLargestNum = input[0]
if firstLargestNum < secondLargestNum {
firstLargestNum = input[1]
secondLargestNum = input[0]
}
for i in 2..<input.count {
if input[i] > firstLargestNum {
secondLargestNum = firstLargestNum
firstLargestNum = input[i]
}else if input[i] < firstLargestNum && input[i] > secondLargestNum {
secondLargestNum = input[i]
}
}
return secondLargestNum
} | mit | 29ce934ceb28987d664324696d536ca9 | 20.526316 | 72 | 0.667075 | 3.631111 | false | false | false | false |
343max/WorldTime | TimeZone.swift | 1 | 1243 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import Foundation
func relativeHours(seconds: Int, shortStyle: Bool = true) -> String? {
guard seconds != 0 || !shortStyle else {
return nil
}
let hours = seconds / 3600
let minutes = abs(hours * 60 - seconds / 60)
let minutesString: String = {
if minutes == 0 && shortStyle {
return ""
} else if minutes == 15 && shortStyle {
return "¼"
} else if minutes == 30 && shortStyle {
return "½"
} else if minutes == 45 && shortStyle {
return "¾"
} else {
return String(format: ":%02d", minutes)
}
}()
let prefix = seconds > 0 ? "+" : (seconds < 0 ? "-" : "±")
return "\(prefix)\(abs(hours))\(minutesString)"
}
extension TimeZone {
func seconds(from timeZone: TimeZone, for date: Date) -> Int {
let selfSeconds = self.secondsFromGMT(for: date)
let otherSeconds = timeZone.secondsFromGMT(for: date)
return otherSeconds - selfSeconds
}
var GMTdiff: String {
get {
return "GMT \(relativeHours(seconds: self.secondsFromGMT(), shortStyle: false)!)"
}
}
}
| mit | b42267cc17b30bdcd95dfe71d48ac1bf | 28.5 | 93 | 0.555287 | 4.214286 | false | false | false | false |
loudnate/Loop | Learn/Configuration/QuantityRangeEntry.swift | 1 | 2555 | //
// QuantityRangeEntry.swift
// Learn
//
// Copyright © 2019 LoopKit Authors. All rights reserved.
//
import HealthKit
import LoopKit
import UIKit
class QuantityRangeEntry: LessonSectionProviding {
var headerTitle: String? {
return numberRange.headerTitle
}
var footerTitle: String? {
return numberRange.footerTitle
}
var cells: [LessonCellProviding] {
return numberRange.cells
}
var minValue: HKQuantity? {
if let minValue = numberRange.minValue?.doubleValue {
return HKQuantity(unit: unit, doubleValue: minValue)
} else {
return nil
}
}
var maxValue: HKQuantity? {
if let maxValue = numberRange.maxValue?.doubleValue {
return HKQuantity(unit: unit, doubleValue: maxValue)
} else {
return nil
}
}
var range: Range<HKQuantity>? {
guard let minValue = minValue, let maxValue = maxValue else {
return nil
}
return minValue..<maxValue
}
var closedRange: ClosedRange<HKQuantity>? {
guard let minValue = minValue, let maxValue = maxValue else {
return nil
}
return minValue...maxValue
}
private let numberRange: NumberRangeEntry
let quantityFormatter: QuantityFormatter
let unit: HKUnit
init(headerTitle: String?, minValue: HKQuantity?, maxValue: HKQuantity?, quantityFormatter: QuantityFormatter, unit: HKUnit, keyboardType: UIKeyboardType) {
self.quantityFormatter = quantityFormatter
self.unit = unit
numberRange = NumberRangeEntry(
headerTitle: headerTitle,
minValue: (minValue?.doubleValue(for: unit)).map(NSNumber.init(value:)),
maxValue: (maxValue?.doubleValue(for: unit)).map(NSNumber.init(value:)),
formatter: quantityFormatter.numberFormatter,
unitString: quantityFormatter.string(from: unit),
keyboardType: keyboardType
)
}
internal class func glucoseRange(minValue: HKQuantity, maxValue: HKQuantity, quantityFormatter: QuantityFormatter, unit: HKUnit) -> QuantityRangeEntry {
return QuantityRangeEntry(
headerTitle: NSLocalizedString("Range", comment: "Section title for glucose range"),
minValue: minValue,
maxValue: maxValue,
quantityFormatter: quantityFormatter,
unit: unit,
keyboardType: unit == .milligramsPerDeciliter ? .numberPad : .decimalPad
)
}
}
| apache-2.0 | 7ee44a6d9d1d950fc1c3090a31d7dbc0 | 28.022727 | 160 | 0.638606 | 5.233607 | false | false | false | false |
i-schuetz/SwiftCharts | SwiftCharts/Axis/ChartAxisYLayerDefault.swift | 3 | 6832 | //
// ChartAxisYLayerDefault.swift
// SwiftCharts
//
// Created by ischuetz on 25/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/// A ChartAxisLayer for Y axes
class ChartAxisYLayerDefault: ChartAxisLayerDefault {
fileprivate var minCalculatedLabelWidth: CGFloat?
fileprivate var maxCalculatedLabelWidth: CGFloat?
override var origin: CGPoint {
return CGPoint(x: offset, y: axis.lastScreen)
}
override var end: CGPoint {
return CGPoint(x: offset, y: axis.firstScreen)
}
override var height: CGFloat {
return axis.screenLength
}
override var visibleFrame: CGRect {
return CGRect(x: offset, y: axis.lastVisibleScreen, width: width, height: axis.visibleScreenLength)
}
var labelsMaxWidth: CGFloat {
let currentWidth: CGFloat = {
if self.labelDrawers.isEmpty {
return self.maxLabelWidth(self.currentAxisValues)
} else {
return self.labelDrawers.reduce(0) {maxWidth, labelDrawer in
return max(maxWidth, labelDrawer.drawers.reduce(0) {maxWidth, drawer in
max(maxWidth, drawer.size.width)
})
}
}
}()
let width: CGFloat = {
switch labelSpaceReservationMode {
case .minPresentedSize: return minCalculatedLabelWidth.maxOpt(currentWidth)
case .maxPresentedSize: return maxCalculatedLabelWidth.maxOpt(currentWidth)
case .fixed(let value): return value
case .current: return currentWidth
}
}()
if !currentAxisValues.isEmpty {
let (min, max): (CGFloat, CGFloat) = (minCalculatedLabelWidth.minOpt(currentWidth), maxCalculatedLabelWidth.maxOpt(currentWidth))
minCalculatedLabelWidth = min
maxCalculatedLabelWidth = max
}
return width
}
override var width: CGFloat {
return labelsMaxWidth + settings.axisStrokeWidth + settings.labelsToAxisSpacingY + settings.axisTitleLabelsToLabelsSpacing + axisTitleLabelsWidth
}
override var widthWithoutLabels: CGFloat {
return settings.axisStrokeWidth + settings.labelsToAxisSpacingY + settings.axisTitleLabelsToLabelsSpacing + axisTitleLabelsWidth
}
override var heightWithoutLabels: CGFloat {
return height
}
override func handleAxisInnerFrameChange(_ xLow: ChartAxisLayerWithFrameDelta?, yLow: ChartAxisLayerWithFrameDelta?, xHigh: ChartAxisLayerWithFrameDelta?, yHigh: ChartAxisLayerWithFrameDelta?) {
super.handleAxisInnerFrameChange(xLow, yLow: yLow, xHigh: xHigh, yHigh: yHigh)
if let xLow = xLow {
axis.offsetFirstScreen(-xLow.delta)
initDrawers()
}
if let xHigh = xHigh {
axis.offsetLastScreen(xHigh.delta)
initDrawers()
}
}
override func generateAxisTitleLabelsDrawers(offset: CGFloat) -> [ChartLabelDrawer] {
if let firstTitleLabel = axisTitleLabels.first {
if axisTitleLabels.count > 1 {
print("WARNING: No support for multiple definition labels on vertical axis. Using only first one.")
}
let axisLabel = firstTitleLabel
let labelSize = axisLabel.textSizeNonRotated
let axisLabelDrawer = ChartLabelDrawer(label: axisLabel, screenLoc: CGPoint(
x: self.offset + offset,
y: axis.lastScreenInit + ((axis.firstScreenInit - axis.lastScreenInit) / 2) - (labelSize.height / 2)))
return [axisLabelDrawer]
} else { // definitionLabels is empty
return []
}
}
override func generateDirectLabelDrawers(offset: CGFloat) -> [ChartAxisValueLabelDrawers] {
var drawers: [ChartAxisValueLabelDrawers] = []
let scalars = valuesGenerator.generate(axis)
currentAxisValues = scalars
for scalar in scalars {
let labels = labelsGenerator.generate(scalar, axis: axis)
let y = axis.screenLocForScalar(scalar)
if let axisLabel = labels.first { // for now y axis supports only one label x value
let labelSize = axisLabel.textSizeNonRotated
let labelY = y - (labelSize.height / 2)
let labelX = labelsX(offset: offset, labelWidth: labelSize.width, textAlignment: axisLabel.settings.textAlignment)
let labelDrawer = ChartLabelDrawer(label: axisLabel, screenLoc: CGPoint(x: labelX, y: labelY))
let labelDrawers = ChartAxisValueLabelDrawers(scalar, [labelDrawer])
drawers.append(labelDrawers)
}
}
return drawers
}
func labelsX(offset: CGFloat, labelWidth: CGFloat, textAlignment: ChartLabelTextAlignment) -> CGFloat {
fatalError("override")
}
fileprivate func maxLabelWidth(_ axisLabels: [ChartAxisLabel]) -> CGFloat {
return axisLabels.reduce(CGFloat(0)) {maxWidth, label in
return max(maxWidth, label.textSizeNonRotated.width)
}
}
fileprivate func maxLabelWidth(_ axisValues: [Double]) -> CGFloat {
return axisValues.reduce(CGFloat(0)) {maxWidth, value in
let labels = labelsGenerator.generate(value, axis: axis)
return max(maxWidth, maxLabelWidth(labels))
}
}
override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) {
axis.zoom(x, y: y, centerX: centerX, centerY: centerY, elastic: chart?.zoomPanSettings.elastic ?? false)
update()
chart?.view.setNeedsDisplay()
}
override func pan(_ deltaX: CGFloat, deltaY: CGFloat) {
axis.pan(deltaX, deltaY: deltaY, elastic: chart?.zoomPanSettings.elastic ?? false)
update()
chart?.view.setNeedsDisplay()
}
override func zoom(_ scaleX: CGFloat, scaleY: CGFloat, centerX: CGFloat, centerY: CGFloat) {
axis.zoom(scaleX, scaleY: scaleY, centerX: centerX, centerY: centerY, elastic: chart?.zoomPanSettings.elastic ?? false)
update()
chart?.view.setNeedsDisplay()
}
func axisLineX(offset: CGFloat) -> CGFloat {
fatalError("Override")
}
override func generateLineDrawer(offset: CGFloat) -> ChartLineDrawer {
let x = axisLineX(offset: offset)
let p1 = CGPoint(x: x, y: axis.firstVisibleScreen)
let p2 = CGPoint(x: x, y: axis.lastVisibleScreen)
return ChartLineDrawer(p1: p1, p2: p2, color: settings.lineColor, strokeWidth: settings.axisStrokeWidth)
}
}
| apache-2.0 | 49605d015d60c72b90c5cf44eec2f2b7 | 37.167598 | 198 | 0.627635 | 4.939986 | false | false | false | false |
lennet/proNotes | app/proNotes/Model/DocumentLayer/MovableLayer.swift | 1 | 1765 | //
// MovableLayer.swift
// proNotes
//
// Created by Leo Thomas on 20/02/16.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import UIKit
class MovableLayer: DocumentLayer {
private final let sizeKey = "size"
private final let originKey = "origin"
var origin: CGPoint
var size: CGSize
init(index: Int, type: DocumentLayerType, docPage: DocumentPage, origin: CGPoint, size: CGSize) {
self.origin = origin
self.size = size
super.init(index: index, type: type, docPage: docPage)
}
required init(coder aDecoder: NSCoder, type: DocumentLayerType) {
origin = aDecoder.decodeCGPoint(forKey: originKey)
size = aDecoder.decodeCGSize(forKey: sizeKey)
super.init(coder: aDecoder, type: type)
}
required init(coder aDecor: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(origin, forKey: originKey)
aCoder.encode(size, forKey: sizeKey)
super.encode(with: aCoder)
}
override func undoAction(_ oldObject: Any?) {
if let value = oldObject as? NSValue {
let frame = value.cgRectValue
origin = frame.origin
size = frame.size
} else {
super.undoAction(oldObject)
}
}
override func isEqual(_ object: Any?) -> Bool {
guard let layer = object as? MovableLayer else {
return false
}
if !super.isEqual(object) {
return false
}
guard layer.origin == origin else {
return false
}
guard layer.size == size else {
return false
}
return true
}
}
| mit | df30f08e51af8387690bfcd4d35a6a54 | 23.84507 | 101 | 0.594671 | 4.323529 | false | false | false | false |
thongtran715/Find-Friends | Pods/Bond/Bond/Extensions/Shared/NSObject+Bond.swift | 1 | 6963 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// 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 extension NSObject {
private struct AssociatedKeys {
static var DisposeBagKey = "bnd_DisposeBagKey"
static var AssociatedObservablesKey = "bnd_AssociatedObservablesKey"
}
// A dispose bag will will dispose upon object deinit.
public var bnd_bag: DisposeBag {
if let disposeBag: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBagKey) {
return disposeBag as! DisposeBag
} else {
let disposeBag = DisposeBag()
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBagKey, disposeBag, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return disposeBag
}
}
}
@objc private class BNDKVOObserver: NSObject {
static private var XXContext = 0
var object: NSObject
let keyPath: String
let listener: AnyObject? -> Void
init(object: NSObject, keyPath: String, options: NSKeyValueObservingOptions, listener: AnyObject? -> Void) {
self.object = object
self.keyPath = keyPath
self.listener = listener
super.init()
self.object.addObserver(self, forKeyPath: keyPath, options: options, context: &BNDKVOObserver.XXContext)
}
func set(value: AnyObject?) {
object.setValue(value, forKey: keyPath)
}
deinit {
object.removeObserver(self, forKeyPath: keyPath)
}
override dynamic func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &BNDKVOObserver.XXContext {
if let newValue: AnyObject? = change?[NSKeyValueChangeNewKey] {
listener(newValue)
}
}
}
}
public extension Observable {
public convenience init(object: NSObject, keyPath: String) {
if let value = object.valueForKeyPath(keyPath) as? Wrapped {
self.init(value)
} else {
fatalError("Dear Sir/Madam, you are creating a Scalar of non-optional \(EventType.self) type, but the value at the given key path is nil or not of \(EventType.self) type. Please check the type or have your Scalar encapsulate optional type like Scalar<\(EventType.self)?>.")
}
var updatingFromSelf = false
let observer = BNDKVOObserver(object: object, keyPath: keyPath, options: .New) { [weak self] value in
updatingFromSelf = true
if let value = value as? EventType {
self?.value = value
} else {
fatalError("Dear Sir/Madam, it appears that the observed key path can hold nil values or values of type different than \(EventType.self). Please check the type or have your Scalar encapsulate optional type like Scalar<\(EventType.self)?>.")
}
updatingFromSelf = false
}
observeNew { value in
if !updatingFromSelf {
observer.set(value as? AnyObject)
}
}
}
}
public extension Observable where Wrapped: OptionalType {
public convenience init(object: NSObject, keyPath: String) {
let initialValue: Wrapped.WrappedType?
if let value = object.valueForKeyPath(keyPath) as? Wrapped.WrappedType {
initialValue = value
} else {
initialValue = nil
}
self.init(EventType(optional: initialValue))
var updatingFromSelf = false
let observer = BNDKVOObserver(object: object, keyPath: keyPath, options: .New) { [weak self] value in
updatingFromSelf = true
if let value = value as? EventType.WrappedType {
self?.value = EventType(optional: value)
} else {
self?.value = EventType(optional: nil)
}
updatingFromSelf = false
}
observeNew { value in
if !updatingFromSelf {
observer.set(value as? AnyObject)
}
}
}
}
public extension NSObject {
internal var bnd_associatedObservables: [String:AnyObject] {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.AssociatedObservablesKey) as? [String:AnyObject] ?? [:]
}
set(observable) {
objc_setAssociatedObject(self, &AssociatedKeys.AssociatedObservablesKey, observable, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public func bnd_associatedObservableForValueForKey<T>(key: String, initial: T? = nil, set: (T -> ())? = nil) -> Observable<T> {
if let observable: AnyObject = bnd_associatedObservables[key] {
return observable as! Observable<T>
} else {
let observable = Observable<T>(initial ?? self.valueForKey(key) as! T)
bnd_associatedObservables[key] = observable
observable
.observeNew { [weak self] (value: T) in
if let set = set {
set(value)
} else {
if let value = value as? AnyObject {
self?.setValue(value, forKey: key)
} else {
self?.setValue(nil, forKey: key)
}
}
}
return observable
}
}
public func bnd_associatedObservableForValueForKey<T: OptionalType>(key: String, initial: T? = nil, set: (T -> ())? = nil) -> Observable<T> {
if let observable: AnyObject = bnd_associatedObservables[key] {
return observable as! Observable<T>
} else {
let observable: Observable<T>
if let initial = initial {
observable = Observable(initial)
} else if let value = self.valueForKey(key) as? T.WrappedType {
observable = Observable(T(optional: value))
} else {
observable = Observable(T(optional: nil))
}
bnd_associatedObservables[key] = observable
observable
.observeNew { [weak self] (value: T) in
if let set = set {
set(value)
} else {
self?.setValue(value.value as! AnyObject?, forKey: key)
}
}
return observable
}
}
}
| mit | c66efc073a5fd3ad138bb299b7bd65f2 | 33.132353 | 279 | 0.666379 | 4.469191 | false | false | false | false |
Jackysonglanlan/Scripts | swift/xunyou_accelerator/Sources/srcLibs/SwifterSwift/stdlib/RangeReplaceableCollectionExtensions.swift | 1 | 4079 | //
// RangeReplaceableCollectionExtensions.swift
// SwifterSwift
//
// Created by Luciano Almeida on 7/2/18.
// Copyright © 2018 SwifterSwift
//
#if canImport(Foundation)
import Foundation
#endif
// MARK: - Initializers
extension RangeReplaceableCollection {
/// Creates a new collection of a given size where for each position of the collection the value will be the result
/// of a call of the given expression.
///
/// let values = Array(expression: "Value", count: 3)
/// print(values)
/// // Prints "["Value", "Value", "Value"]"
///
/// - Parameters:
/// - expression: The expression to execute for each position of the collection.
/// - count: The count of the collection.
public init(expression: @autoclosure () throws -> Element, count: Int) rethrows {
self.init()
if count > 0 { //swiftlint:disable:this empty_count
reserveCapacity(count)
while self.count < count {
append(try expression())
}
}
}
}
// MARK: - Methods
extension RangeReplaceableCollection {
/// SwifterSwift: Returns a new rotated collection by the given places.
///
/// [1, 2, 3, 4].rotated(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotated(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
/// - Returns: The new rotated collection.
public func rotated(by places: Int) -> Self {
//Inspired by: https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate
var copy = self
return copy.rotate(by: places)
}
/// SwifterSwift: Rotate the collection by the given places.
///
/// [1, 2, 3, 4].rotate(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotate(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: The number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start become the end.
/// - Returns: self after rotating.
@discardableResult
public mutating func rotate(by places: Int) -> Self {
guard places != 0 else { return self }
let placesToMove = places%count
if placesToMove > 0 {
let range = index(endIndex, offsetBy: -placesToMove)...
let slice = self[range]
removeSubrange(range)
insert(contentsOf: slice, at: startIndex)
} else {
let range = startIndex..<index(startIndex, offsetBy: -placesToMove)
let slice = self[range]
removeSubrange(range)
append(contentsOf: slice)
}
return self
}
/// SwifterSwift: Removes the first element of the collection which satisfies the given predicate.
///
/// [1, 2, 2, 3, 4, 2, 5].removeFirst { $0 % 2 == 0 } -> [1, 2, 3, 4, 2, 5]
/// ["h", "e", "l", "l", "o"].removeFirst { $0 == "e" } -> ["h", "l", "l", "o"]
///
/// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.
/// - Returns: The first element for which predicate returns true, after removing it. If no elements in the collection satisfy the given predicate, returns `nil`.
@discardableResult
public mutating func removeFirst(where predicate: (Element) throws -> Bool) rethrows -> Element? {
guard let index = try index(where: predicate) else { return nil }
return remove(at: index)
}
#if canImport(Foundation)
/// SwifterSwift: Remove a random value from the collection.
@discardableResult public mutating func removeRandomElement() -> Element? {
guard !isEmpty else { return nil }
return remove(at: index(startIndex, offsetBy: Int.random(in: 0..<count)))
}
#endif
}
| unlicense | 98bb8fc4e20c641739d7856725e555cf | 38.931373 | 181 | 0.603241 | 3.946705 | false | false | false | false |
epiphanyapps/ProductivitySuite | Example/ProductivitySuite/UserSectionController.swift | 1 | 1995 | //
// SectionController.swift
// ProductivitySuite_Example
//
// Created by Walter Vargas-Pena on 7/7/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import IGListKit
import ProductivitySuite
import Kingfisher
final class UserSectionController: ListSectionController {
private var user: User!
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 75)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(withNibName: UserCell.identifier, bundle: nil, for: self, at: index) as? UserCell else {
fatalError()
}
cell.nameLabel.text = user.first + " " + user.last
var imageResource: ImageResource?
if let urlString = user.imageURL, let url = URL(string: urlString) {
imageResource = ImageResource(downloadURL: url)
} else {
imageResource = nil
}
let resizingProcessor = ResizingImageProcessor(referenceSize: CGSize(width: 55, height: 55))
//FIX: - corner processor not working if not last in options array (same applies vice versa)
let cornerProcessor = RoundCornerImageProcessor(cornerRadius: 9)
cell.thumbnailImageView.kf.setImage(with: imageResource,
placeholder: #imageLiteral(resourceName: "placeholder"),
options:[.transition(ImageTransition.fade(0.3)), .processor(cornerProcessor), .processor(resizingProcessor)],
progressBlock: nil,
completionHandler: nil)
return cell
}
override func didUpdate(to object: Any) {
self.user = object as! User
}
override func didSelectItem(at index: Int) {
}
}
| mit | 9c5e8066afcf1ad07d53cce1c51eae4c | 34.607143 | 153 | 0.611334 | 5.165803 | false | false | false | false |
b3log/symphony-ios | HPApp/StoriesLoader.swift | 1 | 1846 | //
// StoriesLoader.swift
// HPApp
//
// Created by James Tang on 28/1/15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import Foundation
class StoriesLoader {
typealias StoriesLoaderCompletion = (stories:[Story]) ->()
enum StorySection : Printable {
case Default
case Recent
case Search(_ : String)
var description : String {
switch (self) {
case .Default: return ""
case .Recent: return "recent"
case .Search(_): return "search"
}
}
}
private (set) var hasMore : Bool = false
private var page : Int = 1
private var isLoading : Bool = false
private let section : StorySection
private let keyword : String?
init(_ section: StorySection = .Default) {
self.section = section
switch (section) {
case let .Search(keyword):
self.keyword = keyword
default:
self.keyword = nil
}
}
func load(page: Int = 1, completion: StoriesLoaderCompletion) {
if isLoading {
return
}
isLoading = true
DesignerNewsService.storiesForSection(self.section.description, page: page, keyword: self.keyword) { [weak self] stories in
if let strongSelf = self {
switch (strongSelf.section) {
case .Search(_):
strongSelf.hasMore = false
default:
strongSelf.hasMore = stories.count > 0
}
strongSelf.isLoading = false
completion(stories: stories)
}
}
}
func next(completion: (stories:[Story]) ->()) {
if isLoading {
return
}
++page
load(page: page, completion: completion)
}
}
| apache-2.0 | 78fdabe3c07cd67d1001257c94d18863 | 23.289474 | 131 | 0.533586 | 4.770026 | false | false | false | false |
hilen/TimedSilver | Sources/UIKit/UIImage+TSRoundedCorner.swift | 3 | 2587 | //
// UIImage+TSRoundedCorner.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 8/5/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
import UIKit
import QuartzCore
import CoreGraphics
import Accelerate
public extension UIImage {
/**
Creates a new image with rounded corners.
- parameter cornerRadius: The corner radius
- returns: a new image
*/
func ts_roundCorners(_ cornerRadius:CGFloat) -> UIImage? {
// If the image does not have an alpha layer, add one
let imageWithAlpha = ts_applyAlpha()
if imageWithAlpha == nil {
return nil
}
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let width = imageWithAlpha?.cgImage?.width
let height = imageWithAlpha?.cgImage?.height
let bits = imageWithAlpha?.cgImage?.bitsPerComponent
let colorSpace = imageWithAlpha?.cgImage?.colorSpace
let bitmapInfo = imageWithAlpha?.cgImage?.bitmapInfo
let context = CGContext(data: nil, width: width!, height: height!, bitsPerComponent: bits!, bytesPerRow: 0, space: colorSpace!, bitmapInfo: (bitmapInfo?.rawValue)!)
let rect = CGRect(x: 0, y: 0, width: CGFloat(width!)*scale, height: CGFloat(height!)*scale)
context?.beginPath()
if (cornerRadius == 0) {
context?.addRect(rect)
} else {
context?.saveGState()
context?.translateBy(x: rect.minX, y: rect.minY)
context?.scaleBy(x: cornerRadius, y: cornerRadius)
let fw = rect.size.width / cornerRadius
let fh = rect.size.height / cornerRadius
context?.move(to: CGPoint(x: fw, y: fh/2))
context?.addArc(tangent1End: CGPoint.init(x: fw, y: fh), tangent2End: CGPoint.init(x: fw/2, y: fh), radius: 1)
context?.addArc(tangent1End: CGPoint.init(x: 0, y: fh), tangent2End: CGPoint.init(x: 0, y: fh/2), radius: 1)
context?.addArc(tangent1End: CGPoint.init(x: 0, y: 0), tangent2End: CGPoint.init(x: fw/2, y: 0), radius: 1)
context?.addArc(tangent1End: CGPoint.init(x: fw, y: 0), tangent2End: CGPoint.init(x: fw, y: fh/2), radius: 1)
context?.restoreGState()
}
context?.closePath()
context?.clip()
context?.draw((imageWithAlpha?.cgImage)!, in: rect)
let image = UIImage(cgImage: (context?.makeImage()!)!, scale:scale, orientation: .up)
UIGraphicsEndImageContext()
return image
}
}
| mit | 1b5865198624c61e10a16459bab8b389 | 37.029412 | 172 | 0.62181 | 4.117834 | false | false | false | false |
BalestraPatrick/Tweetometer | Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Demos/Timelines Demo/ListTimelineViewController.swift | 2 | 1548 | //
// ListTimelineViewController.swift
// FabricSampleApp
//
// Created by Kang Chen on 6/18/15.
// Copyright (c) 2015 Twitter. All rights reserved.
//
import UIKit
class ListTimelineViewController: TWTRTimelineViewController, TWTRTimelineDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let client = TWTRAPIClient.withCurrentUser()
self.dataSource = TWTRListTimelineDataSource(listSlug: "twitter-kit", listOwnerScreenName: "stevenhepting", apiClient: client)
// Note that the delegate is being set *after* the dataSource.
// This is enabled by the change to the `setDataSource:` method
// to load more Tweets on the next runloop
self.timelineDelegate = self;
SVProgressHUD.setDefaultStyle(.dark)
self.showTweetActions = true
self.view.backgroundColor = .lightGray
}
func timelineDidBeginLoading(_ timeline: TWTRTimelineViewController) {
print("Began loading Tweets.")
SVProgressHUD.show(withStatus: "Loading")
}
func timeline(_ timeline: TWTRTimelineViewController, didFinishLoadingTweets tweets: [Any]?, error: Error?) {
if error != nil {
print("Encountered error \(error!)")
SVProgressHUD.showError(withStatus: "Error")
SVProgressHUD.dismiss(withDelay: 1)
} else {
print("Finished loading \(tweets!.count)")
SVProgressHUD.showSuccess(withStatus: "Finished");
SVProgressHUD.dismiss(withDelay: 1)
}
}
}
| mit | 3c7ac28dcb01ccf898d2d3d717cd8548 | 33.4 | 134 | 0.666021 | 4.852665 | false | false | false | false |
gmertk/SwiftSequence | SwiftSequence/Zip.swift | 1 | 2862 | public struct NilPaddedZipGenerator<G0: GeneratorType, G1: GeneratorType> : GeneratorType {
typealias E0 = G0.Element
typealias E1 = G1.Element
private var (g0, g1): (G0?, G1?)
public mutating func next() -> (E0?, E1?)? {
let e0: E0? = g0?.next() ?? {g0 = nil; return nil}()
let e1: E1? = g1?.next() ?? {g1 = nil; return nil}()
return (e0 != nil || e1 != nil) ? (e0, e1) : nil
}
}
public struct NilPaddedZip<S0: SequenceType, S1: SequenceType> : LazySequenceType {
private let (s0, s1): (S0, S1)
public func generate() -> NilPaddedZipGenerator<S0.Generator, S1.Generator> {
return NilPaddedZipGenerator(g0: s0.generate(), g1: s1.generate())
}
}
/// A sequence of pairs built out of two underlying sequences, where the elements of the
/// ith pair are optional ith elements of each underlying sequence. If one sequence is
/// shorter than the other, pairs will continue to be returned after it is exhausted, but
/// with its elements replaced by nil.
/// ```swift
/// zipWithPadding([1, 2, 3], [1, 2])
///
/// (1?, 1?), (2?, 2?), (3?, nil)
/// ```
public func zipWithPadding<S0: SequenceType, S1: SequenceType>(s0: S0, _ s1: S1)
-> NilPaddedZip<S0, S1> {
return NilPaddedZip(s0: s0, s1: s1)
}
public struct PaddedZipGenerator<G0: GeneratorType, G1: GeneratorType> : GeneratorType {
typealias E0 = G0.Element
typealias E1 = G1.Element
private var (g0, g1): (G0?, G1?)
private let (p0, p1): (E0, E1)
public mutating func next() -> (E0, E1)? {
let e0: E0? = g0?.next() ?? {g0 = nil; return nil}()
let e1: E1? = g1?.next() ?? {g1 = nil; return nil}()
return (e0 != nil || e1 != nil) ? (e0 ?? p0, e1 ?? p1) : nil
}
}
public struct PaddedZip<S0: SequenceType, S1: SequenceType> : LazySequenceType {
private let (s0, s1): (S0, S1)
private let (p0, p1): (S0.Generator.Element, S1.Generator.Element)
public func generate() -> PaddedZipGenerator<S0.Generator, S1.Generator> {
return PaddedZipGenerator(g0: s0.generate(), g1: s1.generate(), p0: p0, p1: p1)
}
}
/// A sequence of pairs built out of two underlying sequences, where the elements of the
/// ith pair are the ith elements of each underlying sequence. If one sequence is
/// shorter than the other, pairs will continue to be returned after it is exhausted, but
/// with its elements replaced by its respective pad.
/// - Parameter pad0: the element to pad `s0` with after it is exhausted
/// - Parameter pad1: the element to pad `s1` with after it is exhausted
/// ```swift
/// zipWithPadding([1, 2, 3], [1, 2], pad0: 100, pad1: 900)
///
/// (1, 1), (2, 2), (3, 900)
/// ```
public func zipWithPadding<
S0: SequenceType, S1: SequenceType
>(s0: S0, _ s1: S1, pad0: S0.Generator.Element, pad1: S1.Generator.Element)
-> PaddedZip<S0, S1> {
return PaddedZip(s0: s0, s1: s1, p0: pad0, p1: pad1)
}
| mit | 8d2232e5636990ab3061e31aaebd08c1 | 34.333333 | 91 | 0.646401 | 3.028571 | false | false | false | false |
shujincai/DouYu | DouYu/DouYu/Classes/Main/View/CollectionNormalCell.swift | 1 | 2375 | //
// CollectionNormalCell.swift
// DouYu
//
// Created by pingtong on 2017/6/20.
// Copyright © 2017年 PTDriver. All rights reserved.
//
import UIKit
class CollectionNormalCell: UICollectionViewCell {
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
//热门
var anchorHot: AnchorHotList? {
didSet {
guard let anchorHot = anchorHot else {
return
}
// 1.取出在线人数显示的文字
var onlineStr: String = ""
let online = Int(anchorHot.online!)
if online! >= 10000 {
onlineStr = "\(Int(online!/10000))万在线"
}else {
onlineStr = "\(String(describing: anchorHot.online!))在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
// 2.昵称的显示
nickNameLabel.text = anchorHot.nickname!
// 3.设置封面的图片
guard let iconUrl = URL(string: anchorHot.vertical_src!) else {
return
}
iconImageView.kf.setImage(with: iconUrl)
// 4.房间名称
roomNameLabel.text = anchorHot.room_name!
}
}
var anchor: AnchorRoomList? {
didSet {
guard let anchor = anchor else {
return
}
// 1.取出在线人数显示的文字
var onlineStr: String = ""
let online = Int(anchor.online!)
if online! >= 10000 {
onlineStr = "\(Int(online!/10000))万在线"
}else {
onlineStr = "\(String(describing: anchor.online!))在线"
}
onlineBtn.setTitle(onlineStr, for: .normal)
// 2.昵称的显示
nickNameLabel.text = anchor.nickname!
// 3.设置封面的图片
guard let iconUrl = URL(string: anchor.vertical_src!) else {
return
}
iconImageView.kf.setImage(with: iconUrl)
// 4.房间名称
roomNameLabel.text = anchor.room_name!
}
}
}
| mit | fa8b7899794a41f8159f59aff9a71be1 | 29.27027 | 75 | 0.521429 | 4.696017 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00646-llvm-raw-fd-ostream-write-impl.swift | 1 | 734 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol C {
deinit {
struct e == { x in a {
return [unowned self.e {
class A {
func compose<U : e where A? = B<C> {
override init(b.init() -> {
var f: B) {
}
}
}
let t: C {
typealias R = { c: String = {
}
}
}
}
}
protocol P {
}
}
static let i: NSObject {
}
}
e : U : H) -> {
}
typealias e = compose<T! {
}
let a {
}
}
typealias e : e,
| apache-2.0 | 35a3025e05a363859cdaa556e6a3e13b | 17.35 | 79 | 0.652589 | 2.98374 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.