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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jeanpimentel/PorExtenso | src/main.swift | 1 | 3101 | import Foundation
public class PorExtenso
{
let words = [
["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove"],
["dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
["", "", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"],
["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"]
]
let glue = " e "
let shortScale = [("", ""), ("mil", "mil"), ("milhão", "milhões"), ("bilhão", "bilhões"), ("trilhão", "trilhões"), ("quatrilhão", "quatrilhões"), ("quintilhão", "quintilhões"), ("sextilhão", "sextilhões"), ("septilhão", "septilhões")]
let longScale = [("", ""), ("mil", "mil"), ("milhão", "milhões"), ("mil milhões", "mil milhões"), ("bilião", "biliões"), ("mil bilião", "mil biliões"), ("trilião", "triliões"), ("mil trilião", "mil triliões"), ("quatrilião", "quatriliões")]
public init() {
}
public func convert(n: Int) -> String
{
let pieces = self.slice(n)
var results : Array<String> = [];
for (i, piece) in enumerate(pieces) {
let scale = (piece < 2) ? self.shortScale[i].0 : self.shortScale[i].1
let block = self.convertBlock(piece) + ((i == 0) ? "" : (" " + scale))
results.append(block)
}
return self.glue.join(results.reverse())
}
func convertBlock(n: Int) -> String
{
if n < 10 {
return self.lt10(n)
}
if n < 100 {
return self.gte10lt100(n)
}
if n < 1000 {
return self.gte100lt1000(n)
}
return ""
}
func slice(n: Int) -> Array<Int> {
let nStr = String(n)
let groupSize = 3
let nPieces = Int(ceil(Double(count(nStr)) / Double(groupSize)))
var pieces:Array<Int> = [];
for var i = 1; i <= nPieces; i++ {
let s = ((groupSize*i) <= count(nStr)) ? (groupSize*i) : count(nStr)
let e = (groupSize*i - groupSize)
let sub = nStr[advance(nStr.endIndex, -s) ..< advance(nStr.endIndex, -e)]
pieces.append(sub.toInt()!)
}
return pieces
}
func lt10(n: Int) -> String {
return self.words[0][n]
}
func gte10lt100(n: Int) -> String {
if n < 20 {
return self.words[1][n - 10]
}
let d = n / 10
let u = n % 10
var r = self.words[2][d]
if u > 0 {
r += self.glue + self.lt10(u)
}
return r
}
func gte100lt1000(n: Int) -> String {
let c = n / 100
var n2 = n - (c * 100)
if n2 == 0 {
if c == 1 {
return self.words[3][0]
} else {
return self.words[3][c]
}
}
var r = (n2 < 10) ? self.lt10(n2) : self.gte10lt100(n2)
return self.words[3][c] + self.glue + r
}
} | mit | 04e25f2467b05522afa212d01f41e738 | 25.721739 | 244 | 0.486003 | 3.062812 | false | false | false | false |
BranchMetrics/Branch-Example-Deep-Linking-Branchster-iOS | BranchMonsterFactoryAppClip/ViewController.swift | 1 | 6174 | //
// ViewController.swift
// BranchMonsterFactoryAppClip
//
// Created by Ernest Cho on 10/8/20.
// Copyright © 2020 Branch. All rights reserved.
//
import UIKit
import Branch
class ViewController: UIViewController {
let monster = Monster.shared
@IBOutlet weak var name: UILabel?
@IBOutlet weak var face: UIImageView?
@IBOutlet weak var body: UIImageView?
@IBOutlet weak var color0: UIButton?
@IBOutlet weak var color1: UIButton?
@IBOutlet weak var color2: UIButton?
@IBOutlet weak var color3: UIButton?
@IBOutlet weak var color4: UIButton?
@IBOutlet weak var color5: UIButton?
@IBOutlet weak var color6: UIButton?
@IBOutlet weak var color7: UIButton?
lazy var colors: [(button: UIButton, color: UIColor)] = {
var tmp = [
(self.color0!, self.monster.colors[0]),
(self.color1!, self.monster.colors[1]),
(self.color2!, self.monster.colors[2]),
(self.color3!, self.monster.colors[3]),
(self.color4!, self.monster.colors[4]),
(self.color5!, self.monster.colors[5]),
(self.color6!, self.monster.colors[6]),
(self.color7!, self.monster.colors[7])
]
return tmp;
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.redrawColors()
self.renderMonster()
self.monster.callback = {
self.renderMonster()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
func colorFor(button: UIButton)->(UIColor) {
for (b, c) in self.colors {
if (b.isEqual(button)) {
return c
}
}
// default to black, should not occur
return UIColor.black
}
func buttonFor(color: UIColor)->(UIButton?) {
for (b, c) in self.colors {
if (c.isEqual(color)) {
return b
}
}
// default to the first button, should not occur
return self.color0
}
func redrawColors() {
for (button, color) in self.colors {
self.updateColorButton(button: button, color: color, selected: false)
}
}
func updateColorButton(button: UIButton?, color:UIColor?, selected: Bool) {
button?.backgroundColor = color
if (selected) {
button?.layer.borderWidth = 2.0
} else {
button?.layer.borderWidth = 0.0
}
button?.layer.borderColor = UIColor.black.cgColor
button?.layer.cornerRadius = (button?.frame.size.width ?? 0)/2
}
@IBAction func selectColorButton(sender: UIButton) {
let color = self.colorFor(button: sender)
self.monster.color = color
self.renderMonster()
}
@IBAction func swipeUp(_ gestureRecogniser: UISwipeGestureRecognizer) {
if (gestureRecogniser.state == .ended) {
self.monster.prevFace()
self.renderMonster()
}
}
@IBAction func swipeDown(_ gestureRecogniser: UISwipeGestureRecognizer) {
if (gestureRecogniser.state == .ended) {
self.monster.nextFace()
self.renderMonster()
}
}
@IBAction func swipeRight(_ gestureRecogniser: UISwipeGestureRecognizer) {
if (gestureRecogniser.state == .ended) {
self.monster.nextBody()
self.renderMonster()
}
}
@IBAction func swipeLeft(_ gestureRecogniser: UISwipeGestureRecognizer) {
if (gestureRecogniser.state == .ended) {
self.monster.prevBody()
self.renderMonster()
}
}
func renderMonster() {
if let name = self.name {
UIView.transition(with: name, duration: 0.5, options: .transitionCrossDissolve, animations: {
name.text = self.monster.name
}, completion: nil)
}
if let face = self.face {
UIView.transition(with: face, duration: 0.5, options: .transitionCrossDissolve, animations: {
face.image = self.monster.face
}, completion: nil)
}
if let body = self.body {
UIView.transition(with: body, duration: 0.5, options: .transitionCrossDissolve, animations: {
body.image = self.monster.body
body.backgroundColor = self.monster.color
self.redrawColors()
// don't highlight the color button before data arrives
if (!self.monster.waitingForData) {
self.updateColorButton(button: self.buttonFor(color: self.monster.color), color: self.monster.color, selected: true)
}
}, completion: nil)
}
}
/*
[self.viewingMonster
showShareSheetWithShareText:@"Share Your Monster!"
completion:^(NSString * _Nullable activityType, BOOL completed) {
if (completed) {
// [[Branch getInstance] userCompletedAction:BNCAddToCartEvent];
[[Branch getInstance] sendCommerceEvent:commerceEvent
metadata:nil
withCompletion:^ (NSDictionary *response, NSError *error) {
if (error) { }
}];
}
}];
[UIMenuController sharedMenuController].menuVisible = NO;
[self.shareTextView resignFirstResponder];
*/
@IBAction func shareMonster() {
let lp = BranchLinkProperties()
lp.feature = "monster_sharing"
lp.channel = "appclip"
let buo = self.monster.shareWithBranch()
buo.showShareSheet(withShareText: "Share Your Monster!") { (activityType, success) in
if (success) {
print("should log an event here")
}
}
}
}
| mit | 5c44e1531249d96be16e65c4c4927986 | 30.176768 | 136 | 0.550786 | 4.770479 | false | false | false | false |
Sajjon/ViewComposer | Tests/UtilitiesTests.swift | 1 | 588 | //
// UtilitiesTests.swift
// ViewComposerTests
//
// Created by Alexander Cyon on 2017-06-18.
//
import XCTest
@testable import ViewComposer
class UtilitiesTests: XCTestCase {
func testRemoveNils() {
let optionalString: String? = nil
let strings: [String?] = ["Foo", optionalString, "Bar", optionalString, "Baz"]
XCTAssert(strings.count == 5)
XCTAssert(strings.removeNils().count == 3)
let integers: [Int?] = [2, nil, 4, nil, nil, 5]
XCTAssert(integers.count == 6)
XCTAssert(integers.removeNils().count == 3)
}
}
| mit | 3a3272f15205a1de1cc1b9de81c12b9c | 25.727273 | 86 | 0.62585 | 3.89404 | false | true | false | false |
AlesTsurko/DNMKit | DNM_iOS/DNM_iOS/ComponentSelector.swift | 1 | 6399 | //
// ComponentSelector.swift
// denm_view
//
// Created by James Bean on 10/3/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
// DEPRECATE
/*
public class ComponentSelector: UIView {
// need another layer of isolation between text and id of button
var target: AnyObject?
var componentTypesByID: [String : [String]] = [:]
var componentTypesShownByID: [String : [String]] = [:]
var componentTypesHiddenByID: [String : [String]] = [:]
var buttonSwitchPanelByID: [String : ButtonSwitchPanelWithMasterButtonSwitch] = [:]
var buttonSwitchPanels: [ButtonSwitchPanelWithMasterButtonSwitch] = []
public init(
left: CGFloat = 0,
top: CGFloat = 0,
componentTypesByID: [String : [String]],
target: AnyObject? = nil
)
{
self.componentTypesByID = componentTypesByID
self.target = target
super.init(frame: CGRectMake(left, top, 0, 0))
build()
}
public override init(frame: CGRect) { super.init(frame: frame) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public func build() {
var buttonSwitchPanel_top: CGFloat = 0
for (id, componentTypes) in componentTypesByID {
let componentTypes = componentTypes.filter {$0 != "performer"}
let buttonSwitchPanel = ButtonSwitchPanelWithMasterButtonSwitch(
left: 0,
top: buttonSwitchPanel_top,
id: id,
target: self,
titles: componentTypes
)
addSubview(buttonSwitchPanel)
buttonSwitchPanels.append(buttonSwitchPanel)
buttonSwitchPanelByID[id] = buttonSwitchPanel
buttonSwitchPanel_top += buttonSwitchPanel.frame.height
}
// set initial states
for (id, componentTypes) in componentTypesByID {
componentTypesShownByID[id] = componentTypes
}
setFrame()
}
public func stateHasChangedFromSender(sender: ButtonSwitchPanelWithMasterButtonSwitch) {
// HIDDEN NOT NECESSARY: done within SystemLayer
for (text, isOn) in sender.statesByText {
// filter out master button
if text == sender.id {
if isOn {
if var componentTypesShownWithID = componentTypesShownByID["performer"] {
if !componentTypesShownWithID.contains("performer") {
componentTypesShownWithID.append("performer")
componentTypesShownByID[sender.id] = componentTypesShownWithID
}
}
else {
componentTypesShownByID[sender.id] = ["performer"]
}
}
else {
if var componentTypesShownWithID = componentTypesShownByID["performer"] {
if componentTypesShownWithID.contains("performer") {
componentTypesShownWithID.remove("performer")
componentTypesShownByID[sender.id] = componentTypesShownWithID
}
}
else {
}
}
}
else {
if isOn {
// add if necessary to components SHOWN by ID
if var componentTypesShownWithID = componentTypesShownByID[sender.id] {
if !componentTypesShownWithID.contains(text) {
componentTypesShownWithID.append(text)
componentTypesShownByID[sender.id] = componentTypesShownWithID
}
}
else {
componentTypesShownByID[sender.id] = [text]
}
// remove if necssary to components HIDDEN by ID
if var componentTypesHiddenWithID = componentTypesHiddenByID[sender.id] {
if componentTypesHiddenWithID.contains(text) {
componentTypesHiddenWithID.remove(text)
componentTypesHiddenByID[sender.id] = componentTypesHiddenWithID
}
}
}
else {
// remove if necessary from components SHOWN by ID
if var componentTypesShownWithID = componentTypesShownByID[sender.id] {
if componentTypesShownWithID.contains(text) {
componentTypesShownWithID.remove(text)
componentTypesShownByID[sender.id] = componentTypesShownWithID
}
}
// add if necessary to components HIDDEN by ID
if var componentTypesHiddenWithID = componentTypesHiddenByID[sender.id] {
if !componentTypesHiddenWithID.contains(text) {
componentTypesHiddenWithID.append(text)
componentTypesHiddenByID[sender.id] = componentTypesHiddenWithID
}
}
else { componentTypesHiddenByID[sender.id] = [text] }
}
}
}
//(target as? SystemUIView)?.stateHasChangedFromComponentSelector(self)
}
// WHAT IS UP WITH THIS, SHOULD WORK?
public func layout_flowLeft() {
}
// WHAT IS UP WITH THIS, SHOULD WORK?
public func layout_flowRight() {
for panel in buttonSwitchPanels {
panel.layout_flowRight()
//panel.layer.position.x = frame.width - 0.5 * panel.frame.width
}
}
public func setFrame() {
var maxY: CGFloat = 0
var maxX: CGFloat = 0
for buttonSwitchPanel in buttonSwitchPanels {
if buttonSwitchPanel.frame.maxX > maxX {
maxX = buttonSwitchPanel.frame.maxX
}
if buttonSwitchPanel.frame.maxY > maxY {
maxY = buttonSwitchPanel.frame.maxY
}
}
frame = CGRectMake(frame.minX, frame.minY, maxX, maxY)
}
}
*/ | gpl-2.0 | fa4aa1f78911d620cfdc0a306d688702 | 37.548193 | 93 | 0.535011 | 5.362951 | false | false | false | false |
volodg/iAsync.social | Pods/iAsync.utils/iAsync.utils/Array/HashableArray.swift | 1 | 1046 | //
// HashableArray.swift
// JUtils
//
// Created by Vladimir Gorbenko on 02.10.14.
// Copyright (c) 2014 EmbeddedSources. All rights reserved.
//
import Foundation
public struct HashableArray<T: Equatable> : Hashable, SequenceType, CustomStringConvertible {
internal var array: Array<T>
typealias Generator = Array<T>.Generator
public func generate() -> Generator {
return array.generate()
}
public mutating func removeAll() {
array.removeAll()
}
public mutating func append(el: T) {
array.append(el)
}
public var hashValue: Int {
return array.count
}
public init(array: [T]) {
self.array = array
}
public init() {
self.init(array: [T]())
}
public var description: String {
return "iAsync.utils.HashableArray: \(array)"
}
}
public func ==<T: Equatable>(lhs: HashableArray<T>, rhs: HashableArray<T>) -> Bool {
return lhs.array == rhs.array
}
| mit | cf4533f73083dfd3e60896f691304bad | 19.115385 | 93 | 0.58413 | 4.234818 | false | false | false | false |
karwa/swift-corelibs-foundation | Foundation/NSProcessInfo.swift | 3 | 5038 | // 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
//
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
public struct NSOperatingSystemVersion {
public var majorVersion: Int
public var minorVersion: Int
public var patchVersion: Int
public init() {
self.init(majorVersion: 0, minorVersion: 0, patchVersion: 0)
}
public init(majorVersion: Int, minorVersion: Int, patchVersion: Int) {
self.majorVersion = majorVersion
self.minorVersion = minorVersion
self.patchVersion = patchVersion
}
}
public class NSProcessInfo : NSObject {
internal static let _processInfo = NSProcessInfo()
public class func processInfo() -> NSProcessInfo {
return _processInfo
}
internal override init() {
}
internal static var _environment: [String : String] = {
let dict = __CFGetEnvironment()._nsObject
var env = [String : String]()
dict.enumerateKeysAndObjectsUsingBlock { key, value, stop in
env[(key as! NSString)._swiftObject] = (value as! NSString)._swiftObject
}
return env
}()
public var environment: [String : String] {
return NSProcessInfo._environment
}
public var arguments: [String] {
return Process.arguments // seems reasonable to flip the script here...
}
public var hostName: String {
if let name = NSHost.currentHost().name {
return name
} else {
return "localhost"
}
}
public var processName: String = _CFProcessNameString()._swiftObject
public var processIdentifier: Int32 {
return __CFGetPid()
}
public var globallyUniqueString: String {
let uuid = CFUUIDCreate(kCFAllocatorSystemDefault)
return CFUUIDCreateString(kCFAllocatorSystemDefault, uuid)._swiftObject
}
public var operatingSystemVersionString: String {
return CFCopySystemVersionString()?._swiftObject ?? "Unknown"
}
public var operatingSystemVersion: NSOperatingSystemVersion {
// The following fallback values match Darwin Foundation
let fallbackMajor = -1
let fallbackMinor = 0
let fallbackPatch = 0
guard let systemVersionDictionary = _CFCopySystemVersionDictionary() else {
return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch)
}
let productVersionKey = unsafeBitCast(_kCFSystemVersionProductVersionKey, to: UnsafePointer<Void>.self)
guard let productVersion = unsafeBitCast(CFDictionaryGetValue(systemVersionDictionary, productVersionKey), to: NSString!.self) else {
return NSOperatingSystemVersion(majorVersion: fallbackMajor, minorVersion: fallbackMinor, patchVersion: fallbackPatch)
}
let versionComponents = productVersion._swiftObject.characters.split(separator: ".").flatMap(String.init).flatMap({ Int($0) })
let majorVersion = versionComponents.dropFirst(0).first ?? fallbackMajor
let minorVersion = versionComponents.dropFirst(1).first ?? fallbackMinor
let patchVersion = versionComponents.dropFirst(2).first ?? fallbackPatch
return NSOperatingSystemVersion(majorVersion: majorVersion, minorVersion: minorVersion, patchVersion: patchVersion)
}
internal let _processorCount = __CFProcessorCount()
public var processorCount: Int {
return Int(_processorCount)
}
internal let _activeProcessorCount = __CFActiveProcessorCount()
public var activeProcessorCount: Int {
return Int(_activeProcessorCount)
}
internal let _physicalMemory = __CFMemorySize()
public var physicalMemory: UInt64 {
return _physicalMemory
}
public func isOperatingSystemAtLeastVersion(_ version: NSOperatingSystemVersion) -> Bool {
let ourVersion = operatingSystemVersion
if ourVersion.majorVersion < version.majorVersion {
return false
}
if ourVersion.majorVersion > version.majorVersion {
return true
}
if ourVersion.minorVersion < version.minorVersion {
return false
}
if ourVersion.minorVersion > version.minorVersion {
return true
}
if ourVersion.patchVersion < version.patchVersion {
return false
}
if ourVersion.patchVersion > version.patchVersion {
return true
}
return true
}
public var systemUptime: NSTimeInterval {
return CFGetSystemUptime()
}
}
| apache-2.0 | 4a704ddff60fd49b48b93ffcdc176517 | 32.364238 | 141 | 0.664946 | 5.308746 | false | false | false | false |
suzuki-0000/CountdownLabel | CountdownLabel/LTMorphingLabel/LTMorphingLabel.swift | 1 | 16831 | //
// LTMorphingLabel.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
import UIKit
import QuartzCore
private func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
private func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l >= r
default:
return !(lhs < rhs)
}
}
enum LTMorphingPhases: Int {
case start, appear, disappear, draw, progress, skipFrames
}
typealias LTMorphingStartClosure =
() -> Void
typealias LTMorphingEffectClosure =
(Character, _ index: Int, _ progress: Float) -> LTCharacterLimbo
typealias LTMorphingDrawingClosure =
(LTCharacterLimbo) -> Bool
typealias LTMorphingManipulateProgressClosure =
(_ index: Int, _ progress: Float, _ isNewChar: Bool) -> Float
typealias LTMorphingSkipFramesClosure =
() -> Int
@objc public protocol LTMorphingLabelDelegate {
@objc optional func morphingDidStart(_ label: LTMorphingLabel)
@objc optional func morphingDidComplete(_ label: LTMorphingLabel)
@objc optional func morphingOnProgress(_ label: LTMorphingLabel, progress: Float)
}
// MARK: - LTMorphingLabel
@IBDesignable open class LTMorphingLabel: UILabel {
@IBInspectable open var morphingProgress: Float = 0.0
@IBInspectable open var morphingDuration: Float = 0.6
@IBInspectable open var morphingCharacterDelay: Float = 0.026
@IBInspectable open var morphingEnabled: Bool = true
@IBOutlet open weak var delegate: LTMorphingLabelDelegate?
open var morphingEffect: LTMorphingEffect = .scale
var startClosures = [String: LTMorphingStartClosure]()
var effectClosures = [String: LTMorphingEffectClosure]()
var drawingClosures = [String: LTMorphingDrawingClosure]()
var progressClosures = [String: LTMorphingManipulateProgressClosure]()
var skipFramesClosures = [String: LTMorphingSkipFramesClosure]()
var diffResults: LTStringDiffResult?
var previousText = ""
var currentFrame = 0
var totalFrames = 0
var totalDelayFrames = 0
var totalWidth: Float = 0.0
var previousRects = [CGRect]()
var newRects = [CGRect]()
var charHeight: CGFloat = 0.0
var skipFramesCount: Int = 0
#if TARGET_INTERFACE_BUILDER
let presentingInIB = true
#else
let presentingInIB = false
#endif
override open var font: UIFont! {
get {
return super.font ?? UIFont.systemFont(ofSize: 15)
}
set {
super.font = newValue
setNeedsLayout()
}
}
override open var text: String! {
get {
return super.text ?? ""
}
set {
guard text != newValue else { return }
previousText = text ?? ""
diffResults = previousText.diffWith(newValue)
super.text = newValue ?? ""
morphingProgress = 0.0
currentFrame = 0
totalFrames = 0
setNeedsLayout()
if !morphingEnabled {
return
}
if presentingInIB {
morphingDuration = 0.01
morphingProgress = 0.5
} else if previousText != text {
displayLink.isPaused = false
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.start)"
if let closure = startClosures[closureKey] {
return closure()
}
delegate?.morphingDidStart?(self)
}
}
}
open override func setNeedsLayout() {
super.setNeedsLayout()
previousRects = rectsOfEachCharacter(previousText, withFont: font)
newRects = rectsOfEachCharacter(text ?? "", withFont: font)
}
override open var bounds: CGRect {
get {
return super.bounds
}
set {
super.bounds = newValue
setNeedsLayout()
}
}
override open var frame: CGRect {
get {
return super.frame
}
set {
super.frame = newValue
setNeedsLayout()
}
}
fileprivate lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(
target: self,
selector: #selector(LTMorphingLabel.displayFrameTick)
)
displayLink.add(to: .current, forMode: RunLoop.Mode.common)
return displayLink
}()
deinit {
displayLink.remove(from: .current, forMode: RunLoop.Mode.common)
displayLink.invalidate()
}
lazy var emitterView: LTEmitterView = {
let emitterView = LTEmitterView(frame: self.bounds)
self.addSubview(emitterView)
return emitterView
}()
}
// MARK: - Animation extension
extension LTMorphingLabel {
@objc func displayFrameTick() {
if displayLink.duration > 0.0 && totalFrames == 0 {
var frameRate = Float(0)
if #available(iOS 10.0, tvOS 10.0, *) {
var frameInterval = 1
if displayLink.preferredFramesPerSecond == 60 {
frameInterval = 1
} else if displayLink.preferredFramesPerSecond == 30 {
frameInterval = 2
} else {
frameInterval = 1
}
frameRate = Float(displayLink.duration) / Float(frameInterval)
} else {
frameRate = Float(displayLink.duration) / Float(displayLink.frameInterval)
}
totalFrames = Int(ceil(morphingDuration / frameRate))
let totalDelay = Float((text!).count) * morphingCharacterDelay
totalDelayFrames = Int(ceil(totalDelay / frameRate))
}
currentFrame += 1
if previousText != text && currentFrame < totalFrames + totalDelayFrames + 5 {
morphingProgress += 1.0 / Float(totalFrames)
let closureKey = "\(morphingEffect.description)\(LTMorphingPhases.skipFrames)"
if let closure = skipFramesClosures[closureKey] {
skipFramesCount += 1
if skipFramesCount > closure() {
skipFramesCount = 0
setNeedsDisplay()
}
} else {
setNeedsDisplay()
}
if let onProgress = delegate?.morphingOnProgress {
onProgress(self, morphingProgress)
}
} else {
displayLink.isPaused = true
delegate?.morphingDidComplete?(self)
}
}
// Could be enhanced by kerning text:
// http://stackoverflow.com/questions/21443625/core-text-calculate-letter-frame-in-ios
func rectsOfEachCharacter(_ textToDraw: String, withFont font: UIFont) -> [CGRect] {
var charRects = [CGRect]()
var leftOffset: CGFloat = 0.0
charHeight = "Leg".size(withAttributes: [.font: font]).height
let topOffset = (bounds.size.height - charHeight) / 2.0
for char in textToDraw {
let charSize = String(char).size(withAttributes: [.font: font])
charRects.append(
CGRect(
origin: CGPoint(
x: leftOffset,
y: topOffset
),
size: charSize
)
)
leftOffset += charSize.width
}
totalWidth = Float(leftOffset)
var stringLeftOffSet: CGFloat = 0.0
switch textAlignment {
case .center:
stringLeftOffSet = CGFloat((Float(bounds.size.width) - totalWidth) / 2.0)
case .right:
stringLeftOffSet = CGFloat(Float(bounds.size.width) - totalWidth)
default:
()
}
var offsetedCharRects = [CGRect]()
for r in charRects {
offsetedCharRects.append(r.offsetBy(dx: stringLeftOffSet, dy: 0.0))
}
return offsetedCharRects
}
func limboOfOriginalCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
var currentRect = previousRects[index]
let oriX = Float(currentRect.origin.x)
var newX = Float(currentRect.origin.x)
let diffResult = diffResults!.0[index]
var currentFontSize: CGFloat = font.pointSize
var currentAlpha: CGFloat = 1.0
switch diffResult {
// Move the character that exists in the new text to current position
case .same:
newX = Float(newRects[index].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .move(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
case .moveAndAdd(let offset):
newX = Float(newRects[index + offset].origin.x)
currentRect.origin.x = CGFloat(
LTEasing.easeOutQuint(progress, oriX, newX - oriX)
)
default:
// Otherwise, remove it
// Override morphing effect with closure in extenstions
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.disappear)"
] {
return closure(char, index, progress)
} else {
// And scale it by default
let fontEase = CGFloat(
LTEasing.easeOutQuint(
progress, 0, Float(font.pointSize)
)
)
// For emojis
currentFontSize = max(0.0001, font.pointSize - fontEase)
currentAlpha = CGFloat(1.0 - progress)
currentRect = previousRects[index].offsetBy(
dx: 0,
dy: CGFloat(font.pointSize - currentFontSize)
)
}
}
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: currentFontSize,
drawingProgress: 0.0
)
}
func limboOfNewCharacter(
_ char: Character,
index: Int,
progress: Float) -> LTCharacterLimbo {
let currentRect = newRects[index]
var currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0, Float(font.pointSize))
)
if let closure = effectClosures[
"\(morphingEffect.description)\(LTMorphingPhases.appear)"
] {
return closure(char, index, progress)
} else {
currentFontSize = CGFloat(
LTEasing.easeOutQuint(progress, 0.0, Float(font.pointSize))
)
// For emojis
currentFontSize = max(0.0001, currentFontSize)
let yOffset = CGFloat(font.pointSize - currentFontSize)
return LTCharacterLimbo(
char: char,
rect: currentRect.offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(morphingProgress),
size: currentFontSize,
drawingProgress: 0.0
)
}
}
func limboOfCharacters() -> [LTCharacterLimbo] {
var limbo = [LTCharacterLimbo]()
// Iterate original characters
for (i, character) in previousText.enumerated() {
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, false)
} else {
progress = min(1.0, max(0.0, morphingProgress + morphingCharacterDelay * Float(i)))
}
let limboOfCharacter = limboOfOriginalCharacter(character, index: i, progress: progress)
limbo.append(limboOfCharacter)
}
// Add new characters
for (i, character) in (text!).enumerated() {
if i >= diffResults?.0.count {
break
}
var progress: Float = 0.0
if let closure = progressClosures[
"\(morphingEffect.description)\(LTMorphingPhases.progress)"
] {
progress = closure(i, morphingProgress, true)
} else {
progress = min(1.0, max(0.0, morphingProgress - morphingCharacterDelay * Float(i)))
}
// Don't draw character that already exists
if diffResults?.skipDrawingResults[i] == true {
continue
}
if let diffResult = diffResults?.0[i] {
switch diffResult {
case .moveAndAdd, .replace, .add, .delete:
let limboOfCharacter = limboOfNewCharacter(
character,
index: i,
progress: progress
)
limbo.append(limboOfCharacter)
default:
()
}
}
}
return limbo
}
}
// MARK: - Drawing extension
extension LTMorphingLabel {
override open func didMoveToSuperview() {
if let s = text {
text = s
}
// Load all morphing effects
for effectName: String in LTMorphingEffect.allValues {
let effectFunc = Selector("\(effectName)Load")
if responds(to: effectFunc) {
perform(effectFunc)
}
}
}
override open func drawText(in rect: CGRect) {
if !morphingEnabled || limboOfCharacters().count == 0 {
super.drawText(in: rect)
return
}
for charLimbo in limboOfCharacters() {
let charRect = charLimbo.rect
let willAvoidDefaultDrawing: Bool = {
if let closure = drawingClosures[
"\(morphingEffect.description)\(LTMorphingPhases.draw)"
] {
return closure($0)
}
return false
}(charLimbo)
if !willAvoidDefaultDrawing {
var attrs: [NSAttributedString.Key: Any] = [
.foregroundColor: textColor.withAlphaComponent(charLimbo.alpha)
]
if let font = UIFont(name: font.fontName, size: charLimbo.size) {
attrs[.font] = font
}
let s = String(charLimbo.char)
s.draw(in: charRect, withAttributes: attrs)
}
}
}
}
| mit | 4ecabae6e16d09b76024776851fe2cd3 | 32.18146 | 100 | 0.538727 | 5.176308 | false | false | false | false |
jonesgithub/PageMenu | Demos/Demo 5/PageMenuDemoSegmentedControl/PageMenuDemoSegmentedControl/RecentsTableViewController.swift | 28 | 3874 | //
// RecentsTableViewController.swift
// PageMenuDemoTabbar
//
// Created by Niklas Fahl on 1/9/15.
// Copyright (c) 2015 Niklas Fahl. All rights reserved.
//
import UIKit
class RecentsTableViewController: UITableViewController {
var parentNavigationController : UINavigationController?
var namesArray : [String] = ["Kim White", "Kim White", "David Fletcher", "Anna Hunt", "Timothy Jones", "Timothy Jones", "Timothy Jones", "Lauren Richard", "Lauren Richard", "Juan Rodriguez"]
var photoNameArray : [String] = ["woman1.jpg", "woman1.jpg", "man8.jpg", "woman3.jpg", "man3.jpg", "man3.jpg", "man3.jpg", "woman5.jpg", "woman5.jpg", "man5.jpg"]
var activityTypeArray : NSArray = [0, 1, 1, 0, 2, 1, 2, 0, 0, 2]
var dateArray : NSArray = ["4:22 PM", "Wednesday", "Tuesday", "Sunday", "01/02/15", "12/31/14", "12/28/14", "12/24/14", "12/17/14", "12/14/14"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerNib(UINib(nibName: "RecentsTableViewCell", bundle: nil), forCellReuseIdentifier: "RecentsTableViewCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
println("\(self.title) page: viewWillAppear")
}
override func viewDidAppear(animated: Bool) {
self.tableView.showsVerticalScrollIndicator = false
super.viewDidAppear(animated)
self.tableView.showsVerticalScrollIndicator = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 10
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : RecentsTableViewCell = tableView.dequeueReusableCellWithIdentifier("RecentsTableViewCell") as! RecentsTableViewCell
// Configure the cell...
cell.nameLabel.text = namesArray[indexPath.row]
cell.photoImageView.image = UIImage(named: photoNameArray[indexPath.row])
cell.dateLabel.text = dateArray[indexPath.row] as! NSString as String
cell.nameLabel.textColor = UIColor(red: 85.0/255.0, green: 85.0/255.0, blue: 85.0/255.0, alpha: 1.0)
if activityTypeArray[indexPath.row] as! Int == 0 {
cell.activityImageView.image = UIImage(named: "phone_send")
} else if activityTypeArray[indexPath.row] as! Int == 1 {
cell.activityImageView.image = UIImage(named: "phone_receive")
} else {
cell.activityImageView.image = UIImage(named: "phone_down")
cell.nameLabel.textColor = UIColor.redColor()
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 94.0
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.001
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var newVC : UIViewController = UIViewController()
newVC.view.backgroundColor = UIColor.whiteColor()
newVC.title = "Favorites"
parentNavigationController!.pushViewController(newVC, animated: true)
}
}
| bsd-3-clause | b38561f0adfa9a97ff19222a2990c16c | 40.212766 | 194 | 0.660816 | 4.584615 | false | false | false | false |
huangxinping/XPKit-swift | Source/Extensions/UIKit/UIImage+XPKit.swift | 1 | 33096 | //
// UIImage+XPKit.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
import CoreImage
import CoreGraphics
import Accelerate
import AssetsLibrary
/// Due to a bug in Xcode (typecasting Fails only inside the extension block) I created this alias of CIImage
typealias XPCIImage = CIImage
/// This extesion adds some useful functions to UIImage
public extension UIImage {
// MARK: - Variables -
public var width: CGFloat {
get {
return self.size.width
}
}
public var height: CGFloat {
get {
return self.size.height
}
}
// MARK: - Instance functions -
/**
Compress the image to data(<=20kb stop)
- returns: compress data
*/
public func compress() -> NSData? {
return self.compressWithThreshold(20.0)
}
/**
Compress the image to data(<=thresholdkb stop)
- parameter threshold: threshold kb
- returns: compress data
*/
public func compressWithThreshold(threshold: CGFloat) -> NSData? {
var imageData: NSData?
var compression: Double = 1.0
while compression >= 0.0 {
compression -= 0.1
imageData = UIImageJPEGRepresentation(self, CGFloat(compression))
let imageLength = imageData?.length
if (CGFloat(imageLength!) / 1024.0 as CGFloat) <= threshold {
break
}
}
return imageData
}
/**
Transform the image to base64 string
- returns: Return base64 string
*/
public func base64Encoding() -> NSString? {
let data = UIImagePNGRepresentation(self)
return data?.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
}
/**
Apply the given Blend Mode
- parameter blendMode: The choosed Blend Mode
- returns: Returns the image
*/
public func blendMode(blendMode: CGBlendMode) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.size.width, self.size.height), false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0.0, 0.0, self.size.width, self.size.height), blendMode: blendMode, alpha: 1)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/**
Apply the Blend Mode Overlay
- returns: Returns the image
*/
public func blendOverlay() -> UIImage {
return self.blendMode(.Overlay)
}
/**
Create an image from a given rect of self
- parameter rect: Rect to take the image
- returns: Returns the image from a given rect
*/
public func imageAtRect(rect: CGRect) -> UIImage {
let imageRef: CGImageRef = CGImageCreateWithImageInRect(self.CGImage, rect)!
let subImage: UIImage = UIImage(CGImage: imageRef)
return subImage
}
/**
Scale the image to the minimum given size
- parameter targetSize: The site to scale to
- returns: Returns the scaled image
*/
public func imageByScalingProportionallyToMinimumSize(targetSize: CGSize) -> UIImage? {
let sourceImage: UIImage = self
var newImage: UIImage? = nil
let newTargetSize: CGSize = targetSize
let imageSize: CGSize = sourceImage.size
let width: CGFloat = imageSize.width
let height: CGFloat = imageSize.height
let targetWidth: CGFloat = newTargetSize.width
let targetHeight: CGFloat = newTargetSize.height
var scaleFactor: CGFloat = 0.0
var scaledWidth: CGFloat = targetWidth
var scaledHeight: CGFloat = targetHeight
var thumbnailPoint: CGPoint = CGPointMake(0.0, 0.0)
if CGSizeEqualToSize(imageSize, newTargetSize) == false {
let widthFactor: CGFloat = targetWidth / width
let heightFactor: CGFloat = targetHeight / height
if widthFactor > heightFactor {
scaleFactor = widthFactor
} else {
scaleFactor = heightFactor
}
scaledWidth = width * scaleFactor
scaledHeight = height * scaleFactor
if widthFactor > heightFactor {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5
} else if widthFactor < heightFactor {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5
}
}
UIGraphicsBeginImageContextWithOptions(newTargetSize, false, UIScreen.mainScreen().scale)
var thumbnailRect: CGRect = CGRectZero
thumbnailRect.origin = thumbnailPoint
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
sourceImage.drawInRect(thumbnailRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if newImage == nil {
print("Could not scale image")
}
return newImage
}
/**
Scale the image to the maxinum given size
- parameter targetSize: The site to scale to
- returns: Returns the scaled image
*/
public func imageByScalingProportionallyToMaximumSize(targetSize: CGSize) -> UIImage {
let newTargetSize: CGSize = targetSize
if (self.size.width > newTargetSize.width || newTargetSize.width == newTargetSize.height) && self.size.width > self.size.height {
let factor: CGFloat = (newTargetSize.width * 100) / self.size.width
let newWidth: CGFloat = (self.size.width * factor) / 100
let newHeight: CGFloat = (self.size.height * factor) / 100
let newSize: CGSize = CGSizeMake(newWidth, newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
} else if (self.size.height > newTargetSize.height || newTargetSize.width == newTargetSize.height) && self.size.width < self.size.height {
let factor: CGFloat = (newTargetSize.width * 100) / self.size.height
let newWidth: CGFloat = (self.size.width * factor) / 100
let newHeight: CGFloat = (self.size.height * factor) / 100
let newSize: CGSize = CGSizeMake(newWidth, newHeight)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
} else if (self.size.height > newTargetSize.height || self.size.width > newTargetSize.width) && self.size.width == self.size.height {
let factor: CGFloat = (newTargetSize.height * 100) / self.size.height
let newDimension: CGFloat = (self.size.height * factor) / 100
let newSize: CGSize = CGSizeMake(newDimension, newDimension)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
} else {
let newSize: CGSize = CGSizeMake(self.size.width, self.size.height)
UIGraphicsBeginImageContextWithOptions(newSize, false, UIScreen.mainScreen().scale)
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
}
let returnImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return returnImage
}
/**
Scale the image proportionally to the given size
- parameter targetSize: The site to scale to
- returns: Returns the scaled image
*/
public func imageByScalingProportionallyToSize(targetSize: CGSize) -> UIImage? {
let sourceImage: UIImage = self
var newImage: UIImage? = nil
let newTargetSize: CGSize = targetSize
let imageSize: CGSize = sourceImage.size
let width: CGFloat = imageSize.width
let height: CGFloat = imageSize.height
let targetWidth: CGFloat = newTargetSize.width
let targetHeight: CGFloat = newTargetSize.height
var scaleFactor: CGFloat = 0.0
var scaledWidth: CGFloat = targetWidth
var scaledHeight: CGFloat = targetHeight
var thumbnailPoint: CGPoint = CGPointMake(0.0, 0.0)
if CGSizeEqualToSize(imageSize, newTargetSize) == false {
let widthFactor: CGFloat = targetWidth / width
let heightFactor: CGFloat = targetHeight / height
if widthFactor < heightFactor {
scaleFactor = widthFactor
} else {
scaleFactor = heightFactor
}
scaledWidth = width * scaleFactor
scaledHeight = height * scaleFactor
if widthFactor < heightFactor {
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5
} else if widthFactor > heightFactor {
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5
}
}
UIGraphicsBeginImageContextWithOptions(newTargetSize, false, UIScreen.mainScreen().scale)
var thumbnailRect: CGRect = CGRectZero
thumbnailRect.origin = thumbnailPoint
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
sourceImage.drawInRect(thumbnailRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if newImage == nil {
print("Could not scale image")
}
return newImage
}
/**
Scele the iamge to the given size
- parameter targetSize: The site to scale to
- returns: Returns the scaled image
*/
public func imageByScalingToSize(targetSize: CGSize) -> UIImage? {
let sourceImage: UIImage = self
var newImage: UIImage? = nil
let targetWidth: CGFloat = targetSize.width
let targetHeight: CGFloat = targetSize.height
let scaledWidth: CGFloat = targetWidth
let scaledHeight: CGFloat = targetHeight
let thumbnailPoint: CGPoint = CGPointMake(0.0, 0.0)
UIGraphicsBeginImageContextWithOptions(targetSize, false, UIScreen.mainScreen().scale)
var thumbnailRect: CGRect = CGRectZero
thumbnailRect.origin = thumbnailPoint
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
sourceImage.drawInRect(thumbnailRect)
newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if newImage == nil {
print("Could not scale image")
}
return newImage
}
/**
Rotate the image to the given radians
- parameter radians: Radians to rotate to
- returns: Returns the rotated image
*/
public func imageRotatedByRadians(radians: CGFloat) -> UIImage {
return self.imageRotatedByDegrees(CGFloat(RadiansToDegrees(Float(radians))))
}
/**
Rotate the image to the given degrees
- parameter degrees: Degrees to rotate to
- returns: Returns the rotated image
*/
public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
let rotatedViewBox: UIView = UIView(frame: CGRectMake(0, 0, self.size.width, self.size.height))
let t: CGAffineTransform = CGAffineTransformMakeRotation(CGFloat(DegreesToRadians(Float(degrees))))
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
UIGraphicsBeginImageContextWithOptions(rotatedSize, false, UIScreen.mainScreen().scale)
let bitmap: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2)
CGContextRotateCTM(bitmap, CGFloat(DegreesToRadians(Float(degrees))))
CGContextScaleCTM(bitmap, 1.0, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), self.CGImage)
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/**
Flip the image horizontally
- returns: Returns the flipped image
*/
public func flipImageHorizontally() -> UIImage {
return UIImage(CGImage: self.CGImage!, scale: self.scale, orientation: .UpMirrored)
}
/**
Flip the image vertically
- returns: Returns the flipped image
*/
public func flipImageVertically() -> UIImage {
return UIImage(CGImage: self.CGImage!, scale: self.scale, orientation: .LeftMirrored)
}
/**
Check if the image has alpha
- returns: Returns true if has alpha, false if not
*/
public func hasAlpha() -> Bool {
let alpha: CGImageAlphaInfo = CGImageGetAlphaInfo(self.CGImage)
return (alpha == .First || alpha == .Last || alpha == .PremultipliedFirst || alpha == .PremultipliedLast)
}
/**
Remove the alpha of the image
- returns: Returns the image without alpha
*/
public func removeAlpha() -> UIImage {
if !self.hasAlpha() {
return self
}
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceRGB()!
let mainViewContentContext: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), 8, 0, colorSpace, CGImageGetBitmapInfo(self.CGImage).rawValue)!
CGContextDrawImage(mainViewContentContext, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage)
let mainViewContentBitmapContext: CGImageRef = CGBitmapContextCreateImage(mainViewContentContext)!
let returnImage: UIImage = UIImage(CGImage: mainViewContentBitmapContext)
return returnImage
}
/**
Fill the alpha with the white color
- returns: Returns the filled image
*/
public func fillAlpha() -> UIImage {
return self.fillAlphaWithColor(UIColor.whiteColor())
}
/**
Fill the alpha with the given color
- parameter color: Color to fill
- returns: Returns the filled image
*/
public func fillAlphaWithColor(color: UIColor) -> UIImage {
let imageRect: CGRect = CGRect(origin: CGPointZero, size: self.size)
let cgColor: CGColorRef = color.CGColor
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.mainScreen().scale)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, cgColor)
CGContextFillRect(context, imageRect)
self.drawInRect(imageRect)
let returnImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return returnImage
}
/**
Check if the image is in grayscale
- returns: Returns true if is in grayscale, false if not
*/
public func isGrayscale() -> Bool {
let imgRef: CGImageRef = self.CGImage!
let clrMod: CGColorSpaceModel = CGColorSpaceGetModel(CGImageGetColorSpace(imgRef))
if clrMod == CGColorSpaceModel.Monochrome {
return true
} else {
return false
}
}
/**
Transform the image to grayscale
- returns: Returns the transformed image
*/
public func imageToGrayscale() -> UIImage {
let rect: CGRect = CGRectMake(0.0, 0.0, size.width, size.height)
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
let context: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), 8, 0, colorSpace, CGImageGetBitmapInfo(self.CGImage).rawValue)!
CGContextDrawImage(context, rect, self.CGImage)
let grayscale: CGImageRef = CGBitmapContextCreateImage(context)!
let returnImage: UIImage = UIImage(CGImage: grayscale)
return returnImage
}
/**
Transform the image to black and white
- returns: Returns the transformed image
*/
public func imageToBlackAndWhite() -> UIImage {
let colorSpace: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
let context: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), 8, 0, colorSpace, CGImageGetBitmapInfo(self.CGImage).rawValue)!
CGContextSetInterpolationQuality(context, .High)
CGContextSetShouldAntialias(context, false)
CGContextDrawImage(context, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage)
let bwImage: CGImageRef = CGBitmapContextCreateImage(context)!
let returnImage: UIImage = UIImage(CGImage: bwImage)
return returnImage
}
/**
Invert the color of the image
- returns: Returns the transformed image
*/
public func invertColors() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen .mainScreen().scale)
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), .Copy)
self.drawInRect(CGRectMake(0, 0, self.size.width, self.size.height))
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), .Difference)
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), UIColor.whiteColor().CGColor)
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, self.size.width, self.size.height))
let returnImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return returnImage
}
/**
Apply the bloom effect to the image
- parameter radius: Radius of the bloom
- parameter intensity: Intensity of the bloom
- returns: Returns the transformed image
*/
public func bloom(radius: Float, intensity: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CIBloom")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
filter.setValue(intensity, forKey: kCIInputIntensityKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the bump distortion effect to the image
- parameter center: Vector of the distortion. Use CIVector(x: X, y: Y)
- parameter radius: Radius of the effect
- parameter scale: Scale of the effect
- returns: Returns the transformed image
*/
public func bumpDistortion(center: CIVector, radius: Float, scale: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CIBumpDistortion")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(center, forKey: kCIInputCenterKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
filter.setValue(scale, forKey: kCIInputScaleKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the bump distortion linear effect to the image
- parameter center: Vector of the distortion. Use CIVector(x: X, y: Y)
- parameter radius: Radius of the effect
- parameter angle: Angle of the effect in radians
- parameter scale: Scale of the effect
- returns: Returns the transformed image
*/
public func bumpDistortionLinear(center: CIVector, radius: Float, angle: Float, scale: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CIBumpDistortionLinear")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(center, forKey: kCIInputCenterKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
filter.setValue(angle, forKey: kCIInputAngleKey)
filter.setValue(scale, forKey: kCIInputScaleKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the circular splash distortion effect to the image
- parameter center: Vector of the distortion. Use CIVector(x: X, y: Y)
- parameter radius: Radius of the effect
- returns: Returns the transformed image
*/
public func circleSplashDistortion(center: CIVector, radius: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CICircleSplashDistortion")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(center, forKey: kCIInputCenterKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the circular wrap effect to the image
- parameter center: Vector of the distortion. Use CIVector(x: X, y: Y)
- parameter radius: Radius of the effect
- parameter angle: Angle of the effect in radians
- returns: Returns the transformed image
*/
public func circularWrap(center: CIVector, radius: Float, angle: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CICircularWrap")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(center, forKey: kCIInputCenterKey)
filter.setValue(radius, forKey: kCIInputRadiusKey)
filter.setValue(angle, forKey: kCIInputAngleKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the CMY halftone effect to the image
- parameter center: Vector of the distortion. Use CIVector(x: X, y: Y)
- parameter width: Width value
- parameter angle: Angle of the effect in radians
- parameter sharpness: Sharpness Value
- parameter gcr: GCR value
- parameter ucr: UCR value
- returns: Returns the transformed image
*/
public func cmykHalftone(center: CIVector, width: Float, angle: Float, sharpness: Float, gcr: Float, ucr: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CICMYKHalftone")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(center, forKey: kCIInputCenterKey)
filter.setValue(width, forKey: kCIInputWidthKey)
filter.setValue(sharpness, forKey: kCIInputSharpnessKey)
filter.setValue(angle, forKey: kCIInputAngleKey)
filter.setValue(gcr, forKey: "inputGCR")
filter.setValue(ucr, forKey: "inputUCR")
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the sepia filter to the image
- parameter intensity: Intensity of the filter
- returns: Returns the transformed image
*/
public func sepiaToneWithIntensity(intensity: Float) -> UIImage {
let context: CIContext = CIContext(options: nil)
let filter: CIFilter = CIFilter(name: "CISepiaTone")!
let ciimage: XPCIImage = XPCIImage(image: self)!
filter.setValue(ciimage, forKey: kCIInputImageKey)
filter.setValue(intensity, forKey: kCIInputIntensityKey)
let returnImage: UIImage = UIImage(CGImage: context.createCGImage(filter.outputImage!, fromRect: filter.outputImage!.extent))
return returnImage
}
/**
Apply the blur effect to the image
- parameter blurRadius: Blur radius
- parameter tintColor: Blur tint color
- parameter saturationDeltaFactor: Saturation delta factor, leave it default (1.8) if you don't what is
- parameter maskImage: Apply a mask image, leave it default (nil) if you don't want to mask
- returns: Return the transformed image
*/
public func blur(radius blurRadius: CGFloat, tintColor: UIColor? = nil, saturationDeltaFactor: CGFloat = 1.8, maskImage: UIImage? = nil) -> UIImage? {
if size.width < 1 || size.height < 1 {
print("Invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
if CGImage == nil {
print("Image must be backed by a CGImage: \(self)")
return nil
}
if let maskImage = maskImage where maskImage.CGImage == nil {
print("maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let imageRect = CGRect(origin: CGPointZero, size: size)
var effectImage = self
let hasBlur = Float(blurRadius) > FLT_EPSILON
let hasSaturationChange = Float(abs(saturationDeltaFactor - 1)) > FLT_EPSILON
if hasBlur || hasSaturationChange {
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let effectInContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(effectInContext, 1, -1)
CGContextTranslateCTM(effectInContext, 0, -size.height)
CGContextDrawImage(effectInContext, imageRect, CGImage)
var effectInBuffer = vImage_Buffer(data: CGBitmapContextGetData(effectInContext), height: UInt(CGBitmapContextGetHeight(effectInContext)), width: UInt(CGBitmapContextGetWidth(effectInContext)), rowBytes: CGBitmapContextGetBytesPerRow(effectInContext))
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = vImage_Buffer(data: CGBitmapContextGetData(effectOutContext), height: UInt(CGBitmapContextGetHeight(effectOutContext)), width: UInt(CGBitmapContextGetWidth(effectOutContext)), rowBytes: CGBitmapContextGetBytesPerRow(effectOutContext))
if hasBlur {
let inputRadius = blurRadius * UIScreen.mainScreen().scale
var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
if radius % 2 != 1 {
radius += 1
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s = saturationDeltaFactor
let floatingPointSaturationMatrix = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let saturationMatrix = floatingPointSaturationMatrix.map {
return Int16(round($0 * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let outputContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(outputContext, 1, -1)
CGContextTranslateCTM(outputContext, 0, -size.height)
CGContextDrawImage(outputContext, imageRect, CGImage)
if hasBlur {
CGContextSaveGState(outputContext)
if let image = maskImage {
CGContextClipToMask(outputContext, imageRect, image.CGImage)
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage)
CGContextRestoreGState(outputContext)
}
if let tintColor = tintColor {
CGContextSaveGState(outputContext)
CGContextSetFillColorWithColor(outputContext, tintColor.CGColor)
CGContextFillRect(outputContext, imageRect)
CGContextRestoreGState(outputContext)
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
/**
Save it to photo alnum
- returns: Return YES it saved, If NO failed
*/
public func saveToPhotosAlbum() -> Bool {
let library = ALAssetsLibrary()
var orientation: ALAssetOrientation = .Up
switch self.imageOrientation {
case .Up:
orientation = .Up
case .Down:
orientation = .Down
case .Left:
orientation = .Left
case .Right:
orientation = .Right
case .UpMirrored:
orientation = .UpMirrored
case .DownMirrored:
orientation = .DownMirrored
case .LeftMirrored:
orientation = .LeftMirrored
case .RightMirrored:
orientation = .RightMirrored
}
var ret = true
library.writeImageToSavedPhotosAlbum(self.CGImage, orientation: orientation) { assetURL, error in
if error == nil {
ret = false
}
}
return ret
}
// MARK: - Class functions -
/**
Private, create a CGSize with a given string (100x100)
- parameter sizeString: String with the size
- returns: Returns the created CGSize
*/
private static func sizeForSizeString(sizeString: String) -> CGSize {
let array: Array = sizeString.componentsSeparatedByString("x")
if array.count != 2 {
return CGSizeZero
}
return CGSizeMake(CGFloat(array[0].floatValue), CGFloat(array[1].floatValue))
}
// MARK: - Init functions -
/**
Create a dummy image
- parameter dummy: To use it, name parameter must contain: "dummy.100x100" and "dummy.100x100.#FFFFFF" or "dummy.100x100.blue" (if it's a color defined in UIColor class) if you want to define a color
- returns: Returns the created dummy image
*/
public convenience init?(dummyImageWithSizeAndColor dummy: String) {
var size: CGSize = CGSizeZero, color: UIColor = UIColor.lightGrayColor()
let array: Array = dummy.componentsSeparatedByString(".")
if array.count > 0 {
let sizeString: String = array[0]
if array.count >= 2 {
color = UIColor.colorForColorString(array[1])
}
size = UIImage.sizeForSizeString(sizeString)
}
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
let rect: CGRect = CGRectMake(0.0, 0.0, size.width, size.height)
color.setFill()
CGContextFillRect(context, rect)
let sizeString: String = "\(Int(size.width)) x \(Int(size.height))"
let style: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
style.alignment = .Center
style.minimumLineHeight = size.height / 2
let attributes: Dictionary = [NSParagraphStyleAttributeName: style]
sizeString.drawInRect(rect, withAttributes: attributes)
let result: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: result.CGImage!)
}
/**
Create an image from a given text
- parameter text: Text
- parameter font: Text's font name
- parameter fontSize: Text's font size
- parameter imageSize: Image's size
- returns: Returns the created UIImage
*/
public convenience init?(fromText text: String, font: FontName, fontSize: CGFloat, imageSize: CGSize) {
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale)
text.drawAtPoint(CGPointMake(0.0, 0.0), withAttributes: [NSFontAttributeName: UIFont(fontName: font, size: fontSize)!])
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
/**
Create an image with a background color and with a text with a mask
- parameter maskedText: Text to mask
- parameter font: Text's font name
- parameter fontSize: Text's font size
- parameter imageSize: Image's size
- parameter backgroundColor: Image's background color
- returns: Returns the created UIImage
*/
public convenience init?(maskedText: String, font: FontName, fontSize: CGFloat, imageSize: CGSize, backgroundColor: UIColor) {
let fontName: UIFont = UIFont(fontName: font, size: fontSize)!
let textAttributes = [NSFontAttributeName: fontName]
let textSize: CGSize = maskedText.sizeWithAttributes(textAttributes)
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.mainScreen().scale)
let ctx: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(ctx, backgroundColor.CGColor)
let path: UIBezierPath = UIBezierPath(rect: CGRectMake(0, 0, imageSize.width, imageSize.height))
CGContextAddPath(ctx, path.CGPath)
CGContextFillPath(ctx)
CGContextSetBlendMode(ctx, .DestinationOut)
let center: CGPoint = CGPointMake(imageSize.width / 2 - textSize.width / 2, imageSize.height / 2 - textSize.height / 2)
maskedText.drawAtPoint(center, withAttributes: textAttributes)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
/**
Create an image from a given color
- parameter color: Color value
- returns: Returns the created UIImage
*/
public convenience init?(color: UIColor) {
let rect: CGRect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context: CGContextRef = UIGraphicsGetCurrentContext()!
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(CGImage: image.CGImage!)
}
}
| mit | 56f547fa86d6bb8d3cb7fa3d2288bedc | 31.833333 | 259 | 0.743655 | 4.177206 | false | false | false | false |
ishkawa/APIKit | Tests/APIKitTests/DataParserType/StringDataParserTests.swift | 1 | 1079 | import XCTest
import Foundation
import APIKit
class StringDataParserTests: XCTestCase {
func testAcceptHeader() {
let parser = StringDataParser(encoding: .utf8)
XCTAssertNil(parser.contentType)
}
func testParseData() throws {
let string = "abcdef"
let data = string.data(using: .utf8, allowLossyConversion: false)!
let parser = StringDataParser(encoding: .utf8)
let object = try parser.parse(data: data)
XCTAssertEqual(object as? String, string)
}
func testInvalidString() {
var bytes = [UInt8]([0xed, 0xa0, 0x80]) // U+D800 (high surrogate)
let data = Data(bytes: &bytes, count: bytes.count)
let parser = StringDataParser(encoding: .utf8)
XCTAssertThrowsError(try parser.parse(data: data)) { error in
guard let error = error as? StringDataParser.Error,
case .invalidData(let invalidData) = error else {
XCTFail()
return
}
XCTAssertEqual(data, invalidData)
}
}
}
| mit | a056164a81e953c0e31a3ee5bc55b20e | 29.828571 | 74 | 0.611677 | 4.514644 | false | true | false | false |
yokoe/luckybeast-ios | luckybeast/EyeView.swift | 1 | 1146 | import UIKit
class EyeView: UIView {
enum Status {
case normal
case white
case shining
}
var status: Status = .normal {
didSet {
setNeedsDisplay()
}
}
override func layoutSubviews() {
self.layer.cornerRadius = bounds.width * 0.5
clipsToBounds = true
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
UIColor.black.setFill()
UIRectFill(bounds)
if status == .white {
UIColor.white.setFill()
UIBezierPath(roundedRect: bounds.insetBy(dx: 4, dy: 4), cornerRadius: 8).fill()
}
UIColor.white.setFill()
UIBezierPath(ovalIn: CGRect(x: 4, y: 8, width: 10, height: 10)).fill()
if status == .shining {
UIColor.blue.setStroke()
let path = UIBezierPath(roundedRect: bounds.insetBy(dx: 4, dy: 4), cornerRadius: 8)
path.lineWidth = 3
path.stroke()
}
}
}
| mit | 891823a469938a6816edcd81a7885cc9 | 25.045455 | 95 | 0.550611 | 4.677551 | false | false | false | false |
buscarini/vitemo | vitemo/Carthage/Checkouts/GRMustache.swift/DemoApps/MustacheDemoOSX/MustacheDemoOSX/ViewController.swift | 4 | 2478 | //
// ViewController.swift
// MustacheDemoOSX
//
// Created by Gwendal Roué on 11/02/2015.
// Copyright (c) 2015 Gwendal Roué. All rights reserved.
//
import Cocoa
import Mustache
class ViewController: NSViewController {
@IBOutlet var templateTextView: NSTextView!
@IBOutlet var JSONTextView: NSTextView!
@IBOutlet var renderingTextView: NSTextView!
@IBOutlet var model: Model!
let font = NSFont(name: "Menlo", size: 12)
override func viewDidLoad() {
super.viewDidLoad()
for textView in [templateTextView, JSONTextView] {
textView.automaticQuoteSubstitutionEnabled = false;
textView.textStorage?.font = font
}
}
@IBAction func render(sender: AnyObject) {
var error: NSError?
if let template = Template(string: model.templateString, error: &error) {
// Uncomment and play with those goodies in your templates:
// They are documented at https://github.com/groue/GRMustache.swift/blob/master/Guides/goodies.md
// let percentFormatter = NSNumberFormatter()
// percentFormatter.numberStyle = .PercentStyle
// template.registerInBaseContext("percent", Box(percentFormatter))
// template.registerInBaseContext("each", Box(StandardLibrary.each))
// template.registerInBaseContext("zip", Box(StandardLibrary.zip))
// template.registerInBaseContext("localize", Box(StandardLibrary.Localizer(bundle: nil, table: nil)))
// template.registerInBaseContext("HTMLEscape", Box(StandardLibrary.HTMLEscape))
// template.registerInBaseContext("URLEscape", Box(StandardLibrary.URLEscape))
// template.registerInBaseContext("javascriptEscape", Box(StandardLibrary.javascriptEscape))
let data = model.JSONString.dataUsingEncoding(NSUTF8StringEncoding)!
if let JSONObject: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error),
let string = template.render(BoxAnyObject(JSONObject), error: &error)
{
presentRenderingString(string)
return
}
}
presentRenderingString("\(error!.domain): \(error!.localizedDescription)")
}
func presentRenderingString(string: String) {
self.renderingTextView.string = string
self.renderingTextView.textStorage?.font = font
}
}
| mit | 7174b62e707892fca1c5c8ec7cfdd475 | 39.590164 | 117 | 0.661147 | 5.04277 | false | false | false | false |
DarielChen/DemoCode | iOS动画指南/iOS动画指南 - 4.右拉的3D抽屉效果/SideMenu/MenuItem.swift | 1 | 1816 | //
// MenuItem.swift
// SideMenu
//
// Created by Dariel on 16/7/13.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
let menuColors = [
UIColor(red: 118/255, green: 165/255, blue: 175/255, alpha: 1.0),
UIColor(red: 213/255, green: 166/255, blue: 189/255, alpha: 1.0),
UIColor(red: 106/255, green: 168/255, blue: 79/255, alpha: 1.0),
UIColor(red: 103/255, green: 78/255, blue: 167/255, alpha: 1.0),
UIColor(red: 188/255, green: 238/255, blue: 104/255, alpha: 1.0),
UIColor(red: 102/255, green: 139/255, blue: 139/255, alpha: 1.0),
UIColor(red: 230/255, green: 145/255, blue: 56/255, alpha: 1.0)
]
class MenuItem {
let title: String
let symbol: String
let color: UIColor
init(symbol: String, color: UIColor, title: String) {
self.symbol = symbol
self.color = color
self.title = title
}
class var sharedItems: [MenuItem] {
struct Static {
static let items = MenuItem.sharedMenuItems()
}
return Static.items
}
class func sharedMenuItems() -> [MenuItem] {
var items = [MenuItem]()
items.append(MenuItem(symbol: "🐱", color: menuColors[0], title: "鼠"))
items.append(MenuItem(symbol: "🐂", color: menuColors[1], title: "牛"))
items.append(MenuItem(symbol: "🐯", color: menuColors[2], title: "虎"))
items.append(MenuItem(symbol: "🐰", color: menuColors[3], title: "兔"))
items.append(MenuItem(symbol: "🐲", color: menuColors[4], title: "龙"))
items.append(MenuItem(symbol: "🐍", color: menuColors[5], title: "蛇"))
items.append(MenuItem(symbol: "🐴", color: menuColors[6], title: "马"))
return items
}
}
| mit | 556ebcd821cb8204c39e124b05d7b062 | 30.192982 | 77 | 0.579303 | 3.286506 | false | false | false | false |
jkpang/PPBadgeView | PPBadgeView/swift/PPBadgeView.swift | 1 | 563 | //
// PPBadgeView.swift
// PPBadgeViewSwift
//
// Created by jkpang on 2018/4/17.
// Copyright © 2018年 AndyPang. All rights reserved.
//
import UIKit
public struct PP<Base> {
public let base: Base
public init(_ base: Base) {
self.base = base
}
}
public extension NSObjectProtocol {
var pp: PP<Self> {
return PP(self)
}
}
public enum PPBadgeViewFlexMode {
case head // 左伸缩 Head Flex : <==●
case tail // 右伸缩 Tail Flex : ●==>
case middle // 左右伸缩 Middle Flex : <=●=>
}
| mit | 73c33acb79f65c162aa05c017f1cc7b5 | 18.071429 | 52 | 0.59176 | 3.256098 | false | false | false | false |
editfmah/AeonAPI | Sources/User.swift | 1 | 1864 | //
// User.swift
// AeonAPI
//
// Created by Adrian Herridge on 19/06/2017.
//
//
import Foundation
import SWSQLite
class User : DataObject {
// _id_ && _timestamp_ in base class.
var user_name: String?
var user_password_hash: String?
var user_email: String?
var user_telno: String?
override func populateFromRecord(_ record: Record) {
self.user_name = record["user_name"]?.asString()
self.user_password_hash = record["user_password_hash"]?.asString()
self.user_email = record["user_email"]?.asString()
self.user_telno = record["user_telno"]?.asString()
}
override class func GetTables() -> [Action] {
let actions = [
Action(createTable: "User"),
Action(addColumn: "user_name", type: .String, table: "User"),
Action(addColumn: "user_password_hash", type: .String, table: "User"),
Action(addColumn: "user_email", type: .String, table: "User"),
Action(addColumn: "user_telno", type: .String, table: "User"),
Action(createIndexOnTable: "User", keyColumnName: "user_name", ascending: true)
]
return actions
}
class func Get(id: String) -> User? {
let results = usersdb.query(sql: "SELECT * FROM User WHERE _id_ = ? LIMIT 1", params: [id])
if results.error == nil && results.results.count > 0 {
return User(results.results[0])
}
return nil
}
class func Get(username: String) -> User? {
let results = usersdb.query(sql: "SELECT * FROM User WHERE user_name = ? LIMIT 1", params: [username])
if results.error == nil && results.results.count > 0 {
return User(results.results[0])
}
return nil
}
}
| mit | aed6797fbbcf95be1ab09a8095762553 | 28.125 | 110 | 0.55794 | 3.915966 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBRealm.swift | 1 | 16203 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
import RealmSwift
/// オブジェクトIDのキー名
public let NBRealmObjectIDKey = "id"
public let NBRealmObjectCreatedKey = "created"
public let NBRealmObjectModifiedKey = "modified"
// MARK: - NBRealmEntity -
/// Realmオブジェクトの基底クラス
public class NBRealmObject : RealmSwift.Object {
// MARK: データプロパティ
/// オブジェクトID
public dynamic var id : Int64 = 0 // = NBRealmObjectIDKey
/// 作成日時
public dynamic var created = NSDate()
/// 更新日時
public dynamic var modified = NSDate()
// MARK: 配列・リスト処理
/// RealmSwift.Listオブジェクトを配列に変換する
/// - parameter list: RealmSwift.Listオブジェクト
/// - returns: 変換された配列
public func listToArray<T : NBRealmObject>(list: RealmSwift.List<T>) -> [T] {
return list.toArray()
}
/// 配列をRealmSwift.Listオブジェクトに変換する
/// - parameter array: 配列
/// - returns: 変換されたRealmSwift.Listオブジェクト
public func arrayToList<T : NBRealmObject>(array: [T]) -> RealmSwift.List<T> {
let ret = RealmSwift.List<T>()
ret.appendContentsOf(array)
return ret
}
// MARK: 設定用メソッド
/// 主キー設定
public override static func primaryKey() -> String? {
return NBRealmObjectIDKey
}
}
// MARK: - NBRealmAccessor -
/// Realmオブジェクトのデータアクセサの基底クラス
public class NBRealmAccessor : NSObject {
/// Realmファイルのパス
public static var realmPath: String { return Realm.Configuration.defaultConfiguration.path ?? "" }
/// Realmオブジェクト
public var realm: Realm { return try! Realm() }
}
// MARK: インスタンス管理
public extension NBRealmAccessor {
/// 指定した型の新しいRealmオブジェクトインスタンスを生成する
///
/// 返されるオブジェクトのIDはオートインクリメントされた値が入ります
///
/// - parameter type: 型
/// - parameter previousID: ループ中などに前回のIDを与えることで複数のユニークなIDのオブジェクトを作成できます
/// - returns: 新しいRealmオブジェクトインスタンス
public func createWithType<T : NBRealmObject>(type: T.Type, previousID: Int64? = nil) -> T {
let ret = T()
if let previous = previousID {
ret.id = previous + 1
} else {
ret.id = self.increasedIDWithType(type)
}
return ret
}
/// 渡したオブジェクトのコピーオブジェクトを新しく生成する
///
/// - parameter object: コピーするオブジェクト
/// - returns: 引数のオブジェクトをコピーした新しいRealmオブジェクトインスタンス
public func cloneWithType<T : NBRealmObject>(object: T) -> T {
let ret = T()
ret.id = object.id
ret.created = object.created
ret.modified = object.modified
return ret
}
/// 指定した型のオートインクリメントされたID値を返却する
/// - parameter type: 型
/// - returns: オートインクリメントされたID値
public func increasedIDWithType<T : NBRealmObject>(type: T.Type) -> Int64 {
guard let max = self.realm.objects(type).sorted(NBRealmObjectIDKey, ascending: false).first else {
return 1
}
return max.id + 1
}
}
// MARK: データ追加
public extension NBRealmAccessor {
/// 指定したRealmオブジェクトを一括で追加する
/// - parameter realmObjects: 追加するRealmオブジェクトの配列
public func add<T : NBRealmObject>(realmObjects: [T]) {
let r = self.realm
var i = 0, id: Int64 = 1
try! r.write {
for realmObject in realmObjects {
if i == 0 { id = realmObject.id }
realmObject.id = id + i++
realmObject.created = NSDate()
realmObject.modified = NSDate()
r.add(realmObject, update: true)
}
}
}
/// 指定したRealmオブジェクトを追加する
/// - parameter realmObject: 追加するRealmオブジェクト
public func add<T : NBRealmObject>(realmObject: T) {
self.add([realmObject])
}
}
// MARK: データ更新
public extension NBRealmAccessor {
/// 指定した条件のRealmオブジェクトを一括で更新する
/// - parameter type: Realmオブジェクト型
/// - parameter predicate: 条件
/// - parameter modify: 更新処理
public func modifyWithPredicate<T : NBRealmObject>(type: T.Type, predicate: NSPredicate, modify: (T, Int) -> Void) {
let r = self.realm
try! r.write {
let result = r.objects(type).filter(predicate)
var i = 0
for realmObject in result {
realmObject.modified = NSDate()
modify(realmObject, i++)
}
}
}
/// 指定したIDのRealmオブジェクトを一括で更新する
/// - parameter type: Realmオブジェクト型
/// - parameter ids: IDの配列
/// - parameter modify: 更新処理
public func modifyByIDs<T : NBRealmObject>(type: T.Type, ids: [Int64], modify: (T, Int) -> Void) {
self.modifyWithPredicate(type, predicate: self.predicateIDs(ids), modify: modify)
}
/// Realmオブジェクトの配列を渡して一括で更新する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObjects: 更新するRealmオブジェクトの配列
/// - parameter modify: 更新処理
public func modify<T : NBRealmObject>(type: T.Type, _ realmObjects: [T], modify: (T, Int) -> Void) {
let ids = realmObjects.map { return $0.id }
self.modifyByIDs(type, ids: ids, modify: modify)
}
/// RealmオブジェクトのRealmSwift.List、またはRealmSwift.Resultを渡して一括で更新する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObjects: 更新するRealmオブジェクトの配列
/// - parameter modify: 更新処理
public func modify<T : NBRealmObject, S: SequenceType where S.Generator.Element: NBRealmObject>(type: T.Type, _ realmObjects: S, modify: (T, Int) -> Void) {
let array = realmObjects.map { return $0 as NBRealmObject }
self.modify(type, array, modify: modify)
}
/// 渡したRealmオブジェクトを更新する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObject: 更新するRealmオブジェクト
/// - parameter modify: 更新処理
public func modify<T : NBRealmObject>(type: T.Type, _ realmObject: T, modify: (T, Int) -> Void) {
self.modifyByIDs(type, ids: [realmObject.id], modify: modify)
}
}
// MARK: データ削除
public extension NBRealmAccessor {
/// 指定した条件のRealmオブジェクトを一括で削除する
/// - parameter type: Realmオブジェクト型
/// - parameter predicate: 条件
public func removeWithPredicate<T : NBRealmObject>(type: T.Type, predicate: NSPredicate) {
let r = self.realm
try! r.write {
r.delete(r.objects(type).filter(predicate))
}
}
/// 指定したIDのRealmオブジェクトを一括で削除する
/// - parameter type: Realmオブジェクト型
/// - parameter ids: IDの配列
public func removeByIDs<T : NBRealmObject>(type: T.Type, ids: [Int64]) {
self.removeWithPredicate(type, predicate: self.predicateIDs(ids))
}
/// Realmオブジェクトの配列を渡して一括で削除する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObjects: 削除するRealmオブジェクトの配列
public func remove<T : NBRealmObject>(type: T.Type, _ realmObjects: [T]) {
let ids = realmObjects.map { return $0.id }
self.removeByIDs(type, ids: ids)
}
/// RealmオブジェクトのRealmSwift.List、またはRealmSwift.Resultを渡して一括で削除する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObjects: 削除するRealmオブジェクトの配列
public func remove<T : NBRealmObject, S: SequenceType where S.Generator.Element: NBRealmObject>(type: T.Type, _ realmObjects: S) {
let array = realmObjects.map { return $0 as NBRealmObject }
self.remove(type, array)
}
/// 渡したRealmオブジェクトを削除する
/// - parameter type: Realmオブジェクト型
/// - parameter realmObject: 削除するRealmオブジェクト
public func remove<T : NBRealmObject>(type: T.Type, _ realmObject: T) {
self.removeByIDs(type, ids: [realmObject.id])
}
}
// MARK: データ取得
public extension NBRealmAccessor {
/// 指定した条件・ソートでRealmオブジェクトを配列で取得する
/// - parameter type: Realmオブジェクト型
/// - parameter condition: 条件オブジェクト
/// - parameter sort: ソート([プロパティ名 : 昇順/降順]の辞書)
/// - returns: Realmオブジェクトの配列
public func fetch<T : NBRealmObject>(type: T.Type, condition: NSPredicate? = nil, sort: [String : Bool]? = [NBRealmObjectIDKey: false]) -> [T] {
return self.getResults(type, condition: condition, sort: sort).map { return $0 }
}
/// 指定した条件のRealmオブジェクト数を取得する
/// - parameter type: Realmオブジェクト型
/// - parameter condition: 条件オブジェクト
/// - returns: Realmオブジェクトの配列
public func count<T : NBRealmObject>(type: T.Type, condition: NSPredicate? = nil) -> Int {
return self.getResults(type, condition: condition).count
}
/// 指定した条件・ソートでの結果オブジェクトを取得する
/// - parameter type: Realmオブジェクト型
/// - parameter condition: 条件オブジェクト
/// - parameter sort: ソート([プロパティ名 : 昇順/降順]の辞書)
/// - returns: Realmオブジェクトの配列
private func getResults<T : NBRealmObject>(type: T.Type, condition: NSPredicate? = nil, sort: [String : Bool]? = nil) -> RealmSwift.Results<T> {
var result = self.realm.objects(type)
if let f = condition {
result = result.filter(f)
}
if let s = sort {
s.forEach {
result = result.sorted($0.0, ascending: $0.1)
}
}
return result
}
}
// MARK: 検索条件
public extension NBRealmAccessor {
/// 複数の検索条件を1つにまとめて返却する
/// - parameter conditions: 検索条件文字列の配列
/// - parameter type: 結合種別
/// - returns: 検索条件オブジェクト
public func compoundPredicateWithConditions(conditions: [String], type: NSCompoundPredicateType = .AndPredicateType) -> NSPredicate {
var predicates = [NSPredicate]()
for condition in conditions {
predicates.append(NSPredicate(format: condition))
}
return self.compoundPredicateWithPredicates(predicates, type: type)
}
/// 複数の検索条件を1つにまとめて返却する
/// - parameter predicates: 検索条件オブジェクトの配列
/// - parameter type: 結合種別
/// - returns: 検索条件オブジェクト
public func compoundPredicateWithPredicates(predicates: [NSPredicate], type: NSCompoundPredicateType = .AndPredicateType) -> NSPredicate {
let ret: NSPredicate
switch type {
case .AndPredicateType: ret = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
case .OrPredicateType: ret = NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
case .NotPredicateType: ret = NSCompoundPredicate(notPredicateWithSubpredicate: self.compoundPredicateWithPredicates(predicates))
}
return ret
}
/// IDの配列からのIN条件の検索条件を生成する
/// - parameter ids: IDの配列
/// - returns: 検索条件オブジェクト
public func predicateIDs(ids: [Int64]) -> NSPredicate {
return NSPredicate(format: "\(NBRealmObjectIDKey) IN {%@}", argumentArray: ids.map { return NSNumber(longLong: $0) } )
}
/// あいまい検索を行うための検索条件を生成する
/// - parameter property: プロパティ名
/// - parameter q: 検索文字列
/// - returns: 検索条件オブジェクト
public func predicateContainsString(property: String, _ q: String) -> NSPredicate {
return NSPredicate(format: "\(property) CONTAINS '\(q)'")
}
/// 値の完全一致検索を行うための検索条件を生成する
/// - parameter property: プロパティ名
/// - parameter v: 値
/// - returns: 検索条件オブジェクト
public func predicateEqauls(property: String, _ v: AnyObject) -> NSPredicate {
return NSPredicate(format: "\(property) = %@", argumentArray: [v])
}
}
// MARK: ソート
public extension NBRealmAccessor {
/// IDでソートするための辞書を返す
/// - parameter ascending: 昇順/降順
/// - parameter seed: 既にソート用の辞書がある場合に渡すと、追記される
/// - returns: ソート用の辞書
public func sortID(ascending: Bool = true, seed: [String : Bool] = [:]) -> [String : Bool] {
return self.sortOf(NBRealmObjectIDKey, ascending: ascending, seed: seed)
}
/// 作成日時でソートするための辞書を返す
/// - parameter ascending: 昇順/降順
/// - parameter seed: 既にソート用の辞書がある場合に渡すと、追記される
/// - returns: ソート用の辞書
public func sortCreated(ascending: Bool = true, seed: [String : Bool] = [:]) -> [String : Bool] {
return self.sortOf(NBRealmObjectCreatedKey, ascending: ascending, seed: seed)
}
/// 作成日時でソートするための辞書を返す
/// - parameter ascending: 昇順/降順
/// - parameter seed: 既にソート用の辞書がある場合に渡すと、追記される
/// - returns: ソート用の辞書
public func sortModified(ascending: Bool = true, seed: [String : Bool] = [:]) -> [String : Bool] {
return self.sortOf(NBRealmObjectModifiedKey, ascending: ascending, seed: seed)
}
/// 指定したプロパティでソートするための辞書を返す
/// - parameter property: プロパティ名
/// - parameter ascending: 昇順/降順
/// - parameter seed: 既にソート用の辞書がある場合に渡すと、追記される
/// - returns: ソート用の辞書
public func sortOf(property: String, ascending: Bool = true, var seed: [String : Bool] = [:]) -> [String : Bool] {
seed[property] = ascending
return seed
}
}
// MARK: - RealmSwift拡張 -
extension RealmSwift.List {
/// 自身のデータを配列に変換する
/// - returns: 変換された配列
func toArray() -> [Element] {
return self.map { return $0 }
}
/// 自身のデータを渡された配列でリセットする
/// - parameter array: 配列
func resetWithArray(array: [Element]) {
self.removeAll()
self.appendContentsOf(array)
}
}
// MARK: - RealmSwift拡張 -
public extension String {
/// Realm用にエスケープした文字列
public var stringEscapedForRealm: String {
return self.replace("\\", "\\\\").replace("'", "\\'")
}
}
| apache-2.0 | 5980e914c233eb6f2931bed17b16f1ff | 33.146907 | 160 | 0.61899 | 3.726864 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Frontend/Browser/OpenSearch.swift | 2 | 10951 | /* 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 UIKit
import Shared
import SWXMLHash
private let TypeSearch = "text/html"
private let TypeSuggest = "application/x-suggestions+json"
private let SearchTermsAllowedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*-_."
class OpenSearchEngine: NSObject, NSCoding {
static let PreferredIconSize = 30
let shortName: String
let engineID: String?
let image: UIImage
let isCustomEngine: Bool
let searchTemplate: String
fileprivate let suggestTemplate: String?
fileprivate let SearchTermComponent = "{searchTerms}"
fileprivate let LocaleTermComponent = "{moz:locale}"
fileprivate lazy var searchQueryComponentKey: String? = self.getQueryArgFromTemplate()
init(engineID: String?, shortName: String, image: UIImage, searchTemplate: String, suggestTemplate: String?, isCustomEngine: Bool) {
self.shortName = shortName
self.image = image
self.searchTemplate = searchTemplate
self.suggestTemplate = suggestTemplate
self.isCustomEngine = isCustomEngine
self.engineID = engineID
}
required init?(coder aDecoder: NSCoder) {
guard let searchTemplate = aDecoder.decodeObject(forKey: "searchTemplate") as? String,
let shortName = aDecoder.decodeObject(forKey: "shortName") as? String,
let isCustomEngine = aDecoder.decodeObject(forKey: "isCustomEngine") as? Bool,
let image = aDecoder.decodeObject(forKey: "image") as? UIImage else {
assertionFailure()
return nil
}
self.searchTemplate = searchTemplate
self.shortName = shortName
self.isCustomEngine = isCustomEngine
self.image = image
self.engineID = aDecoder.decodeObject(forKey: "engineID") as? String
self.suggestTemplate = nil
}
func encode(with aCoder: NSCoder) {
aCoder.encode(searchTemplate, forKey: "searchTemplate")
aCoder.encode(shortName, forKey: "shortName")
aCoder.encode(isCustomEngine, forKey: "isCustomEngine")
aCoder.encode(image, forKey: "image")
aCoder.encode(engineID, forKey: "engineID")
}
/**
* Returns the search URL for the given query.
*/
func searchURLForQuery(_ query: String) -> URL? {
return getURLFromTemplate(searchTemplate, query: query)
}
/**
* Return the arg that we use for searching for this engine
* Problem: the search terms may not be a query arg, they may be part of the URL - how to deal with this?
**/
fileprivate func getQueryArgFromTemplate() -> String? {
// we have the replace the templates SearchTermComponent in order to make the template
// a valid URL, otherwise we cannot do the conversion to NSURLComponents
// and have to do flaky pattern matching instead.
let placeholder = "PLACEHOLDER"
let template = searchTemplate.replacingOccurrences(of: SearchTermComponent, with: placeholder)
let components = URLComponents(string: template)
let searchTerm = components?.queryItems?.filter { item in
return item.value == placeholder
}
guard let term = searchTerm, !term.isEmpty else { return nil }
return term[0].name
}
/**
* check that the URL host contains the name of the search engine somewhere inside it
**/
fileprivate func isSearchURLForEngine(_ url: URL?) -> Bool {
guard let urlHost = url?.host,
let queryEndIndex = searchTemplate.range(of: "?")?.lowerBound,
let templateURL = URL(string: searchTemplate.substring(to: queryEndIndex)),
let templateURLHost = templateURL.host else { return false }
return urlHost.localizedCaseInsensitiveContains(templateURLHost)
}
/**
* Returns the query that was used to construct a given search URL
**/
func queryForSearchURL(_ url: URL?) -> String? {
if isSearchURLForEngine(url) {
if let key = searchQueryComponentKey,
let value = url?.getQuery()[key] {
return value.replacingOccurrences(of: "+", with: " ").removingPercentEncoding
}
}
return nil
}
/**
* Returns the search suggestion URL for the given query.
*/
func suggestURLForQuery(_ query: String) -> URL? {
if let suggestTemplate = suggestTemplate {
return getURLFromTemplate(suggestTemplate, query: query)
}
return nil
}
fileprivate func getURLFromTemplate(_ searchTemplate: String, query: String) -> URL? {
let allowedCharacters = CharacterSet(charactersIn: SearchTermsAllowedCharacters)
if let escapedQuery = query.addingPercentEncoding(withAllowedCharacters: allowedCharacters) {
// Escape the search template as well in case it contains not-safe characters like symbols
let templateAllowedSet = NSMutableCharacterSet()
templateAllowedSet.formUnion(with: CharacterSet.URLAllowedCharacterSet())
// Allow brackets since we use them in our template as our insertion point
templateAllowedSet.formUnion(with: CharacterSet(charactersIn: "{}"))
if let encodedSearchTemplate = searchTemplate.addingPercentEncoding(withAllowedCharacters: templateAllowedSet as CharacterSet) {
let localeString = Locale.current.identifier
let urlString = encodedSearchTemplate
.replacingOccurrences(of: SearchTermComponent, with: escapedQuery, options: NSString.CompareOptions.literal, range: nil)
.replacingOccurrences(of: LocaleTermComponent, with: localeString, options: NSString.CompareOptions.literal, range: nil)
return URL(string: urlString)
}
}
return nil
}
}
/**
* OpenSearch XML parser.
*
* This parser accepts standards-compliant OpenSearch 1.1 XML documents in addition to
* the Firefox-specific search plugin format.
*
* OpenSearch spec: http://www.opensearch.org/Specifications/OpenSearch/1.1
*/
class OpenSearchParser {
fileprivate let pluginMode: Bool
init(pluginMode: Bool) {
self.pluginMode = pluginMode
}
func parse(_ file: String, engineID: String) -> OpenSearchEngine? {
let data = try? Data(contentsOf: URL(fileURLWithPath: file))
if data == nil {
print("Invalid search file")
return nil
}
let rootName = pluginMode ? "SearchPlugin" : "OpenSearchDescription"
let docIndexer: XMLIndexer! = SWXMLHash.parse(data!)[rootName][0]
if docIndexer.element == nil {
print("Invalid XML document")
return nil
}
let shortNameIndexer = docIndexer["ShortName"]
if shortNameIndexer.all.count != 1 {
print("ShortName must appear exactly once")
return nil
}
let shortName = shortNameIndexer.element?.text
if shortName == nil {
print("ShortName must contain text")
return nil
}
let urlIndexers = docIndexer["Url"].all
if urlIndexers.isEmpty {
print("Url must appear at least once")
return nil
}
var searchTemplate: String!
var suggestTemplate: String?
for urlIndexer in urlIndexers {
let type = urlIndexer.element?.attribute(by: "type")?.text
if type == nil {
print("Url element requires a type attribute", terminator: "\n")
return nil
}
if type != TypeSearch && type != TypeSuggest {
// Not a supported search type.
continue
}
var template = urlIndexer.element?.attribute(by: "template")?.text
if template == nil {
print("Url element requires a template attribute", terminator: "\n")
return nil
}
if pluginMode {
let paramIndexers = urlIndexer["Param"].all
if !paramIndexers.isEmpty {
template! += "?"
var firstAdded = false
for paramIndexer in paramIndexers {
if firstAdded {
template! += "&"
} else {
firstAdded = true
}
let name = paramIndexer.element?.attribute(by: "name")?.text
let value = paramIndexer.element?.attribute(by: "value")?.text
if name == nil || value == nil {
print("Param element must have name and value attributes", terminator: "\n")
return nil
}
template! += name! + "=" + value!
}
}
}
if type == TypeSearch {
searchTemplate = template
} else {
suggestTemplate = template
}
}
if searchTemplate == nil {
print("Search engine must have a text/html type")
return nil
}
let imageIndexers = docIndexer["Image"].all
var largestImage = 0
var largestImageElement: XMLElement?
// TODO: For now, just use the largest icon.
for imageIndexer in imageIndexers {
let imageWidth = Int(imageIndexer.element?.attribute(by: "width")?.text ?? "")
let imageHeight = Int(imageIndexer.element?.attribute(by: "height")?.text ?? "")
// Only accept square images.
if imageWidth != imageHeight {
continue
}
if let imageWidth = imageWidth {
if imageWidth > largestImage {
if imageIndexer.element?.text != nil {
largestImage = imageWidth
largestImageElement = imageIndexer.element
}
}
}
}
let uiImage: UIImage
if let imageElement = largestImageElement,
let imageURL = URL(string: imageElement.text),
let imageData = try? Data(contentsOf: imageURL),
let image = UIImage.imageFromDataThreadSafe(imageData) {
uiImage = image
} else {
print("Error: Invalid search image data")
return nil
}
return OpenSearchEngine(engineID: engineID, shortName: shortName!, image: uiImage, searchTemplate: searchTemplate, suggestTemplate: suggestTemplate, isCustomEngine: false)
}
}
| mpl-2.0 | 87069ca6a5d21377138be5080a50e30a | 37.024306 | 179 | 0.605424 | 5.423972 | false | false | false | false |
PraveenSakthivel/BRGO-IOS | BRGO/Menu.swift | 1 | 5366 | //
// Menu.swift
// BRGO
//
// Created by Praveen Sakthivel on 7/19/16.
// Copyright © 2016 TBLE Technologies. All rights reserved.
//
import UIKit
class Menu: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let background = UIView()
background.backgroundColor = Colors.secondary
self.tableView.tableFooterView = background
self.tableView.separatorColor = Colors.tertiary
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 8
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50;
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
switch (indexPath as NSIndexPath).row {
case 0:
cell.textLabel?.text = "BRGO"
case 1:
cell.textLabel?.text = "News"
case 2:
cell.textLabel?.text = "Calendar"
case 3:
cell.textLabel?.text = "Websites"
case 4:
cell.textLabel?.text = "School Handbook"
case 5:
cell.textLabel?.text = "Homework Planner"
case 6:
cell.textLabel?.text = "Student ID"
case 7:
cell.textLabel?.text = "Settings"
default:
cell.textLabel?.text = "BRGO"
}
if (indexPath as NSIndexPath).row > 0
{
cell.backgroundColor = Colors.secondary
cell.textLabel!.textColor = Colors.primary
}
else{
cell.backgroundColor = Colors.primary
cell.textLabel?.textColor = Colors.secondary
}
cell.textLabel!.font = UIFont(name:"Bodoni 72", size: 16)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.tableView.deselectRow(at: indexPath, animated:true)
switch (indexPath as NSIndexPath).row {
case 0:
print("")
case 1:
performSegue(withIdentifier: "MenuNews", sender:self)
case 2:
performSegue(withIdentifier: "MenuCalendar", sender:self)
case 3:
performSegue(withIdentifier: "menuWeb", sender:self)
case 4:
performSegue(withIdentifier: "menuHandbook", sender:self)
case 5:
performSegue(withIdentifier: "menuPlanner", sender:self)
case 6:
performSegue(withIdentifier: "menuID", sender:self)
case 7:
performSegue(withIdentifier: "menuSettings", sender:self)
default:
performSegue(withIdentifier: "MenuNews", sender:self)
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | af9d72db17bc35b564e0b1a3b7d31ff5 | 35.006711 | 157 | 0.643057 | 5.178571 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/iOS Collection/Business/Business/iPad/Home/View/iPadMiddleMenuView.swift | 1 | 1442 | //
// iPadMiddleMenuView.swift
// Business
//
// Created by 朱双泉 on 2018/11/12.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
protocol iPadMiddleMenuViewDelegate {
func dockDidSelect(toIndex: Int)
}
class iPadMiddleMenuView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
addMenus()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var delegate: iPadMiddleMenuViewDelegate?
func addMenus() {
for i in 0..<6 {
let button = iPadMenuButton(type: .system)
button.tintColor = .lightGray
button.setTitle(" CoderZsq - " + "\(i)", for: .normal)
button.setImage(UIImage(named: "Mark"), for: .normal)
button.addTarget(self, action: #selector(menuClick(sender:)), for: .touchDown)
button.tag = subviews.count
addSubview(button)
}
}
@objc
func menuClick(sender: UIButton) {
delegate?.dockDidSelect(toIndex: sender.tag)
}
override func layoutSubviews() {
super.layoutSubviews()
var index: CGFloat = 0
for view in subviews {
view.height = height / CGFloat(subviews.count)
view.width = width
view.left = 0
view.top = view.height * index
index += 1
}
}
}
| mit | 9ad89e1c93e77910bf260e1a896f6520 | 24.625 | 90 | 0.577003 | 4.245562 | false | false | false | false |
Mindera/Alicerce | Tests/AlicerceTests/Logging/Log+Item.swift | 1 | 706 | import Foundation
@testable import Alicerce
extension Log.Item {
static func dummy(
timestamp: Date = Date(),
module: String? = "module",
level: Log.Level = .verbose,
message: String = "message",
thread: String = "thread",
queue: String = "queue",
file: String = "filename.ext",
line: Int = 1337,
function: String = "function"
) -> Self {
.init(
timestamp: timestamp,
module: module,
level: level,
message: message,
thread: thread,
queue: queue,
file: file,
line: line,
function: function
)
}
}
| mit | 58d5382a66ab6be3e4fcf267ae0d6734 | 22.533333 | 38 | 0.492918 | 4.584416 | false | false | false | false |
PrinceChen/DouYu | DouYu/DouYu/Classes/Home/View/AmuseMenuView.swift | 1 | 2794 | //
// AmuseMenuView.swift
// DouYu
//
// Created by prince.chen on 2017/3/3.
// Copyright © 2017年 prince.chen. All rights reserved.
//
import UIKit
private let kMenuCellID = "kMenuCellID"
class AmuseMenuView: UIView {
var groups: [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
autoresizingMask = UIViewAutoresizing()
collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
}
}
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if groups == nil {
return 0
}
let pageNum = (groups!.count - 1) / 8 + 1
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
// cell.backgroundColor = UIColor.randomColor()
setupCellDataWithCell(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellDataWithCell(cell: AmuseMenuViewCell, indexPath: IndexPath) {
let startIndex = indexPath.item * 8
var endIndex = (indexPath.item + 1) * 8 - 1
if endIndex > groups!.count - 1 {
endIndex = groups!.count - 1
}
// cell.clipsToBounds = true
cell.groups = Array(groups![startIndex...endIndex])
}
}
extension AmuseMenuView: UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int((scrollView.contentOffset.x + scrollView.bounds.width * 0.5) / scrollView.bounds.width)
}
}
| mit | 2ef316522ce715f5986c2fb35cfae7db | 30.359551 | 125 | 0.660695 | 5.306084 | false | false | false | false |
justindarc/firefox-ios | Client/Frontend/Browser/OpenWithSettingsViewController.swift | 1 | 4385 | /* 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 Shared
class OpenWithSettingsViewController: ThemedTableViewController {
typealias MailtoProviderEntry = (name: String, scheme: String, enabled: Bool)
var mailProviderSource = [MailtoProviderEntry]()
fileprivate let prefs: Prefs
fileprivate var currentChoice: String = "mailto"
init(prefs: Prefs) {
self.prefs = prefs
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsOpenWithSectionName
tableView.accessibilityIdentifier = "OpenWithPage.Setting.Options"
let headerFooterFrame = CGRect(width: self.view.frame.width, height: SettingsUX.TableViewHeaderFooterHeight)
let headerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
headerView.titleLabel.text = Strings.SettingsOpenWithPageTitle.uppercased()
headerView.showTopBorder = false
headerView.showBottomBorder = true
let footerView = ThemedTableSectionHeaderFooterView(frame: headerFooterFrame)
footerView.showTopBorder = false
footerView.showBottomBorder = false
tableView.tableHeaderView = headerView
tableView.tableFooterView = footerView
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
appDidBecomeActive()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.prefs.setString(currentChoice, forKey: PrefsKeys.KeyMailToOption)
}
@objc func appDidBecomeActive() {
reloadMailProviderSource()
updateCurrentChoice()
tableView.reloadData()
}
func updateCurrentChoice() {
var previousChoiceAvailable: Bool = false
if let prefMailtoScheme = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) {
mailProviderSource.forEach({ (name, scheme, enabled) in
if scheme == prefMailtoScheme {
previousChoiceAvailable = enabled
}
})
}
if !previousChoiceAvailable {
self.prefs.setString(mailProviderSource[0].scheme, forKey: PrefsKeys.KeyMailToOption)
}
if let updatedMailToClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) {
self.currentChoice = updatedMailToClient
}
}
func reloadMailProviderSource() {
if let path = Bundle.main.path(forResource: "MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) {
mailProviderSource = dictRoot.map { dict in
let nsDict = dict as! NSDictionary
return (name: nsDict["name"] as! String, scheme: nsDict["scheme"] as! String,
enabled: canOpenMailScheme(nsDict["scheme"] as! String))
}
}
}
func canOpenMailScheme(_ scheme: String) -> Bool {
if let url = URL(string: scheme) {
return UIApplication.shared.canOpenURL(url)
}
return false
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ThemedTableViewCell()
let option = mailProviderSource[indexPath.row]
cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.name, enabled: option.enabled)
cell.accessoryType = (currentChoice == option.scheme && option.enabled) ? .checkmark : .none
cell.isUserInteractionEnabled = option.enabled
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mailProviderSource.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.currentChoice = mailProviderSource[indexPath.row].scheme
tableView.reloadData()
}
}
| mpl-2.0 | 84d2aad99ec687ec2eb16211ea3ed776 | 36.478632 | 155 | 0.678221 | 5.57888 | false | false | false | false |
yelken/policiavirtual-ios | Kit Iot Wearable/WearableService.swift | 1 | 4645 | //
// WearableService.swift
// kit-iot-wearable
//
// Created by Vitor Leal on 4/1/15.
// Copyright (c) 2015 Telefonica VIVO. All rights reserved.
//
import Foundation
import CoreBluetooth
let ServiceUUID = CBUUID(string: "FFE0")
let CharacteristicUIID = CBUUID(string: "FFE1")
let WearableServiceStatusNotification = "WearableServiceChangedStatusNotification"
let WearableCharacteristicNewValue = "WearableCharacteristicNewValue"
let WearableUpdateLocation = "WearableUpdateLocation"
class WearableService: NSObject, CBPeripheralDelegate {
var peripheral: CBPeripheral?
var peripheralCharacteristic: CBCharacteristic?
init(initWithPeripheral peripheral: CBPeripheral) {
super.init()
self.peripheral = peripheral
self.peripheral?.delegate = self
}
deinit {
self.reset()
}
// MARK: - Start discovering services
func startDiscoveringServices() {
self.peripheral?.discoverServices([ServiceUUID])
}
// MARK: - Reset
func reset() {
if peripheral != nil {
peripheral = nil
}
self.sendWearableServiceStatusNotification(false)
}
// MARK: - Look for bluetooth with the service FFEO
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
let uuidsForBTService: [CBUUID] = [CharacteristicUIID]
if (peripheral != self.peripheral || error != nil) {
return
}
if ((peripheral.services == nil) || (peripheral.services.count == 0)) {
return
}
// Find characteristics
for service in peripheral.services {
if service.UUID == ServiceUUID {
peripheral.discoverCharacteristics(uuidsForBTService, forService: service as! CBService)
}
}
}
// MARK: - Look for the bluetooth characteristics
func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) {
if (peripheral != self.peripheral || error != nil) {
return
}
for characteristic in service.characteristics {
if characteristic.UUID == CharacteristicUIID {
self.peripheralCharacteristic = (characteristic as! CBCharacteristic)
peripheral.setNotifyValue(true, forCharacteristic: characteristic as! CBCharacteristic)
self.sendWearableServiceStatusNotification(true)
}
}
}
// MARK: - Did update the characteristic value
func peripheral(peripheral: CBPeripheral!, didUpdateValueForCharacteristic characteristic: CBCharacteristic!, error: NSError!) {
if ((error) != nil) {
println("Error changing notification state: %@", error.description)
}
if (!characteristic.UUID.isEqual(peripheralCharacteristic?.UUID)) {
return
}
var value = NSString(bytes: characteristic.value.bytes, length: characteristic.value.length, encoding: NSUTF8StringEncoding)
value = value?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if let optionalValue = value {
self.sendWearableCharacteristicNewValue(optionalValue)
}
}
// MARK: - Send command
func sendCommand(command: NSString) {
let str = NSString(string: command)
let data = NSData(bytes: str.UTF8String, length: str.length)
self.peripheral?.writeValue(data, forCharacteristic: self.peripheralCharacteristic, type: CBCharacteristicWriteType.WithoutResponse)
}
// MARK: - Send wearable connected notification
func sendWearableServiceStatusNotification(isBluetoothConnected: Bool) {
let userInfo = ["isConnected": isBluetoothConnected]
NSNotificationCenter.defaultCenter().postNotificationName(WearableServiceStatusNotification, object: self, userInfo: userInfo)
}
// MARK: - Send characteristic value
func sendWearableCharacteristicNewValue(value: NSString) {
let userInfo = ["value": value]
NSNotificationCenter.defaultCenter().postNotificationName(WearableCharacteristicNewValue, object: self, userInfo: userInfo)
}
func sendWearableUpdateLocation(value: NSString) {
let userInfo = ["value": value]
NSNotificationCenter.defaultCenter().postNotificationName(WearableUpdateLocation, object: self, userInfo: userInfo)
}
}
| mit | 5e3501aae01af9461e4affa10cb738e1 | 32.417266 | 140 | 0.655113 | 5.490544 | false | false | false | false |
CreazyShadow/SimpleDemo | SimpleApp/SimpleApp/视图/ListView/TestTableViewViewController.swift | 1 | 2413 | //
// TestTableViewViewController.swift
// SimpleApp
//
// Created by wuyp on 16/8/7.
// Copyright © 2016年 wuyp. All rights reserved.
//
import UIKit
@objc(TestTableViewViewController)
class TestTableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//MARK: life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.addSubview(self.tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: tableView delegate & datasource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let model: CellModel = self.source[(indexPath as NSIndexPath).row]
return model.isSelected! ? 120 : 40
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "CELL")!
cell.textLabel?.text = self.source[(indexPath as NSIndexPath).row].name
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source.count
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model: CellModel = self.source[(indexPath as NSIndexPath).row]
model.isSelected = !model.isSelected
let indexs: [IndexPath] = [indexPath]
self.tableView .reloadRows(at: indexs, with: .bottom)
}
//MARK: lazy load
lazy var tableView: UITableView = {
let temp: UITableView = UITableView(frame: self.view.bounds, style: .grouped)
temp.delegate = self
temp.dataSource = self
temp.register(ExpandTableViewCell.self, forCellReuseIdentifier: "CELL")
return temp
}()
lazy var source: [CellModel] = {
var temp: [CellModel] = []
for i in 1...10 {
let model: CellModel = CellModel()
model.name = "AAA\(i)"
model.isSelected = false
temp.append(model)
}
return temp
}()
}
| apache-2.0 | 0f141535b7d1df6db12ea654d5a2c693 | 28.753086 | 100 | 0.634025 | 4.938525 | false | false | false | false |
Suninus/ruby-china-ios | RubyChina/Controllers/ComposeController.swift | 5 | 11774 | //
// ComposeController.swift
// RubyChina
//
// Created by Jianqiu Xiao on 5/30/15.
// Copyright (c) 2015 Jianqiu Xiao. All rights reserved.
//
import AFNetworking
import MBProgressHUD
import SZTextView
import SwiftyJSON
import UIKit
class ComposeController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var bodyTextView = SZTextView()
var cells = [UITableViewCell(), UITableViewCell(), UITableViewCell()]
var failureView = FailureView()
var loadingView = LoadingView()
var reply: JSON = [:]
var tableView = UITableView()
var titleField = UITextField()
var topic: JSON = [:]
override func viewDidLoad() {
navigationItem.leftBarButtonItem = navigationController?.viewControllers.count == 1 ? splitViewController?.displayModeButtonItem() : nil
navigationItem.leftItemsSupplementBackButton = true
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("done"))
title = reply["topic_id"].int == nil ? (topic["id"].int == nil ? "发帖" : "编辑") : (reply["id"] == nil ? "回复" : "编辑")
view.backgroundColor = Helper.backgroundColor
tableView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
tableView.backgroundColor = .clearColor()
tableView.dataSource = self
tableView.delegate = self
tableView.frame = view.bounds
tableView.scrollEnabled = false
tableView.tableFooterView = UIView()
view.addSubview(tableView)
failureView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("loadData")))
view.addSubview(failureView)
view.addSubview(loadingView)
titleField.autocapitalizationType = .None
titleField.autocorrectionType = .No
titleField.clearButtonMode = .WhileEditing
titleField.delegate = self
titleField.frame.size.height = 44
titleField.placeholder = "标题"
titleField.returnKeyType = .Next
titleField.text = topic["title"].string
bodyTextView.autocapitalizationType = .None
bodyTextView.autocorrectionType = .No
bodyTextView.contentInset = UIEdgeInsets(top: -8, left: -4, bottom: -8, right: -4)
bodyTextView.font = .systemFontOfSize(17)
bodyTextView.placeholder = "正文"
bodyTextView.text = topic["body"].string ?? reply["body"].string
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
tableView.deselectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: true)
Helper.trackView(self)
}
override func viewDidAppear(animated: Bool) {
loadData()
}
func loadData() {
if topic["id"].int == nil && reply["id"].int == nil || topic["body"].string != nil || reply["body"].string != nil { autoBecomeFirstResponder(); return }
if loadingView.refreshing { return }
failureView.hide()
loadingView.show()
let path = topic["id"].int != nil ? "/topics/" + topic["id"].stringValue + ".json" : "/replies/" + reply["id"].stringValue + ".json"
AFHTTPRequestOperationManager(baseURL: Helper.baseURL).GET(path, parameters: nil, success: { (operation, responseObject) in
self.loadingView.hide()
self.topic = JSON(responseObject)["topic"]
self.reply = JSON(responseObject)["reply"]
self.titleField.text = self.topic["title"].string
self.bodyTextView.text = self.topic["body"].string ?? self.reply["body"].string
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: .None)
self.autoBecomeFirstResponder()
}) { (operation, error) in
self.loadingView.hide()
self.failureView.show()
}
}
func autoBecomeFirstResponder() {
if reply["topic_id"].int != nil { bodyTextView.becomeFirstResponder() }
else if topic["node_id"].int == nil {}
else if titleField.text == "" { titleField.becomeFirstResponder() }
else { bodyTextView.becomeFirstResponder() }
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row != 2 && reply["topic_id"].int != nil { return 0 }
if indexPath.row == 2 { return tableView.frame.height - min(UIApplication.sharedApplication().statusBarFrame.width, UIApplication.sharedApplication().statusBarFrame.height) - navigationController!.navigationBar.frame.height - 44 * (reply["topic_id"].int != nil ? 0 : 2) - tableView.contentInset.bottom }
return tableView.rowHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row != 2 && reply["topic_id"].int != nil { return UITableViewCell() }
let cell = cells[indexPath.row]
switch indexPath.row {
case 0:
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.text = topic["node_name"].string != nil ? "[" + topic["node_name"].stringValue + "]" : "节点"
cell.textLabel?.textColor = topic["node_name"].string != nil ? .blackColor() : UIColor(red: 199/255.0, green: 199/255.0, blue: 215/255.0, alpha: 1)
case 1:
cell.accessoryView = titleField
cell.selectionStyle = .None
titleField.frame.size.width = tableView.frame.width - tableView.separatorInset.left * 2
case 2:
cell.accessoryView = bodyTextView
cell.selectionStyle = .None
bodyTextView.frame.size.width = tableView.frame.width - tableView.separatorInset.left * 2
bodyTextView.frame.size.height = self.tableView(tableView, heightForRowAtIndexPath: indexPath) - 24
default: 0
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
titleField.resignFirstResponder()
bodyTextView.resignFirstResponder()
navigationController?.pushViewController(NodesController(), animated: true)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
bodyTextView.becomeFirstResponder()
return false
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
tableView.reloadData()
}
func keyboardWillShow(notification: NSNotification) {
keyboardVisibleHeight(notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue().height)
}
func keyboardWillHide(notification: NSNotification) {
keyboardVisibleHeight(0)
}
func keyboardVisibleHeight(height: CGFloat) {
tableView.contentInset.bottom = height
tableView.scrollIndicatorInsets.bottom = height
cells[2].frame.size.height = self.tableView(tableView, heightForRowAtIndexPath: NSIndexPath(forRow: 2, inSection: 0))
bodyTextView.frame.size.height = cells[2].frame.height - 24
}
func done() {
if reply["topic_id"].int == nil && topic["node_id"].int == nil {
tableView(tableView, didSelectRowAtIndexPath: NSIndexPath(forRow: 0, inSection: 0))
} else if reply["topic_id"].int == nil && titleField.text == "" {
titleField.becomeFirstResponder()
} else if bodyTextView.text == "" {
bodyTextView.becomeFirstResponder()
} else if Defaults.userId == nil {
Helper.signIn(self)
} else {
promot()
}
}
func promot() {
tableView.endEditing(true)
let alertController = UIAlertController(title: "确定提交吗?", message: nil, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "提交", style: .Default, handler: { (_) in self.submit() }))
presentViewController(alertController, animated: true, completion: nil)
}
func submit() {
let progressHUD = MBProgressHUD.showHUDAddedTo(view, animated: false)
let parameters = [
"node_id": topic["node_id"].object,
"title": titleField.text!,
"body": bodyTextView.text!,
]
let success = { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) -> Void in
progressHUD.hide(true)
let topicController = self.navigationController?.viewControllers.filter({ ($0 as? TopicController) != nil }).last as? TopicController
if self.reply["topic_id"].int == nil {
let topic = JSON(responseObject)["topic"]
if self.topic["id"].int == nil {
let topicController = TopicController()
topicController.topic = topic
self.navigationController?.viewControllers = [topicController]
} else {
topicController?.topic = topic
topicController?.title = topic["title"].string
topicController?.topicBodyCell = TopicBodyCell()
topicController?.tableView.reloadData()
self.navigationController?.popViewControllerAnimated(true)
}
} else {
let reply = JSON(responseObject)["reply"]
self.reply["id"] == nil ? topicController?.addReply(reply) : topicController?.updateReply(reply)
self.navigationController?.popViewControllerAnimated(true)
}
}
let failure = { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
if operation.response != nil && operation.response.statusCode == 401 { progressHUD.hide(false); Helper.signIn(self); return }
progressHUD.labelText = "网络错误"
progressHUD.mode = .Text
progressHUD.hide(true, afterDelay: 2)
}
if reply["topic_id"].int == nil {
if topic["id"].int == nil {
AFHTTPRequestOperationManager(baseURL: Helper.baseURL).POST("/topics.json", parameters: parameters, success: success, failure: failure)
} else {
AFHTTPRequestOperationManager(baseURL: Helper.baseURL).PATCH("/topics/" + topic["id"].stringValue + ".json", parameters: parameters, success: success, failure: failure)
}
} else {
if reply["id"].int == nil {
AFHTTPRequestOperationManager(baseURL: Helper.baseURL).POST("/topics/" + reply["topic_id"].stringValue + "/replies.json", parameters: parameters, success: success, failure: failure)
} else {
AFHTTPRequestOperationManager(baseURL: Helper.baseURL).PATCH("/replies/" + reply["id"].stringValue + ".json", parameters: parameters, success: success, failure: failure)
}
}
}
func selectNode(node: JSON) {
topic["node_id"].object = node["id"].object
topic["node_name"].object = node["name"].object
cells[0].textLabel?.text = "[" + node["name"].stringValue + "]"
cells[0].textLabel?.textColor = .blackColor()
navigationController?.popToViewController(self, animated: true)
}
}
| mit | 4275fa93b2200aec4ada3e86196699b1 | 46.25 | 311 | 0.645417 | 5.081526 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/SESV2/SESV2_Paginator.swift | 1 | 28885 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension SESV2 {
/// List the dedicated IP addresses that are associated with your AWS account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func getDedicatedIpsPaginator<Result>(
_ input: GetDedicatedIpsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, GetDedicatedIpsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: getDedicatedIps,
tokenKey: \GetDedicatedIpsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func getDedicatedIpsPaginator(
_ input: GetDedicatedIpsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (GetDedicatedIpsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: getDedicatedIps,
tokenKey: \GetDedicatedIpsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// List all of the configuration sets associated with your account in the current region. Configuration sets are groups of rules that you can apply to the emails you send. You apply a configuration set to an email by including a reference to the configuration set in the headers of the email. When you apply a configuration set to an email, all of the rules in that configuration set are applied to the email.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listConfigurationSetsPaginator<Result>(
_ input: ListConfigurationSetsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListConfigurationSetsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listConfigurationSets,
tokenKey: \ListConfigurationSetsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listConfigurationSetsPaginator(
_ input: ListConfigurationSetsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListConfigurationSetsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listConfigurationSets,
tokenKey: \ListConfigurationSetsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the existing custom verification email templates for your account in the current AWS Region. For more information about custom verification email templates, see Using Custom Verification Email Templates in the Amazon SES Developer Guide. You can execute this operation no more than once per second.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listCustomVerificationEmailTemplatesPaginator<Result>(
_ input: ListCustomVerificationEmailTemplatesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListCustomVerificationEmailTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listCustomVerificationEmailTemplates,
tokenKey: \ListCustomVerificationEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listCustomVerificationEmailTemplatesPaginator(
_ input: ListCustomVerificationEmailTemplatesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListCustomVerificationEmailTemplatesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listCustomVerificationEmailTemplates,
tokenKey: \ListCustomVerificationEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// List all of the dedicated IP pools that exist in your AWS account in the current Region.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDedicatedIpPoolsPaginator<Result>(
_ input: ListDedicatedIpPoolsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDedicatedIpPoolsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDedicatedIpPools,
tokenKey: \ListDedicatedIpPoolsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDedicatedIpPoolsPaginator(
_ input: ListDedicatedIpPoolsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDedicatedIpPoolsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDedicatedIpPools,
tokenKey: \ListDedicatedIpPoolsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Show a list of the predictive inbox placement tests that you've performed, regardless of their statuses. For predictive inbox placement tests that are complete, you can use the GetDeliverabilityTestReport operation to view the results.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDeliverabilityTestReportsPaginator<Result>(
_ input: ListDeliverabilityTestReportsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDeliverabilityTestReportsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDeliverabilityTestReports,
tokenKey: \ListDeliverabilityTestReportsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDeliverabilityTestReportsPaginator(
_ input: ListDeliverabilityTestReportsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDeliverabilityTestReportsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDeliverabilityTestReports,
tokenKey: \ListDeliverabilityTestReportsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Retrieve deliverability data for all the campaigns that used a specific domain to send email during a specified time range. This data is available for a domain only if you enabled the Deliverability dashboard for the domain.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listDomainDeliverabilityCampaignsPaginator<Result>(
_ input: ListDomainDeliverabilityCampaignsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListDomainDeliverabilityCampaignsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listDomainDeliverabilityCampaigns,
tokenKey: \ListDomainDeliverabilityCampaignsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listDomainDeliverabilityCampaignsPaginator(
_ input: ListDomainDeliverabilityCampaignsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListDomainDeliverabilityCampaignsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listDomainDeliverabilityCampaigns,
tokenKey: \ListDomainDeliverabilityCampaignsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a list of all of the email identities that are associated with your AWS account. An identity can be either an email address or a domain. This operation returns identities that are verified as well as those that aren't. This operation returns identities that are associated with Amazon SES and Amazon Pinpoint.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listEmailIdentitiesPaginator<Result>(
_ input: ListEmailIdentitiesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListEmailIdentitiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listEmailIdentities,
tokenKey: \ListEmailIdentitiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listEmailIdentitiesPaginator(
_ input: ListEmailIdentitiesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListEmailIdentitiesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listEmailIdentities,
tokenKey: \ListEmailIdentitiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists the email templates present in your Amazon SES account in the current AWS Region. You can execute this operation no more than once per second.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listEmailTemplatesPaginator<Result>(
_ input: ListEmailTemplatesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListEmailTemplatesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listEmailTemplates,
tokenKey: \ListEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listEmailTemplatesPaginator(
_ input: ListEmailTemplatesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListEmailTemplatesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listEmailTemplates,
tokenKey: \ListEmailTemplatesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Lists all of the import jobs.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listImportJobsPaginator<Result>(
_ input: ListImportJobsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListImportJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listImportJobs,
tokenKey: \ListImportJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listImportJobsPaginator(
_ input: ListImportJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListImportJobsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listImportJobs,
tokenKey: \ListImportJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Retrieves a list of email addresses that are on the suppression list for your account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listSuppressedDestinationsPaginator<Result>(
_ input: ListSuppressedDestinationsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListSuppressedDestinationsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listSuppressedDestinations,
tokenKey: \ListSuppressedDestinationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listSuppressedDestinationsPaginator(
_ input: ListSuppressedDestinationsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListSuppressedDestinationsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listSuppressedDestinations,
tokenKey: \ListSuppressedDestinationsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension SESV2.GetDedicatedIpsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.GetDedicatedIpsRequest {
return .init(
nextToken: token,
pageSize: self.pageSize,
poolName: self.poolName
)
}
}
extension SESV2.ListConfigurationSetsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListConfigurationSetsRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListCustomVerificationEmailTemplatesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListCustomVerificationEmailTemplatesRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListDedicatedIpPoolsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListDedicatedIpPoolsRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListDeliverabilityTestReportsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListDeliverabilityTestReportsRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListDomainDeliverabilityCampaignsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListDomainDeliverabilityCampaignsRequest {
return .init(
endDate: self.endDate,
nextToken: token,
pageSize: self.pageSize,
startDate: self.startDate,
subscribedDomain: self.subscribedDomain
)
}
}
extension SESV2.ListEmailIdentitiesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListEmailIdentitiesRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListEmailTemplatesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListEmailTemplatesRequest {
return .init(
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListImportJobsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListImportJobsRequest {
return .init(
importDestinationType: self.importDestinationType,
nextToken: token,
pageSize: self.pageSize
)
}
}
extension SESV2.ListSuppressedDestinationsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> SESV2.ListSuppressedDestinationsRequest {
return .init(
endDate: self.endDate,
nextToken: token,
pageSize: self.pageSize,
reasons: self.reasons,
startDate: self.startDate
)
}
}
| apache-2.0 | eb24b21fb5384dc704a4416a185f2ef8 | 44.922099 | 416 | 0.65927 | 5.033107 | false | false | false | false |
optimizely/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/ObjectFilter.swift | 2 | 6548 | //
// ObjectFilter.swift
// Mixpanel
//
// Created by Yarden Eitan on 8/24/16.
// Copyright © 2016 Mixpanel. All rights reserved.
//
import Foundation
import UIKit
class ObjectFilter: CustomStringConvertible {
var name: String? = nil
var predicate: NSPredicate? = nil
var index: Int? = nil
var unique: Bool
var nameOnly: Bool
init() {
self.unique = false
self.nameOnly = false
}
var description: String {
var desc = ""
if let name = name {
desc += "name: \(name),"
}
if let index = index {
desc += "index: \(index),"
}
if let predicate = predicate {
desc += "predicate: \(predicate)"
}
return desc
}
func apply(on views: [AnyObject]) -> [AnyObject] {
var result = [AnyObject]()
let currentClass: AnyClass? = NSClassFromString(name!)
if currentClass != nil || name == "*" {
for view in views {
var children = getChildren(of: view, searchClass: currentClass)
if let index = index, index < children.count {
if view.isKind(of: UIView.self) {
children = [children[index]]
} else {
children = []
}
}
result += children
}
}
if !nameOnly {
if unique && result.count != 1 {
return []
}
if let predicate = predicate {
return result.filter { predicate.evaluate(with: $0) }
}
}
return result
}
/*
Apply this filter to the views. For any view that
matches this filter's class / predicate pattern, return
its parents.
*/
func applyReverse(on views: [AnyObject]) -> [AnyObject] {
var result = [AnyObject]()
for view in views {
if doesApply(on: view) {
result += getParents(of: view)
}
}
return result
}
/*
Returns whether the given view would pass this filter.
*/
func doesApply(on view: AnyObject) -> Bool {
let typeValidation = name == "*" || (name != nil && NSClassFromString(name!) != nil && view.isKind(of: NSClassFromString(name!)!))
let predicateValidation = predicate == nil || predicate!.evaluate(with: view)
let indexValidation = index == nil || isSibling(view, at: index!)
let uniqueValidation = !unique || isSibling(view, of: 1)
return typeValidation && (nameOnly || (predicateValidation && indexValidation && uniqueValidation))
}
/*
Returns whether any of the given views would pass this filter
*/
func doesApply(on views: [AnyObject]) -> Bool {
for view in views {
if doesApply(on: view) {
return true
}
}
return false
}
/*
Returns true if the given view is at the index given by number in
its parent's subviews. The view's parent must be of type UIView
*/
func isSibling(_ view: AnyObject, at index: Int) -> Bool {
return isSibling(view, at: index, of: nil)
}
func isSibling(_ view: AnyObject, of count: Int) -> Bool {
return isSibling(view, at: nil, of: count)
}
func isSibling(_ view: AnyObject, at index: Int?, of count: Int?) -> Bool {
guard let name = name else {
return false
}
let parents = self.getParents(of: view)
for parent in parents {
if let parent = parent as? UIView {
let siblings = getChildren(of: parent, searchClass: NSClassFromString(name))
if index == nil || (index! < siblings.count && siblings[index!] === view) && (count == nil || siblings.count == count!) {
return true
}
}
}
return false
}
func getParents(of object: AnyObject) -> [AnyObject] {
var result = [AnyObject]()
if let object = object as? UIView {
if let superview = object.superview {
result.append(superview)
}
if let nextResponder = object.next, nextResponder != object.superview {
result.append(nextResponder)
}
} else if let object = object as? UIViewController {
if let parentViewController = object.parent {
result.append(parentViewController)
}
if let presentingViewController = object.presentingViewController {
result.append(presentingViewController)
}
if let keyWindow = MixpanelInstance.sharedUIApplication()?.keyWindow, keyWindow.rootViewController == object {
result.append(keyWindow)
}
}
return result
}
func getChildren(of object: AnyObject, searchClass: AnyClass?) -> [AnyObject] {
var children = [AnyObject]()
if let window = object as? UIWindow,
let rootVC = window.rootViewController,
let sClass = searchClass,
rootVC.isKind(of: sClass) {
children.append(rootVC)
} else if let view = object as? UIView {
for subview in view.subviews {
if searchClass == nil || subview.isKind(of: searchClass!) {
children.append(subview)
}
}
} else if let viewController = object as? UIViewController {
for child in viewController.children {
if searchClass == nil || child.isKind(of: searchClass!) {
children.append(child)
}
}
if let presentedVC = viewController.presentedViewController,
(searchClass == nil || presentedVC.isKind(of: searchClass!)) {
children.append(presentedVC)
}
if viewController.isViewLoaded && (searchClass == nil || viewController.view.isKind(of: searchClass!)) {
children.append(viewController.view)
}
}
// Reorder the cells in a table view so that they are arranged by y position
if let sClass = searchClass, sClass.isSubclass(of: UITableViewCell.self) {
children.sort {
return ($0 as! UITableViewCell).frame.origin.y < ($1 as! UITableViewCell).frame.origin.y
}
}
return children
}
}
| apache-2.0 | e3d42e89b53a5cbe0f5bffb03581a618 | 31.251232 | 138 | 0.5404 | 4.867658 | false | false | false | false |
danger/danger-swift | Sources/Runner/MarathonScriptManager.swift | 1 | 651 | import DangerDependenciesResolver
import Foundation
import Logger
func getScriptManager(_ logger: Logger) throws -> ScriptManager {
let homeFolder: String
if #available(OSX 10.12, *) {
homeFolder = FileManager.default.homeDirectoryForCurrentUser.path
} else {
homeFolder = NSHomeDirectory()
}
let folder = "\(homeFolder)/.danger-swift/"
let packageFolder = folder + "Packages/"
let scriptFolder = folder + "Scripts/"
let packageManager = try PackageManager(folder: packageFolder, logger: logger)
return try ScriptManager(folder: scriptFolder, packageManager: packageManager, logger: logger)
}
| mit | c011efe5a2e48f8fc6357b319e62b366 | 28.590909 | 98 | 0.72043 | 4.683453 | false | false | false | false |
benlangmuir/swift | test/AutoDiff/stdlib/derivative_customization.swift | 21 | 1364 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import DifferentiationUnittest
import StdlibUnittest
var DerivativeCustomizationTests = TestSuite("DerivativeCustomization")
DerivativeCustomizationTests.testWithLeakChecking("withDerivative") {
do {
var counter = 0
func callback(_ x: inout Tracked<Float>) { counter += 1 }
_ = gradient(at: 4) { (x: Tracked<Float>) -> Tracked<Float> in
// Non-active value should not be differentiated, so `callback` should
// not be called.
_ = x.withDerivative(callback)
return x.withDerivative(callback) + x.withDerivative(callback)
}
expectEqual(2, counter)
}
expectEqual(
30,
gradient(at: 4) { (x: Tracked<Float>) in
x.withDerivative { $0 = 10 } + x.withDerivative { $0 = 20 }
})
}
DerivativeCustomizationTests.testWithLeakChecking("withoutDerivative") {
expectEqual(
0,
gradient(at: Tracked<Float>(4)) { x -> Tracked<Float> in
withoutDerivative(at: x) { x in
x * x * x
}
})
expectEqual(
0,
gradient(at: Tracked<Float>(4)) { x -> Tracked<Float> in
let y = withoutDerivative(at: x)
return y * y * y
})
expectEqual(
2,
gradient(at: Tracked<Float>(4)) { x -> Tracked<Float> in
let y = withoutDerivative(at: x)
return x + y * y * y + x
})
}
runAllTests()
| apache-2.0 | 41830a7a0b30a7f7fec5466797393c7c | 24.735849 | 76 | 0.632698 | 3.706522 | false | true | false | false |
wang-chuanhui/CHSDK | Source/CHUI/AlertPrompt.swift | 1 | 2650 | //
// AlertPrompt.swift
// Pods
//
// Created by 王传辉 on 2017/8/7.
//
//
import Foundation
public class AlertPrompt {
public static let alert = AlertPrompt(style: .alert)
public static let actionSheet = AlertPrompt(style: .actionSheet)
public let style: UIAlertControllerStyle
public init(style: UIAlertControllerStyle) {
self.style = style
}
}
public extension AlertPrompt {
func confirm(message: String? = nil, title: String? = nil, action: @escaping () -> () = { }) {
prompt(title: title, message: message, cancel: "确定", action: [], doAction: { (_) in
action()
})
}
func cancel(message: String? = nil, title: String? = nil, action: @escaping () -> () = { }) {
prompt(title: title, message: message, cancel: "取消", action: [], doAction: { (_) in
action()
})
}
func prompt<T: CustomStringConvertible>(title: String?, message: String?, cancel: T?, action: [T], doAction: @escaping (T) -> ()) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
if let cancel = cancel {
alert.addAction(UIAlertAction(title: cancel.description, style: .cancel, handler: { (action) in
doAction(cancel)
}))
}
action.forEach { (action) in
alert.addAction(UIAlertAction(title: action.description, style: .default, handler: { (a) in
doAction(action)
}))
}
let vc = UIApplication.shared.delegate?.window??.rootViewController
vc?.present(alert, animated: true, completion: nil)
}
func prompt(title: String?, message: String?, input: [(placeholder: String?, text: String?)], completion: @escaping ([String]?) -> ()) {
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
completion(nil)
}))
alert.addAction(UIAlertAction(title: "确定", style: .default, handler: { (action) in
let text = alert.textFields.map({$0.map({$0.text ?? ""})})
completion(text)
}))
input.forEach { (item) in
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = item.placeholder
textField.text = item.text
})
}
let vc = UIApplication.shared.delegate?.window??.rootViewController
vc?.present(alert, animated: true, completion: nil)
}
}
| mit | 2dd4ab4c5203bdb1b69a66f96f0a79f6 | 34.04 | 140 | 0.584094 | 4.336634 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/WordPressTest/RegisterDomainDetailsServiceProxyMock.swift | 1 | 6069 | import Foundation
@testable import WordPress
fileprivate struct CartResponseMock: CartResponseProtocol {}
class RegisterDomainDetailsServiceProxyMock: RegisterDomainDetailsServiceProxyProtocol {
enum MockData {
static let firstName = "First"
static let lastName = "Last"
static let phone = "+90.2334432"
static let phoneCountryCode = "90"
static let phoneNumber = "2334432"
static let city = "Istanbul"
static let email = "[email protected]"
static let countryCode = "US"
static let countryName = "United States"
static let stateCode = "AL"
static let stateName = "Alabama"
static let address1 = "address1"
static let organization = "organization"
static let postalCode = "12345"
}
private let validateDomainContactInformationSuccess: Bool
private let validateDomainContactInformationResponseSuccess: Bool
private let createShoppingCartSuccess: Bool
private let redeemCartUsingCreditsSuccess: Bool
private let changePrimaryDomainSuccess: Bool
private let emptyPrefillData: Bool
init(validateDomainContactInformationSuccess: Bool = true,
validateDomainContactInformationResponseSuccess: Bool = true,
createShoppingCartSuccess: Bool = true,
emptyPrefillDataSuccess: Bool = true,
redeemCartUsingCreditsSuccess: Bool = true,
changePrimaryDomainSuccess: Bool = true,
emptyPrefillData: Bool = false) {
self.validateDomainContactInformationSuccess = validateDomainContactInformationSuccess
self.validateDomainContactInformationResponseSuccess = validateDomainContactInformationResponseSuccess
self.createShoppingCartSuccess = createShoppingCartSuccess
self.redeemCartUsingCreditsSuccess = redeemCartUsingCreditsSuccess
self.changePrimaryDomainSuccess = changePrimaryDomainSuccess
self.emptyPrefillData = emptyPrefillData
}
func validateDomainContactInformation(contactInformation: [String: String],
domainNames: [String],
success: @escaping (ValidateDomainContactInformationResponse) -> Void,
failure: @escaping (Error) -> Void) {
guard validateDomainContactInformationSuccess else {
failure(NSError())
return
}
var response = ValidateDomainContactInformationResponse()
response.success = validateDomainContactInformationResponseSuccess
success(response)
}
func getDomainContactInformation(success: @escaping (DomainContactInformation) -> Void,
failure: @escaping (Error) -> Void) {
guard validateDomainContactInformationSuccess else {
failure(NSError())
return
}
if emptyPrefillData {
let contactInformation = DomainContactInformation()
success(contactInformation)
} else {
var contactInformation = DomainContactInformation()
contactInformation.firstName = MockData.firstName
contactInformation.lastName = MockData.lastName
contactInformation.phone = MockData.phone
contactInformation.city = MockData.city
contactInformation.email = MockData.email
contactInformation.countryCode = MockData.countryCode
contactInformation.state = MockData.stateCode
contactInformation.address1 = MockData.address1
contactInformation.organization = MockData.organization
contactInformation.postalCode = MockData.postalCode
success(contactInformation)
}
}
func getSupportedCountries(success: @escaping ([WPCountry]) -> Void,
failure: @escaping (Error) -> Void) {
guard validateDomainContactInformationSuccess else {
failure(NSError())
return
}
let country1 = WPCountry()
country1.code = "TR"
country1.name = "Turkey"
let country2 = WPCountry()
country2.code = MockData.countryCode
country2.name = MockData.countryName
success([country1, country2])
}
func getStates(for countryCode: String,
success: @escaping ([WPState]) -> Void,
failure: @escaping (Error) -> Void) {
guard validateDomainContactInformationSuccess else {
failure(NSError())
return
}
let state1 = WPState()
state1.code = MockData.stateCode
state1.name = MockData.stateName
let state2 = WPState()
state2.code = "AK"
state2.name = "Alaska"
success([state1, state2])
}
func createShoppingCart(siteID: Int,
domainSuggestion: DomainSuggestion,
privacyProtectionEnabled: Bool,
success: @escaping (CartResponseProtocol) -> Void,
failure: @escaping (Error) -> Void) {
guard createShoppingCartSuccess else {
failure(NSError())
return
}
let response = CartResponseMock()
success(response)
}
func redeemCartUsingCredits(cart: CartResponseProtocol,
domainContactInformation: [String: String],
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
guard redeemCartUsingCreditsSuccess else {
failure(NSError())
return
}
success()
}
func changePrimaryDomain(siteID: Int,
newDomain: String,
success: @escaping () -> Void,
failure: @escaping (Error) -> Void) {
guard changePrimaryDomainSuccess else {
failure(NSError())
return
}
success()
}
}
| gpl-2.0 | b39ae9e8c522b4c3e1a4c26b405b7c17 | 38.927632 | 112 | 0.6174 | 5.671963 | false | false | false | false |
nalexn/ViewInspector | Sources/ViewInspector/SwiftUI/Overlay.swift | 1 | 7123 | import SwiftUI
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension ViewType {
struct Overlay: KnownViewType {
public static var typePrefix: String = ""
public static var isTransitive: Bool { true }
}
}
// MARK: - Extraction
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView {
func overlay(_ index: Int? = nil) throws -> InspectableView<ViewType.Overlay> {
return try contentForModifierLookup
.overlay(parent: self, api: [.overlay, .overlayStyle], index: index)
}
func background(_ index: Int? = nil) throws -> InspectableView<ViewType.Overlay> {
return try contentForModifierLookup
.overlay(parent: self, api: [.background, .backgroundStyle], index: index)
}
}
// MARK: - Content
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.Overlay: SingleViewContent {
public static func child(_ content: Content) throws -> Content {
return content
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
extension ViewType.Overlay: MultipleViewContent {
public static func children(_ content: Content) throws -> LazyGroup<Content> {
return try Inspector.viewsInContainer(view: content.view, medium: content.medium)
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension Content {
func overlay(parent: UnwrappedView, api: ViewType.Overlay.API, index: Int?
) throws -> InspectableView<ViewType.Overlay> {
return try overlay(parent: parent, api: [api], index: index)
}
func overlay(parent: UnwrappedView, api: [ViewType.Overlay.API], index: Int?
) throws -> InspectableView<ViewType.Overlay> {
let modifiers = modifiersMatching { modifier in
api.contains(where: {
modifier.modifierType.contains($0.modifierName)
})
}
let hasMultipleOverlays = modifiers.count > 1
let apiName = api.first!.rawValue
guard let (modifier, rootView) = modifiers.lazy.compactMap({ modifier -> (Any, Any)? in
for anApi in api {
do {
let rootView = try Inspector.attribute(path: anApi.rootViewPath, value: modifier)
try anApi.verifySignature(content: rootView, hasMultipleOverlays: hasMultipleOverlays)
return (modifier, rootView)
} catch { continue }
}
return nil
}).dropFirst(index ?? 0).first else {
let parentName = Inspector.typeName(value: view)
throw InspectionError.modifierNotFound(
parent: parentName, modifier: apiName, index: index ?? 0)
}
let alignment = (try? Inspector
.attribute(path: "modifier|alignment", value: modifier,
type: Alignment.self)) ?? .center
let edges = (try? Inspector
.attribute(path: "modifier|ignoresSafeAreaEdges", value: modifier,
type: Edge.Set.self)) ?? .all
let overlayParams = ViewType.Overlay.Params(alignment: alignment, ignoresSafeAreaEdges: edges)
let medium = self.medium.resettingViewModifiers()
.appending(viewModifier: overlayParams)
let content = try Inspector.unwrap(content: Content(rootView, medium: medium))
let base = apiName + "(\(ViewType.indexPlaceholder))"
let call = ViewType.inspectionCall(base: base, index: index)
return try .init(content, parent: parent, call: call, index: index)
}
}
// MARK: - ViewType.Overlay.API
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType.Overlay {
enum API: String {
case border
case overlay
case overlayStyle
case overlayPreferenceValue
case background
case backgroundStyle
case backgroundPreferenceValue
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
internal extension ViewType.Overlay.API {
var modifierName: String {
switch self {
case .border, .overlay, .overlayPreferenceValue:
return "_OverlayModifier"
case .overlayStyle:
return "_OverlayStyleModifier"
case .background, .backgroundPreferenceValue:
return "_BackgroundModifier"
case .backgroundStyle:
return "_BackgroundStyleModifier"
}
}
var rootViewPath: String {
switch self {
case .border, .overlay, .overlayPreferenceValue:
return "modifier|overlay"
case .background, .backgroundPreferenceValue:
return "modifier|background"
case .overlayStyle, .backgroundStyle:
return "modifier|style"
}
}
func verifySignature(content: Any, hasMultipleOverlays: Bool) throws {
let reportFailure: () throws -> Void = {
throw InspectionError.notSupported("Different view signature")
}
switch self {
case .overlayStyle, .backgroundStyle:
break
case .border:
let stroke = try? InspectableView<ViewType.Shape>(Content(content), parent: nil, index: nil).strokeStyle()
if stroke == nil {
try reportFailure()
}
case .overlay:
let otherCases = [ViewType.Overlay.API.border, .overlayPreferenceValue]
if hasMultipleOverlays, otherCases.contains(where: {
(try? $0.verifySignature(content: content, hasMultipleOverlays: hasMultipleOverlays)) != nil
}) {
try reportFailure()
}
case .background:
if (try? ViewType.Overlay.API.backgroundPreferenceValue
.verifySignature(content: content, hasMultipleOverlays: hasMultipleOverlays)) != nil {
try reportFailure()
}
case .overlayPreferenceValue, .backgroundPreferenceValue:
if Inspector.typeName(value: content, generics: .remove) != "_PreferenceReadingView" {
try reportFailure()
}
}
}
}
// MARK: - Custom Attributes
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
public extension InspectableView where View == ViewType.Overlay {
func alignment() throws -> Alignment {
guard let params = content.medium.viewModifiers
.compactMap({ $0 as? ViewType.Overlay.Params }).first else {
throw InspectionError.attributeNotFound(label: "alignment", type: "Overlay")
}
return params.alignment
}
func ignoresSafeAreaEdges() throws -> Edge.Set {
guard let params = content.medium.viewModifiers
.compactMap({ $0 as? ViewType.Overlay.Params }).first else {
throw InspectionError.attributeNotFound(label: "ignoresSafeAreaEdges", type: "Background")
}
return params.ignoresSafeAreaEdges
}
}
@available(iOS 13.0, macOS 10.15, tvOS 13.0, *)
private extension ViewType.Overlay {
struct Params {
let alignment: Alignment
let ignoresSafeAreaEdges: Edge.Set
}
}
| mit | b9c7f4ad42981595cec682bd9daa9f00 | 35.528205 | 118 | 0.62235 | 4.613342 | false | false | false | false |
EgeTart/MedicineDMW | DWM/PersonalController.swift | 1 | 14306 | //
// PersonalController.swift
// DWM
//
// Created by 高永效 on 15/9/22.
// Copyright © 2015年 EgeTart. All rights reserved.
//
import UIKit
import Alamofire
class PersonalController: UIViewController, LoginDelegate, AlertViewDelegate {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var optionTableView: UITableView!
@IBOutlet weak var avatorImage: UIImageView!
@IBOutlet weak var professionalButton: UIButton!
@IBOutlet weak var settingButton: UIButton!
@IBOutlet weak var nameLabel: UILabel!
var isLogin: Bool!
let homeDirectory = NSHomeDirectory()
var filePath = ""
lazy var backgroundView: UIView = {
let _backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height))
_backgroundView.backgroundColor = UIColor(white: 0, alpha: 0.5)
return _backgroundView
}()
override func viewDidLoad() {
super.viewDidLoad()
isLogin = NSUserDefaults.standardUserDefaults().boolForKey("loginState")
let fileUrl = NSURL(string: homeDirectory)!.URLByAppendingPathComponent("/Documents/avator.png")
filePath = "\(fileUrl)"
setupUI()
optionTableView.registerNib(UINib(nibName: "optionCell", bundle: nil), forCellReuseIdentifier: "optionCell")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = true
if isLogin != nil && isLogin == false {
loginButton.hidden = false
} else {
loginButton.hidden = true
}
}
//MARK: UI初始化
func setupUI() {
loginButton.layer.borderWidth = 1.0
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.layer.cornerRadius = 12.5
loginButton.clipsToBounds = true
avatorImage.layer.cornerRadius = 40
optionTableView.tableFooterView = UIView()
professionalButton.layer.borderColor = UIColor.whiteColor().CGColor
professionalButton.layer.borderWidth = 1.0
professionalButton.layer.cornerRadius = 12.5
settingButton.layer.borderColor = UIColor.whiteColor().CGColor
settingButton.layer.borderWidth = 1.0
settingButton.layer.cornerRadius = 12.5
if isLogin == false {
professionalButton.hidden = true
professionalButton.layer.opacity = 0.0
settingButton.hidden = true
settingButton.layer.opacity = 0.0
nameLabel.hidden = true
nameLabel.layer.opacity = 0.0
avatorImage.image = UIImage(named: "avator")
}
else {
loginButton.hidden = true
professionalButton.hidden = true
if let image = UIImage(contentsOfFile: filePath) {
avatorImage.image = image
}
else {
avatorImage.image = UIImage(named: "avator")
}
}
}
// MARK: 设置状态的颜色
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "login" {
let destinationVC = segue.destinationViewController as! LoginController
destinationVC.delegate = self
}
}
//MARK: 对登陆成功做出响应
func loginSuccess() {
professionalButton.hidden = true
settingButton.hidden = false
nameLabel.hidden = false
loginButton.hidden = true
if let image = UIImage(contentsOfFile: filePath) {
avatorImage.image = image
}
else {
avatorImage.image = UIImage(named: "avator")
}
self.optionTableView.reloadData()
UIView.animateWithDuration(0.2) { () -> Void in
self.professionalButton.layer.opacity = 1.0
self.settingButton.layer.opacity = 1.0
self.nameLabel.layer.opacity = 1.0
}
}
//MARK: 跳转到登陆界面
@IBAction func login(sender: AnyObject) {
(sender as! UIButton).hidden = true
self.performSegueWithIdentifier("login", sender: self)
}
@IBAction func registerSuccess(segue: UIStoryboardSegue) {
print("register success")
loginSuccess()
loginButton.hidden = true
optionTableView.reloadData()
}
//MARK: 对AlertView的按钮点击做出响应
func alertView(button clickedButton: UIButton) {
if clickedButton.tag == 202 {
loginButton.hidden = false
loginButton.layer.opacity = 0
Alamofire.request(.POST, "http://112.74.131.194:8080/MedicineProject/App/user/loginOut", parameters: nil, encoding: ParameterEncoding.URL, headers: nil).responseJSON(completionHandler: { (_, _, result) -> Void in
let state = result.value!["result"] as! String
if state == "success" {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "account")
NSUserDefaults.standardUserDefaults().setValue(nil, forKey: "password")
self.loginButton.layer.opacity = 1.0
self.professionalButton.layer.opacity = 0
self.settingButton.layer.opacity = 0.0
self.nameLabel.layer.opacity = 0.0
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "loginState")
self.optionTableView.reloadData()
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.professionalButton.hidden = true
self.settingButton.hidden = true
self.nameLabel.hidden = true
self.avatorImage.image = UIImage(named: "avator")
})
})
}
else {
//MARK: need some message to metion user
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "loginState")
NSUserDefaults.standardUserDefaults().synchronize()
let alert = UIAlertController(title: "提示", message: "出错啦....", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
self.tabBarController?.tabBar.hidden = false
clickedButton.superview?.superview?.removeFromSuperview()
backgroundView.hidden = true
}
}
//MARK: 为tableview提供数据
extension PersonalController: UITableViewDataSource {
//根据是否登陆来确定section的个数
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
isLogin = NSUserDefaults.standardUserDefaults().boolForKey("loginState")
if isLogin == true {
return 3
}
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 {
return 3
}
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("optionCell") as! optionCell
if indexPath.section == 1 {
switch indexPath.row {
case 0:
cell.typeImage.image = UIImage(named: "about")
cell.label.text = "关于我们"
case 1:
cell.typeImage.image = UIImage(named: "share")
cell.label.text = "分享给朋友"
case 2:
cell.typeImage.image = UIImage(named: "feedback")
cell.label.text = "意见反馈"
default:
break
}
}
if indexPath.section == 2 {
cell.typeImage.image = UIImage(named: "exit")
cell.label.text = "退出登录"
}
return cell
}
}
//MARK: 实现tableview的delegate方法
extension PersonalController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
return 0
}
return 8
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0 {
self.performSegueWithIdentifier("collection", sender: self)
}
else if indexPath.section == 1 && indexPath.row == 1 {
let shareParames = NSMutableDictionary()
shareParames.SSDKSetupShareParamsByText("分享内容",
images : UIImage(named: "shareImg.png"),
url : NSURL(string:"http://mob.com"),
title : "分享标题",
type : SSDKContentType.Auto)
//2.进行分享
ShareSDK.showShareActionSheet(self.view, items: nil, shareParams: shareParames) { (state : SSDKResponseState, platformType : SSDKPlatformType, userdata : [NSObject : AnyObject]!, contentEnity : SSDKContentEntity!, error : NSError!, Bool end) -> Void in
switch state{
case SSDKResponseState.Success: print("分享成功")
case SSDKResponseState.Fail: print("分享失败,错误描述:\(error)")
case SSDKResponseState.Cancel: print("分享取消")
default:
break
}
}
}
else if indexPath.section == 2 {
let alertView = NSBundle.mainBundle().loadNibNamed("AlertView", owner: nil, options: nil).last as! AlertView
alertView.delegate = self
alertView.frame.size = CGSize(width: 280, height: 130)
alertView.center = self.view.center
self.tabBarController?.tabBar.hidden = true
backgroundView.hidden = false
self.view.addSubview(backgroundView)
self.view.addSubview(alertView)
}
else if indexPath.section == 1 && indexPath.row == 2 {
self.performSegueWithIdentifier("feedback", sender: self)
}
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.selected = false
}
}
extension PersonalController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBAction func changeAvator(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let albumAction = UIAlertAction(title: "从相册获取", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
}
let cameraAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.Default) { (action: UIAlertAction) -> Void in
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(imagePicker, animated: true, completion: nil)
}
let cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil)
actionSheet.addAction(albumAction)
actionSheet.addAction(cameraAction)
actionSheet.addAction(cancleAction)
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerEditedImage] as! UIImage
avatorImage.image = image
uploadAvator(image)
picker.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: Upload user's avator
func uploadAvator(avator: UIImage) {
saveAvator(avator)
let headers = ["Cookie":"JSESSIONID=\(session!)", "Content-Type": "multipart/form-data"]
let fileURL = NSURL(fileURLWithPath: filePath)
Alamofire.upload(
.POST,
"http://112.74.131.194:8080/MedicineProject/upload/image/portrait",
headers: headers,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(fileURL: fileURL, name: "img")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print(response)
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
func saveAvator(avator: UIImage) {
UIImagePNGRepresentation(avator)!.writeToFile(filePath, atomically: true)
}
} | mit | 7026717c72133b6fd687bccd13a7b5f7 | 34.867347 | 264 | 0.582545 | 5.449225 | false | false | false | false |
bcadam/streamline | Code/Controllers/ConversationListViewController.swift | 1 | 7284 | import UIKit
class ConversationListViewController: ATLConversationListViewController, ATLConversationListViewControllerDelegate, ATLConversationListViewControllerDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
self.navigationController!.navigationBar.tintColor = ATLBlueColor()
let title = NSLocalizedString("Logout", comment: "")
let logoutItem = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: Selector("logoutButtonTapped:"))
self.navigationItem.setLeftBarButtonItem(logoutItem, animated: false)
let composeItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: Selector("composeButtonTapped:"))
self.navigationItem.setRightBarButtonItem(composeItem, animated: false)
}
// MARK - ATLConversationListViewControllerDelegate Methods
func conversationListViewController(conversationListViewController: ATLConversationListViewController, didSelectConversation conversation:LYRConversation) {
self.presentControllerWithConversation(conversation)
}
func conversationListViewController(conversationListViewController: ATLConversationListViewController, didDeleteConversation conversation: LYRConversation, deletionMode: LYRDeletionMode) {
print("Conversation deleted")
}
func conversationListViewController(conversationListViewController: ATLConversationListViewController, didFailDeletingConversation conversation: LYRConversation, deletionMode: LYRDeletionMode, error: NSError?) {
print("Failed to delete conversation with error: \(error)")
}
func conversationListViewController(conversationListViewController: ATLConversationListViewController, didSearchForText searchText: String, completion: ((Set<NSObject>!) -> Void)?) {
UserManager.sharedManager.queryForUserWithName(searchText) { (participants: NSArray?, error: NSError?) in
if error == nil {
if let callback = completion {
callback(NSSet(array: participants as! [AnyObject]) as Set<NSObject>)
}
} else {
if let callback = completion {
callback(nil)
}
print("Error searching for Users by name: \(error)")
}
}
}
func conversationListViewController(conversationListViewController: ATLConversationListViewController!, avatarItemForConversation conversation: LYRConversation!) -> ATLAvatarItem! {
let userID: String = conversation.lastMessage.sender.userID
if userID == PFUser.currentUser()!.objectId {
return PFUser.currentUser()
}
let user: PFUser? = UserManager.sharedManager.cachedUserForUserID(userID)
if user == nil {
UserManager.sharedManager.queryAndCacheUsersWithIDs([userID], completion: { (participants, error) in
if participants != nil && error == nil {
self.reloadCellForConversation(conversation)
} else {
print("Error querying for users: \(error)")
}
})
}
return user;
}
// MARK - ATLConversationListViewControllerDataSource Methods
func conversationListViewController(conversationListViewController: ATLConversationListViewController, titleForConversation conversation: LYRConversation) -> String {
if conversation.metadata["title"] != nil {
return conversation.metadata["title"] as! String
} else {
let listOfParticipant = Array(conversation.participants)
let unresolvedParticipants: NSArray = UserManager.sharedManager.unCachedUserIDsFromParticipants(listOfParticipant)
let resolvedNames: NSArray = UserManager.sharedManager.resolvedNamesFromParticipants(listOfParticipant)
if (unresolvedParticipants.count > 0) {
UserManager.sharedManager.queryAndCacheUsersWithIDs(unresolvedParticipants as! [String]) { (participants: NSArray?, error: NSError?) in
if (error == nil) {
if (participants?.count > 0) {
self.reloadCellForConversation(conversation)
}
} else {
print("Error querying for Users: \(error)")
}
}
}
if (resolvedNames.count > 0 && unresolvedParticipants.count > 0) {
let resolved = resolvedNames.componentsJoinedByString(", ")
return "\(resolved) and \(unresolvedParticipants.count) others"
} else if (resolvedNames.count > 0 && unresolvedParticipants.count == 0) {
return resolvedNames.componentsJoinedByString(", ")
} else {
return "Conversation with \(conversation.participants.count) users..."
}
}
}
// MARK:- Conversation Selection From Push Notification
func presentConversation(conversation: LYRConversation) {
self.presentControllerWithConversation(conversation)
}
// MARK:- Conversation Selection
// The following method handles presenting the correct `ConversationViewController`, regardeless of the current state of the navigation stack.
func presentControllerWithConversation(conversation: LYRConversation) {
let shouldShowAddressBar: Bool = conversation.participants.count > 2 || conversation.participants.count == 0
let conversationViewController: ConversationViewController = ConversationViewController(layerClient: self.layerClient)
conversationViewController.displaysAddressBar = shouldShowAddressBar
conversationViewController.conversation = conversation
if self.navigationController!.topViewController == self {
self.navigationController!.pushViewController(conversationViewController, animated: true)
} else {
var viewControllers = self.navigationController!.viewControllers
let listViewControllerIndex: Int = self.navigationController!.viewControllers.indexOf(self)!
viewControllers[listViewControllerIndex + 1 ..< viewControllers.count] = [conversationViewController]
self.navigationController!.setViewControllers(viewControllers, animated: true)
}
}
// MARK - Actions
func composeButtonTapped(sender: AnyObject) {
let controller = ConversationViewController(layerClient: self.layerClient)
controller.displaysAddressBar = true
self.navigationController!.pushViewController(controller, animated: true)
}
func logoutButtonTapped(sender: AnyObject) {
print("logOutButtonTapAction")
self.layerClient.deauthenticateWithCompletion { (success: Bool, error: NSError?) in
if error == nil {
PFUser.logOut()
self.navigationController!.popToRootViewControllerAnimated(true)
} else {
print("Failed to deauthenticate: \(error)")
}
}
}
}
| apache-2.0 | 9ff2112b1c6d1f3080227bc53a2a1703 | 48.216216 | 215 | 0.674492 | 6.188615 | false | false | false | false |
kumabook/MusicFav | MusicFav/OAuthRequestRetrier.swift | 1 | 2229 | //
// OAuthRequestAdapter.swift
// MusicFav
//
// Created by Hiroki Kumamoto on 2017/12/31.
// Copyright © 2017 Hiroki Kumamoto. All rights reserved.
//
import Foundation
import Alamofire
import OAuthSwift
open class OAuthRequestRetrier: RequestRetrier {
internal let oauth: OAuth2Swift
private let lock = NSLock()
private var isRefreshing = false
private var requestsToRetry: [RequestRetryCompletion] = []
public init(_ oauth: OAuth2Swift) {
self.oauth = oauth
}
public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
lock.lock()
defer { lock.unlock() }
if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 {
requestsToRetry.append(completion)
if !isRefreshing {
refreshTokens { [weak self] succeeded in
guard let strongSelf = self else { return }
strongSelf.refreshed(succeeded)
strongSelf.lock.lock() ; defer { strongSelf.lock.unlock() }
strongSelf.requestsToRetry.forEach { $0(succeeded, 0.0) }
strongSelf.requestsToRetry.removeAll()
}
}
} else {
completion(false, 0.0)
}
}
private typealias RefreshCompletion = (_ succeeded: Bool) -> Void
private func refreshTokens(completion: @escaping RefreshCompletion) {
guard !isRefreshing else { return }
isRefreshing = true
oauth.renewAccessToken(
withRefreshToken: oauth.client.credential.oauthRefreshToken,
success: { [weak self] (credential, response, parameters) in
guard let strongSelf = self else { return }
completion(true)
strongSelf.isRefreshing = false
}, failure: { [weak self] (error) in
guard let strongSelf = self else { return }
completion(false)
strongSelf.isRefreshing = false
}
)
}
public func refreshed(_ succeeded: Bool) {}
}
| mit | d0ae9e4db43a96c6473410449253c572 | 33.276923 | 140 | 0.589767 | 5.145497 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Room/TimelineCells/Styles/Plain/PlainRoomCellLayoutConstants.swift | 1 | 1828 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// Plain room cells layout constants
@objcMembers
final class PlainRoomCellLayoutConstants: NSObject {
/// Inner content view margins
static let innerContentViewMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 57, bottom: 0.0, right: 0)
// Reactions
static let reactionsViewTopMargin: CGFloat = 1.0
static let reactionsViewLeftMargin: CGFloat = 55.0
static let reactionsViewRightMargin: CGFloat = 15.0
// Read receipts
static let readReceiptsViewTopMargin: CGFloat = 5.0
static let readReceiptsViewRightMargin: CGFloat = 6.0
static let readReceiptsViewHeight: CGFloat = 16.0
static let readReceiptsViewWidth: CGFloat = 150.0
// Read marker
static let readMarkerViewHeight: CGFloat = 2.0
// Timestamp
static let timestampLabelHeight: CGFloat = 18.0
static let timestampLabelWidth: CGFloat = 39.0
// Others
static let encryptedContentLeftMargin: CGFloat = 15.0
static let urlPreviewViewTopMargin: CGFloat = 8.0
// Threads
static let threadSummaryViewTopMargin: CGFloat = 8.0
static let threadSummaryViewHeight: CGFloat = 40.0
static let fromAThreadViewTopMargin: CGFloat = 8.0
}
| apache-2.0 | 6ed97c8fe901db37c8c0d5520802f2ae | 30.517241 | 108 | 0.723742 | 4.687179 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Components/ChartLimitLine.swift | 12 | 2068 | //
// ChartLimitLine.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
/// The limit line is an additional feature for all Line, Bar and ScatterCharts.
/// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis).
public class ChartLimitLine: ChartComponentBase
{
@objc
public enum ChartLimitLabelPosition: Int
{
case LeftTop
case LeftBottom
case RightTop
case RightBottom
}
/// limit / maximum (the y-value or xIndex)
public var limit = Double(0.0)
private var _lineWidth = CGFloat(2.0)
public var lineColor = NSUIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0)
public var lineDashPhase = CGFloat(0.0)
public var lineDashLengths: [CGFloat]?
public var valueTextColor = NSUIColor.blackColor()
public var valueFont = NSUIFont.systemFontOfSize(13.0)
public var label = ""
public var labelPosition = ChartLimitLabelPosition.RightTop
public override init()
{
super.init()
}
public init(limit: Double)
{
super.init()
self.limit = limit
}
public init(limit: Double, label: String)
{
super.init()
self.limit = limit
self.label = label
}
/// set the line width of the chart (min = 0.2, max = 12); default 2
public var lineWidth: CGFloat
{
get
{
return _lineWidth
}
set
{
if (newValue < 0.2)
{
_lineWidth = 0.2
}
else if (newValue > 12.0)
{
_lineWidth = 12.0
}
else
{
_lineWidth = newValue
}
}
}
} | apache-2.0 | 5fd45263160123d2eca7a900eb5e0801 | 23.341176 | 138 | 0.574468 | 4.263918 | false | false | false | false |
barbosa/clappr-ios | Pod/Classes/Formatter/DateFormatter.swift | 1 | 473 | public class DateFormatter {
private static let hourInSeconds:Double = 1 * 60 * 60
public class func formatSeconds(totalSeconds: NSTimeInterval) -> String {
let date = NSDate(timeIntervalSince1970: totalSeconds)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.dateFormat = totalSeconds < hourInSeconds ? "mm:ss" : "HH:mm:ss"
return formatter.stringFromDate(date)
}
} | bsd-3-clause | 733594b8295234b5dd364157efc46e4d | 42.090909 | 82 | 0.69556 | 4.927083 | false | false | false | false |
cloudant/swift-cloudant | Source/SwiftCloudant/Operations/Documents/PutDocumentOperation.swift | 1 | 3384 | //
// PutDocumentOperation.swift
// SwiftCloudant
//
// Created by stefan kruger on 05/03/2016.
// Copyright (c) 2016 IBM Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
/**
Creates or updates a document.
Usage example:
```
let create = PutDocumentOperation(id: "example", body: ["hello":"world"], databaseName: "exampleDB") { (response, httpInfo, error) in
if let error = error {
// handle the error
} else {
// successfull request.
}
}
```
*/
public class PutDocumentOperation: CouchDatabaseOperation, JSONOperation {
/**
Creates the operation.
- parameter id: the id of the document to create or update, or nil if the server should generate an ID.
- parameter revision: the revision of the document to update, or `nil` if it is a create.
- parameter body: the body of the document
- parameter databaseName: the name of the database where the document will be created / updated.
- parameter completionHandler: optional handler to run when the operation completes.
*/
public init(id: String? = nil, revision: String? = nil, body: [String: Any], databaseName:String, completionHandler: (([String : Any]?, HTTPInfo?, Error?) -> Void)? = nil) {
self.id = id;
self.revision = revision
self.body = body
self.databaseName = databaseName
self.completionHandler = completionHandler
}
public let completionHandler: (([String : Any]?, HTTPInfo?, Error?) -> Void)?
public let databaseName: String
/**
The document that this operation will modify.
*/
public let id: String?
/**
The revision of the document being updated or `nil` if this operation is creating a document.
*/
public let revision: String?
/** Body of document. Must be serialisable with NSJSONSerialization */
public let body: [String: Any]
public func validate() -> Bool {
return JSONSerialization.isValidJSONObject(body)
}
public var method: String {
get {
if let _ = id {
return "PUT"
} else {
return "POST"
}
}
}
public private(set) var data: Data?
public var endpoint: String {
get {
if let id = id {
return "/\(self.databaseName)/\(id)"
} else {
return "/\(self.databaseName)"
}
}
}
public var parameters: [String: String] {
get {
var items:[String:String] = [:]
if let revision = revision {
items["rev"] = revision
}
return items
}
}
public func serialise() throws {
data = try JSONSerialization.data(withJSONObject: body)
}
}
| apache-2.0 | a8b72e65339ea9ef32b0c4c000b4f5ec | 28.426087 | 177 | 0.606678 | 4.610354 | false | false | false | false |
liuchuo/Swift-practice | 20150609-1.playground/Contents.swift | 1 | 411 | //: Playground - noun: a place where people can play
import UIKit
let andSign1:Character = "&"
let andSign2 = "\u{26}"
let lamda1:Character = "λ"
let lamda2 = "\u{03bb}"
let smile1 : Character = "😀"
let smile3 = "\u{001f602}"
let smile4 = "\u{001f602}"
let smile5 = "\u{001f602}"
let smile6 = "\u{001f602}"
let smile7 = "\u{001f701}"
let lalala = "(●'◡'●)ノ♥"
let hahaha = "ヾ(*´∀`*)ノ "
| gpl-2.0 | a1e1df72e036439785e737eb6b4f3b1f | 21.823529 | 52 | 0.618557 | 2.282353 | false | false | false | false |
alskipp/SwiftForms | SwiftForms/descriptors/FormSectionDescriptor.swift | 2 | 901 | //
// FormSectionDescriptor.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import Foundation
public class FormSectionDescriptor: NSObject {
public var headerTitle: String
public var footerTitle: String
public var rows: [FormRowDescriptor] = []
public init(headerTitle: String = "", footerTitle: String = "") {
self.headerTitle = headerTitle
self.footerTitle = footerTitle
}
public func addRow(row: FormRowDescriptor) {
rows.append(row)
}
public func removeRow(row: FormRowDescriptor) {
if let index = rows.indexOf(row) {
rows.removeAtIndex(index)
}
}
}
public func +(section: FormSectionDescriptor, row: FormRowDescriptor) -> FormSectionDescriptor {
section.addRow(row)
return section
}
| mit | 3afc8df50eb71d01f6a9bcedb7563c0c | 24 | 96 | 0.66 | 4.663212 | false | false | false | false |
liyang1217/- | 斗鱼/斗鱼/Casses/Tool/Common.swift | 1 | 320 | //
// Common.swift
// 斗鱼
//
// Created by BARCELONA on 16/9/20.
// Copyright © 2016年 LY. All rights reserved.
//
import UIKit
let kStatusBarH: CGFloat = 20
let kNavigationBarH: CGFloat = 44
let kTabBarH: CGFloat = 44
let kScreenW = UIScreen.main.bounds.width
let kScreenH = UIScreen.main.bounds.height
| mit | 1fc8a659aea5f5343e52efd3f78b7032 | 14.65 | 46 | 0.70607 | 3.260417 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Example/Pods/QuickLayout/QuickLayout/QLCompatibility.swift | 9 | 445 | //
// QLCompatibility.swift
// Pods
//
// Created by Daniel Huri on 5/12/18.
//
import Foundation
public typealias QLAttribute = NSLayoutConstraint.Attribute
public typealias QLRelation = NSLayoutConstraint.Relation
#if os(OSX)
import AppKit
public typealias QLView = NSView
public typealias QLPriority = NSLayoutConstraint.Priority
#else
import UIKit
public typealias QLView = UIView
public typealias QLPriority = UILayoutPriority
#endif
| apache-2.0 | fba4b63b10047d7bef4bfe7e4d4dd301 | 20.190476 | 59 | 0.797753 | 4.278846 | false | false | false | false |
material-motion/motion-transitioning-objc | examples/supplemental/HexColor.swift | 4 | 1422 | /*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
extension UIColor {
private convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(hexColor: Int) {
self.init(red: (hexColor >> 16) & 0xff, green: (hexColor >> 8) & 0xff, blue: hexColor & 0xff)
}
static var primaryColor: UIColor {
return UIColor(hexColor: 0xFF80AB)
}
static var secondaryColor: UIColor {
return UIColor(hexColor: 0xC51162)
}
static var backgroundColor: UIColor {
return UIColor(hexColor: 0x212121)
}
}
| apache-2.0 | b1bfcfdd6718da0581d034ed76be63eb | 31.318182 | 112 | 0.710267 | 3.906593 | false | false | false | false |
wwq0327/iOS9Example | Pinterest/Pinterest/PhotoStreamViewController.swift | 1 | 1282 | //
// PhotoStreamViewController.swift
// RWDevCon
//
// Created by Mic Pringle on 26/02/2015.
// Copyright (c) 2015 Ray Wenderlich. All rights reserved.
//
import UIKit
import AVFoundation
class PhotoStreamViewController: UICollectionViewController {
var photos = Photo.allPhotos()
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
if let patternImage = UIImage(named: "Pattern") {
view.backgroundColor = UIColor(patternImage: patternImage)
}
collectionView!.backgroundColor = UIColor.clearColor()
collectionView!.contentInset = UIEdgeInsets(top: 23, left: 5, bottom: 10, right: 5)
}
}
extension PhotoStreamViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("AnnotatedPhotoCell", forIndexPath: indexPath) as! AnnotatedPhotoCell
cell.photo = photos[indexPath.item]
return cell
}
}
| apache-2.0 | ff720c83dd0f789cd337d44fec44f3db | 26.869565 | 138 | 0.74337 | 5.10757 | false | false | false | false |
dcutting/song | Sources/Song/Interpreter/BuiltIns.swift | 1 | 11841 | func evaluateEq(arguments: [Expression], context: Context) throws -> Expression {
guard arguments.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let result: Expression
do {
result = try booleanOp(arguments: arguments, context: context) {
.bool($0 == $1)
}
} catch EvaluationError.notABoolean {
do {
result = try numberOp(arguments: arguments, context: context) {
try .bool($0.equalTo($1))
}
} catch EvaluationError.notANumber {
do {
result = try characterOp(arguments: arguments, context: context) {
.bool($0 == $1)
}
} catch EvaluationError.notACharacter {
result = try listOp(arguments: arguments, context: context) { left, right in
guard left.count == right.count else { return .no }
for (l, r) in zip(left, right) {
let lrEq = try evaluateEq(arguments: [l, r], context: context)
if case .no = lrEq {
return .no
}
}
return .yes
}
// TODO: need propr equality check for listCons too.
}
}
}
return result
}
func evaluateNeq(arguments: [Expression], context: Context) throws -> Expression {
let equalCall = Expression.call("Eq", arguments)
let notCall = Expression.call("Not", [equalCall])
return try notCall.evaluate(context: context)
}
func evaluateNot(arguments: [Expression], context: Context) throws -> Expression {
var bools = try toBools(arguments: arguments, context: context)
guard bools.count == 1 else { throw EvaluationError.signatureMismatch(arguments) }
let left = bools.removeFirst()
return .bool(!left)
}
func evaluateAnd(arguments: [Expression], context: Context) throws -> Expression {
var bools = try toBools(arguments: arguments, context: context)
guard bools.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = bools.removeFirst()
let right = bools.removeFirst()
return .bool(left && right)
}
func evaluateOr(arguments: [Expression], context: Context) throws -> Expression {
var bools = try toBools(arguments: arguments, context: context)
guard bools.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = bools.removeFirst()
let right = bools.removeFirst()
return .bool(left || right)
}
func evaluateNumberConstructor(arguments: [Expression], context: Context) throws -> Expression {
var numbers = arguments
guard numbers.count == 1 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let result: Expression
do {
let string = try left.evaluate(context: context).asString()
let number = try Number.convert(from: string)
result = .number(number)
} catch EvaluationError.numericMismatch {
throw EvaluationError.notANumber(left)
}
return result
}
func evaluateStringConstructor(arguments: [Expression], context: Context) throws -> Expression {
let output = try prepareOutput(for: arguments, context: context)
return .string(output)
}
func evaluateTruncateConstructor(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 1 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
return .number(left.truncate())
}
func evaluatePlus(arguments: [Expression], context: Context) throws -> Expression {
guard arguments.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let result: Expression
do {
result = try numberOp(arguments: arguments, context: context) {
.number($0.plus($1))
}
} catch EvaluationError.notANumber {
result = try listOp(arguments: arguments, context: context) {
.list($0 + $1)
}
}
return result
}
func evaluateMinus(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
let result: Expression
if numbers.count == 1 {
let right = numbers.removeFirst()
result = .number(right.negate())
} else if numbers.count == 2 {
let left = numbers.removeFirst()
let right = numbers.removeFirst()
result = .number(left.minus(right))
} else {
throw EvaluationError.signatureMismatch(arguments)
}
return result
}
func evaluateTimes(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .number(left.times(right))
}
func evaluateDividedBy(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .number(left.floatDividedBy(right))
}
func evaluateMod(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .number(try left.modulo(right))
}
func evaluateDiv(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .number(try left.integerDividedBy(right))
}
func evaluateLessThan(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .bool(left.lessThan(right))
}
func evaluateGreaterThan(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .bool(left.greaterThan(right))
}
func evaluateLessThanOrEqual(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .bool(left.lessThanOrEqualTo(right))
}
func evaluateGreaterThanOrEqual(arguments: [Expression], context: Context) throws -> Expression {
var numbers = try toNumbers(arguments: arguments, context: context)
guard numbers.count == 2 else { throw EvaluationError.signatureMismatch(arguments) }
let left = numbers.removeFirst()
let right = numbers.removeFirst()
return .bool(left.greaterThanOrEqualTo(right))
}
func evaluateIn(arguments: [Expression], context: Context) throws -> Expression {
let evaluated = try arguments.map { expr -> Expression in try expr.evaluate(context: context) }
let output = evaluated.map { $0.out() }.joined(separator: " ")
_stdOut.put(output)
let line = _stdIn.get() ?? ""
return .string(line)
}
func evaluateOut(arguments: [Expression], context: Context) throws -> Expression {
let output = try prepareOutput(for: arguments, context: context)
_stdOut.put(output + "\n")
return .string(output)
}
func evaluateErr(arguments: [Expression], context: Context) throws -> Expression {
let output = try prepareOutput(for: arguments, context: context)
_stdErr.put(output + "\n")
return .string(output)
}
/* Helpers. */
private func prepareOutput(for arguments: [Expression], context: Context) throws -> String {
let evaluated = try arguments.map { expr -> Expression in try expr.evaluate(context: context) }
return evaluated.map { $0.out() }.joined(separator: " ")
}
private func extractNumber(_ expression: Expression, context: Context) throws -> Number {
if case .number(let number) = try expression.evaluate(context: context) {
return number
}
throw EvaluationError.notANumber(expression)
}
private func extractBool(_ expression: Expression, context: Context) throws -> Bool {
if case .bool(let value) = try expression.evaluate(context: context) {
return value
}
throw EvaluationError.notABoolean(expression)
}
private func extractCharacter(_ expression: Expression, context: Context) throws -> Character {
if case .char(let value) = try expression.evaluate(context: context) {
return value
}
throw EvaluationError.notACharacter
}
private func extractList(_ expression: Expression, context: Context) throws -> [Expression] {
if case .list(let list) = try expression.evaluate(context: context) {
return list
}
throw EvaluationError.notAList(expression)
}
private func toNumbers(arguments: [Expression], context: Context) throws -> [Number] {
return try arguments.map { arg -> Number in
let evaluatedArg = try arg.evaluate(context: context)
guard case let .number(n) = evaluatedArg else {
throw EvaluationError.notANumber(evaluatedArg)
}
return n
}
}
private func toBools(arguments: [Expression], context: Context) throws -> [Bool] {
return try arguments.map { arg -> Bool in
let evaluatedArg = try arg.evaluate(context: context)
guard case let .bool(n) = evaluatedArg else {
throw EvaluationError.notABoolean(evaluatedArg)
}
return n
}
}
private func numberOp(arguments: [Expression], context: Context, callback: (Number, Number) throws -> Expression) throws -> Expression {
var numbers = arguments
let left = try extractNumber(numbers.removeFirst(), context: context)
let right = try extractNumber(numbers.removeFirst(), context: context)
return try callback(left, right)
}
private func booleanOp(arguments: [Expression], context: Context, callback: (Bool, Bool) throws -> Expression) throws -> Expression {
var bools = arguments
let left = try extractBool(bools.removeFirst(), context: context)
let right = try extractBool(bools.removeFirst(), context: context)
return try callback(left, right)
}
private func characterOp(arguments: [Expression], context: Context, callback: (Character, Character) throws -> Expression) throws -> Expression {
var chars = arguments
let left = try extractCharacter(chars.removeFirst(), context: context)
let right = try extractCharacter(chars.removeFirst(), context: context)
return try callback(left, right)
}
private func listOp(arguments: [Expression], context: Context, callback: ([Expression], [Expression]) throws -> Expression) throws -> Expression {
var lists = arguments
let left = try extractList(lists.removeFirst(), context: context)
let right = try extractList(lists.removeFirst(), context: context)
return try callback(left, right)
}
| mit | ee43a5146a16966a1cbe7ececea35ed7 | 39.831034 | 146 | 0.683726 | 4.429854 | false | false | false | false |
kimsand/Jupiter80Librarian | Jupiter80Librarian/Utility/NotificationToken.swift | 1 | 1187 | // Code via <https://oleb.net/blog/2018/01/notificationcenter-removeobserver/>
// Copyright (c) 2018, Ole Begemann. All rights reserved.
import Foundation
/// Wraps the observer token received from
/// NotificationCenter.addObserver(forName:object:queue:using:)
/// and unregisters it in deinit.
final class NotificationToken: NSObject {
let notificationCenter: NotificationCenter
let token: Any
init(notificationCenter: NotificationCenter = .default, token: Any) {
self.notificationCenter = notificationCenter
self.token = token
}
deinit {
notificationCenter.removeObserver(token)
}
}
extension NotificationCenter {
/// Convenience wrapper for addObserver(forName:object:queue:using:)
/// that returns our custom NotificationToken.
func observe(name: NSNotification.Name?,
object obj: Any?,
queue: OperationQueue? = nil,
using block: @escaping (Notification) -> ())
-> NotificationToken
{
let token = addObserver(forName: name, object: obj, queue: queue, using: block)
return NotificationToken(notificationCenter: self, token: token)
}
}
| mit | a3c886c3c4bd4f24faac2ad659e61d1c | 32.914286 | 87 | 0.684078 | 4.904959 | false | false | false | false |
sjf0213/DingShan | DingshanSwift/DingshanSwift/TopBarView.swift | 1 | 1570 | //
// TopBarView.swift
// DingshanSwift
//
// Created by 宋炬峰 on 15/8/29.
// Copyright (c) 2015年 song jufeng. All rights reserved.
//
import Foundation
class TopBarView:UIView
{
var title = ""{
didSet{
self.titleLabel.text = title
}
}
var backBtnHidden = false{
didSet{
self.backBtn.hidden = backBtnHidden
}
}
var backBlock: (() -> Void)? // 最简单的闭包,用来navi返回按钮
private var titleLabel = UILabel()
private var backBtn = UIButton()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame aRect: CGRect) {
super.init(frame: aRect);
self.backgroundColor = NAVI_COLOR
let topline = UIView(frame: CGRect(x: 0, y: TopBar_H - 0.5, width: self.bounds.width, height: 0.5))
topline.backgroundColor = UIColor.grayColor()
self.addSubview(topline)
titleLabel = UILabel(frame: CGRect(x:44, y:20, width:self.bounds.size.width - 88, height:self.bounds.size.height - 20))
titleLabel.textAlignment = NSTextAlignment.Center
self.addSubview(titleLabel)
backBtn.frame = CGRect(x: 0, y: 20, width: 44, height: 44)
backBtn.setImage(UIImage(named:"back_btn"), forState: UIControlState.Normal)
self.addSubview(backBtn)
backBtn.addTarget(self, action: Selector("onTapBack"), forControlEvents: UIControlEvents.TouchUpInside)
}
func onTapBack() {
self.backBlock?()
}
} | mit | 7c8c8b5bdfc04f03ef6c7c271104d3b0 | 28.557692 | 127 | 0.617839 | 3.98961 | false | false | false | false |
wbraynen/SwiftMusicPlayer | MusicPlayer/Album.swift | 1 | 3332 | //
// Album.swift
// MusicPlayer2
//
// Created by William Braynen on 12/2/15.
// Copyright © 2015 Will Braynen. All rights reserved.
//
import UIKit
class Album: CustomStringConvertible {
let filenameFor100image, filenameFor375image, filenameFor1400image: String
let title, year, filenameBase: String
let tracks: [String]
var totalTracks: Int {
return tracks.count
}
var description: String {
return "(\(year)) \(title)"
}
required init( title: String, year: String, filenameBase: String ) {
self.title = title
self.year = year
self.tracks = Album.fetchTracks( title )
self.filenameBase = filenameBase
self.filenameFor100image = "\(filenameBase).100.jpg"
self.filenameFor375image = "\(filenameBase).375.jpg"
self.filenameFor1400image = "\(filenameBase).1400.jpg"
}
class func fetchTracks( albumTitle: String ) -> [String] {
let slowTracks = [
"It's Hard To Hear",
"I'm Grillin My Meat And There Is Enough For Two",
"The Foreboding: The Neighbors Are Quiet",
"[Outtakes] Whispers",
"A Tiger Is Not A Submarine",
"I'm [on?] A Mountain Top",
"Hush",
"Summertime",
"[Outtakes] Aengus's Got A Ride"]
let birdsheartTracks = [
"Julia's Bedtime Song: Uncle Vills, I Want to Go to the Forest",
"Fall On Your Back, Wake Up in the Sun",
"The Bird's Heart: A Song in Nine Parts - II. The Muttering Sound Gone",
"Fairy Dream Maker with a Stitched Cello",
"Ambience Forging",
"Mango Dog",
"Why Muertos?",
"'Mountain Bike and Upright Meet in Forest' by Bart Fade 'Em",
"Fairy Dream Maker without a Stitched Cello",
"Someone Is Watching the Telly",
"They Took My Pitcherometer",
"Dissatisfaction",
"Weird",
"The Three of Us Are a Little Drunk But We Are Friendly"]
let valentinevignettes = [
"The Chord",
"Valentine #3",
"Valentine #",
"Valetine",
"Thingy",
"Silliness"]
let pipesanddreams = [
"Birds Calling in the Ravine",
"Laconic Trio",
"(Haiku Of) Raindrops",
"Palo Alto",
"Rêverie", // Unicode support :)
"The Little One With the Big One",
"The Big One: Shouldn't've Eaten the Little One! (But Then Feeling Better)",
"Serejka Plans Improv"]
let awaketooearly = [
"Awake Too Early",
"You are Sweet, but Your Sweetness Has Hurt Me",
"Stewardess of Jalapenos",
"844 Miles",
"Delo Hozyaiskoe",
"Marginal Love",
"You Take My Heart To Strangers"]
// album titles : tracks names
let allTracks = [
"Slow" : slowTracks,
"The Bird's Heart": birdsheartTracks,
"Valentine Vignettes": valentinevignettes,
"Pipes and Dreams": pipesanddreams,
"Awake Too Early": awaketooearly]
return allTracks[albumTitle]!
}
}
| mit | 4c3a66f40a652153b953d49c589aa3de | 31.647059 | 88 | 0.545045 | 4.041262 | false | false | false | false |
ctarda/blogsamples | open-closed-principle/Step2/OpenClosedPrincipleStep2.playground/section-1.swift | 1 | 2712 | /*
The backend provides a Program object in the services response. Also, it provides a "type" that identifies the type of program.
*/
enum ProgramType {
case Movie
case Episode
case LiveProgram
}
// Simplified Program, for the shake of the example.
class Program {
private(set) var title: String
private(set) var type: ProgramType
init(title: String, type: ProgramType) {
self.title = title
self.type = type
}
}
// Protocol that abstract the behaviour: navigating to the view that contains the Program's extended info.
protocol Router {
func canHandleProgram(program: Program)->Bool
func navigateTo(program: Program)
}
// Implementation of the Router protocol that navigates to the Movie extended info
final class MovieRouter: Router {
func canHandleProgram(program: Program)->Bool {
return program.type == .Movie
}
func navigateTo(program: Program) {
println("It is a movie, navigate to Movie Details")
}
}
// Implementation of the Router protocol that navigates to the Episode extended info
final class EpisodeRouter: Router {
func canHandleProgram(program: Program)->Bool {
return program.type == .Episode
}
func navigateTo(program: Program) {
println("It is an Episode, navigate to Episode Details")
}
}
// Implementation of the Router protocol that navigates to the LiveProgram extended info
final class LiveProgramRouter: Router {
func canHandleProgram(program: Program)->Bool {
return program.type == .LiveProgram
}
func navigateTo(program: Program) {
println("It is a LiveProgram, navigate to Live Program Details")
}
}
/*
Function to be called when the user taps a program. All logic related to navigation has been removed from this function. A naive implementation of this method would loop the routers array, and when it finds one that responds true to canHandleProgram, it would call navigateTo on it.
Here, we use the first element returned by filter. If we add more routers, we do not need to touch this method. If the implementation of Program changes we do not need to touch this method either.
*/
func navigateToDetails(program: Program, routers:[Router]) {
let matchingRouters = routers.filter({$0.canHandleProgram(program)})
if let router = matchingRouters.first {
router.navigateTo(program)
}
}
let routers:[Router] = [MovieRouter(), EpisodeRouter(), LiveProgramRouter()]
let sampleMovie = Program(title: "The Quiet Man", type: .Movie)
let sampleEpisode = Program(title: "CSI: S43E02", type: .Episode)
navigateToDetails(sampleMovie, routers)
//navigateToDetails(sampleEpisode, routers)
| mit | 36313b128312c0a35c282d421d7e278b | 33.769231 | 286 | 0.719027 | 4.374194 | false | false | false | false |
MrSongzj/MSDouYuZB | MSDouYuZB/MSDouYuZB/Classes/Main/Controller/CustomNavigationController.swift | 1 | 1504 | //
// CustomNavigationController.swift
// MSDouYuZB
//
// Created by jiayuan on 2017/8/11.
// Copyright © 2017年 mrsong. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
guard let systemGes = interactivePopGestureRecognizer else { return }
// 取出 View
guard let gesView = systemGes.view else { return }
/*
// 打印一个类里的成员变量
var count: UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0 ..< Int(count) {
let ivar = ivars[i]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
*/
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targetObjc = targets?.first else { return }
// 取出 target
guard let target = targetObjc.value(forKey: "target") else { return }
// 取出 action
let action = Selector(("handleNavigationTransition:"))
// 创建自定义手势
let panGes = UIPanGestureRecognizer(target: target, action: action)
gesView.addGestureRecognizer(panGes)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
| mit | 9b0ebd0a3fdec17b66096aa85eea25e2 | 32.022727 | 90 | 0.631108 | 4.763934 | false | false | false | false |
dduan/swift | validation-test/compiler_crashers_fixed/01274-resolvetypedecl.swift | 11 | 812 | // 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
// RUN: not %target-swift-frontend %s -parse
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
nType, Bool) -> Bool {
}
protocol A {
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
}
}
struct d<f : e, g: e where g.h == f.h> {
}
protocol e {
}
func b(c) -> <d>(() -> d) {
}
protocol A {
}
struct X<Y> : A {
func b(b: X.Type) {
}
}
protocol a {
}
class b<h : c, i : c where h.g == i> : a {
}
struct c<d, e: b where d.c == e> {
| apache-2.0 | 7a4f771b2a3892dff51298c18d35d627 | 21.555556 | 78 | 0.608374 | 2.671053 | false | false | false | false |
Restofire/Restofire-Gloss | Tests/ServiceSpec/ServiceSpec.swift | 1 | 1465 | // _____ ____ __.
// / _ \ _____ _______ | |/ _|____ ___.__.
// / /_\ \\__ \\_ __ \ | < \__ \< | |
// / | \/ __ \| | \/ | | \ / __ \\___ |
// \____|__ (____ /__| |____|__ (____ / ____|
// \/ \/ \/ \/\/
//
// Copyright (c) 2015 RahulKatariya. All rights reserved.
//
import Quick
import Nimble
import Alamofire
import Restofire
class ServiceSpec: QuickSpec {
let timeout: NSTimeInterval = 21
let pollInterval: NSTimeInterval = 3
override func spec() {
beforeSuite {
Restofire.defaultConfiguration.baseURL = "http://www.mocky.io/v2/"
Restofire.defaultConfiguration.headers = ["Content-Type": "application/json"]
Restofire.defaultConfiguration.validation.acceptableStatusCodes = [200..<201]
Restofire.defaultConfiguration.validation.acceptableContentTypes = ["application/json"]
Restofire.defaultConfiguration.logging = true
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.timeoutIntervalForRequest = 10
sessionConfiguration.timeoutIntervalForResource = 10
sessionConfiguration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders
Restofire.defaultConfiguration.manager = Alamofire.Manager(configuration: sessionConfiguration)
}
}
}
| mit | b8aef9795230b3384c132efab1373009 | 36.564103 | 107 | 0.567235 | 4.771987 | false | true | false | false |
jbruce2112/cutlines | Cutlines/View/PolaroidView.swift | 1 | 1089 | //
// PolaroidView.swift
// Cutlines
//
// Created by John on 3/6/17.
// Copyright © 2017 Bruce32. All rights reserved.
//
import Foundation
import UIKit
/// PolaroidView sets the style
/// of a UIImageView to resemble a polaroid photo.
class PolaroidView: UIView {
var image: UIImage?
private var imageView = UIImageView()
override func layoutSubviews() {
super.layoutSubviews()
imageView.image = image
addSubview(imageView)
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFill
imageView.translatesAutoresizingMaskIntoConstraints = false
var constraints = [NSLayoutConstraint]()
constraints.append(imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 15))
constraints.append(imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15))
constraints.append(imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15))
constraints.append(imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -60))
NSLayoutConstraint.activate(constraints)
}
}
| mit | a4a170d99f1ff8ef3b5b2f796d845a1f | 26.897436 | 102 | 0.762868 | 4.217054 | false | false | false | false |
exsortis/TenCenturiesKit | Sources/TenCenturiesKit/Models/UploadError.swift | 1 | 848 | import Foundation
public struct UploadError {
public let name : String
public let size : Int
public let type : String
public let reason : String
}
extension UploadError : Serializable {
public init?(from json: JSONDictionary) {
guard let name = json["name"] as? String,
let size = json["size"] as? Int,
let type = json["type"] as? String,
let reason = json["reason"] as? String
else { return nil }
self.name = name
self.size = size
self.type = type
self.reason = reason
}
public func toDictionary() -> JSONDictionary {
let dict : JSONDictionary = [
"name" : name,
"size" : size,
"type" : type,
"reason" : reason,
]
return dict
}
}
| mit | 40d58eaac183fbb9c851b281f18e1923 | 21.315789 | 50 | 0.523585 | 4.583784 | false | false | false | false |
colinhumber/UIScrollView-InfiniteScroll | InfiniteScrollViewDemoSwift/CustomInfiniteIndicator.swift | 3 | 3858 | //
// CustomInfiniteIndicator.swift
// InfiniteScrollViewDemoSwift
//
// Created by pronebird on 5/3/15.
// Copyright (c) 2015 pronebird. All rights reserved.
//
import UIKit
private let rotationAnimationKey = "rotation"
class CustomInfiniteIndicator: UIView {
var thickness: CGFloat = 2
var outerColor = UIColor.grayColor().colorWithAlphaComponent(0.2)
lazy var innerColor: UIColor = {
return self.tintColor
}()
private var animating = false
private let innerCircle = CAShapeLayer()
private let outerCircle = CAShapeLayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
unregisterFromAppStateNotifications()
}
override func layoutSublayersOfLayer(layer: CALayer!) {
setupBezierPaths()
}
override func didMoveToWindow() {
super.didMoveToWindow()
if window != nil {
restartAnimationIfNeeded()
}
}
// MARK: - Private
private func commonInit() {
registerForAppStateNotifications()
hidden = true
backgroundColor = UIColor.clearColor()
outerCircle.strokeColor = outerColor.CGColor
outerCircle.fillColor = UIColor.clearColor().CGColor
outerCircle.lineWidth = thickness
innerCircle.strokeColor = innerColor.CGColor
innerCircle.fillColor = UIColor.clearColor().CGColor
innerCircle.lineWidth = thickness
layer.addSublayer(outerCircle)
layer.addSublayer(innerCircle)
}
private func addAnimation() {
layer.addAnimation(animation(), forKey: rotationAnimationKey)
}
func restartAnimationIfNeeded() {
let anim = layer.animationForKey(rotationAnimationKey)
if animating && anim == nil {
addAnimation()
}
}
private func registerForAppStateNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "restartAnimationIfNeeded", name: UIApplicationWillEnterForegroundNotification, object: nil)
}
private func unregisterFromAppStateNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func animation() -> CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.toValue = NSNumber(double: M_PI * 2)
animation.duration = 1
animation.repeatCount = Float.infinity
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
return animation
}
private func setupBezierPaths() {
let center = CGPointMake(bounds.size.width * 0.5, bounds.size.height * 0.5)
let radius = bounds.size.width * 0.5 - thickness
let ringPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(0), endAngle: CGFloat(M_PI * 2), clockwise: true)
let quarterRingPath = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(-M_PI_4), endAngle: CGFloat(M_PI_2 - M_PI_4), clockwise: true)
outerCircle.path = ringPath.CGPath
innerCircle.path = quarterRingPath.CGPath
}
// MARK: - Public
func isAnimating() -> Bool {
return animating
}
func startAnimating() {
if animating {
return
}
animating = true
hidden = false
addAnimation()
}
func stopAnimationg() {
if !animating {
return
}
animating = false
hidden = true
layer.removeAnimationForKey(rotationAnimationKey)
}
}
| mit | 9219bd3a73fd534e67493a7f4cf3c65a | 27.367647 | 165 | 0.630119 | 5.292181 | false | false | false | false |
KYawn/myiOS | WeatherBeauty/WeatherBeauty/ViewController.swift | 1 | 2124 | //
// ViewController.swift
// WeatherBeauty
//
// Created by K.Yawn Xoan on 3/16/15.
// Copyright (c) 2015 K.Yawn Xoan. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var weatherNum: UILabel!
@IBOutlet weak var cityName: UILabel!
@IBOutlet weak var image3: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var url = "https://api.thinkpage.cn/v2/weather/now.json?city=beijing&language=zh-chs&unit=c&key=PLXYYE660V"
var req = NSURLRequest(URL: NSURL(string: url)!)
NSURLConnection.sendAsynchronousRequest(req, queue: NSOperationQueue()) { (_, data, e) -> Void in
if e == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let json:AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: nil, error:nil) {
var weatherInfo:AnyObject? = json?.objectForKey("weather")!
var firstArray:AnyObject? = (weatherInfo as NSArray).objectAtIndex(0)
var myCityName = firstArray?.objectForKey("city_name")! as NSString
var nowWeather: AnyObject? = (firstArray as NSDictionary).objectForKey("now")
var pictureCode = nowWeather?.objectForKey("code") as NSString
var temperature = nowWeather?.objectForKey("temperature") as NSString
self.cityName.text = myCityName
self.image3.image = UIImage(named: "\(pictureCode)")
self.weatherNum.text = "\(temperature)°"
}
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 6dcbe4cbd5fb0d00eca32d05629acb02 | 36.910714 | 116 | 0.54781 | 5.16545 | false | false | false | false |
icanzilb/RxGesture | Example/RxGesture/ViewController.swift | 1 | 6147 | //
// ViewController.swift
// RxGesture
//
// Created by Marin Todorov on 03/22/2016.
// Copyright (c) 2016 Marin Todorov. All rights reserved.
//
import UIKit
import RxSwift
import RxGesture
let infoList = [
"Tap the red square",
"Swipe the square down",
"Swipe horizontally (e.g. left or right)",
"Do a long press",
"Drag the square to a different location",
"Rotate the square",
"Do either a tap, long press, or swipe in any direction"
]
let codeList = [
"myView.rx.gesture(.tap).subscribeNext {...}",
"myView.rx.gesture(.swipeDown).subscribeNext {...}",
"myView.rx.gesture(.swipeLeft, .swipeRight).subscribeNext {",
"myView.rx.gesture(.longPress).subscribeNext {...}",
"myView.rx.gesture(.pan(.changed), .pan(.ended)]).subscribeNext {...}",
"myView.rx.gesture(.rotate(.changed), .rotate(.ended)]).subscribeNext {...}",
"myView.rx.gesture().subscribeNext {...}"
]
class ViewController: UIViewController {
@IBOutlet var myView: UIView!
@IBOutlet var myViewText: UILabel!
@IBOutlet var info: UILabel!
@IBOutlet var code: UITextView!
private let nextStep😁 = PublishSubject<Void>()
private let bag = DisposeBag()
private var stepBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
nextStep😁.scan(0, accumulator: {acc, _ in
return acc < 6 ? acc + 1 : 0
})
.startWith(0)
.subscribe(onNext: step)
.addDisposableTo(bag)
}
func step(step: Int) {
//release previous recognizers
stepBag = DisposeBag()
info.text = "\(step+1). \(infoList[step])"
code.text = codeList[step]
//add current step recognizer
switch step {
case 0: //tap recognizer
myView.rx.gesture(.tap).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.backgroundColor = UIColor.blue
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 1: //swipe down
myView.rx.gesture(.swipeDown).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform(scaleX: 1.0, y: 2.0)
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 2: //swipe horizontally
myView.rx.gesture(.swipeLeft, .swipeRight).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 3: //long press
myView.rx.gesture(.longPress).subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
case 4: //panning
myView.rx.gesture(.pan(.changed)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .pan(let data):
this.myViewText.text = "(\(data.translation.x), \(data.translation.y))"
this.myView.transform = CGAffineTransform(translationX: data.translation.x, y: data.translation.y)
default: break
}
}).addDisposableTo(stepBag)
myView.rx.gesture(.pan(.ended)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .pan(_):
UIView.animate(withDuration: 0.5, animations: {
this.myViewText.text = nil
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
default: break
}
}).addDisposableTo(stepBag)
case 5: //rotating
myView.rx.gesture(.rotate(.changed)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .rotate(let data):
this.myViewText.text = String(format: "angle: %.2f", data.rotation)
this.myView.transform = CGAffineTransform(rotationAngle: data.rotation)
default: break
}
}).addDisposableTo(stepBag)
myView.rx.gesture(.rotate(.ended)).subscribe(onNext: {[weak self] gesture in
guard let this = self else {return}
switch gesture {
case .rotate(_):
UIView.animate(withDuration: 0.5, animations: {
this.myViewText.text = nil
this.myView.transform = CGAffineTransform.identity
this.nextStep😁.onNext()
})
default: break
}
}).addDisposableTo(stepBag)
case 6: //any gesture
myView.rx.gesture().subscribe(onNext: {[weak self] _ in
guard let this = self else {return}
UIView.animate(withDuration: 0.5, animations: {
this.myView.backgroundColor = UIColor.red
this.nextStep😁.onNext()
})
}).addDisposableTo(stepBag)
default: break
}
print("active gestures: \(myView.gestureRecognizers!.count)")
}
}
| mit | 5322d39f7970b0875541dc40c300e3df | 36.546012 | 118 | 0.535131 | 4.818898 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/CliqzTabButton.swift | 2 | 1736 | //
// CliqzTabButton.swift
// Client
//
// Created by Sahakyan on 8/11/16.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
import SnapKit
class CliqzTabsButton: TabsButton {
let BackgroundInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
fileprivate var _image: UIImage?
var image: UIImage? {
set {
_image = newValue?.withRenderingMode(.alwaysTemplate)
self.backgroundImage.image = _image
}
get {
return _image
}
}
lazy var backgroundImage: UIImageView = {
let imageView = UIImageView()
if let i = self.image {
imageView.image = i
}
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.backgroundImage)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
super.updateConstraints()
backgroundImage.snp_remakeConstraints { (make) -> Void in
make.edges.equalTo(self).inset(BackgroundInsets)
}
}
override func clone() -> UIView {
let button = CliqzTabsButton()
button.accessibilityLabel = accessibilityLabel
button.title.text = title.text
// Copy all of the styable properties over to the new TabsButton
button.title.font = title.font
button.title.textColor = title.textColor
button.title.layer.cornerRadius = title.layer.cornerRadius
button.titleBackgroundColor = self.titleBackgroundColor
button.borderWidth = self.borderWidth
button.borderColor = self.borderColor
button.image = image
return button
}
override dynamic var textColor: UIColor? {
get { return title.textColor }
set {
title.textColor = newValue
self.backgroundImage.tintColor = textColor
}
}
}
| mpl-2.0 | d5b3e5255602f7ee820db0539a4b1a1e | 21.24359 | 74 | 0.718732 | 3.675847 | false | false | false | false |
zixun/CocoaChinaPlus | Code/CocoaChinaPlus/Application/Business/CocoaChina/Profile/CCAboutViewController.swift | 1 | 1048 | //
// CCAboutViewController.swift
// CocoaChinaPlus
//
// Created by zixun on 15/10/3.
// Copyright © 2015年 zixun. All rights reserved.
//
import UIKit
class CCAboutViewController: ZXBaseViewController {
fileprivate var scrollView:UIScrollView!
required init(navigatorURL URL: URL?, query: Dictionary<String, String>) {
super.init(navigatorURL: URL, query: query)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView = UIScrollView(frame: self.view.bounds)
self.scrollView.delegate = self
self.view.addSubview(self.scrollView)
let imageview = UIImageView(image: R.image.about())
imageview.frame = self.scrollView.bounds
imageview.autoresizingMask = UIViewAutoresizing.flexibleHeight
self.scrollView.addSubview(imageview)
}
}
extension CCAboutViewController : UIScrollViewDelegate {
}
| mit | 95581ef1d63dc98c74a819d468d3b955 | 25.794872 | 78 | 0.677512 | 4.465812 | false | false | false | false |
mshhmzh/firefox-ios | Utils/AppInfo.swift | 4 | 2164 | /* 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
public class AppInfo {
public static var appVersion: String {
return NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
}
public static var majorAppVersion: String {
return appVersion.componentsSeparatedByString(".").first ?? "0"
}
/// Return the shared container identifier (also known as the app group) to be used with for example background
/// http requests. It is the base bundle identifier with a "group." prefix.
public static func sharedContainerIdentifier() -> String? {
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
return "group." + baseBundleIdentifier
}
return nil
}
/// Return the keychain access group.
public static func keychainAccessGroupWithPrefix(prefix: String) -> String? {
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
return prefix + "." + baseBundleIdentifier
}
return nil
}
/// Return the base bundle identifier.
///
/// This function is smart enough to find out if it is being called from an extension or the main application. In
/// case of the former, it will chop off the extension identifier from the bundle since that is a suffix not part
/// of the *base* bundle identifier.
public static func baseBundleIdentifier() -> String? {
let bundle = NSBundle.mainBundle()
if let packageType = bundle.objectForInfoDictionaryKey("CFBundlePackageType") as? NSString {
if let baseBundleIdentifier = bundle.bundleIdentifier {
if packageType == "XPC!" {
let components = baseBundleIdentifier.componentsSeparatedByString(".")
return components[0..<components.count-1].joinWithSeparator(".")
}
return baseBundleIdentifier
}
}
return nil
}
} | mpl-2.0 | 8ffdbe2baa66f2f431552f4c7c55bf6c | 41.45098 | 117 | 0.660351 | 5.396509 | false | false | false | false |
ShengHuaWu/SHGradientColorView | SHGradientColorView/ViewController.swift | 1 | 1467 | //
// ViewController.swift
// SHGradientColorView
//
// Created by WuShengHua on 5/4/15.
// Copyright (c) 2015 ShengHuaWu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var gradientColorView: SHGradientColorView? = nil
// MARK: View life cycle
override func viewDidLoad() {
super.viewDidLoad()
let frame = CGRectMake(30, 100, 300, 60)
let gradientColorView = SHGradientColorView(frame: frame, startColor: UIColor.yellowColor(), endColor: UIColor.blueColor(), direction: SHGradientDirection.horizontal)
self.view.addSubview(gradientColorView)
self.gradientColorView = gradientColorView
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.frame = CGRectMake(150, 200, 80, 44)
button.setTitle("Change", forState: UIControlState.Normal)
button.setTitleColor(UIColor.redColor(), forState: UIControlState.Normal)
button.addTarget(self, action: "changeColor:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
}
// MARK: Button action
func changeColor(button: UIButton) {
if let gradientView = self.gradientColorView {
// gradientView.startColor = UIColor.redColor()
// gradientView.endColor = UIColor.greenColor()
gradientView.direction = SHGradientDirection.vertical
}
}
}
| mit | 252fc36516647835e63afea3412c3fba | 34.780488 | 174 | 0.685072 | 4.747573 | false | false | false | false |
NickAger/NADocumentPicker | Pod/Classes/NADocumentPicker.swift | 1 | 3325 | //
// NADocumentPicker.swift
// Encapsulates UIKit document picker UI
// iDiffView
//
// "Why doesn't Dropbox support iOS's open dialog?" - see discussion here: https://www.dropboxforum.com/hc/en-us/community/posts/204836509-Why-doesn-t-Dropbox-support-iOS-s-open-dialog-
//
// Created by Nick Ager on 25/01/2016.
// Copyright © 2016 RocketBox Ltd. All rights reserved.
//
import UIKit
import MobileCoreServices
import BrightFutures
/**
Error type for `NADocumentPicker`
- NoDocumentPicked: is the error returned by the `Future`
from `show` when no document is choosen by the user.
*/
public enum NADocumentPickerErrors: Error {
case noDocumentPicked
}
/**
Encapsulates UIKit document picker UI, providing a simple API.
`show` is the only API entry.
*/
open class NADocumentPicker : NSObject {
fileprivate let parentViewController: UIViewController
fileprivate var keepInMemory: NADocumentPicker?
/*private*/ let promise = Promise<URL, Error>()
/**
Shows the document picker, returning a `Future` containing the document picked
or `NoDocumentPicked`.
See also:
- [nickager.com](http://nickager.com/blog/2016/03/07/DocumentPicker)
- [github](https://github.com/NickAger/NADocumentPicker)
- Parameter view: The view from which the popover document menu appears
- Parameter parentViewController: The associated parent view controller
- Parameter documentTypes: An array of document types to be opened, by default PlainText
- Returns: A `Future` containing the document picked or `NoDocumentPicked`
*/
open class func show(from view: UIView, parentViewController: UIViewController, documentTypes: [String] = [kUTTypePlainText as String]) -> Future<URL, Error> {
let instance = NADocumentPicker(parentViewController: parentViewController)
return instance.showDocumentPicker(from: view, parentViewController: parentViewController, documentTypes: documentTypes)
}
/*private*/ init(parentViewController: UIViewController) {
self.parentViewController = parentViewController
super.init()
keepInMemoryUntilComplete()
}
private func showDocumentPicker(from view: UIView, parentViewController: UIViewController, documentTypes: [String]) -> Future<URL, Error> {
let documentPicker = UIDocumentPickerViewController(documentTypes:documentTypes, in: UIDocumentPickerMode.open)
documentPicker.delegate = self
parentViewController.present(documentPicker, animated: true)
return promise.future
}
private func keepOurselvesInMemory() {
keepInMemory = self
}
private func freeOurselvesFromMemory() {
keepInMemory = nil
}
private func keepInMemoryUntilComplete() {
keepOurselvesInMemory()
self.promise.future.onComplete { [unowned self] _ in
self.freeOurselvesFromMemory()
}
}
}
// MARK: UIDocumentPickerDelegate
extension NADocumentPicker : UIDocumentPickerDelegate {
public func documentPicker(_: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
promise.success(url)
}
public func documentPickerWasCancelled(_: UIDocumentPickerViewController) {
promise.failure(NADocumentPickerErrors.noDocumentPicked)
}
}
| mit | df4381fef8ff54e0d7b57e44e379e544 | 34.361702 | 186 | 0.724128 | 4.688293 | false | false | false | false |
jongensvantechniek/CoreData-CRUD-Swift-3.1-example | CoreDataCRUD/HTTPStatusCode.swift | 1 | 2548 | //
// HTTPStatusCode.swift
// CoreDataCRUD
//
// Copyright © 2016 Jongens van Techniek. All rights reserved.
//
import Foundation
/**
Enum for HTTP response codes.
*/
enum HTTPStatusCode: Int {
//1xx Informationals
case `continue` = 100
case switchingProtocols = 101
//2xx Successfuls
case ok = 200
case created = 201
case accepted = 202
case nonAuthoritativeInformation = 203
case noContent = 204
case resetContent = 205
case partialContent = 206
//3xx Redirections
case multipleChoices = 300
case movedPermanently = 301
case found = 302
case seeOther = 303
case notModified = 304
case useProxy = 305
case unused = 306
case temporaryRedirect = 307
//4xx Client Errors
case badRequest = 400
case unauthorized = 401
case paymentRequired = 402
case forbidden = 403
case notFound = 404
case methodNotAllowed = 405
case notAcceptable = 406
case proxyAuthenticationRequired = 407
case requestTimeout = 408
case conflict = 409
case gone = 410
case lengthRequired = 411
case preconditionFailed = 412
case requestEntityTooLarge = 413
case requestURITooLong = 414
case unsupportedMediaType = 415
case requestedRangeNotSatisfiable = 416
case expectationFailed = 417
//5xx Server Errors
case internalServerError = 500
case notImplemented = 501
case badGateway = 502
case serviceUnavailable = 503
case gatewayTimeout = 504
case httpVersionNotSupported = 505
static let getAll = [
`continue`,
switchingProtocols,
ok,
created,
accepted,
nonAuthoritativeInformation,
noContent,
resetContent,
partialContent,
multipleChoices,
movedPermanently,
found,
seeOther,
notModified,
useProxy,
unused,
temporaryRedirect,
badRequest,
unauthorized,
paymentRequired,
forbidden,
notFound,
methodNotAllowed,
notAcceptable,
proxyAuthenticationRequired,
requestTimeout,
conflict,
gone,
lengthRequired,
preconditionFailed,
requestEntityTooLarge,
requestURITooLong,
unsupportedMediaType,
requestedRangeNotSatisfiable,
expectationFailed,
internalServerError,
notImplemented,
badGateway,
serviceUnavailable,
gatewayTimeout,
httpVersionNotSupported
]
}
| mit | f4986eb543bcf2ab2f0fac0c670d2c0e | 22.154545 | 63 | 0.64311 | 5.176829 | false | false | false | false |
GeoThings/LakestoneCore | Source/extension_Location.swift | 1 | 1806 | //
// extension_Location.swift
// geoBingAnKit
//
// Created by Taras Vozniuk on 10/25/16.
// Copyright © 2016 GeoThings. 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.
#if COOPER
import android.location
#else
import CoreLocation
#endif
extension Location {
#if COOPER
public var latitude: Double {
return self.getLatitude()
}
public var longitude: Double {
return self.getLongitude()
}
public init(latitude: Double, longitude: Double){
let targetLocation = Location("LakestoneCore.Location")
targetLocation.setLatitude(latitude)
targetLocation.setLongitude(longitude)
return targetLocation
}
#endif
public func adding(meters: Double) -> Location {
let earthRadius: Double = 6371 * 1000
#if COOPER
let pi = Math.PI
#else
let pi = Double.pi
#endif
let newLatitude = self.latitude + (meters / earthRadius) * (180.0 / pi)
#if COOPER
let newLongitude = self.longitude + (meters / earthRadius) * (180.0 / pi) / Math.cos(self.latitude * pi / 180.0)
#else
let newLongitude = self.longitude + (meters / earthRadius) * (180.0 / pi) / cos(self.latitude * pi / 180.0)
#endif
return Location(latitude: newLatitude, longitude: newLongitude)
}
}
| apache-2.0 | a8f84557ba01f1736884e9c3fc0872b0 | 25.15942 | 115 | 0.686981 | 3.661258 | false | false | false | false |
ImperialDevelopment/IDPopup | IDPopup/Classes/IDPopupController.swift | 1 | 11156 | //
// IDPopupController.swift
//
// Created by Michael Schoder on 11.08.17.
//
//
import UIKit
/// Controller class which manages showing and dismissing Popups and the view hierarchy.
class IDPopupController {
/// Stored instance of the IDPopupController
fileprivate static var instance: IDPopupController?
/// Singleton instance of the IDPopupController. Checks if a view hierarchy setup is needed and setups if so.
static var shared: IDPopupController {
if let instance = instance {
instance.setupViewHierachyIfNeeded()
return instance
} else {
instance = IDPopupController()
instance?.setupViewHierachyIfNeeded()
return instance!
}
}
/// UIWindow on which the IDPopups are displayed. Level is 1 under the Statusbar.
fileprivate var popupWindow: PopupWindow!
/// Array of currently shown Popups in order they got added.
fileprivate var shownPopups = [IDPopup]()
/// Dictionary of Popups by Identifiers.
fileprivate var showPopupsByIdentifiers = [String: IDPopup]()
/// Array of currently shown identified Popups.
fileprivate var shownIdentifiers: [String] {
return Array(showPopupsByIdentifiers.keys)
}
/// Configuration which is used in the IDPopupController
fileprivate var configuration: IDPopupConfiguration {
return IDPopupConfiguration.current
}
// MARK: - View Hierachy Preperation
/// Flag if a setup of the view hierarchy is needed. Checked by checking if self.popupWindow is nil
fileprivate var viewHierachySetupNeeded: Bool {
return popupWindow == nil
}
/// Initializes and shows the popupWindow if needed.
fileprivate func setupViewHierachyIfNeeded() {
if viewHierachySetupNeeded {
let screenSize = UIScreen.main.bounds.size
popupWindow = PopupWindow(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height))
popupWindow.windowLevel = UIWindowLevelStatusBar - 1
popupWindow.backgroundColor = UIColor.clear
popupWindow.isUserInteractionEnabled = true
popupWindow.isHidden = false
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
}
}
// MARK: - Popup Handling
/// Shows the given IDPopup and manages the Constraints and Animations. The new Popup is inserted in the view hierarchy at index 0. PopupOverflow is managed, if needed.
///
/// - Parameter popup: IDPopup to be shown
func show(_ popup: IDPopup) {
if configuration.ignoredPopupClasses.contains(where: { (popupType) in
return popup.isKind(of: popupType)
}) {
return
}
if let identifier = popup.identifier {
if shownIdentifiers.contains(identifier) {
if let popupForIdentifier = showPopupsByIdentifiers[identifier] {
popupForIdentifier.text = popup.text
popupForIdentifier.shake()
return
}
}
}
popup.translatesAutoresizingMaskIntoConstraints = false
popupWindow.insertSubview(popup, at: 0)
popup.bottomConstraint = NSLayoutConstraint(item: popup, attribute: .bottom, relatedBy: .equal, toItem: popupWindow, attribute: .bottom, multiplier: 1.0, constant: configuration.popupHeight)
popup.leftConstraint = NSLayoutConstraint(item: popup, attribute: .leading, relatedBy: .equal, toItem: popupWindow, attribute: .leading, multiplier: 1.0, constant: configuration.leftPopupInset)
popup.rightContraint = NSLayoutConstraint(item: popup, attribute: .trailing, relatedBy: .equal, toItem: popupWindow, attribute: .trailing, multiplier: 1.0, constant: -configuration.rightPopupInset)
NSLayoutConstraint.activate([
popup.leftConstraint,
popup.rightContraint,
popup.bottomConstraint,
NSLayoutConstraint(item: popup, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: configuration.popupHeight)
])
popupWindow.layoutIfNeeded()
NSLayoutConstraint.deactivate([popup.bottomConstraint])
popup.bottomConstraint = NSLayoutConstraint(item: popup, attribute: .bottom, relatedBy: .equal, toItem: popupWindow, attribute: .bottom, multiplier: 1.0, constant: -configuration.popupDistance)
NSLayoutConstraint.activate([popup.bottomConstraint])
if let newestShown = shownPopups.last {
NSLayoutConstraint.deactivate([newestShown.bottomConstraint])
newestShown.bottomConstraint = NSLayoutConstraint.init(item: newestShown, attribute: .bottom, relatedBy: .equal, toItem: popup, attribute: .top, multiplier: 1.0, constant: -configuration.popupDistance)
NSLayoutConstraint.activate([newestShown.bottomConstraint])
}
UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
self.popupWindow.layoutIfNeeded()
}, completion: { (success) in
self.dismissPopupOverflow()
})
shownPopups.append(popup)
if let identifier = popup.identifier {
showPopupsByIdentifiers[identifier] = popup
}
}
/// Dismisses th given popup and manages the Constraints.
///
/// - Parameter popup: Popup to be dismissed.
func dismiss(_ popup: IDPopup) {
dismiss(popup, completion: {})
}
/// Dismissed the given popup and manages the Constraints.
///
/// - Parameters:
/// - popup: Popup to be dismissed.
/// - completion: Completion-Block which is called after the animation finished
fileprivate func dismiss(_ popup: IDPopup, completion: @escaping (()->Void)) {
guard let popupIdx = shownPopups.index(of: popup) else {
return
}
let previousIdx = popupIdx - 1
let nextIdx = popupIdx + 1
NSLayoutConstraint.activate([
NSLayoutConstraint(item: popup, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: popup.frame.size.width)
])
NSLayoutConstraint.deactivate([popup.rightContraint])
popupWindow.layoutIfNeeded()
popup.leftConstraint.constant = popupWindow.frame.width
if popupIdx == shownPopups.count - 1 && shownPopups.count > 1{
let previousPopup = shownPopups[previousIdx]
NSLayoutConstraint.deactivate([previousPopup.bottomConstraint])
previousPopup.bottomConstraint = NSLayoutConstraint.init(item: previousPopup, attribute: .bottom, relatedBy: .equal, toItem: popupWindow, attribute: .bottom, multiplier: 1.0, constant: -configuration.popupDistance)
NSLayoutConstraint.activate([previousPopup.bottomConstraint])
} else if previousIdx >= 0 && nextIdx < shownPopups.count {
let previousPopup = shownPopups[previousIdx]
let nextPopup = shownPopups[nextIdx]
NSLayoutConstraint.deactivate([previousPopup.bottomConstraint])
previousPopup.bottomConstraint = NSLayoutConstraint.init(item: previousPopup, attribute: .bottom, relatedBy: .equal, toItem: nextPopup, attribute: .top, multiplier: 1.0, constant: -configuration.popupDistance)
NSLayoutConstraint.activate([previousPopup.bottomConstraint])
}
UIView.animate(withDuration: 0.3, delay: 0.0, options: .curveEaseInOut, animations: {
self.popupWindow.layoutIfNeeded()
}, completion: { (success) in
popup.removeFromSuperview()
if let popupIdx = self.shownPopups.index(of: popup) {
self.shownPopups.remove(at: popupIdx)
}
if let identifier = popup.identifier {
self.showPopupsByIdentifiers[identifier] = nil
}
completion()
})
}
/// Dismissed recursively the oldest IDPopup until the popuplimit isnt exceeded anymore. Nothing happens if no limit is set.
fileprivate func dismissPopupOverflow() {
guard let maxPopupCount = configuration.maxPopupCount else {
return
}
if self.shownPopups.count > maxPopupCount {
if let firstPopup = shownPopups.first {
dismiss(firstPopup, completion: {
self.dismissPopupOverflow()
})
}
}
}
/// Dismissed all IDPopup which are currently shown
func dismissAll() {
for popup in shownPopups {
dismiss(popup)
}
}
/// Dismissed the Popup with the given identifier
func dissmiss(identifier: String) {
if let popup = showPopupsByIdentifiers[identifier] {
popup.dismiss()
}
}
// MARK: - Keayboard Handling
/// Handles the Window-Frame for when the Keyboard is shown
@objc func keyboardWillShow(_ notification: Notification) {
guard let userInfo = notification.userInfo else {
return
}
guard let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect else {
return
}
let screenHeight = UIScreen.main.bounds.size.height
let keyboardHeight = keyboardFrame.height
UIView.animate(withDuration: 0.3, animations: {
self.popupWindow.frame.size.height = screenHeight - keyboardHeight
self.popupWindow.layoutIfNeeded()
})
}
/// Handles the Window-Frame for when the Keyboard is hidden
@objc func keyboardWillHide(_ notification: Notification) {
let screenHeight = UIScreen.main.bounds.size.height
UIView.animate(withDuration: 0.3, animations: {
self.popupWindow.frame.size.height = screenHeight
self.popupWindow.layoutIfNeeded()
})
}
}
/// Helper subclass of UIWindow to override hitTest.
class PopupWindow: UIWindow {
/// Checks if a IDPopup or any of its childs was touched. Else the hitbox of this Window is ignored.
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, with: event) {
if hitView.isInIDPopup || hitView is IDPopup {
return hitView
}
}
return nil
}
}
extension UIView {
/// Flag if a UIView is inside an IDPopup. Recursivly tests against the superview. Stops if super is in a IDPopup or there is no superview anymore.
fileprivate var isInIDPopup: Bool {
if superview != nil {
if superview is IDPopup {
return true
} else {
return superview!.isInIDPopup
}
} else {
return false
}
}
}
| mit | 7b0f39b9e0f1c8ff31aa0ac5c8f201e6 | 40.626866 | 226 | 0.657225 | 4.99597 | false | true | false | false |
LiuXingCode/LXScollContentViewSwift | LXScrollContentView/LXScrollContentViewLib/LXSegmentBar.swift | 1 | 5338 | //
// LXSegmentBar.swift
// LXScrollContentView
//
// Created by 刘行 on 2017/4/28.
// Copyright © 2017年 刘行. All rights reserved.
//
import UIKit
@objc protocol LXSegmentBarDelegate {
@objc optional func segmentBar(_ segmentBar: LXSegmentBar, selectedIndex: Int)
}
public class LXSegmentBar: UIView {
weak var delegate : LXSegmentBarDelegate?
var titles : [String] = [String](){
didSet{
for titleLabel in titleLabels {
titleLabel.removeFromSuperview()
}
titleLabels.removeAll()
for title in titles {
let label = UILabel()
label.backgroundColor = self.style.backgroundColor
label.tag = 888 + titleLabels.count
label.text = title
label.textAlignment = .center
label.font = style.titleFont
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(labelTapClick(_:)))
label.addGestureRecognizer(tapGes)
label.textColor = self.selectedIndex == titleLabels.count ? self.style.selectedTitleColor : self.style.normalTitleColor
self.scrollView.addSubview(label)
titleLabels.append(label)
}
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
var selectedIndex : Int = 0 {
didSet{
guard oldValue != selectedIndex && selectedIndex >= 0 && selectedIndex < self.titleLabels.count else {
return
}
let oldSelectedLabel = self.titleLabels[oldValue];
let newSelectedLabel = self.titleLabels[selectedIndex]
oldSelectedLabel.textColor = self.style.normalTitleColor
newSelectedLabel.textColor = self.style.selectedTitleColor
self.setupIndicatorFrame(animated: true)
}
}
fileprivate lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView(frame: self.bounds)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
fileprivate lazy var titleLabels : [UILabel] = {
let titleLabels = [UILabel]()
return titleLabels
}()
fileprivate lazy var indicatorView : UIView = {
let indicatorView = UIView()
indicatorView.backgroundColor = self.style.indicatorColor
return indicatorView
}()
fileprivate var style : LXSegmentBarStyle
init(frame: CGRect, style: LXSegmentBarStyle) {
self.style = style
super.init(frame: frame)
setupUI()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
override public func layoutSubviews() {
super.layoutSubviews()
guard titleLabels.count > 0 else {
return
}
scrollView.bringSubview(toFront: indicatorView)
scrollView.frame = bounds
var totalLabelWidth : CGFloat = 0
for label in titleLabels {
label.sizeToFit()
totalLabelWidth += label.bounds.width
}
var itemMargin = (bounds.width - totalLabelWidth) / CGFloat(titleLabels.count)
if itemMargin < style.itemMinMargin {
itemMargin = style.itemMinMargin
}
var startX : CGFloat = 0
for label in titleLabels {
label.frame = CGRect(x: startX, y: 0, width: label.bounds.width + itemMargin, height: bounds.height)
startX += label.bounds.width
}
scrollView.contentSize = CGSize(width: startX, height: scrollView.bounds.size.height)
setupIndicatorFrame(animated: false)
}
}
extension LXSegmentBar {
fileprivate func setupUI(){
addSubview(scrollView)
scrollView.addSubview(indicatorView)
}
fileprivate func setupIndicatorFrame(animated: Bool) {
let selectedLabel = titleLabels[selectedIndex]
UIView.animate(withDuration: 0.1, animations: {
self.indicatorView.frame = CGRect(x: selectedLabel.frame.origin.x, y: self.bounds.height - self.style.indicatorHeight - self.style.indicatorBottomMargin, width: selectedLabel.bounds.width, height: self.style.indicatorHeight)
}) { (_) in
self.scrollRectToVisibleCenter(animated: animated)
}
}
fileprivate func scrollRectToVisibleCenter(animated: Bool) {
let selectedLabel = titleLabels[selectedIndex]
scrollView.scrollRectToVisible(CGRect(x: selectedLabel.center.x - scrollView.bounds.width / 2.0, y: 0, width: scrollView.frame.size.width, height: scrollView.frame.size.height), animated: animated)
}
}
extension LXSegmentBar {
@objc fileprivate func labelTapClick(_ tap: UITapGestureRecognizer) {
let selectedLabel = tap.view as! UILabel
selectedIndex = selectedLabel.tag - 888
delegate?.segmentBar?(self, selectedIndex: selectedIndex)
}
}
| mit | 317885b10fc4171b2764cc0230ef54ca | 33.816993 | 236 | 0.62737 | 5.207234 | false | false | false | false |
Joachimdj/JobResume | Apps/Kort sagt/KortSagt-master/KortSagt/ItemViewController.swift | 1 | 4072 |
//
// ItemViewController.swift
// KortSagt
//
// Created by Joachim on 20/03/15.
// Copyright (c) 2015 Joachim Dittman. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class ItemViewController: UIViewController {
@IBOutlet weak var TextArea: UITextView!
@IBOutlet weak var webView: UIWebView!
var videoId = ""
override func viewDidLoad() {
isPresented = true
if(is_searching == true){ videoId = filteredVideos[selectedVideo].id}
else
{ videoId = videos[selectedVideo].id}
let url = "https://www.googleapis.com/youtube/v3/videos?id=\(videoId)&key=AIzaSyA0T0fCHDyQzKCH0z0xs-i8Vh6DeSMcUuQ&part=snippet"
Alamofire.request(.GET, url,encoding: .URLEncodedInURL).responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
self.TextArea.text = json["items"][0]["snippet"]["description"].string
print(json["items"][0]["snippet"]["description"].string)
self.webView.mediaPlaybackRequiresUserAction = false
case .Failure(let error):
print("Request failed with error: \(error)")
}
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Luk", style: .Plain, target: self, action: "tapCloseButton")
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.blackColor()
let url1 = NSURL(string: "https://www.youtube.com/embed/\(self.videoId)?autoplay=1&modestbranding=1&autohide=1&showinfo=0&controls=0")
let request = NSURLRequest(URL: url1!)
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
if (UIDevice.currentDevice().model.rangeOfString("iPad") != nil) {
var webViewIpad: UIWebView
webViewIpad = UIWebView(frame: CGRectMake(0.5, 40, screenHeight,screenWidth))
self.view.addSubview(webViewIpad)
webViewIpad.loadRequest(request)
webViewIpad.alpha = 0.0
UIView.animateWithDuration(0.5, animations: {
webViewIpad.alpha = 1.0
})
}
else
{
self.webView.alpha = 0.0
self.view.addSubview(self.webView)
self.webView.loadRequest(request)
UIView.animateWithDuration(0.5, animations: {
self.webView.alpha = 1.0
})
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tapCloseButton() {
isPresented = false
if(isPresented == false){
self.dismissViewControllerAnimated(true, completion: nil)}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
} | mit | 2728e16cafdb1e265da91b9e302ba9b3 | 39.73 | 155 | 0.44499 | 6.293663 | false | false | false | false |
lightsprint09/LADVSwift | LADVSwift/AthletDetails+JSONDecodable.swift | 1 | 921 | //
// AthletDetails+JSONDecodable.swift
// Leichatletik
//
// Created by Lukas Schmidt on 28.01.17.
// Copyright © 2017 freiraum. All rights reserved.
//
import Foundation
extension AthletDetails: JSONCodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
id = try decoder.decode("id")
athletnumber = try decoder.decode("athletnumber")
firstname = try decoder.decode("forename")
lastname = try decoder.decode("surname")
gender = Gender(string: try decoder.decode("sex"))!
yearOfBirth = try decoder.decode("birthyear")
allClubs = [try Club(object: object)]
let competitions = (try decoder.decode("meldungen") as [Ausschreibung]?) ?? []
self.competitions = competitions.sorted(by: { $0.date > $1.date })
performances = (try decoder.decode("leistungen")as [Performance]?) ?? []
}
}
| mit | d53fe94a376f1d32858bca05179bc187 | 34.384615 | 86 | 0.652174 | 3.833333 | false | false | false | false |
JohnEstropia/CoreStore | Demo/Sources/Demos/Classic/ColorsDemo/Classic.ColorsDemo.MainView.swift | 1 | 7640 | //
// Demo
// Copyright © 2020 John Rommel Estropia, Inc. All rights reserved.
import CoreStore
import SwiftUI
// MARK: - Classic.ColorsDemo
extension Classic.ColorsDemo {
// MARK: - Classic.ColorsDemo.MainView
struct MainView: View {
// MARK: Internal
init() {
let listMonitor = Classic.ColorsDemo.palettesMonitor
self.listMonitor = listMonitor
self.listHelper = .init(listMonitor: listMonitor)
self._filter = Binding(
get: { Classic.ColorsDemo.filter },
set: { Classic.ColorsDemo.filter = $0 }
)
}
// MARK: View
var body: some View {
let detailView: AnyView
if let selectedObject = self.listHelper.selectedObject() {
detailView = AnyView(
Classic.ColorsDemo.DetailView(selectedObject)
)
}
else {
detailView = AnyView(EmptyView())
}
let listMonitor = self.listMonitor
return VStack(spacing: 0) {
Classic.ColorsDemo.ListView
.init(
listMonitor: listMonitor,
onPaletteTapped: {
self.listHelper.setSelectedPalette($0)
}
)
.navigationBarTitle(
Text("Colors (\(self.listHelper.count) objects)")
)
.frame(minHeight: 0, maxHeight: .infinity)
.edgesIgnoringSafeArea(.vertical)
detailView
.edgesIgnoringSafeArea(.all)
.frame(minHeight: 0, maxHeight: .infinity)
}
.navigationBarItems(
leading: HStack {
EditButton()
Button(
action: { self.clearColors() },
label: { Text("Clear") }
)
},
trailing: HStack {
Button(
action: { self.changeFilter() },
label: { Text(self.filter.rawValue) }
)
Button(
action: { self.shuffleColors() },
label: { Text("Shuffle") }
)
Button(
action: { self.addColor() },
label: { Text("Add") }
)
}
)
}
// MARK: Private
private let listMonitor: ListMonitor<Classic.ColorsDemo.Palette>
@ObservedObject
private var listHelper: ListHelper
@Binding
private var filter: Classic.ColorsDemo.Filter
private func changeFilter() {
Classic.ColorsDemo.filter = Classic.ColorsDemo.filter.next()
}
private func clearColors() {
Classic.ColorsDemo.dataStack.perform(
asynchronous: { transaction in
try transaction.deleteAll(From<Classic.ColorsDemo.Palette>())
},
completion: { _ in }
)
}
private func addColor() {
Classic.ColorsDemo.dataStack.perform(
asynchronous: { transaction in
_ = transaction.create(Into<Classic.ColorsDemo.Palette>())
},
completion: { _ in }
)
}
private func shuffleColors() {
Classic.ColorsDemo.dataStack.perform(
asynchronous: { transaction in
for palette in try transaction.fetchAll(From<Classic.ColorsDemo.Palette>()) {
palette.setRandomHue()
}
},
completion: { _ in }
)
}
// MARK: - Classic.ColorsDemo.MainView.ListHelper
fileprivate final class ListHelper: ObservableObject, ListObjectObserver {
// MARK: FilePrivate
fileprivate private(set) var count: Int = 0
fileprivate init(listMonitor: ListMonitor<Classic.ColorsDemo.Palette>) {
listMonitor.addObserver(self)
self.count = listMonitor.numberOfObjects()
}
fileprivate func selectedObject() -> ObjectMonitor<Classic.ColorsDemo.Palette>? {
return self.selectedPalette.flatMap {
guard !$0.isDeleted else {
return nil
}
return Classic.ColorsDemo.dataStack.monitorObject($0)
}
}
fileprivate func setSelectedPalette(_ palette: Classic.ColorsDemo.Palette?) {
guard self.selectedPalette != palette else {
return
}
self.objectWillChange.send()
if let palette = palette, !palette.isDeleted {
self.selectedPalette = palette
}
else {
self.selectedPalette = nil
}
}
// MARK: ListObserver
typealias ListEntityType = Classic.ColorsDemo.Palette
func listMonitorDidChange(_ monitor: ListMonitor<Classic.ColorsDemo.Palette>) {
self.objectWillChange.send()
self.count = monitor.numberOfObjects()
}
func listMonitorDidRefetch(_ monitor: ListMonitor<ListEntityType>) {
self.objectWillChange.send()
self.count = monitor.numberOfObjects()
}
// MARK: ListObjectObserver
func listMonitor(_ monitor: ListMonitor<Classic.ColorsDemo.Palette>, didDeleteObject object: Classic.ColorsDemo.Palette, fromIndexPath indexPath: IndexPath) {
if self.selectedPalette == object {
self.setSelectedPalette(nil)
}
}
// MARK: Private
private var selectedPalette: Classic.ColorsDemo.Palette?
}
}
}
#if DEBUG
struct _Demo_Classic_ColorsDemo_MainView_Preview: PreviewProvider {
// MARK: PreviewProvider
static var previews: some View {
let minimumSamples = 10
try! Classic.ColorsDemo.dataStack.perform(
synchronous: { transaction in
let missing = minimumSamples
- (try transaction.fetchCount(From<Classic.ColorsDemo.Palette>()))
guard missing > 0 else {
return
}
for _ in 0..<missing {
let palette = transaction.create(Into<Classic.ColorsDemo.Palette>())
palette.setRandomHue()
}
}
)
return Classic.ColorsDemo.MainView()
}
}
#endif
| mit | cc2e003ee08a76dcf7299860c8a02a29 | 29.927126 | 170 | 0.449012 | 6.52906 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Core/Operations/AppOperations/LocalMessageFetchingOperation.swift | 1 | 2012 | //
// LocalMessageFetchingOperation.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 20/09/2017.
//
import Foundation
import UserNotifications
class LocalMessageFetchingOperation : MMOperation {
let notificationExtensionStorage: AppGroupMessageStorage?
let finishBlock: ([MM_MTMessage]) -> Void
let userNotificationCenterStorage: UserNotificationCenterStorage
var result = Set<MM_MTMessage>()
init(userNotificationCenterStorage: UserNotificationCenterStorage, notificationExtensionStorage: AppGroupMessageStorage?, finishBlock: @escaping ([MM_MTMessage]) -> Void) {
self.notificationExtensionStorage = notificationExtensionStorage
self.finishBlock = finishBlock
self.userNotificationCenterStorage = userNotificationCenterStorage
super.init(isUserInitiated: false)
}
override func execute() {
self.retrieveMessagesFromNotificationServiceExtension(completion: { messages in
self.logDebug("Retrieved \(messages.count) messages from notification extension storage.")
self.result.formUnion(messages)
self.retrieveMessagesFromUserNotificationCenter(completion: { messages in
self.logDebug("Retrieved \(messages.count) messages from notification center.")
self.result.formUnion(messages)
self.finish()
})
})
}
private func retrieveMessagesFromNotificationServiceExtension(completion: @escaping ([MM_MTMessage]) -> Void) {
if let messages = notificationExtensionStorage?.retrieveMessages() {
if !messages.isEmpty {
notificationExtensionStorage?.cleanupMessages()
}
completion(messages)
} else {
completion([])
}
}
private func retrieveMessagesFromUserNotificationCenter(completion: @escaping ([MM_MTMessage]) -> Void) {
userNotificationCenterStorage.getDeliveredMessages(completionHandler: completion)
}
override func finished(_ errors: [NSError]) {
assert(userInitiated == Thread.isMainThread)
logDebug("finished with errors: \(errors)")
let messages = Array(result)
finishBlock(messages)
}
}
| apache-2.0 | c22df530b6c6900e7ee30b750e779d40 | 32.533333 | 173 | 0.776839 | 4.521348 | false | false | false | false |
grandiere/box | box/View/Settings/VSettingsCellDistance.swift | 1 | 3479 | import UIKit
class VSettingsCellDistance:VSettingsCell
{
private weak var segmented:UISegmentedControl!
private let kLabelLeft:CGFloat = 10
private let kLabelWidth:CGFloat = 200
private let kSegmentedTop:CGFloat = 34
private let kSegmentedHeight:CGFloat = 32
private let kSegmentedRight:CGFloat = -10
private let kSegmentedWidth:CGFloat = 190
override init(frame:CGRect)
{
super.init(frame:frame)
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.font = UIFont.regular(size:15)
labelTitle.textColor = UIColor.white
labelTitle.text = NSLocalizedString("VSettingsCellDistance_labelTitle", comment:"")
let segmentedItems:[String] = [
NSLocalizedString("VSettingsCellDistance_segmentedMetres", comment:""),
NSLocalizedString("VSettingsCellDistance_segmentedFeet", comment:"")]
let segmented:UISegmentedControl = UISegmentedControl(
items:segmentedItems)
segmented.translatesAutoresizingMaskIntoConstraints = false
segmented.clipsToBounds = true
segmented.tintColor = UIColor.gridBlue
segmented.addTarget(
self,
action:#selector(actionSegmented(sender:)),
for:UIControlEvents.valueChanged)
self.segmented = segmented
addSubview(labelTitle)
addSubview(segmented)
NSLayoutConstraint.equalsVertical(
view:labelTitle,
toView:self)
NSLayoutConstraint.leftToLeft(
view:labelTitle,
toView:self,
constant:kLabelLeft)
NSLayoutConstraint.width(
view:labelTitle,
constant:kLabelWidth)
NSLayoutConstraint.topToTop(
view:segmented,
toView:self,
constant:kSegmentedTop)
NSLayoutConstraint.height(
view:segmented,
constant:kSegmentedHeight)
NSLayoutConstraint.rightToRight(
view:segmented,
toView:self,
constant:kSegmentedRight)
NSLayoutConstraint.width(
view:segmented,
constant:kSegmentedWidth)
updateSegmented()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionSegmented(sender segmented:UISegmentedControl)
{
let selected:Int = segmented.selectedSegmentIndex
let distance:MDistanceProtocol
if selected == 0
{
distance = MDistanceMetre()
}
else
{
distance = MDistanceFoot()
}
MSession.sharedInstance.settings?.changeDistance(
distance:distance)
}
//MARK: private
private func updateSegmented()
{
guard
let currentDistance:MDistanceProtocol = MSession.sharedInstance.settings?.currentDistance()
else
{
return
}
let index:Int
if let _:MDistanceFoot = currentDistance as? MDistanceFoot
{
index = 1
}
else
{
index = 0
}
segmented.selectedSegmentIndex = index
}
}
| mit | 05be7cdf0d1e3766bd9c7b7622d77c8f | 27.516393 | 103 | 0.597873 | 5.906621 | false | false | false | false |
vgorloff/AUHost | Sources/EffectWindowController.swift | 1 | 1299 | //
// EffectWindowController.swift
// AUHost
//
// Created by Vlad Gorlov on 16.01.16.
// Copyright © 2016 WaveLabs. All rights reserved.
//
import AppKit
import mcxRuntime
private let log = Logger.getLogger(EffectWindowController.self)
class EffectWindowController: NSWindowController {
enum Event {
case windowWillClose
}
var eventHandler: ((Event) -> Void)?
private lazy var customWindow = NSWindow(contentRect: CGRect(x: 1118, y: 286, width: 480, height: 270),
styleMask: [.titled, .closable, .miniaturizable, .resizable, .nonactivatingPanel],
backing: .buffered, defer: true)
init() {
super.init(window: nil)
window = customWindow
window?.delegate = self
setupUI()
}
required init?(coder: NSCoder) {
fatalError("Please use this class from code.")
}
deinit {
log.deinitialize()
}
}
extension EffectWindowController: NSWindowDelegate {
func windowWillClose(_: Notification) {
eventHandler?(.windowWillClose)
}
}
extension EffectWindowController {
private func setupUI() {
windowFrameAutosaveName = NSWindow.FrameAutosaveName(NSStringFromClass(EffectWindowController.self) + ":WindowFrame")
}
}
| mit | 1ee2b8c33e1636906bfbb644d43e5353 | 23.037037 | 126 | 0.650231 | 4.538462 | false | false | false | false |
KaushalElsewhere/AllHandsOn | TryMadhu/TryMadhu/AppDelegate.swift | 1 | 2592 | //
// AppDelegate.swift
// TryMadhu
//
// Created by Kaushal Elsewhere on 15/05/2017.
// Copyright © 2017 Elsewhere. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds)
var coordinator: AppCoordinator!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let firstController = FirstController()
let navController = UINavigationController(rootViewController: firstController)
coordinator = AppCoordinator(nav: navController, rootController: firstController)
window?.rootViewController = navController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 0378ec6c8c4f3b5830ab1a85894fc7f5 | 45.267857 | 285 | 0.741413 | 5.835586 | false | false | false | false |
HendrikNoeller/Clock | Clock iOS/Clock/Clock/ViewController.swift | 1 | 1504 | //
// ViewController.swift
// Clock
//
// Created by Hendrik Noeller on 29.03.15.
// Copyright (c) 2015 Hendrik Noeller. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
var timer : NSTimer?
var formatter : NSDateFormatter?
override func viewDidLoad() {
super.viewDidLoad()
textLabel.numberOfLines = 1;
textLabel.adjustsFontSizeToFitWidth = true;
formatter = NSDateFormatter()
formatter?.dateFormat = "HH:mm:ss"
startTimer()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
startTimer()
}
func applicationWillEnterForeground() {
startTimer()
}
func applicationDidEnterBackground() {
timer?.invalidate()
}
func startTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("tick"), userInfo: nil, repeats: true)
tick()
}
func tick() {
if let dateString = formatter?.stringFromDate(NSDate()) {
textLabel.text = dateString
}
}
}
| mit | 7276fc09405b7a0ea5196738b7568a3f | 26.345455 | 171 | 0.65891 | 5.352313 | false | false | false | false |
ben-ng/swift | test/decl/protocol/protocols.swift | 2 | 16512 | // RUN: %target-typecheck-verify-swift
protocol EmptyProtocol { }
protocol DefinitionsInProtocols {
init() {} // expected-error {{protocol initializers may not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
// Protocol decl.
protocol Test {
func setTitle(_: String)
func erase() -> Bool
var creator: String { get }
var major : Int { get }
var minor : Int { get }
var subminor : Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
static var staticProperty: Int // expected-error{{property in protocol must have explicit { get } or { get set } specifier}}
}
protocol Test2 {
var property: Int { get }
var title: String = "The Art of War" { get } // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
static var title2: String = "The Art of War" // expected-error{{initial value is not allowed here}} expected-error {{property in protocol must have explicit { get } or { get set } specifier}}
associatedtype mytype
associatedtype mybadtype = Int
}
func test1() {
var v1: Test
var s: String
v1.setTitle(s)
v1.creator = "Me" // expected-error {{cannot assign to property: 'creator' is a get-only property}}
}
protocol Bogus : Int {} // expected-error{{inheritance from non-protocol type 'Int'}}
// Explicit conformance checks (successful).
protocol CustomStringConvertible { func print() } // expected-note{{protocol requires function 'print()' with type '() -> ()'}} expected-note{{protocol requires}} expected-note{{protocol requires}} expected-note{{protocol requires}}
struct TestFormat { }
protocol FormattedPrintable : CustomStringConvertible {
func print(format: TestFormat)
}
struct X0 : Any, CustomStringConvertible {
func print() {}
}
class X1 : Any, CustomStringConvertible {
func print() {}
}
enum X2 : Any { }
extension X2 : CustomStringConvertible {
func print() {}
}
// Explicit conformance checks (unsuccessful)
struct NotPrintableS : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableS' does not conform to protocol 'CustomStringConvertible'}}
class NotPrintableC : CustomStringConvertible, Any {} // expected-error{{type 'NotPrintableC' does not conform to protocol 'CustomStringConvertible'}}
enum NotPrintableO : Any, CustomStringConvertible {} // expected-error{{type 'NotPrintableO' does not conform to protocol 'CustomStringConvertible'}}
struct NotFormattedPrintable : FormattedPrintable { // expected-error{{type 'NotFormattedPrintable' does not conform to protocol 'CustomStringConvertible'}}
func print(format: TestFormat) {} // expected-note{{candidate has non-matching type '(TestFormat) -> ()'}}
}
// Circular protocols
protocol CircleMiddle : CircleStart { func circle_middle() } // expected-error {{circular protocol inheritance CircleMiddle}}
// expected-error @+1 {{circular protocol inheritance CircleStart}}
protocol CircleStart : CircleEnd { func circle_start() }
protocol CircleEnd : CircleMiddle { func circle_end()}
protocol CircleEntry : CircleTrivial { }
protocol CircleTrivial : CircleTrivial { } // expected-error{{circular protocol inheritance CircleTrivial}}
struct Circle {
func circle_start() {}
func circle_middle() {}
func circle_end() {}
}
func testCircular(_ circle: Circle) {
// FIXME: It would be nice if this failure were suppressed because the protocols
// have circular definitions.
_ = circle as CircleStart // expected-error{{'Circle' is not convertible to 'CircleStart'; did you mean to use 'as!' to force downcast?}} {{14-16=as!}}
}
// <rdar://problem/14750346>
protocol Q : C, H { }
protocol C : E { }
protocol H : E { }
protocol E { }
//===----------------------------------------------------------------------===//
// Associated types
//===----------------------------------------------------------------------===//
protocol SimpleAssoc {
associatedtype Associated // expected-note{{protocol requires nested type 'Associated'}}
}
struct IsSimpleAssoc : SimpleAssoc {
struct Associated {}
}
struct IsNotSimpleAssoc : SimpleAssoc {} // expected-error{{type 'IsNotSimpleAssoc' does not conform to protocol 'SimpleAssoc'}}
protocol StreamWithAssoc {
associatedtype Element
func get() -> Element // expected-note{{protocol requires function 'get()' with type '() -> NotAStreamType.Element'}}
}
struct AnRange<Int> : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
// Okay: Word is a typealias for Int
struct AWordStreamType : StreamWithAssoc {
typealias Element = Int
func get() -> Int {}
}
struct NotAStreamType : StreamWithAssoc { // expected-error{{type 'NotAStreamType' does not conform to protocol 'StreamWithAssoc'}}
typealias Element = Float
func get() -> Int {} // expected-note{{candidate has non-matching type '() -> Int'}}
}
// Okay: Infers Element == Int
struct StreamTypeWithInferredAssociatedTypes : StreamWithAssoc {
func get() -> Int {}
}
protocol SequenceViaStream {
associatedtype SequenceStreamTypeType : IteratorProtocol // expected-note{{protocol requires nested type 'SequenceStreamTypeType'}}
func makeIterator() -> SequenceStreamTypeType
}
struct IntIterator : IteratorProtocol /*, Sequence, ReplPrintable*/ {
typealias Element = Int
var min : Int
var max : Int
var stride : Int
mutating func next() -> Int? {
if min >= max { return .none }
let prev = min
min += stride
return prev
}
typealias Generator = IntIterator
func makeIterator() -> IntIterator {
return self
}
}
extension IntIterator : SequenceViaStream {
typealias SequenceStreamTypeType = IntIterator
}
struct NotSequence : SequenceViaStream { // expected-error{{type 'NotSequence' does not conform to protocol 'SequenceViaStream'}}
typealias SequenceStreamTypeType = Int // expected-note{{possibly intended match 'NotSequence.SequenceStreamTypeType' (aka 'Int') does not conform to 'IteratorProtocol'}}
func makeIterator() -> Int {}
}
protocol GetATuple {
associatedtype Tuple
func getATuple() -> Tuple
}
struct IntStringGetter : GetATuple {
typealias Tuple = (i: Int, s: String)
func getATuple() -> Tuple {}
}
//===----------------------------------------------------------------------===//
// Default arguments
//===----------------------------------------------------------------------===//
// FIXME: Actually make use of default arguments, check substitutions, etc.
protocol ProtoWithDefaultArg {
func increment(_ value: Int = 1) // expected-error{{default argument not permitted in a protocol method}}
}
struct HasNoDefaultArg : ProtoWithDefaultArg {
func increment(_: Int) {}
}
//===----------------------------------------------------------------------===//
// Variadic function requirements
//===----------------------------------------------------------------------===//
protocol IntMaxable {
func intmax(first: Int, rest: Int...) -> Int // expected-note 2{{protocol requires function 'intmax(first:rest:)' with type '(Int, Int...) -> Int'}}
}
struct HasIntMax : IntMaxable {
func intmax(first: Int, rest: Int...) -> Int {}
}
struct NotIntMax1 : IntMaxable { // expected-error{{type 'NotIntMax1' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: [Int]) -> Int {} // expected-note{{candidate has non-matching type '(Int, [Int]) -> Int'}}
}
struct NotIntMax2 : IntMaxable { // expected-error{{type 'NotIntMax2' does not conform to protocol 'IntMaxable'}}
func intmax(first: Int, rest: Int) -> Int {} // expected-note{{candidate has non-matching type '(Int, Int) -> Int'}}
}
//===----------------------------------------------------------------------===//
// 'Self' type
//===----------------------------------------------------------------------===//
protocol IsEqualComparable {
func isEqual(other: Self) -> Bool // expected-note{{protocol requires function 'isEqual(other:)' with type '(WrongIsEqual) -> Bool'}}
}
struct HasIsEqual : IsEqualComparable {
func isEqual(other: HasIsEqual) -> Bool {}
}
struct WrongIsEqual : IsEqualComparable { // expected-error{{type 'WrongIsEqual' does not conform to protocol 'IsEqualComparable'}}
func isEqual(other: Int) -> Bool {} // expected-note{{candidate has non-matching type '(Int) -> Bool'}}
}
//===----------------------------------------------------------------------===//
// Using values of existential type.
//===----------------------------------------------------------------------===//
func existentialSequence(_ e: Sequence) { // expected-error{{has Self or associated type requirements}}
var x = e.makeIterator() // expected-error{{'Sequence' is not convertible to 'Sequence.Iterator'}}
x.next()
x.nonexistent()
}
protocol HasSequenceAndStream {
associatedtype R : IteratorProtocol, Sequence
func getR() -> R
}
func existentialSequenceAndStreamType(_ h: HasSequenceAndStream) { // expected-error{{has Self or associated type requirements}}
// FIXME: Crummy diagnostics.
var x = h.getR() // expected-error{{member 'getR' cannot be used on value of protocol type 'HasSequenceAndStream'; use a generic constraint instead}}
x.makeIterator()
x.next()
x.nonexistent()
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol IntIntSubscriptable {
subscript (i: Int) -> Int { get }
}
protocol IntSubscriptable {
associatedtype Element
subscript (i: Int) -> Element { get }
}
struct DictionaryIntInt {
subscript (i: Int) -> Int {
get {
return i
}
}
}
func testSubscripting(_ iis: IntIntSubscriptable, i_s: IntSubscriptable) { // expected-error{{has Self or associated type requirements}}
var i: Int = iis[17]
var i2 = i_s[17] // expected-error{{member 'subscript' cannot be used on value of protocol type 'IntSubscriptable'; use a generic constraint instead}}
}
//===----------------------------------------------------------------------===//
// Static methods
//===----------------------------------------------------------------------===//
protocol StaticP {
static func f()
}
protocol InstanceP {
func f() // expected-note{{protocol requires function 'f()' with type '() -> ()'}}
}
struct StaticS1 : StaticP {
static func f() {}
}
struct StaticS2 : InstanceP { // expected-error{{type 'StaticS2' does not conform to protocol 'InstanceP'}}
static func f() {} // expected-note{{candidate operates on a type, not an instance as required}}
}
struct StaticAndInstanceS : InstanceP {
static func f() {}
func f() {}
}
func StaticProtocolFunc() {
let a: StaticP = StaticS1()
a.f() // expected-error{{static member 'f' cannot be used on instance of type 'StaticP'}}
}
func StaticProtocolGenericFunc<t : StaticP>(_: t) {
t.f()
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Eq {
static func ==(lhs: Self, rhs: Self) -> Bool
}
extension Int : Eq { }
// Matching prefix/postfix.
prefix operator <>
postfix operator <>
protocol IndexValue {
static prefix func <> (_ max: Self) -> Int
static postfix func <> (min: Self) -> Int
}
prefix func <> (max: Int) -> Int { return 0 }
postfix func <> (min: Int) -> Int { return 0 }
extension Int : IndexValue {}
//===----------------------------------------------------------------------===//
// Class protocols
//===----------------------------------------------------------------------===//
protocol IntrusiveListNode : class {
var next : Self { get }
}
final class ClassNode : IntrusiveListNode {
var next : ClassNode = ClassNode()
}
struct StructNode : IntrusiveListNode { // expected-error{{non-class type 'StructNode' cannot conform to class protocol 'IntrusiveListNode'}}
// expected-error@-1{{value type 'StructNode' cannot have a stored property that references itself}}
var next : StructNode
}
final class ClassNodeByExtension { }
struct StructNodeByExtension { }
extension ClassNodeByExtension : IntrusiveListNode {
var next : ClassNodeByExtension {
get {
return self
}
set {}
}
}
extension StructNodeByExtension : IntrusiveListNode { // expected-error{{non-class type 'StructNodeByExtension' cannot conform to class protocol 'IntrusiveListNode'}}
var next : StructNodeByExtension {
get {
return self
}
set {}
}
}
final class GenericClassNode<T> : IntrusiveListNode {
var next : GenericClassNode<T> = GenericClassNode()
}
struct GenericStructNode<T> : IntrusiveListNode { // expected-error{{non-class type 'GenericStructNode<T>' cannot conform to class protocol 'IntrusiveListNode'}}
// expected-error@-1{{value type 'GenericStructNode<T>' cannot have a stored property that references itself}}
var next : GenericStructNode<T>
}
// Refined protocols inherit class-ness
protocol IntrusiveDListNode : IntrusiveListNode {
var prev : Self { get }
}
final class ClassDNode : IntrusiveDListNode {
var prev : ClassDNode = ClassDNode()
var next : ClassDNode = ClassDNode()
}
struct StructDNode : IntrusiveDListNode { // expected-error{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveDListNode'}}
// expected-error@-1{{non-class type 'StructDNode' cannot conform to class protocol 'IntrusiveListNode'}}
// expected-error@-2{{value type 'StructDNode' cannot have a stored property that references itself}}
var prev : StructDNode
var next : StructDNode
}
@objc protocol ObjCProtocol {
func foo() // expected-note{{protocol requires function 'foo()' with type '() -> ()'}}
}
protocol NonObjCProtocol : class { //expected-note{{protocol 'NonObjCProtocol' declared here}}
func bar()
}
class DoesntConformToObjCProtocol : ObjCProtocol { // expected-error{{type 'DoesntConformToObjCProtocol' does not conform to protocol 'ObjCProtocol'}}
}
@objc protocol ObjCProtocolRefinement : ObjCProtocol { }
@objc protocol ObjCNonObjCProtocolRefinement : NonObjCProtocol { } //expected-error{{@objc protocol 'ObjCNonObjCProtocolRefinement' cannot refine non-@objc protocol 'NonObjCProtocol'}}
// <rdar://problem/16079878>
protocol P1 {
associatedtype Assoc // expected-note 2{{protocol requires nested type 'Assoc'}}
}
protocol P2 {
}
struct X3<T : P1> where T.Assoc : P2 {}
struct X4 : P1 { // expected-error{{type 'X4' does not conform to protocol 'P1'}}
func getX1() -> X3<X4> { return X3() } // expected-error{{cannot convert return expression of type 'X3<_>' to return type 'X3<X4>'}}
}
protocol ShouldntCrash {
// rdar://16109996
let fullName: String { get } // expected-error {{'let' declarations cannot be computed properties}}
// <rdar://problem/17200672> Let in protocol causes unclear errors and crashes
let fullName2: String // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}}
// <rdar://problem/16789886> Assert on protocol property requirement without a type
var propertyWithoutType { get } // expected-error {{type annotation missing in pattern}} expected-error {{computed property must have an explicit type}}
}
// rdar://problem/18168866
protocol FirstProtocol {
weak var delegate : SecondProtocol? { get } // expected-error{{'weak' may only be applied to class and class-bound protocol types, not 'SecondProtocol'}}
}
protocol SecondProtocol {
func aMethod(_ object : FirstProtocol)
}
// <rdar://problem/19495341> Can't upcast to parent types of type constraints without forcing
class C1 : P2 {}
func f<T : C1>(_ x : T) {
_ = x as P2
}
class C2 {}
func g<T : C2>(_ x : T) {
x as P2 // expected-error{{'T' is not convertible to 'P2'; did you mean to use 'as!' to force downcast?}} {{5-7=as!}}
}
class C3 : P1 {} // expected-error{{type 'C3' does not conform to protocol 'P1'}}
func h<T : C3>(_ x : T) {
_ = x as P1 // expected-error{{protocol 'P1' can only be used as a generic constraint because it has Self or associated type requirements}}
}
protocol P4 {
associatedtype T // expected-note {{protocol requires nested type 'T'}}
}
class C4 : P4 { // expected-error {{type 'C4' does not conform to protocol 'P4'}}
associatedtype T = Int // expected-error {{associated types can only be defined in a protocol; define a type or introduce a 'typealias' to satisfy an associated type requirement}} {{3-17=typealias}}
}
| apache-2.0 | 9c9dcc4fe906761d1065a9ad7b6aea9d | 34.206823 | 232 | 0.650194 | 4.540005 | false | false | false | false |
kevin-zqw/ReactiveCocoa | ReactiveCocoaTests/Swift/SchedulerSpec.swift | 2 | 6499 | //
// SchedulerSpec.swift
// ReactiveCocoa
//
// Created by Justin Spahr-Summers on 2014-07-13.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import Nimble
import Quick
@testable
import ReactiveCocoa
class SchedulerSpec: QuickSpec {
override func spec() {
describe("ImmediateScheduler") {
it("should run enqueued actions immediately") {
var didRun = false
ImmediateScheduler().schedule {
didRun = true
}
expect(didRun) == true
}
}
describe("UIScheduler") {
func dispatchSyncInBackground(action: () -> ()) {
let group = dispatch_group_create()
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), action)
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
}
it("should run actions immediately when on the main thread") {
let scheduler = UIScheduler()
var values: [Int] = []
expect(NSThread.isMainThread()) == true
scheduler.schedule {
values.append(0)
}
expect(values) == [ 0 ]
scheduler.schedule {
values.append(1)
}
scheduler.schedule {
values.append(2)
}
expect(values) == [ 0, 1, 2 ]
}
it("should enqueue actions scheduled from the background") {
let scheduler = UIScheduler()
var values: [Int] = []
dispatchSyncInBackground {
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(0)
}
return
}
expect(values) == []
expect(values).toEventually(equal([ 0 ]))
dispatchSyncInBackground {
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(1)
}
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(2)
}
return
}
expect(values) == [ 0 ]
expect(values).toEventually(equal([ 0, 1, 2 ]))
}
it("should run actions enqueued from the main thread after those from the background") {
let scheduler = UIScheduler()
var values: [Int] = []
dispatchSyncInBackground {
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(0)
}
return
}
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(1)
}
scheduler.schedule {
expect(NSThread.isMainThread()) == true
values.append(2)
}
expect(values) == []
expect(values).toEventually(equal([ 0, 1, 2 ]))
}
}
describe("QueueScheduler") {
it("should run enqueued actions on a global queue") {
var didRun = false
let scheduler: QueueScheduler
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(qos: QOS_CLASS_DEFAULT)
} else {
scheduler = QueueScheduler(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
}
scheduler.schedule {
didRun = true
expect(NSThread.isMainThread()) == false
}
expect{didRun}.toEventually(beTruthy())
}
describe("on a given queue") {
var scheduler: QueueScheduler!
beforeEach {
if #available(OSX 10.10, *) {
scheduler = QueueScheduler(qos: QOS_CLASS_DEFAULT)
} else {
scheduler = QueueScheduler(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
}
dispatch_suspend(scheduler.queue)
}
it("should run enqueued actions serially on the given queue") {
var value = 0
for _ in 0..<5 {
scheduler.schedule {
expect(NSThread.isMainThread()) == false
value++
}
}
expect(value) == 0
dispatch_resume(scheduler.queue)
expect{value}.toEventually(equal(5))
}
it("should run enqueued actions after a given date") {
var didRun = false
scheduler.scheduleAfter(NSDate()) {
didRun = true
expect(NSThread.isMainThread()) == false
}
expect(didRun) == false
dispatch_resume(scheduler.queue)
expect{didRun}.toEventually(beTruthy())
}
it("should repeatedly run actions after a given date") {
let disposable = SerialDisposable()
var count = 0
let timesToRun = 3
disposable.innerDisposable = scheduler.scheduleAfter(NSDate(), repeatingEvery: 0.01, withLeeway: 0) {
expect(NSThread.isMainThread()) == false
if ++count == timesToRun {
disposable.dispose()
}
}
expect(count) == 0
dispatch_resume(scheduler.queue)
expect{count}.toEventually(equal(timesToRun))
}
}
}
describe("TestScheduler") {
var scheduler: TestScheduler!
var startDate: NSDate!
// How much dates are allowed to differ when they should be "equal."
let dateComparisonDelta = 0.00001
beforeEach {
startDate = NSDate()
scheduler = TestScheduler(startDate: startDate)
expect(scheduler.currentDate) == startDate
}
it("should run immediately enqueued actions upon advancement") {
var string = ""
scheduler.schedule {
string += "foo"
expect(NSThread.isMainThread()) == true
}
scheduler.schedule {
string += "bar"
expect(NSThread.isMainThread()) == true
}
expect(string) == ""
scheduler.advance()
expect(scheduler.currentDate).to(beCloseTo(startDate))
expect(string) == "foobar"
}
it("should run actions when advanced past the target date") {
var string = ""
scheduler.scheduleAfter(15) {
string += "bar"
expect(NSThread.isMainThread()) == true
}
scheduler.scheduleAfter(5) {
string += "foo"
expect(NSThread.isMainThread()) == true
}
expect(string) == ""
scheduler.advanceByInterval(10)
expect(scheduler.currentDate).to(beCloseTo(startDate.dateByAddingTimeInterval(10), within: dateComparisonDelta))
expect(string) == "foo"
scheduler.advanceByInterval(10)
expect(scheduler.currentDate).to(beCloseTo(startDate.dateByAddingTimeInterval(20), within: dateComparisonDelta))
expect(string) == "foobar"
}
it("should run all remaining actions in order") {
var string = ""
scheduler.scheduleAfter(15) {
string += "bar"
expect(NSThread.isMainThread()) == true
}
scheduler.scheduleAfter(5) {
string += "foo"
expect(NSThread.isMainThread()) == true
}
scheduler.schedule {
string += "fuzzbuzz"
expect(NSThread.isMainThread()) == true
}
expect(string) == ""
scheduler.run()
expect(scheduler.currentDate) == NSDate.distantFuture()
expect(string) == "fuzzbuzzfoobar"
}
}
}
}
| mit | e5f9ca6e04322ec5e3ba2388e9740b99 | 21.883803 | 116 | 0.634098 | 3.765353 | false | false | false | false |
zhubch/DropDownMenu | Example/ZHDropDownMenu/ViewController.swift | 1 | 3295 | //
// ViewController.swift
// ZHDropDownMenu-Demo
//
// Created by zhubch on 3/8/16.
//
// Copyright (c) 2016 zhubch <[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 ZHDropDownMenu
class ViewController: UIViewController, ZHDropDownMenuDelegate{
@IBOutlet weak var menu1: ZHDropDownMenu!
@IBOutlet weak var menu2: ZHDropDownMenu!
@IBOutlet weak var menu3: ZHDropDownMenu!
@IBOutlet weak var menu4: ZHDropDownMenu!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "ZHDropDownMenu"
menu1.options = ["北京","南昌","深圳","西安","上海","厦门","广州","北京","南昌","深圳","西安","上海","厦门","广州"] //设置下拉列表项数据
menu1.menuHeight = 240;//设置最大高度
menu2.options = ["男","女"]
menu2.showBorder = false //不显示边框
menu2.menuHeight = 100;//设置最大高度
menu3.options = ["1992","1993","1994","1995","1996","1997","1998"]
menu3.defaultValue = "1992" //设置默认值
menu3.showBorder = false
menu4.options = ["天气太冷了","没睡好觉,困死了","就是不想上班"]
menu4.editable = true //可编辑
menu1.delegate = self //设置代理
menu2.delegate = self
menu3.delegate = self
menu4.delegate = self
// test() //自动刷新UI
}
func test() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) {
self.menu1.menuHeight = 150.0
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10) {
self.menu1.options = ["I can","Eat","Glass"]
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 15) {
self.menu1.rowHeight = 50.0
}
}
//选择完后回调
func dropDownMenu(_ menu: ZHDropDownMenu, didSelect index: Int) {
print("\(menu) choosed at index \(index)")
}
//编辑完成后回调
func dropDownMenu(_ menu: ZHDropDownMenu, didEdit text: String) {
print("\(menu) input text \(text)")
}
}
| mit | cfffb8dd0a16eaa17b50cd493ad63908 | 32.193548 | 107 | 0.635245 | 3.988372 | false | false | false | false |
ChaosCoder/Fluency | Fluency/SplitTask.swift | 1 | 805 | import Foundation
class SplitTask : Task
{
var nextTasks : [Task]
override init()
{
nextTasks = []
super.init()
}
required init(task: Task) {
let splitTask = task as! SplitTask
nextTasks = splitTask.nextTasks
super.init(task: task)
}
final override func execute()
{
let nextContext = Context(process:self.context.process, task: self.originalTask, result: self.context.result)
finish(self.context.result)
for task in nextTasks
{
task.start(nextContext)
}
}
override func plantUML(visited: [Task]) -> String
{
var uml = "===\(addressString)===\n"
if visited.contains(self) || plantUMLVisited > 0
{
return uml
}
for task in nextTasks
{
uml += "===\(addressString)=== --> " + task.plantUML(visited + [self])
}
return uml
}
} | mit | 28ea0f6cbf3c6ae73e04fde91fd48661 | 16.148936 | 111 | 0.638509 | 2.992565 | false | false | false | false |
qxuewei/XWSwiftWB | XWSwiftWB/XWSwiftWB/Classes/Compose/View/ComposeTitleView.swift | 1 | 1385 | //
// ComposeTitleView.swift
// XWSwiftWB
//
// Created by 邱学伟 on 2016/11/9.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
import SnapKit
class ComposeTitleView: UIView {
fileprivate let titleLB : UILabel = UILabel()
fileprivate let screenNameLB : UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: - UI
extension ComposeTitleView {
fileprivate func setUpUI() {
addSubview(titleLB)
addSubview(screenNameLB)
titleLB.font = UIFont.systemFont(ofSize: 15.0)
titleLB.text = "发微博"
screenNameLB.font = UIFont.systemFont(ofSize: 13.0)
screenNameLB.textColor = UIColor.lightGray
let titleLBSnp : ConstraintViewDSL = titleLB.snp
screenNameLB.text = UserAccountViewModel.shareInstance.account?.screen_name
titleLBSnp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(self)
}
let screenNameLBSnp : ConstraintViewDSL = screenNameLB.snp
screenNameLBSnp.makeConstraints { (make) in
make.centerX.equalTo(titleLBSnp.centerX)
make.top.equalTo(titleLBSnp.bottom).offset(3)
}
}
}
| apache-2.0 | 5ed67509318852393a9f9dc2929b6419 | 28.652174 | 83 | 0.650293 | 4.071642 | false | false | false | false |
cailingyun2010/swift-keyboard | 01-表情键盘/EmotionViewController.swift | 1 | 7599 | //
// EmoticonViewController.swift
// 表情键盘界面布局
//
// Created by xiaomage on 15/9/16.
// Copyright © 2015年 小码哥. All rights reserved.
//
import UIKit
private let XMGEmoticonCellReuseIdentifier = "XMGEmoticonCellReuseIdentifier"
class EmoticonViewController: UIViewController {
/// 定义闭包属性,用于传递选中的表情
var emotionDidSelctedCallBack:(emotion: Emoticon) -> () // 定义
init(callBack: (emotion: Emoticon) -> ()) {
self.emotionDidSelctedCallBack = callBack // 赋值
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()
// 1.初始化UI
setupUI()
}
/**
初始化UI
*/
private func setupUI()
{
// 1.添加子控件
view.addSubview(collectionVeiw)
view.addSubview(toolbar)
// 2.布局子控件
collectionVeiw.translatesAutoresizingMaskIntoConstraints = false
toolbar.translatesAutoresizingMaskIntoConstraints = false
// 提示: 如果想自己封装一个框架, 最好不要依赖其它框架
var cons = [NSLayoutConstraint]()
let dict = ["collectionVeiw": collectionVeiw, "toolbar": toolbar]
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[collectionVeiw]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionVeiw]-[toolbar(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
view.addConstraints(cons)
}
func itemClick(item: UIBarButtonItem)
{
collectionVeiw.scrollToItemAtIndexPath(NSIndexPath(forItem: 0, inSection: item.tag), atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
}
// MARK: - 懒加载
private lazy var collectionVeiw: UICollectionView = {
let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
// 注册cell
clv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: XMGEmoticonCellReuseIdentifier)
clv.dataSource = self
clv.delegate = self
return clv
}()
private lazy var toolbar: UIToolbar = {
let bar = UIToolbar()
bar.tintColor = UIColor.darkGrayColor()
var items = [UIBarButtonItem]()
var index = 0
for title in ["最近", "默认", "emoji", "浪小花"]
{
let item = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: "itemClick:")
item.tag = index++
items.append(item)
items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
}
items.removeLast()
bar.items = items
return bar
}()
private lazy var packages: [EmoticonPackage] = EmoticonPackage.loadPackages()
}
extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate
{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return packages.count
}
// 告诉系统每组有多少行
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return packages[section].emoticons?.count ?? 0
}
// 告诉系统每行显示什么内容
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionVeiw.dequeueReusableCellWithReuseIdentifier(XMGEmoticonCellReuseIdentifier, forIndexPath: indexPath) as! EmoticonCell
cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.greenColor()
// 1.取出对应的组
let package = packages[indexPath.section]
// 2.取出对应组对应行的模型
let emoticon = package.emoticons![indexPath.item]
// 3.赋值给cell
cell.emoticon = emoticon
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let emotion = packages[indexPath.section].emoticons![indexPath.item]
emotionDidSelctedCallBack(emotion: emotion)
}
}
class EmoticonCell: UICollectionViewCell {
var emoticon: Emoticon?
{
didSet{
// 1.判断是否是图片表情
if emoticon!.chs != nil
{
iconButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath!), forState: UIControlState.Normal)
}else
{
// 防止重用
iconButton.setImage(nil, forState: UIControlState.Normal)
}
// 2.设置emoji表情
// 注意: 加上??可以防止重用
iconButton.setTitle(emoticon!.emojiStr ?? "", forState: UIControlState.Normal)
// 3.判断是否是删除按钮
if emoticon!.isRemoveButton
{
iconButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
iconButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
}else {
iconButton.setImage(nil, forState: UIControlState.Highlighted)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
/**
初始化UI
*/
private func setupUI()
{
contentView.addSubview(iconButton)
iconButton.backgroundColor = UIColor.whiteColor()
iconButton.frame = CGRectInset(contentView.bounds, 4, 4)
// iconButton.frame = CGRectInset(contentView.bounds, 4, 4)
iconButton.userInteractionEnabled = false
}
// MARK: - 懒加载
private lazy var iconButton: UIButton = {
let btn = UIButton()
btn.titleLabel?.font = UIFont.systemFontOfSize(32)
return btn
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/// 自定义布局
class EmoticonLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
super.prepareLayout()
// 1.设置cell相关属性
let width = collectionView!.bounds.width / 7
itemSize = CGSize(width: width, height: width)
minimumInteritemSpacing = 0
minimumLineSpacing = 0
scrollDirection = UICollectionViewScrollDirection.Horizontal
// 2.设置collectionview相关属性
collectionView?.pagingEnabled = true
collectionView?.bounces = false
collectionView?.showsHorizontalScrollIndicator = false
// 注意:最好不要乘以0.5, 因为CGFloat不准确, 所以如果乘以0.5在iPhone4/4身上会有问题
let y = (collectionView!.bounds.height - 3 * width) * 0.45
collectionView?.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
}
}
| mit | 488a02031a7a13f9b7f4f7aecac23818 | 34.014634 | 178 | 0.636946 | 5.005579 | false | false | false | false |
danielgindi/ios-charts | ChartsDemo-iOS/Swift/Demos/BubbleChartViewController.swift | 2 | 4609 | //
// BubbleChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
#if canImport(UIKit)
import UIKit
#endif
import Charts
class BubbleChartViewController: DemoBaseViewController {
@IBOutlet var chartView: BubbleChartView!
@IBOutlet var sliderX: UISlider!
@IBOutlet var sliderY: UISlider!
@IBOutlet var sliderTextX: UITextField!
@IBOutlet var sliderTextY: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Bubble Chart"
self.options = [.toggleValues,
.toggleIcons,
.toggleHighlight,
.animateX,
.animateY,
.animateXY,
.saveToGallery,
.togglePinchZoom,
.toggleAutoScaleMinMax,
.toggleData]
chartView.delegate = self
chartView.chartDescription.enabled = false
chartView.dragEnabled = false
chartView.setScaleEnabled(true)
chartView.maxVisibleCount = 200
chartView.pinchZoomEnabled = true
chartView.legend.horizontalAlignment = .right
chartView.legend.verticalAlignment = .top
chartView.legend.orientation = .vertical
chartView.legend.drawInside = false
chartView.legend.font = UIFont(name: "HelveticaNeue-Light", size: 10)!
chartView.leftAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)!
chartView.leftAxis.spaceTop = 0.3
chartView.leftAxis.spaceBottom = 0.3
chartView.leftAxis.axisMinimum = 0
chartView.rightAxis.enabled = false
chartView.xAxis.labelPosition = .bottom
chartView.xAxis.labelFont = UIFont(name: "HelveticaNeue-Light", size: 10)!
sliderX.value = 10
sliderY.value = 50
slidersValueChanged(nil)
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value))
}
func setDataCount(_ count: Int, range: UInt32) {
let yVals1 = (0..<count).map { (i) -> BubbleChartDataEntry in
let val = Double(arc4random_uniform(range))
let size = CGFloat(arc4random_uniform(range))
return BubbleChartDataEntry(x: Double(i), y: val, size: size, icon: UIImage(named: "icon"))
}
let yVals2 = (0..<count).map { (i) -> BubbleChartDataEntry in
let val = Double(arc4random_uniform(range))
let size = CGFloat(arc4random_uniform(range))
return BubbleChartDataEntry(x: Double(i), y: val, size: size, icon: UIImage(named: "icon"))
}
let yVals3 = (0..<count).map { (i) -> BubbleChartDataEntry in
let val = Double(arc4random_uniform(range))
let size = CGFloat(arc4random_uniform(range))
return BubbleChartDataEntry(x: Double(i), y: val, size: size)
}
let set1 = BubbleChartDataSet(entries: yVals1, label: "DS 1")
set1.drawIconsEnabled = false
set1.setColor(ChartColorTemplates.colorful()[0], alpha: 0.5)
set1.drawValuesEnabled = true
let set2 = BubbleChartDataSet(entries: yVals2, label: "DS 2")
set2.drawIconsEnabled = false
set2.iconsOffset = CGPoint(x: 0, y: 15)
set2.setColor(ChartColorTemplates.colorful()[1], alpha: 0.5)
set2.drawValuesEnabled = true
let set3 = BubbleChartDataSet(entries: yVals3, label: "DS 3")
set3.setColor(ChartColorTemplates.colorful()[2], alpha: 0.5)
set3.drawValuesEnabled = true
let data = [set1, set2, set3] as BubbleChartData
data.setDrawValues(false)
data.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 7)!)
data.setHighlightCircleWidth(1.5)
data.setValueTextColor(.white)
chartView.data = data
}
override func optionTapped(_ option: Option) {
super.handleOption(option, forChartView: chartView)
}
// MARK: - Actions
@IBAction func slidersValueChanged(_ sender: Any?) {
sliderTextX.text = "\(Int(sliderX.value))"
sliderTextY.text = "\(Int(sliderY.value))"
self.updateChartData()
}
}
| apache-2.0 | 6d6e65c17911741dc65ef0689048ad51 | 34.72093 | 103 | 0.596788 | 4.678173 | false | false | false | false |
RobotRebels/ios-common | ToboxCommon/Helpers/DeviceUID.swift | 1 | 1525 | //
// DeviceUID.swift
// ToboxCommon
//
// Created by Ilya Lunkin on 23/10/2016.
// Copyright © 2016 Tobox. All rights reserved.
//
import Foundation
import SwiftKeychainWrapper
public class DeviceUID {
public static var uid: String { return uuid ?? DeviceUID().getuid() }
private static var uuid = String?()
private let keyName = "deviceUID"
private static let wrapper = KeychainWrapper(serviceName: "Tobox",
accessGroup: "group.com.tobox.ToBox")
private init() {}
private func getuid() -> String {
var uid = DeviceUID.wrapper.stringForKey(keyName)
if uid == nil {
uid = DeviceUID.valueForUserDefaultsKey(keyName)
}
if uid == nil {
uid = UIDevice.currentDevice().identifierForVendor?.UUIDString ?? ""
}
DeviceUID.uuid = uid
save(uid!)
return uid!
}
private func save(uid: String) {
if DeviceUID.valueForUserDefaultsKey(keyName) == nil {
DeviceUID.setValue(uid, forUserDefaultsKey: keyName)
}
if DeviceUID.wrapper.stringForKey(keyName) == nil {
DeviceUID.wrapper.setString(uid, forKey: keyName)
}
}
private class func setValue(value: AnyObject?, forUserDefaultsKey key: String) {
NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
NSUserDefaults.standardUserDefaults().synchronize()
}
private class func valueForUserDefaultsKey(key: String) -> String? {
return NSUserDefaults.standardUserDefaults().objectForKey(key) as? String
}
}
| mit | 6479995d9aa1718afe375250ad15bc1b | 29.48 | 84 | 0.676509 | 4.354286 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/Tests/RxSwiftTests/Observable+ReduceTests.swift | 13 | 9407 | //
// Observable+ReduceTests.swift
// Tests
//
// Created by Krunoslav Zaher on 4/29/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import XCTest
import RxSwift
import RxTest
class ObservableReduceTest : RxTest {
}
extension ObservableReduceTest {
func test_ReduceWithSeed_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let res = scheduler.start { xs.reduce(42, accumulator: +) }
let correctMessages = [
next(250, 42),
completed(250)
]
let correctSubscriptions = [
Subscription(200, 250)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeed_Return() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 24),
completed(250)
])
let res = scheduler.start { xs.reduce(42, accumulator: +) }
let correctMessages = [
next(250, 42 + 24),
completed(250)
]
let correctSubscriptions = [
Subscription(200, 250)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeed_Throw() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
error(210, testError),
])
let res = scheduler.start { xs.reduce(42, accumulator: +) }
let correctMessages = [
error(210, testError, Int.self)
]
let correctSubscriptions = [
Subscription(200, 210)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeed_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.reduce(42, accumulator: +) }
let correctMessages: [Recorded<Event<Int>>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeed_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 3),
next(250, 4),
completed(260)
])
let res = scheduler.start { xs.reduce(42, accumulator: +) }
let correctMessages = [
next(260, 42 + 0 + 1 + 2 + 3 + 4),
completed(260)
]
let correctSubscriptions = [
Subscription(200, 260)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeed_AccumulatorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 3),
next(250, 4),
completed(260)
])
let res = scheduler.start {
xs.reduce(42) { (a: Int, x: Int) throws -> Int in
if x < 3 {
return a + x
}
else {
throw testError
}
}
}
let correctMessages = [
error(240, testError, Int.self)
]
let correctSubscriptions = [
Subscription(200, 240)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_Empty() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
completed(250)
])
let res = scheduler.start { xs.reduce(42, accumulator: +) { $0 * 5 } }
let correctMessages = [
next(250, 42 * 5),
completed(250)
]
let correctSubscriptions = [
Subscription(200, 250)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_Return() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 24),
completed(250)
])
let res = scheduler.start { xs.reduce(42, accumulator: +, mapResult: { $0 * 5 }) }
let correctMessages = [
next(250, (42 + 24) * 5),
completed(250)
]
let correctSubscriptions = [
Subscription(200, 250)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_Throw() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
error(210, testError),
])
let res = scheduler.start { xs.reduce(42, accumulator: +, mapResult: { $0 * 5 }) }
let correctMessages: [Recorded<Event<Int>>] = [
error(210, testError, Int.self)
]
let correctSubscriptions = [
Subscription(200, 210)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_Never() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
])
let res = scheduler.start { xs.reduce(42, accumulator: +, mapResult: { $0 * 5 }) }
let correctMessages: [Recorded<Event<Int>>] = [
]
let correctSubscriptions = [
Subscription(200, 1000)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_Range() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 3),
next(250, 4),
completed(260)
])
let res = scheduler.start { xs.reduce(42, accumulator: +, mapResult: { $0 * 5 }) }
let correctMessages = [
next(260, (42 + 0 + 1 + 2 + 3 + 4) * 5),
completed(260)
]
let correctSubscriptions = [
Subscription(200, 260)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_AccumulatorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 3),
next(250, 4),
completed(260)
])
let res = scheduler.start { xs.reduce(42, accumulator: { a, x in if x < 3 { return a + x } else { throw testError } }, mapResult: { $0 * 5 }) }
let correctMessages = [
error(240, testError, Int.self)
]
let correctSubscriptions = [
Subscription(200, 240)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
func test_ReduceWithSeedAndResult_SelectorThrows() {
let scheduler = TestScheduler(initialClock: 0)
let xs = scheduler.createHotObservable([
next(150, 1),
next(210, 0),
next(220, 1),
next(230, 2),
next(240, 3),
next(250, 4),
completed(260)
])
let res = scheduler.start { xs.reduce(42, accumulator: +, mapResult: { (_: Int) throws -> Int in throw testError }) }
let correctMessages = [
error(260, testError, Int.self)
]
let correctSubscriptions = [
Subscription(200, 260)
]
XCTAssertEqual(res.events, correctMessages)
XCTAssertEqual(xs.subscriptions, correctSubscriptions)
}
#if TRACE_RESOURCES
func testReduceReleasesResourcesOnComplete() {
_ = Observable<Int>.just(1).reduce(0, accumulator: +, mapResult: { $0 }).subscribe()
}
func testReduceReleasesResourcesOnError() {
_ = Observable<Int>.just(1).reduce(0, accumulator: +).subscribe()
}
#endif
}
| mit | eff4f20a147d7f8a3359fd801ea4b932 | 25.797721 | 151 | 0.54731 | 4.760121 | false | true | false | false |
mtviewdave/PhotoPicker | PhotoPicker/Util/ICPhotoAlbumAccess.swift | 1 | 2440 | //
// ICPhotoAlbumAccess.swift
// PhotoPicker
//
// Created by David Schreiber on 6/29/15.
// Copyright (c) 2015 Metebelis Labs LLC. All rights reserved.
//
import UIKit
import Photos
import AssetsLibrary
private var icAlert : ICAlertView?
func authorizePhotoAlbumAccess(explainerText : String,completion : ((accessGranted : Bool)->()) ) {
// iOS >= 8.0
if objc_getClass("PHPhotoLibrary") != nil {
switch PHPhotoLibrary.authorizationStatus() {
case .NotDetermined:
PHPhotoLibrary.requestAuthorization({ (authStatus) -> Void in
completion(accessGranted: (authStatus == .Authorized))
});
case .Authorized:
completion(accessGranted:true)
case .Denied:
// In iOS >= 8, you can take the user to their Settings to allow them to
// enable permissions
let newICAlert = ICAlertView(title:"We need your permission",message:"Ingerchat does not have permission to access your photos. " + explainerText + ", you will need to go to the Settings app and give Ingerchat permission.", cancelButtonTitle: "Never Mind", otherButtonTitle: "Go to Settings",callback: { (result) -> () in
if result == ICAlertViewResult.Other {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
icAlert = nil
})
icAlert = newICAlert
newICAlert.show()
case .Restricted:
UIAlertView(title: nil, message: "You do not have permission to access the photo album.", delegate: nil, cancelButtonTitle: "OK").show()
}
} else {
switch ALAssetsLibrary.authorizationStatus() {
case .NotDetermined:
completion(accessGranted: true) // A clever lie; will cause authorization alert to appear
case .Authorized:
completion(accessGranted: true)
case .Denied:
UIAlertView(title: "We need your permission", message: "Ingerchat does not have permission to access your photos. " + explainerText + ", you will need to go to the Settings app and give Ingerchat permission.", delegate: nil, cancelButtonTitle: "OK").show()
case .Restricted:
UIAlertView(title: nil, message: "You do not have permission to access the photo album.", delegate: nil, cancelButtonTitle: "OK").show()
}
}
} | apache-2.0 | 0cd5a3eeacdbf5e3cd557f9165c74805 | 45.942308 | 333 | 0.643443 | 4.84127 | false | false | false | false |
cuappdev/podcast-ios | old/Podcast/DiscoverCollectionViewHeaderView.swift | 1 | 2702 | //
// DiscoverTableViewHeaderView.swift
// Podcast
//
// Created by Kevin Greer on 2/19/17.
// Copyright © 2017 Cornell App Development. All rights reserved.
//
import UIKit
enum DiscoverHeaderType: String {
case topics = "Topics"
case series = "Series"
case episodes = "Episodes"
case continueListening = "Jump Back In"
}
protocol DiscoverTableViewHeaderDelegate: class {
func discoverTableViewHeaderDidPressBrowse(sender: DiscoverCollectionViewHeaderView)
}
class DiscoverCollectionViewHeaderView: UIView {
let edgePadding: CGFloat = 18
var headerHeight: CGFloat = 60
var mainLabel: UILabel!
var browseButton: UIButton!
weak var delegate: DiscoverTableViewHeaderDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
mainLabel = UILabel(frame: .zero)
mainLabel.font = ._14SemiboldFont()
mainLabel.textColor = .charcoalGrey
addSubview(mainLabel)
mainLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(edgePadding)
make.height.equalTo(headerHeight)
make.top.equalToSuperview()
}
browseButton = UIButton(frame: .zero)
browseButton.titleLabel?.font = ._12RegularFont()
browseButton.setTitleColor(.slateGrey, for: .normal)
browseButton.addTarget(self, action: #selector(pressBrowse), for: .touchUpInside)
addSubview(browseButton)
browseButton.snp.makeConstraints { make in
make.trailing.equalToSuperview().inset(edgePadding)
make.height.equalTo(headerHeight)
make.top.equalToSuperview()
}
}
func configure(sectionType: DiscoverHeaderType) {
mainLabel.text = "Top \(sectionType.rawValue)"
switch sectionType {
case .topics:
browseButton.setTitle("Browse all \(sectionType.rawValue.lowercased())", for: .normal)
mainLabel.text = "All \(sectionType.rawValue)"
case .series:
browseButton.setTitle("Browse top \(sectionType.rawValue.lowercased())", for: .normal)
case .episodes:
browseButton.isEnabled = false
browseButton.isHidden = true
case .continueListening:
headerHeight = 30
browseButton.isEnabled = false
browseButton.isHidden = true
backgroundColor = .offWhite
mainLabel.text = sectionType.rawValue
}
}
@objc func pressBrowse() {
delegate?.discoverTableViewHeaderDidPressBrowse(sender: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 6fe8c6a9fc136134586b5c95b82c676e | 31.154762 | 98 | 0.656424 | 4.910909 | false | false | false | false |
Allow2CEO/browser-ios | Client/Frontend/Settings/SettingsContentViewController.swift | 1 | 5756 | /* 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 Shared
import SnapKit
import UIKit
import WebKit
let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild.
/**
* A controller that manages a single web view and provides a way for
* the user to navigate back to Settings.
*/
class SettingsContentViewController: UIViewController, WKNavigationDelegate {
let interstitialBackgroundColor: UIColor
var settingsTitle: NSAttributedString?
var url: URL!
var timer: Timer?
var isLoaded: Bool = false {
didSet {
if isLoaded {
UIView.transition(from: interstitialView, to: webView,
duration: 0.5,
options: UIViewAnimationOptions.transitionCrossDissolve,
completion: { finished in
self.interstitialView.removeFromSuperview()
self.interstitialSpinnerView.stopAnimating()
})
}
}
}
fileprivate var isError: Bool = false {
didSet {
if isError {
interstitialErrorView.isHidden = false
UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView,
duration: 0.5,
options: UIViewAnimationOptions.transitionCrossDissolve,
completion: { finished in
self.interstitialSpinnerView.removeFromSuperview()
self.interstitialSpinnerView.stopAnimating()
})
}
}
}
// The view shown while the content is loading in the background web view.
fileprivate var interstitialView: UIView!
fileprivate var interstitialSpinnerView: UIActivityIndicatorView!
fileprivate var interstitialErrorView: UILabel!
// The web view that displays content.
var webView: WKWebView!
fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) {
if self.isLoaded {
return
}
if timeout > 0 {
self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(SettingsContentViewController.SELdidTimeOut), userInfo: nil, repeats: false)
} else {
self.timer = nil
}
self.webView.load(URLRequest(url: url))
self.interstitialSpinnerView.startAnimating()
}
init(backgroundColor: UIColor = UIColor.white, title: NSAttributedString? = nil) {
interstitialBackgroundColor = backgroundColor
settingsTitle = title
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// This background agrees with the web page background.
// Keeping the background constant prevents a pop of mismatched color.
view.backgroundColor = interstitialBackgroundColor
self.webView = makeWebView()
view.addSubview(webView)
self.webView.snp.remakeConstraints { make in
make.edges.equalTo(self.view)
}
// Destructuring let causes problems.
let ret = makeInterstitialViews()
self.interstitialView = ret.0
self.interstitialSpinnerView = ret.1
self.interstitialErrorView = ret.2
view.addSubview(interstitialView)
self.interstitialView.snp.remakeConstraints { make in
make.edges.equalTo(self.view)
}
startLoading()
}
func makeWebView() -> WKWebView {
let config = WKWebViewConfiguration()
let webView = WKWebView(
frame: CGRect(x: 0, y: 0, width: 1, height: 1),
configuration: config
)
webView.navigationDelegate = self
return webView
}
fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) {
let view = UIView()
// Keeping the background constant prevents a pop of mismatched color.
view.backgroundColor = interstitialBackgroundColor
let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
view.addSubview(spinner)
let error = UILabel()
if let _ = settingsTitle {
error.text = "Page load error"
error.textColor = UIColor.red // Firefox Orange!
error.textAlignment = NSTextAlignment.center
}
error.isHidden = true
view.addSubview(error)
spinner.snp.makeConstraints { make in
make.center.equalTo(view)
return
}
error.snp.makeConstraints { make in
make.center.equalTo(view)
make.left.equalTo(view.snp.left).offset(20)
make.right.equalTo(view.snp.right).offset(-20)
make.height.equalTo(44)
return
}
return (view, spinner, error)
}
func SELdidTimeOut() {
self.timer = nil
self.isError = true
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
SELdidTimeOut()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
SELdidTimeOut()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
}
| mpl-2.0 | 9107e24b68ad252a6880858a6440a04f | 32.660819 | 179 | 0.629256 | 5.409774 | false | false | false | false |
Evgeniy-Odesskiy/Bond | BondTests/UIButtonTests.swift | 12 | 2420 | //
// UIButtonTests.swift
// Bond
//
// Created by Anthony Egerton on 11/03/2015.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
import XCTest
import Bond
class UIButtonTests: XCTestCase {
func testUIButtonEnabledBond() {
var dynamicDriver = Dynamic<Bool>(false)
let button = UIButton()
button.enabled = true
XCTAssert(button.enabled == true, "Initial value")
dynamicDriver ->> button.designatedBond
XCTAssert(button.enabled == false, "Value after binding")
dynamicDriver.value = true
XCTAssert(button.enabled == true, "Value after dynamic change")
}
func testUIButtonTitleBond() {
var dynamicDriver = Dynamic<String>("b")
let button = UIButton()
button.titleLabel?.text = "a"
XCTAssert(button.titleLabel?.text == "a", "Initial value")
dynamicDriver ->> button.dynTitle
XCTAssert(button.titleLabel?.text == "b", "Value after binding")
dynamicDriver.value = "c"
XCTAssert(button.titleLabel?.text == "c", "Value after dynamic change")
}
func testUIButtonImageBond() {
let image1 = UIImage()
let image2 = UIImage()
var dynamicDriver = Dynamic<UIImage?>(nil)
let button = UIButton()
button.setImage(image1, forState: .Normal)
XCTAssert(button.imageForState(.Normal) == image1, "Initial value")
dynamicDriver ->> button.dynImageForNormalState
XCTAssert(button.imageForState(.Normal) == nil, "Value after binding")
dynamicDriver.value = image2
XCTAssert(button.imageForState(.Normal) == image2, "Value after dynamic change")
}
func testUIButtonDynamic() {
let button = UIButton()
var observedValue = UIControlEvents.AllEvents
let bond = Bond<UIControlEvents>() { v in observedValue = v }
XCTAssert(button.dynEvent.valid == false, "Should be faulty initially")
button.dynEvent.filter(==, .TouchUpInside) ->> bond
XCTAssert(observedValue == UIControlEvents.AllEvents, "Value after binding should not be changed")
button.sendActionsForControlEvents(.TouchDragInside)
XCTAssert(observedValue == UIControlEvents.AllEvents, "Dynamic change does not pass test - should not update observedValue")
button.sendActionsForControlEvents(.TouchUpInside)
XCTAssert(observedValue == UIControlEvents.TouchUpInside, "Dynamic change passes test - should update observedValue")
}
}
| mit | c037547025a6afbb46ee01ac56043da9 | 30.842105 | 128 | 0.692975 | 4.583333 | false | true | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.Version.swift | 1 | 2009 | import Foundation
public extension AnyCharacteristic {
static func version(
_ value: String = "",
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Version",
format: CharacteristicFormat? = .string,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.version(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func version(
_ value: String = "",
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Version",
format: CharacteristicFormat? = .string,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<String> {
GenericCharacteristic<String>(
type: .version,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | f7ea9542b10507db2b49ebdc90b64194 | 31.934426 | 67 | 0.569438 | 5.489071 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Notification/ViewCell/CPMesNotificationCell.swift | 1 | 1924 | //
// CPMesNotificationCell.swift
// BeeFun
//
// Created by WengHengcong on 3/7/16.
// Copyright © 2016 JungleSong. All rights reserved.
//
import UIKit
class CPMesNotificationCell: BFBaseCell {
@IBOutlet weak var typeImageV: UIImageView!
@IBOutlet weak var notificationLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var reposBtn: UIButton!
var noti: ObjNotification? {
didSet {
notiCell_fillData()
}
}
override func p_customCellView() {
super.p_customCellView()
//test
//if you want to change position or size by set frame property,you first disable autolayout.
// typeImageV.frame = CGRectMake(50, 10, 44, 44);
}
func notiCell_fillData() {
if let type = noti?.subject?.type {
let notiType: SubjectType? = SubjectType(rawValue: type)
if notiType != nil {
typeImageV.isHidden = false
switch notiType! {
case .issue:
typeImageV.image = UIImage(named: "octicon_issue_25")
case .pullRequest:
typeImageV.image = UIImage(named: "octicon_pull_request_25")
case .release:
typeImageV.image = UIImage(named: "coticon_tag_25")
case .commit:
typeImageV.image = UIImage(named: "octicon_commit_25")
}
} else {
typeImageV.isHidden = true
}
}
if let title = noti?.subject?.title {
notificationLabel.text = title
}
if let name = noti?.repository?.name {
reposBtn.setTitle(name, for: UIControlState())
}
if let time = noti?.updated_at {
//time
timeLabel.text = BFTimeHelper.shared.readableTime(rare: time, prefix: nil)
}
}
}
| mit | 4e60d04e63f15e666dc6ec51bb914e62 | 24.986486 | 100 | 0.554342 | 4.370455 | false | false | false | false |
stephentyrone/swift | stdlib/public/core/StringComparable.swift | 3 | 3365 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
extension StringProtocol {
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func == <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .equal)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func != <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs == rhs)
}
@inlinable
@_specialize(where Self == String, RHS == String)
@_specialize(where Self == String, RHS == Substring)
@_specialize(where Self == Substring, RHS == String)
@_specialize(where Self == Substring, RHS == Substring)
@_effects(readonly)
public static func < <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return _stringCompare(
lhs._wholeGuts, lhs._offsetRange,
rhs._wholeGuts, rhs._offsetRange,
expecting: .less)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func > <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return rhs < lhs
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func <= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(rhs < lhs)
}
@inlinable @inline(__always) // forward to other operator
@_effects(readonly)
public static func >= <RHS: StringProtocol>(lhs: Self, rhs: RHS) -> Bool {
return !(lhs < rhs)
}
}
extension String: Equatable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
@_semantics("string.equals")
public static func == (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .equal)
}
}
extension String: Comparable {
@inlinable @inline(__always) // For the bitwise comparision
@_effects(readonly)
public static func < (lhs: String, rhs: String) -> Bool {
return _stringCompare(lhs._guts, rhs._guts, expecting: .less)
}
}
extension Substring: Equatable {}
// TODO(SR-12457): Generalize `~=` over `StringProtocol`. Below are
// concrete overloads to give us most of the benefit without potential harm
// to expression type checking performance.
extension String {
@_alwaysEmitIntoClient
@inline(__always)
@_effects(readonly)
public static func ~= (lhs: String, rhs: Substring) -> Bool {
return lhs == rhs
}
}
extension Substring {
@_alwaysEmitIntoClient
@inline(__always)
@_effects(readonly)
public static func ~= (lhs: Substring, rhs: String) -> Bool {
return lhs == rhs
}
}
| apache-2.0 | bd43d3d5fafd5106b0af4db61dbeef7f | 30.745283 | 80 | 0.641902 | 4.174938 | false | false | false | false |
mibaldi/IOS_MIMO_APP | iosAPP/models/Notification.swift | 1 | 1355 | //
// Notification.swift
// iosAPP
//
// Created by MIMO on 28/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import Foundation
extension NSDate {
class var declaredDatatype: String {
return String.declaredDatatype
}
class func fromDatatypeValue(stringValue: String) -> NSDate {
return SQLDateFormatter.dateFromString(stringValue)!
}
var datatypeValue: String {
return SQLDateFormatter.stringFromDate(self)
}
}
let SQLDateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
return formatter
}()
class Notification: NSObject {
var notificationId = Int64()
var firedate = NSDate()
var recipeId = Int64()
var taskId = Int64()
static func findNotification(task:Task) -> Notification?{
var currentNotification : Notification?
do{
if let dso = try NotificationsDataHelper.findNotificationByTask((task.taskIdServer)){
currentNotification = dso
}
}catch _{
print("Error al encontrar Notification")
}
return currentNotification
}
} | apache-2.0 | c11abd2896236158acf56ff7f4704427 | 25.568627 | 97 | 0.64771 | 4.589831 | false | false | false | false |
Chaosspeeder/YourGoals | Pods/Eureka/Source/Core/Cell.swift | 2 | 5315 | // Cell.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 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.
import Foundation
import UIKit
/// Base class for the Eureka cells
open class BaseCell: UITableViewCell, BaseCellType {
/// Untyped row associated to this cell.
public var baseRow: BaseRow! { return nil }
/// Block that returns the height for this cell.
public var height: (() -> CGFloat)?
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public required override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function that returns the FormViewController this cell belongs to.
*/
public func formViewController() -> FormViewController? {
var responder: AnyObject? = self
while responder != nil {
if let formVC = responder as? FormViewController {
return formVC
}
responder = responder?.next
}
return nil
}
open func setup() {}
open func update() {}
open func didSelect() {}
/**
If the cell can become first responder. By default returns false
*/
open func cellCanBecomeFirstResponder() -> Bool {
return false
}
/**
Called when the cell becomes first responder
*/
@discardableResult
open func cellBecomeFirstResponder(withDirection: Direction = .down) -> Bool {
return becomeFirstResponder()
}
/**
Called when the cell resigns first responder
*/
@discardableResult
open func cellResignFirstResponder() -> Bool {
return resignFirstResponder()
}
}
/// Generic class that represents the Eureka cells.
open class Cell<T>: BaseCell, TypedCellType where T: Equatable {
public typealias Value = T
/// The row associated to this cell
public weak var row: RowOf<T>!
private var updatingCellForTintColorDidChange = false
/// Returns the navigationAccessoryView if it is defined or calls super if not.
override open var inputAccessoryView: UIView? {
if let v = formViewController()?.inputAccessoryView(for: row) {
return v
}
return super.inputAccessoryView
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
required public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
/**
Function responsible for setting up the cell at creation time.
*/
open override func setup() {
super.setup()
}
/**
Function responsible for updating the cell each time it is reloaded.
*/
open override func update() {
super.update()
textLabel?.text = row.title
textLabel?.textColor = row.isDisabled ? .gray : .black
detailTextLabel?.text = row.displayValueFor?(row.value) ?? (row as? NoValueDisplayTextConformance)?.noValueDisplayText
}
/**
Called when the cell was selected.
*/
open override func didSelect() {}
override open var canBecomeFirstResponder: Bool {
return false
}
open override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
if result {
formViewController()?.beginEditing(of: self)
}
return result
}
open override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
if result {
formViewController()?.endEditing(of: self)
}
return result
}
open override func tintColorDidChange() {
super.tintColorDidChange()
/* Protection from infinite recursion in case an update method changes the tintColor */
if !updatingCellForTintColorDidChange && row != nil {
updatingCellForTintColorDidChange = true
row.updateCell()
updatingCellForTintColorDidChange = false
}
}
/// The untyped row associated to this cell.
public override var baseRow: BaseRow! { return row }
}
| lgpl-3.0 | 7b80c288fdf32cb6ec3c575cc2c145b4 | 30.449704 | 126 | 0.66604 | 5.110577 | false | false | false | false |
bryan1anderson/iMessage-to-Day-One-Importer | iMessage Importer/GroupMessasgeMemberJoin.swift | 1 | 5873 | //
// GroupMessasgeMemberJoin.swift
// iMessage Importer
//
// Created by Bryan on 9/19/17.
// Copyright © 2017 Bryan Lloyd Anderson. All rights reserved.
//
import Foundation
import SQLite
import Contacts
struct GroupMessageMemberJoin: Equatable {
let group: Group
let messages: [OldMessage]
let members: [Member]?
let date: Date
init(group: Group, messages: [OldMessage], members: [Member]?, date: Date) {
self.group = group
self.messages = messages
self.members = members
self.date = date
}
static func ==(lhs: GroupMessageMemberJoin, rhs: GroupMessageMemberJoin) -> Bool {
let messagesAreSame = containSameElements(lhs.messages, rhs.messages)
let membersAreSame = containSameElements(lhs.members ?? [], rhs.members ?? [])
return messagesAreSame && membersAreSame
}
}
extension GroupMessageMemberJoin: ContactsProtocol {
func getNameString(for contacts: [OldContact]) -> String? {
if contacts.count > 0 {
// print(contacts)
let names = contacts.flatMap({ "\($0.first?.capitalized ?? "") \($0.last?.capitalized ?? "")" }).removeDuplicates()
let nameString = names.joined(separator: " ")
return nameString
} else {
return nil
}
}
func getReadableString(completion: @escaping (_ entry: Entry) -> ()) {
// let handleID = Expression<Int>("handle_id")
// let group = DispatchGroup()
// var contactsArray = [CNContact]()
let members = self.members ?? []
// group.enter()
let contacts = members.flatMap({ getContacts(member: $0) })
var addressContacts = [CNContact]()
// if conversationName == nil || conversationName == "" {
let phone = contacts.flatMap({ $0.values }).first
let memberPhone = members.flatMap({ $0.address }).first
var conversationName = self.getNameString(for: contacts) ?? phone
if conversationName != nil {
// return
} else {
conversationName = memberPhone
addressContacts = self.members?.flatMap({ self.getContactsFromAddressBook(member: $0) }) ?? []
let nameString = getNameString(for: addressContacts)
if let nameString = nameString {
conversationName = nameString
}
}
// }
let title = "Messages with: \(conversationName ?? "UNKNOWN")"
var text = ""
/*
`31-Dec-11` `Brantly` What are you doing tonight?
*/
let messages = self.messages.sorted(by: { $0.date < $1.date })
for message in messages {
let handle = message.address
let contact = contacts.first(where: { (oldContact) -> Bool in
guard let handle = handle else { return false }
return oldContact.values.contains(handle)
})
let firstName = contacts.first?.first ?? addressContacts.first?.givenName
//if handleID == 0, handle is ME
let meString = "### Me"
let name = message.isFromMe ? meString : "#### \(firstName ?? handle ?? "UNKNOWN NAME")"
let messageText = message.text ?? ""
let line = "\n \(name) \n \(messageText) \n ###### \(message.dateString()) \n "
text.append(line)
}
// group.notify(queue: .main) {
var tags = [String]()
if let conversationName = conversationName {
tags.append(conversationName)
} else {
tags.append("UNKNOWN")
}
let escapedString = text.replacingOccurrences(of: "\n", with: "\n").replacingOccurrences(of: "“", with: "").replacingOccurrences(of: "”", with: "").replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: "\'", with: "")
let entry = Entry(date: date.yesterday, tags: tags, title: title, body: escapedString, hasAttachments: false, attachments: nil)
completion(entry)
// }
}
func getContactsFromAddressBook(member: Member) -> [CNContact] {
guard let number = member.address else { return [] }
let group = DispatchGroup()
group.enter()
var contactsArray = [CNContact]()
getContacts(phoneNumber: number) { (contacts) in
contactsArray = contacts
group.leave()
}
group.wait()
// let contact = Contact(handle: handle, contacts: contactsArray)
return contactsArray
}
func getContacts(member: Member) -> [OldContact] {
guard let number = member.address else { return [] }
let filteredContacts = ContactImporter.shared.oldContacts.filter { (oldContact) -> Bool in
let values = oldContact.values.filter({ (value) -> Bool in
let value = value.cleaned
let phoneNumberToCompare = value.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
if phoneNumberToCompare.contains(number) || number.contains(phoneNumberToCompare)
&& phoneNumberToCompare.characters.count > 5 {
return true
} else {
return false
}
})
return values.count > 0
}
return filteredContacts
}
}
| mit | f486826e2163625b9078521b6100595f | 32.919075 | 237 | 0.532038 | 4.994043 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGeometry/Shape/PathCoder.swift | 1 | 13035 | //
// PathCoder.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
extension Shape {
public init?(data: Data) {
self.init()
var data = data
var last = Point()
var last_control = Point()
func decode_point(_ data: inout Data) -> Point? {
guard let x = try? data.decode(BEUInt64.self) else { return nil }
guard let y = try? data.decode(BEUInt64.self) else { return nil }
return Point(x: Double(bitPattern: UInt64(x)), y: Double(bitPattern: UInt64(y)))
}
while let command = data.popFirst() {
switch command {
case 0: self.close()
case 1:
guard let p0 = decode_point(&data) else { return nil }
self.move(to: p0)
last = p0
last_control = p0
case 2:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p1 = decode_point(&data) else { return nil }
self.line(to: p1)
last = p1
last_control = p1
}
case 3:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p2 = decode_point(&data) else { return nil }
let p1 = 2 * last - last_control
self.quad(to: p2, control: p1)
last = p2
last_control = p1
}
case 4:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p1 = decode_point(&data) else { return nil }
guard let p2 = decode_point(&data) else { return nil }
self.quad(to: p2, control: p1)
last = p2
last_control = p1
}
case 5:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p3 = decode_point(&data) else { return nil }
let p1 = 2 * last - last_control
let p2 = p1
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
case 6:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p2 = decode_point(&data) else { return nil }
guard let p3 = decode_point(&data) else { return nil }
let p1 = 2 * last - last_control
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
case 7:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let m = try? data.decode(BEUInt64.self) else { return nil }
guard let p3 = decode_point(&data) else { return nil }
let p1 = Double(bitPattern: UInt64(m)) * (last - last_control).unit + last
let p2 = p1
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
case 8:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let m = try? data.decode(BEUInt64.self) else { return nil }
guard let p2 = decode_point(&data) else { return nil }
guard let p3 = decode_point(&data) else { return nil }
let p1 = Double(bitPattern: UInt64(m)) * (last - last_control).unit + last
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
case 9:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p1 = decode_point(&data) else { return nil }
guard let p3 = decode_point(&data) else { return nil }
let p2 = p1
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
case 10:
guard let count = try? data.decode(UInt8.self) else { return nil }
for _ in 0..<count {
guard let p1 = decode_point(&data) else { return nil }
guard let p2 = decode_point(&data) else { return nil }
guard let p3 = decode_point(&data) else { return nil }
self.curve(to: p3, control1: p1, control2: p2)
last = p3
last_control = p2
}
default: return nil
}
}
}
public var data: Data {
var data = Data()
var buffer = Data()
for component in self {
data.append(1)
data.encode(BEUInt64(component.start.x.bitPattern))
data.encode(BEUInt64(component.start.y.bitPattern))
var last = component.start
var last_control = component.start
var last_command: UInt8 = 1
var counter: UInt8 = 0
buffer.removeAll(keepingCapacity: true)
func encode_command(_ c: UInt8) {
guard last_command != c || counter == .max else { return }
if counter != 0 {
data.append(last_command)
data.append(counter)
data.append(buffer)
}
last_command = c
counter = 0
buffer.removeAll(keepingCapacity: true)
}
for segment in component {
switch segment {
case let .line(p1):
encode_command(2)
buffer.encode(BEUInt64(p1.x.bitPattern))
buffer.encode(BEUInt64(p1.y.bitPattern))
last = p1
last_control = p1
counter += 1
case let .quad(p1, p2):
if p1.almostEqual(2 * last - last_control) {
encode_command(3)
buffer.encode(BEUInt64(p2.x.bitPattern))
buffer.encode(BEUInt64(p2.y.bitPattern))
} else {
encode_command(4)
buffer.encode(BEUInt64(p1.x.bitPattern))
buffer.encode(BEUInt64(p1.y.bitPattern))
buffer.encode(BEUInt64(p2.x.bitPattern))
buffer.encode(BEUInt64(p2.y.bitPattern))
}
last = p2
last_control = p1
counter += 1
case let .cubic(p1, p2, p3):
if p1.almostEqual(2 * last - last_control) {
if p1.almostEqual(p2) {
encode_command(5)
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
} else {
encode_command(6)
buffer.encode(BEUInt64(p2.x.bitPattern))
buffer.encode(BEUInt64(p2.y.bitPattern))
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
}
} else if (p1 - last).unit.almostEqual((last - last_control).unit) {
if p1.almostEqual(p2) {
encode_command(7)
buffer.encode(BEUInt64(p1.distance(to: last).bitPattern))
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
} else {
encode_command(8)
buffer.encode(BEUInt64(p1.distance(to: last).bitPattern))
buffer.encode(BEUInt64(p2.x.bitPattern))
buffer.encode(BEUInt64(p2.y.bitPattern))
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
}
} else {
if p1.almostEqual(p2) {
encode_command(9)
buffer.encode(BEUInt64(p1.x.bitPattern))
buffer.encode(BEUInt64(p1.y.bitPattern))
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
} else {
encode_command(10)
buffer.encode(BEUInt64(p1.x.bitPattern))
buffer.encode(BEUInt64(p1.y.bitPattern))
buffer.encode(BEUInt64(p2.x.bitPattern))
buffer.encode(BEUInt64(p2.y.bitPattern))
buffer.encode(BEUInt64(p3.x.bitPattern))
buffer.encode(BEUInt64(p3.y.bitPattern))
}
}
last = p3
last_control = p2
counter += 1
}
}
if counter != 0 {
data.append(last_command)
data.append(counter)
data.append(buffer)
}
if component.isClosed {
data.append(0)
}
}
return data
}
}
| mit | 3ec9f3e3a98fd7f57dd9714728c4be8a | 37.910448 | 94 | 0.403989 | 5.162376 | false | false | false | false |
samodom/TestableUIKit | TestableUIKit/UIResponder/UIView/UIViewDrawSpy.swift | 1 | 2485 | //
// UIViewDrawSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 12/10/16.
// Copyright © 2016 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UIView {
private static let drawCalledKeyString = UUIDKeyString()
private static let drawCalledKey =
ObjectAssociationKey(drawCalledKeyString)
private static let drawCalledReference =
SpyEvidenceReference(key: drawCalledKey)
private static let drawRectKeyString = UUIDKeyString()
private static let drawRectKey =
ObjectAssociationKey(drawRectKeyString)
private static let drawRectReference =
SpyEvidenceReference(key: drawRectKey)
private static let drawCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UIView.draw(_:)),
spy: #selector(UIView.spy_draw(_:))
)
/// Spy controller for ensuring that a subclass calls its superclass implementation
/// of `draw(_:)` when the same method is invoked on it.
public enum DrawSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UIView.self
public static let vector = SpyVector.indirect
public static let coselectors: Set = [drawCoselectors]
public static let evidence: Set = [drawCalledReference, drawRectReference]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `draw(_:)`
dynamic public func spy_draw(_ rect: CGRect) {
superclassDrawCalled = true
superclassDrawRect = rect
spy_draw(rect)
}
/// Indicates whether the `draw(_:)` method has been called on this object's superclass.
public final var superclassDrawCalled: Bool {
get {
return loadEvidence(with: UIView.drawCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UIView.drawCalledReference)
}
}
/// Provides the captured rect from a call to the `draw(_:)` method, if called.
public final var superclassDrawRect: CGRect? {
get {
return loadEvidence(with: UIView.drawRectReference) as? CGRect
}
set {
let reference = UIView.drawRectReference
guard let rect = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(rect, with: reference)
}
}
}
| mit | 033df620abfe1e2f5c4753675c108c07 | 29.666667 | 92 | 0.663849 | 5.207547 | false | false | false | false |
TomHarte/CLK | OSBindings/Mac/Clock SignalTests/65816kromTests.swift | 1 | 6321 | //
// krom65816Tests.swift
// Clock Signal
//
// Created by Thomas Harte on 02/11/2020.
// Copyright 2020 Thomas Harte. All rights reserved.
//
import Foundation
import XCTest
// This utilises krom's SNES-centric 65816 tests, comparing step-by-step to
// the traces offered by LilaQ at emudev.de as I don't want to implement a
// SNES just for the sake of result inspection.
//
// So:
// https://github.com/PeterLemon/SNES/tree/master/CPUTest/CPU for the tests;
// https://emudev.de/q00-snes/65816-the-cpu/ for the traces.
class Krom65816Tests: XCTestCase {
// MARK: - Test Runner
func runTest(_ name: String, pcLimit: UInt32? = nil) {
var testData: Data?
if let filename = Bundle(for: type(of: self)).url(forResource: name, withExtension: "sfc") {
testData = try? Data(contentsOf: filename)
}
var testOutput: String?
if let filename = Bundle(for: type(of: self)).url(forResource: name + "-trace_compare", withExtension: "log") {
testOutput = try? String(contentsOf: filename)
}
XCTAssertNotNil(testData)
XCTAssertNotNil(testOutput)
let outputLines = testOutput!.components(separatedBy: "\r\n")
// Assumptions about the SFC file format follow; I couldn't find a spec but those
// produced by krom appear just to be binary dumps. Fingers crossed!
let machine = CSTestMachine6502(processor: .processor65816)
machine.setData(testData!, atAddress: 0x8000)
// This reproduces the state seen at the first line of all of LilaQ's traces;
// TODO: determine whether (i) this is the SNES state at reset, or merely how
// some sort of BIOS leaves it; and (ii) if the former, whether I have post-reset
// state incorrect. I strongly suspect it's a SNES-specific artefact?
machine.setValue(0x8000, for: .programCounter)
machine.setValue(0x0000, for: .A)
machine.setValue(0x0000, for: .X)
machine.setValue(0x0000, for: .Y)
machine.setValue(0x00ff, for: .stackPointer)
machine.setValue(0x34, for: .flags)
// There seems to be some Nintendo-special register at address 0x0000.
machine.setValue(0xb5, forAddress: 0x0000)
// Poke some fixed values for SNES registers to get past initial setup.
machine.setValue(0x42, forAddress: 0x4210) // "RDNMI", apparently; this says: CPU version 2, vblank interrupt request.
var allowNegativeError = false
var lineNumber = 1
var previousPC = 0
for line in outputLines {
// At least one of the traces ends with an empty line; my preference is not to
// modify the originals if possible.
if line == "" {
break
}
machine.runForNumber(ofInstructions: 1)
let newPC = Int(machine.value(for: .lastOperationAddress))
// Stop right now if a PC limit has been specified and this is it.
if let pcLimit = pcLimit, pcLimit == newPC {
break
}
func machineState() -> String {
// Formulate my 65816 state in the same form as the test machine
var cpuState = ""
let emulationFlag = machine.value(for: .emulationFlag) != 0
cpuState += String(format: "%06x ", machine.value(for: .lastOperationAddress))
cpuState += String(format: "A:%04x ", machine.value(for: .A))
cpuState += String(format: "X:%04x ", machine.value(for: .X))
cpuState += String(format: "Y:%04x ", machine.value(for: .Y))
cpuState += String(format: "S:%04x ", machine.value(for: .stackPointer))
cpuState += String(format: "D:%04x ", machine.value(for: .direct))
cpuState += String(format: "DB:%02x ", machine.value(for: .dataBank))
let flags = machine.value(for: .flags)
cpuState += (flags & 0x80) != 0 ? "N" : "n"
cpuState += (flags & 0x40) != 0 ? "V" : "v"
if emulationFlag {
cpuState += "1B"
} else {
cpuState += (flags & 0x20) != 0 ? "M" : "m"
cpuState += (flags & 0x10) != 0 ? "X" : "x"
}
cpuState += (flags & 0x08) != 0 ? "D" : "d"
cpuState += (flags & 0x04) != 0 ? "I" : "i"
cpuState += (flags & 0x02) != 0 ? "Z" : "z"
cpuState += (flags & 0x01) != 0 ? "C" : "c"
cpuState += " "
return cpuState
}
// Permit a fix-up of the negative flag only if this line followed a test of $4210.
var cpuState = machineState()
if cpuState != line && allowNegativeError {
machine.setValue(machine.value(for: .flags) ^ 0x80, for: .flags)
cpuState = machineState()
}
XCTAssertEqual(cpuState, line, "Mismatch on line #\(lineNumber); after instruction #\(String(format:"%02x", machine.value(forAddress: UInt32(previousPC))))")
if cpuState != line {
break
}
lineNumber += 1
previousPC = newPC
// Check whether a 'RDNMI' toggle needs to happen by peeking at the next instruction;
// if it's BIT $4210 then toggle the top bit at address $4210.
//
// Coupling here: assume that by the time the test 65816 is aware it's on a new instruction
// it's because the actual 65816 has read a new opcode, and that if the 65816 has just read
// a new opcode then it has already advanced the program counter.
let programCounter = machine.value(for: .programCounter)
let nextInstr = [
machine.value(forAddress: UInt32(programCounter - 1)),
machine.value(forAddress: UInt32(programCounter + 0)),
machine.value(forAddress: UInt32(programCounter + 1))
]
allowNegativeError = nextInstr[0] == 0x2c && nextInstr[1] == 0x10 && nextInstr[2] == 0x42
}
}
// MARK: - Tests
func testADC() { runTest("CPUADC") }
func testAND() { runTest("CPUAND") }
func testASL() { runTest("CPUASL") }
func testBIT() { runTest("CPUBIT") }
func testBRA() { runTest("CPUBRA") }
func testCMP() { runTest("CPUCMP") }
func testDEC() { runTest("CPUDEC") }
func testEOR() { runTest("CPUEOR") }
func testINC() { runTest("CPUINC") }
func testJMP() { runTest("CPUJMP") }
func testLDR() { runTest("CPULDR") }
func testLSR() { runTest("CPULSR") }
func testMOV() { runTest("CPUMOV") }
func testORA() { runTest("CPUORA") }
func testPHL() { runTest("CPUPHL") }
func testPSR() { runTest("CPUPSR") }
func testROL() { runTest("CPUROL") }
func testROR() { runTest("CPUROR") }
func testSBC() { runTest("CPUSBC") }
func testSTR() { runTest("CPUSTR") }
func testTRN() { runTest("CPUTRN") }
// Ensure the MSC tests stop before they attempt to test STP and WAI;
// the test relies on SNES means for scheduling a future interrupt.
func testMSC() { runTest("CPUMSC", pcLimit: 0x8523) }
}
| mit | f978757ce38c19cf8752fd3b63001a35 | 36.850299 | 160 | 0.669198 | 3.075912 | false | true | false | false |
Aevit/SCScreenshot | SCScreenshot/SCScreenshot/Views/SSPhotoCell.swift | 1 | 1473 | //
// SSPhotoCell.swift
// SCScreenshot
//
// Created by Aevit on 15/9/16.
// Copyright (c) 2015年 Aevit. All rights reserved.
//
import UIKit
import ScreenShotManagerKit
import Photos
class SSPhotoCell: UICollectionViewCell {
internal var picBtn: UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
if (picBtn != nil) {
picBtn?.setImage(nil, forState: UIControlState.Normal)
}
super.prepareForReuse()
}
func commonInit() {
if picBtn != nil {
return
}
let aBtn: UIButton = UIButton(type: UIButtonType.Custom)
aBtn.frame = self.bounds
aBtn.userInteractionEnabled = false
aBtn.imageView!.contentMode = UIViewContentMode.ScaleAspectFill
self.addSubview(aBtn)
picBtn = aBtn
}
func fillData(info: AnyObject) {
if let asset: PHAsset = info as? PHAsset {
let imageWidth = UIScreen.mainScreen().scale * picBtn!.frame.size.width
SCPhotoTool.requestAImage(asset, size: CGSizeMake(imageWidth, imageWidth), didRequestAImage: { (resultImage, info) -> Void in
self.picBtn!.setImage(resultImage, forState: UIControlState.Normal)
})
}
}
}
| mit | 0f1cbabe1cf15288f47343ad8d332ea7 | 26.240741 | 137 | 0.615228 | 4.339233 | false | false | false | false |
ashfurrow/RxSwift | RxExample/RxExample/ViewController.swift | 2 | 1245 | //
// ViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 4/25/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS)
import UIKit
typealias OSViewController = UIViewController
#elseif os(OSX)
import Cocoa
typealias OSViewController = NSViewController
#endif
class ViewController: OSViewController {
#if TRACE_RESOURCES
#if !RX_NO_MODULE
private let startResourceCount = RxSwift.resourceCount
#else
private let startResourceCount = resourceCount
#endif
#endif
var disposeBag = DisposeBag()
override func viewDidLoad() {
#if TRACE_RESOURCES
print("Number of start resources = \(resourceCount)")
#endif
}
deinit {
#if TRACE_RESOURCES
print("View controller disposed with \(resourceCount) resources")
let numberOfResourcesThatShouldRemain = startResourceCount
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
assert(resourceCount <= numberOfResourcesThatShouldRemain, "Resources weren't cleaned properly")
})
#endif
}
} | mit | 287e1c9eb779d0fc1afbad58d7006e2a | 23.92 | 108 | 0.694779 | 4.322917 | false | false | false | false |
justinlevi/asymptotik-rnd-scenekit-kaleidoscope | Atk_Rnd_VisualToys/FrequencyCounter.swift | 2 | 813 | //
// FrequencyCounter.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 8/7/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
import QuartzCore
class FrequencyCounter {
private var _elapsedTimer:ElapsedTimer = ElapsedTimer()
private var _count:Int = 0
func start() {
_elapsedTimer.start()
_count = 0
}
func increment() {
_count += 1
}
var count:Int {
get {
return _count
}
}
var frequency:Double {
get {
let elapsed = _elapsedTimer.elapsed
if elapsed <= 0 {
return 0.0
}
else {
return Double(NSTimeInterval(_count) / elapsed)
}
}
}
} | mit | 3754df715a19233d3edbbaf110568528 | 17.930233 | 63 | 0.509225 | 4.169231 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.