repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jgwhite/gazpacho | Gazpacho/EpisodeViewController.swift | 1 | 2865 | //
// EpisodeViewController.swift
// Gazpacho
//
// Created by Jamie White on 16/06/2015.
// Copyright ยฉ 2015 Jamie White. All rights reserved.
//
import Cocoa
import AVKit
import AVFoundation
import WebKit
class EpisodeViewController: NSViewController, WebPolicyDelegate {
@IBOutlet weak var playerView: AVPlayerView!
@IBOutlet weak var webView: WebView!
let avdiStyles = "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://avdi.org/stylesheets/code.css\" />"
let ourStyles = "<style type=\"text/css\">body { font-family: sans-serif; font-size: 14px; line-height: 1.4 } p { max-width: 40em } pre { margin: 1.4em 0; border-left: 5px solid #f92661; padding-left: 10px }</style>"
var episode: Episode? {
didSet {
if episode != oldValue {
update()
}
}
}
var credentials: Credentials? {
didSet {
update()
}
}
override func viewDidLoad() {
update()
}
func update() {
displayHTML()
displayVideo()
}
func displayHTML() {
if let html = self.episode?.description {
let htmlWithCSS = avdiStyles + ourStyles + html
webView.mainFrame.loadHTMLString(htmlWithCSS, baseURL: NSURL(string: "http://www.rubytapas.com/")!)
}
}
func displayVideo() {
if let url = self.episode?.url, let credentials = self.credentials {
let token = Base64.encode("\(credentials.username):\(credentials.password)")
let headers = ["Authorization": "Basic \(token!)"]
let asset = AVURLAsset(URL: NSURL(string: url)!, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
let item = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: item)
playerView.player = player
player.play()
}
}
func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) {
if let url = request.URL {
let urlString = url.absoluteString
if !blacklisted(urlString) && whitelisted(urlString) {
listener.use()
} else {
NSWorkspace.sharedWorkspace().openURL(url)
}
}
}
private func blacklisted(str: String) -> Bool {
return BLACKLIST.contains() { str.hasPrefix($0) }
}
private func whitelisted(str: String) -> Bool {
return WHITELIST.contains() { str.hasPrefix($0) }
}
private let WHITELIST = [
"https://rubytapas.dpdcart.com",
"http://www.rubytapas.com/",
"http://avdi.org"
]
private let BLACKLIST = [
"https://rubytapas.dpdcart.com/subscriber/download"
]
}
| mit | fc01c39fe356eb26c7eb31537f6a89fb | 28.833333 | 220 | 0.600908 | 4.3003 | false | false | false | false |
emilstahl/swift | test/IDE/comment_attach.swift | 10 | 12074 | // NOTE: This file is sensitive to line numbers. Thus RUN and CHECK lines come
// below the code.
//
// NOTE: Please don't change this file to use FileCheck's feature to match
// relative line numbers: those lines are comments and we don't want to see
// anything extra in a test for documentation comments.
//===--- Check that we attach comments to all kinds of declarations.
/// decl_func_1 Aaa.
func decl_func_1() {}
/// decl_func_2 Aaa.
func decl_func_2<T>(t: T) {}
/// decl_func_3 Aaa.
@unknown_attribute
func decl_func_3() {}
@unknown_attribute
/// decl_func_4 Aaa. IS_DOC_NOT_ATTACHED
func decl_func_4() {}
@unknown_attribute
func
/// decl_func_5 Aaa. IS_DOC_NOT_ATTACHED
decl_func_5() {}
/// decl_var_1 Aaa.
var decl_var_1: Int
/// decl_var_2 decl_var_3 Aaa.
var (decl_var_2, decl_var_3): (Int, Float)
/// decl_var_4 Aaa.
@unknown_attribute
var decl_var_4: Int
/// decl_var_5 Aaa.
var decl_var_5: Int {
get {}
set {}
}
var decl_var_6: Int {
/// decl_var_6_get Aaa.
get {}
/// decl_var_6_set Aaa.
set {}
}
/// decl_var_7 Aaa.
var decl_var_7: Int = 0 {
willSet {}
didSet {}
}
var decl_var_8: Int = 0 {
/// decl_var_8_get Aaa.
willSet {}
/// decl_var_8_set Aaa.
didSet {}
}
/// decl_val_1 Aaa.
let decl_val_1: Int = 0
/// decl_val_2 decl_val_3 Aaa.
let (decl_val_2, decl_val_3): (Int, Float) = (0, 0.0)
/// decl_val_4 Aaa.
@unknown_attribute
let decl_val_4: Int = 0
/// decl_typealias_1 Aaa.
typealias decl_typealias_1 = Int
/// decl_struct_1 Aaa.
struct decl_struct_1 {
/// instanceVar1 Aaa.
var instanceVar1: Int
/// instanceVar2 instanceVar3 Aaa.
var (instanceVar2, instanceVar3): (Int, Float)
/// instanceVar4 Aaa.
@unknown_attribute
var instanceVar4: Int
/// instanceVar5 Aaa.
var instanceVar5: Int {
get {}
set {}
}
var instanceVar6: Int {
/// instanceVar6_get Aaa.
get {}
/// instanceVar6_set Aaa.
set {}
}
/// instanceVar7 Aaa.
var instanceVar7: Int = 0 {
willSet {}
didSet {}
}
var instanceVar8: Int = 0 {
/// instanceVar8_get Aaa.
willSet {}
/// instanceVar8_set Aaa.
didSet {}
}
/// instanceFunc1 Aaa.
func instanceFunc1() {}
/// instanceFunc2 Aaa.
@mutable
func instanceFunc2() {}
/// instanceFunc3 Aaa.
func instanceFunc3<T>(t: T) {}
/// instanceFunc4 Aaa.
@unknown_attribute
func instanceFunc4() {}
/// init(). Aaa.
init() {}
/// subscript Aaa.
subscript(i: Int) -> Double { return 0.0 }
/// NestedStruct Aaa.
struct NestedStruct {}
/// NestedClass Aaa.
class NestedClass {}
/// NestedEnum Aaa.
enum NestedEnum {}
// Can not declare a nested protocol.
// protocol NestedProtocol {}
/// NestedTypealias Aaa.
typealias NestedTypealias = Int
/// staticVar Aaa.
static var staticVar: Int = 4
/// staticFunc1 Aaa.
static func staticFunc1() {}
}
/// decl_enum_1 Aaa.
enum decl_enum_1 {
/// Case1 Aaa.
case Case1
/// Case2 Aaa.
case Case2(Int)
/// Case3 Aaa.
case Case3(Int, Float)
/// Case4 Case5 Aaa.
case Case4, Case5
}
/// decl_class_1 Aaa.
class decl_class_1 {
}
/// decl_protocol_1 Aaa.
protocol decl_protocol_1 {
/// NestedTypealias Aaa.
typealias NestedTypealias
/// instanceFunc1 Aaa.
func instanceFunc1()
/// propertyWithGet Aaa.
var propertyWithGet: Int { get }
/// propertyWithGetSet Aaa.
var propertyWithGetSet: Int { get set }
}
// FIXME: While there is nothing stopping us from attaching comments to
// extensions, how would we use those comments?
/// decl_extension_1 Aaa.
extension decl_extension_1 {
}
/***/
func emptyBlockDocComment() {}
/**/
func weirdBlockDocComment() {}
/// docCommentWithGybLineNumber Aaa.
/// Bbb.
// ###line 1010
/// Ccc.
// ###line 1010
func docCommentWithGybLineNumber() {}
/**
func unterminatedBlockDocComment() {}
// RUN: %target-swift-ide-test -print-comments -source-filename %s > %t.txt
// RUN: FileCheck %s -check-prefix=WRONG < %t.txt
// RUN: FileCheck %s < %t.txt
// Some comments are not attached to anything.
// WRONG-NOT: IS_DOC_NOT_ATTACHED
// CHECK: comment_attach.swift:14:6: Func/decl_func_1 RawComment=[/// decl_func_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:17:6: Func/decl_func_2 RawComment=[/// decl_func_2 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:17:21: Param/t RawComment=none
// CHECK-NEXT: comment_attach.swift:21:6: Func/decl_func_3 RawComment=[/// decl_func_3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:25:6: Func/decl_func_4 RawComment=none
// CHECK-NEXT: comment_attach.swift:30:3: Func/decl_func_5 RawComment=none
// CHECK-NEXT: comment_attach.swift:34:5: Var/decl_var_1 RawComment=[/// decl_var_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:37:6: Var/decl_var_2 RawComment=[/// decl_var_2 decl_var_3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:37:18: Var/decl_var_3 RawComment=[/// decl_var_2 decl_var_3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:41:5: Var/decl_var_4 RawComment=[/// decl_var_4 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:44:5: Var/decl_var_5 RawComment=[/// decl_var_5 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:45:3: Func/<getter for decl_var_5> RawComment=none
// CHECK-NEXT: comment_attach.swift:46:3: Func/<setter for decl_var_5> RawComment=none
// CHECK-NEXT: comment_attach.swift:49:5: Var/decl_var_6 RawComment=none
// CHECK-NEXT: comment_attach.swift:51:3: Func/<getter for decl_var_6> RawComment=none
// CHECK-NEXT: comment_attach.swift:53:3: Func/<setter for decl_var_6> RawComment=none
// CHECK-NEXT: comment_attach.swift:57:5: Var/decl_var_7 RawComment=[/// decl_var_7 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:58:3: Func/<willSet for decl_var_7> RawComment=none
// CHECK-NEXT: comment_attach.swift:59:3: Func/<didSet for decl_var_7> RawComment=none
// CHECK-NEXT: comment_attach.swift:62:5: Var/decl_var_8 RawComment=none
// CHECK-NEXT: comment_attach.swift:64:3: Func/<willSet for decl_var_8> RawComment=none
// CHECK-NEXT: comment_attach.swift:66:3: Func/<didSet for decl_var_8> RawComment=none
// CHECK-NEXT: comment_attach.swift:71:5: Var/decl_val_1 RawComment=[/// decl_val_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:74:6: Var/decl_val_2 RawComment=[/// decl_val_2 decl_val_3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:74:18: Var/decl_val_3 RawComment=[/// decl_val_2 decl_val_3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:78:5: Var/decl_val_4 RawComment=[/// decl_val_4 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:82:11: TypeAlias/decl_typealias_1 RawComment=[/// decl_typealias_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:85:8: Struct/decl_struct_1 RawComment=[/// decl_struct_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:87:7: Var/decl_struct_1.instanceVar1 RawComment=[/// instanceVar1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:90:8: Var/decl_struct_1.instanceVar2 RawComment=[/// instanceVar2 instanceVar3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:90:22: Var/decl_struct_1.instanceVar3 RawComment=[/// instanceVar2 instanceVar3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:94:7: Var/decl_struct_1.instanceVar4 RawComment=[/// instanceVar4 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:97:7: Var/decl_struct_1.instanceVar5 RawComment=[/// instanceVar5 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:98:5: Func/decl_struct_1.<getter for decl_struct_1.instanceVar5> RawComment=none
// CHECK-NEXT: comment_attach.swift:99:5: Func/decl_struct_1.<setter for decl_struct_1.instanceVar5> RawComment=none
// CHECK-NEXT: comment_attach.swift:102:7: Var/decl_struct_1.instanceVar6 RawComment=none
// CHECK-NEXT: comment_attach.swift:104:5: Func/decl_struct_1.<getter for decl_struct_1.instanceVar6> RawComment=none
// CHECK-NEXT: comment_attach.swift:106:5: Func/decl_struct_1.<setter for decl_struct_1.instanceVar6> RawComment=none
// CHECK-NEXT: comment_attach.swift:110:7: Var/decl_struct_1.instanceVar7 RawComment=[/// instanceVar7 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:111:5: Func/decl_struct_1.<willSet for decl_struct_1.instanceVar7> RawComment=none
// CHECK-NEXT: comment_attach.swift:112:5: Func/decl_struct_1.<didSet for decl_struct_1.instanceVar7> RawComment=none
// CHECK-NEXT: comment_attach.swift:115:7: Var/decl_struct_1.instanceVar8 RawComment=none
// CHECK-NEXT: comment_attach.swift:117:5: Func/decl_struct_1.<willSet for decl_struct_1.instanceVar8> RawComment=none
// CHECK-NEXT: comment_attach.swift:119:5: Func/decl_struct_1.<didSet for decl_struct_1.instanceVar8> RawComment=none
// CHECK-NEXT: comment_attach.swift:124:8: Func/decl_struct_1.instanceFunc1 RawComment=[/// instanceFunc1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:128:8: Func/decl_struct_1.instanceFunc2 RawComment=[/// instanceFunc2 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:131:8: Func/decl_struct_1.instanceFunc3 RawComment=[/// instanceFunc3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:131:25: Param/t RawComment=none
// CHECK-NEXT: comment_attach.swift:135:8: Func/decl_struct_1.instanceFunc4 RawComment=[/// instanceFunc4 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:138:3: Constructor/decl_struct_1.init RawComment=[/// init(). Aaa.\n] BriefComment=[init(). Aaa.]
// CHECK-NEXT: comment_attach.swift:141:3: Subscript/decl_struct_1.subscript RawComment=[/// subscript Aaa.\n]
// CHECK-NEXT: comment_attach.swift:141:13: Param/decl_struct_1.i RawComment=none
// CHECK-NEXT: comment_attach.swift:141:31: Func/decl_struct_1.<getter for decl_struct_1.subscript> RawComment=none
// CHECK-NEXT: comment_attach.swift:144:10: Struct/decl_struct_1.NestedStruct RawComment=[/// NestedStruct Aaa.\n]
// CHECK-NEXT: comment_attach.swift:147:9: Class/decl_struct_1.NestedClass RawComment=[/// NestedClass Aaa.\n]
// CHECK-NEXT: comment_attach.swift:150:8: Enum/decl_struct_1.NestedEnum RawComment=[/// NestedEnum Aaa.\n]
// CHECK-NEXT: comment_attach.swift:156:13: TypeAlias/decl_struct_1.NestedTypealias RawComment=[/// NestedTypealias Aaa.\n]
// CHECK-NEXT: comment_attach.swift:159:14: Var/decl_struct_1.staticVar RawComment=[/// staticVar Aaa.\n]
// CHECK-NEXT: comment_attach.swift:162:15: Func/decl_struct_1.staticFunc1 RawComment=[/// staticFunc1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:166:6: Enum/decl_enum_1 RawComment=[/// decl_enum_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:168:8: EnumElement/decl_enum_1.Case1 RawComment=[/// Case1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:171:8: EnumElement/decl_enum_1.Case2 RawComment=[/// Case2 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:174:8: EnumElement/decl_enum_1.Case3 RawComment=[/// Case3 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:177:8: EnumElement/decl_enum_1.Case4 RawComment=[/// Case4 Case5 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:177:15: EnumElement/decl_enum_1.Case5 RawComment=[/// Case4 Case5 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:181:7: Class/decl_class_1 RawComment=[/// decl_class_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:185:10: Protocol/decl_protocol_1 RawComment=[/// decl_protocol_1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:187:13: AssociatedType/decl_protocol_1.NestedTypealias RawComment=[/// NestedTypealias Aaa.\n]
// CHECK-NEXT: comment_attach.swift:190:8: Func/decl_protocol_1.instanceFunc1 RawComment=[/// instanceFunc1 Aaa.\n]
// CHECK-NEXT: comment_attach.swift:193:7: Var/decl_protocol_1.propertyWithGet RawComment=[/// propertyWithGet Aaa.\n]
// CHECK-NEXT: comment_attach.swift:193:30: Func/decl_protocol_1.<getter for decl_protocol_1.propertyWithGet> RawComment=none
// CHECK-NEXT: comment_attach.swift:196:7: Var/decl_protocol_1.propertyWithGetSet RawComment=[/// propertyWithGetSet Aaa.\n]
// CHECK-NEXT: comment_attach.swift:196:33: Func/decl_protocol_1.<getter for decl_protocol_1.propertyWithGetSet> RawComment=none
// CHECK-NEXT: comment_attach.swift:196:37: Func/decl_protocol_1.<setter for decl_protocol_1.propertyWithGetSet> RawComment=none
// CHECK-NEXT: comment_attach.swift:207:6: Func/emptyBlockDocComment RawComment=[/***/]
// CHECK-NEXT: comment_attach.swift:210:6: Func/weirdBlockDocComment RawComment=[/**/]
// CHECK-NEXT: comment_attach.swift:217:6: Func/docCommentWithGybLineNumber RawComment=[/// docCommentWithGybLineNumber Aaa.\n/// Bbb.\n/// Ccc.\n]
| apache-2.0 | 6f084b7c210698a2426533733b983916 | 38.586885 | 147 | 0.708713 | 3.156601 | false | false | false | false |
zjjzmw1/com.demo1.ios | Demo1/Home/ViewController/PolylineOriginal.swift | 1 | 2881 | //
// Polyline.swift
// TransitApp
//
// Created by Mohamed Salem on 12/17/15.
// Copyright ยฉ 2015 Machometus. All rights reserved.
//
import UIKit
import MapKit
@objc class Polyline3: NSObject {
// Polyline error type
enum PolylineError: ErrorType {
case SingleCoordinateDecodingError
case ChunkExtractingError
}
// Decode google maps polyline string to coordinate
class func decodeSingleCoordinate(byteArray byteArray: UnsafePointer<Int8>, length: Int, inout position: Int, precision: Double = 1e5) throws -> Double {
guard position < length else { throw PolylineError.SingleCoordinateDecodingError }
let bitMask = Int8(0x1F)
var coordinate: Int32 = 0
var currentChar: Int8
var componentCounter: Int32 = 0
var component: Int32 = 0
repeat {
currentChar = byteArray[position] - 63
component = Int32(currentChar & bitMask)
coordinate |= (component << (5*componentCounter))
position++
componentCounter++
} while ((currentChar & 0x20) == 0x20) && (position < length) && (componentCounter < 6)
if (componentCounter == 6) && ((currentChar & 0x20) == 0x20) {
throw PolylineError.SingleCoordinateDecodingError
}
if (coordinate & 0x01) == 0x01 {
coordinate = ~(coordinate >> 1)
}
else {
coordinate = coordinate >> 1
}
return Double(coordinate) / precision
}
// Decode array of google maps polyline string to an array of coordinates
class func decodePolyline(encodedPolyline: String, precision: Double = 1e5) -> [CLLocationCoordinate2D]? {
let data = encodedPolyline.dataUsingEncoding(NSUTF8StringEncoding)!
let byteArray = unsafeBitCast(data.bytes, UnsafePointer<Int8>.self)
let length = Int(data.length)
var position = Int(0)
var decodedCoordinates = [CLLocationCoordinate2D]()
var lat = 0.0
var lon = 0.0
while position < length {
do {
let resultingLat = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lat += resultingLat
let resultingLon = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lon += resultingLon
}
catch {
return nil
}
decodedCoordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
return decodedCoordinates
}
}
| mit | 6b534abc0169732e3f396e9098940f08 | 29.967742 | 157 | 0.575 | 5.179856 | false | false | false | false |
deege/deegeu-ios-swift-make-phone-talk | deegeu-ios-swift-make-phone-talk/ViewController.swift | 1 | 3317 | //
// ViewController.swift
// deegeu-ios-swift-make-phone-talk
//
// Created by Daniel Spiess on 11/13/15.
// Copyright ยฉ 2015 Daniel Spiess. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVSpeechSynthesizerDelegate {
let speechSynthesizer = AVSpeechSynthesizer()
var speechVoice : AVSpeechSynthesisVoice?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
speechSynthesizer.delegate = self
// This is a hack since the following line doesn't work. You also need to
// make sure the voices are downloaded.
//speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-AU")
let voices = AVSpeechSynthesisVoice.speechVoices()
for voice in voices {
if "en-AU" == voice.language {
self.speechVoice = voice
break;
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// This is the action called when the user presses the button.
@IBAction func speak(sender: AnyObject) {
let speechUtterance = AVSpeechUtterance(string: "How can you tell which one of your friends has the new iPhone 6s plus?")
// set the voice
speechUtterance.voice = self.speechVoice
// rate is 0.0 to 1.0 (default defined by AVSpeechUtteranceDefaultSpeechRate)
speechUtterance.rate = 0.1
// multiplier is between >0.0 and 2.0 (default 1.0)
speechUtterance.pitchMultiplier = 1.25
// Volume from 0.0 to 1.0 (default 1.0)
speechUtterance.volume = 0.75
// Delays before and after saying the phrase
speechUtterance.preUtteranceDelay = 0.0
speechUtterance.postUtteranceDelay = 0.0
speechSynthesizer.speakUtterance(speechUtterance)
// Give the answer, but with a different voice
let speechUtterance2 = AVSpeechUtterance(string: "Don't worry, they'll tell you.")
speechUtterance2.voice = self.speechVoice
speechSynthesizer.speakUtterance(speechUtterance2)
}
// Called before speaking an utterance
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didStartSpeechUtterance utterance: AVSpeechUtterance) {
print("About to say '\(utterance.speechString)'");
}
// Called when the synthesizer is finished speaking the utterance
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didFinishSpeechUtterance utterance: AVSpeechUtterance) {
print("Finished saying '\(utterance.speechString)");
}
// This method is called before speaking each word in the utterance.
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
let startIndex = utterance.speechString.startIndex.advancedBy(characterRange.location)
let endIndex = startIndex.advancedBy(characterRange.length)
print("Will speak the word '\(utterance.speechString.substringWithRange(startIndex..<endIndex))'");
}
}
| mit | 297536d4464525d52ac418e1941e37e1 | 37.55814 | 146 | 0.679131 | 5.246835 | false | false | false | false |
oneWarcraft/WJWMusic | WJWMusic/WJWMusic/Classes/Model/MusicModel.swift | 1 | 601 | //
// MusicModel.swift
// WJWMusic
//
// Created by ็็ปงไผ on 16/8/4.
// Copyright ยฉ 2016ๅนด WangJiwei. All rights reserved.
//
import UIKit
class MusicModel: NSObject {
var name : String = ""
var filename : String = ""
var lrcname : String = ""
var singer : String = ""
var singerIcon : String = ""
var icon : String = ""
init(dict : [String : NSObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
}
| apache-2.0 | b877dbb8dd8ce19c17367e14d3b31692 | 17.5 | 76 | 0.559122 | 4 | false | false | false | false |
iOS-mamu/SS | P/Library/Eureka/Source/Rows/PickerInlineRow.swift | 1 | 2089 | //
// PickerInlineRow.swift
// Eureka
//
// Created by Martin Barreto on 2/23/16.
// Copyright ยฉ 2016 Xmartlabs. All rights reserved.
//
import Foundation
open class PickerInlineCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
//MARK: PickerInlineRow
open class _PickerInlineRow<T> : Row<T, PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable {
public typealias InlineRow = PickerRow<T>
open var options = [T]()
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic inline row where the user can pick an option from a picker view
public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
onExpandInlineRow { cell, row, _ in
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
}
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
toggleInlineRow()
}
}
public func setupInlineRow(_ inlineRow: InlineRow) {
inlineRow.options = self.options
inlineRow.displayValueFor = self.displayValueFor
}
}
| mit | ba12b3473a646d02baa8015f7baa57d6 | 26.116883 | 112 | 0.628831 | 4.81106 | false | false | false | false |
oneWarcraft/WJWMusic | WJWMusic/WJWMusic/Classes/Tools/CALayer-Extension.swift | 1 | 602 | //
// CALayer-Extension.swift
// WJWMusic
//
// Created by ็็ปงไผ on 16/8/5.
// Copyright ยฉ 2016ๅนด WangJiwei. All rights reserved.
//
import UIKit
extension CALayer {
func pauseAnim() {
let pauseTime = convertTime(CACurrentMediaTime(), fromLayer: nil)
speed = 0
timeOffset = pauseTime
}
func resumeAnim() {
let pauseTime = timeOffset
speed = 1.0
timeOffset = 0
beginTime = 0
let timeInteval = convertTime(CACurrentMediaTime(), fromLayer: nil) - pauseTime
beginTime = timeInteval
}
}
| apache-2.0 | 718b3e8bf87fa20cfdc8722e2bcf4cb3 | 16.969697 | 87 | 0.595278 | 4.425373 | false | false | false | false |
CoderXiaoming/Ronaldo | SaleManager/SaleManager/Main/Controller/SAMLoginController.swift | 1 | 14252 | //
// SAMLoginController.swift
// SaleManager
//
// Created by apple on 16/11/11.
// Copyright ยฉ 2016ๅนด YZH. All rights reserved.
//
import UIKit
import AFNetworking
import MBProgressHUD
///็จไบ่ฏปๅ ๆๅกๅจๅฐๅ ็Key
private let severAddStrKey = "severAddStrKey"
///็จไบ่ฏปๅ ็จๆทๅ ็Key
private let userNameStrKey = "userNameStrKey"
///็จไบ่ฏปๅ ๅฏ็ ็Key
private let passWordStrKey = "passWordStrKey"
///็ปๅฝ็้ข็จๅฐๅจ็ป็ๅบ็กๆถ้ฟ
private let animationDuration = 0.7
class SAMLoginController: UIViewController {
//MARK: - viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
//ๆฃๆฅ็ปๅฝ็ถๆ
checkSeverStr()
//ๅๅงๅ่ฎพ็ฝฎUI
setupUI()
//่ฎฐๅฝๅๅงๆฐๆฎ
logoOriBotDis = logoBotDis.constant
logoAnimBotDis = (ScreenH - logoView.bounds.height) * 0.6
}
//MARK: - ๆฃๆฅ็ปๅฝ็ถๆ
fileprivate func checkSeverStr() {
//่ฏปๅ ๆๅกๅจๅฐๅ ๅนถๅฏน็ปๆ่ฟ่กๅคๆญ
severAddStr = UserDefaults.standard.string(forKey: severAddStrKey)
if severAddStr == nil { //ๆฒกๆๆๅกๅจๅฐๅ
//ไฟฎๆนๅฝขๅ๏ผๆพ็คบๆๅกๅจๅฐๅๅกซๅ็้ข
loginView.transform = CGAffineTransform(translationX: ScreenW, y: 0)
serverView.transform = CGAffineTransform(translationX: ScreenW, y: 0)
}else { //ๆๆๅกๅจๅฐๅ
//ๅฏนserverAddTF่ฎพๅผ๏ผๆพ็คบ็จๆทๅ็้ข
serverAddTF.text = severAddStr
//ๅคๆญ ๆฏๅฆๆ็จๆทๅ๏ผๆ็จๆทๅ็ๅๆๆฏๆฌๅฐๆๆๅกๅจๅฐๅ๏ผ
userNameStr = UserDefaults.standard.string(forKey: userNameStrKey)
if userNameStr != nil { //ๆ็จๆทๅ
userNameTF.text = userNameStr
remNameBtn.isSelected = true
}
//ๅคๆญ ๆฏๅฆๆๅฏ็
PWDStr = UserDefaults.standard.string(forKey: passWordStrKey)
if PWDStr != nil { //ๆๅฏ็
PwdTF.text = PWDStr
remPwdBtn.isSelected = true
loginBtn.isEnabled = true
}
//ๆฃๆฅๆ้ฎ็ถๆ
checkBtnState(serverAddTF)
}
}
//MARK: - ๅๅงๅ่ฎพ็ฝฎUI
fileprivate func setupUI() {
//่ฎพ็ฝฎไธคไธชๆ้ฎ็่พน่ง
loginBtn.layer.cornerRadius = 7
confirmBtn.layer.cornerRadius = 7
//่ฎพ็ฝฎ็จๆทๅ ๅฏ็ ๆก็ไปฃ็ ๅนถ่ฟ่ก็ๅฌ
userNameTF.addTarget(self, action: #selector(SAMLoginController.checkBtnState(_:)), for: .editingChanged)
PwdTF.addTarget(self, action: #selector(SAMLoginController.checkBtnState(_:)), for: .editingChanged)
serverAddTF.addTarget(self, action: #selector(SAMLoginController.checkBtnState(_:)), for: .editingChanged)
//็ผฉๅฐlogo๏ผๆนไพฟๆง่กๅ็ปญๅจ็ป
logoView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
//็ฆๆญข็จๆทไบคไบ
view.isUserInteractionEnabled = false
}
//MARK: - ็้ขไบคไบ็นๅปไบไปถๅค็
//่ฎฐไฝๅๅญๆ้ฎ็นๅป
@IBAction func remNameBtnClick(_ sender: AnyObject) {
remNameBtn.isSelected = !remNameBtn.isSelected
if !remNameBtn.isSelected {
remPwdBtn.isSelected = false
}
}
//่ฎฐไฝๅฏ็ ๆ้ฎ็นๅป
@IBAction func remPwdBtnClick(_ sender: UIButton) {
remPwdBtn.isSelected = !remPwdBtn.isSelected
if remPwdBtn.isSelected {
remNameBtn.isSelected = true
}
}
//็ปๅฝๆ้ฎ็นๅป
@IBAction func loginBtnClick(_ sender: AnyObject) {
//่ฎฐๅฝ็จๆทๅๅๅฏ็
userNameStr = userNameTF.text
PWDStr = PwdTF.text
UIView.animate(withDuration: 0.4, animations: {
//้ๅบ็ผ่พ็ถๆ
self.endEditing()
}, completion: { (_) in
//ๆง่กๅจ็ป
self.loginAnim()
})
}
//็นๅป็้ข้ๅบ็ผ่พ็ถๆ
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//TODO: - ็ปๅฝๆต่ฏ
// loginRequest(userName: "็่ถ
่ถ
", passWord: "yzh0918")
endEditing()
}
//ๆๅกๅจๅฐๅ็กฎ่ฎคๆ้ฎ็นๅป ๅ ่ฟๅๆๅกๅจ่ฎพ็ฝฎ็้ขๆ้ฎ็นๅป ๅค็ๅจไธ้ขๅจ็ป้กนไธญ
//MARK: - ็ปๆ็้ข็ผ่พ็ถๆ
fileprivate func endEditing() {
view.endEditing(false)
}
//MARK: - ๆฃๆฅ ็กฎ่ฎคใ็ปๅฝ ๆ้ฎ็็ถๆ
func checkBtnState(_ textField: UITextField) {
switch textField {
case serverAddTF:
confirmBtn.isEnabled = serverAddTF.hasText
case userNameTF, PwdTF:
loginBtn.isEnabled = userNameTF.hasText && PwdTF.hasText
default :
break
}
}
//MARK: - ๅ้็จๆท็ปๅฝ่ฏทๆฑ
fileprivate func loginRequest(userName: String, passWord: String) {
//ๅๅปบ่ฏทๆฑ่ทฏๅพ๏ผ่ฏทๆฑๅๆฐ
let URLStr = String(format: "http://%@/handleLogin.ashx", severAddStr!)
let parameters = ["userName": userName, "pwd": passWord]
//ๅ้่ฏทๆฑ
SAMNetWorker.sharedLoginNetWorker().get(URLStr, parameters: parameters, progress: nil, success: {[weak self] (Task, json) in
//ๅคๆญ่ฟๅๆฐๆฎ็ถๆ
let Json = json as! [String: AnyObject]
let status = Json["head"]! as! [String: String]
if status["status"]! == "fail" { //็จๆทๅๆ่
ๅฏ็ ้่ฏฏ
self!.showLoginDefeatInfo("็จๆทๅๆ่
ๅฏ็ ้่ฏฏ")
} else { //็ปๅฝๆๅ
//ๆจกๅๅๆฐๆฎ
let arr = Json["body"] as! [[String: String]]
let dict = arr[0]
let id = dict["id"]
let employeeID = dict["employeeID"]
let appPower = dict["appPower"]
let deptID = dict["deptID"]
let model = SAMUserAuth.auth(id, employeeID: employeeID, appPower: appPower, deptID: deptID)
model.userName = self!.userNameTF.text
//ๆง่ก็ปๅฝๆๅๅจ็ป
self!.loginSuccessAnim()
}
}) {[weak self] (Task, Error) in
self!.showLoginDefeatInfo("่ฏทๆฃๆฅ็ฝ็ป")
}
}
//MARK: - ็ปๅฝๅบ็ฐ้่ฏฏๆถๅๆ็คบ็ๆถๆฏ
fileprivate func showLoginDefeatInfo(_ title: String!) {
//ๆง่กๅจ็ป
loginDefeatAnim()
//ๅฑ็คบ้่ฏฏไฟกๆฏ
let _ = SAMHUD.showMessage(title, superView: view, hideDelay: animationDuration * 2, animated: true)
}
//MARK: - ๆๆๅจ็ป้ๅ
///่ฟๅ
ฅ็้ขๅจๆๆขๅคlog
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//ๅจๆๅๅคlogo
UIView.animate(withDuration: animationDuration, animations: {
self.logoView.transform = CGAffineTransform.identity
}, completion: { (_) in
//ๆขๅค้กต้ข็จๆทไบคไบ
self.view.isUserInteractionEnabled = true
})
}
///ๆๅกๅจๅฐๅ็กฎ่ฎคๆ้ฎ็นๅปๅๆง่กๅจ็ป
@IBAction func severBtnClick(_ sender: AnyObject) {
//้ๅบ็้ข็ผ่พ็ถๆ
endEditing()
if serverAddTF.text == "yzh@08890918" { //ๆญฃ็กฎๆฟๆดป็
//ๆง่กๅจ็ป
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 7, options: .curveEaseIn, animations: {
self.loginView.transform = CGAffineTransform.identity
self.serverView.transform = CGAffineTransform.identity
}, completion: nil)
//่ตๅผๆๅกๅจๅฐๅ
severAddStr = "120.27.133.57:2017"
}else { //้่ฏฏๆฟๆดป็
let _ = SAMHUD.showMessage("่พๅ
ฅ้่ฏฏ", superView: KeyWindow!, hideDelay: SAMHUDNormalDuration, animated: true)
}
}
///่ฟๅๆๅกๅจ่ฎพ็ฝฎ็้ขๆ้ฎ็นๅปๅจ็ป
@IBAction func loginBackBtnClick(_ sender: UIButton) {
//้ๅบ็้ข็ผ่พ็ถๆ
endEditing()
//ๆง่กๅจ็ป
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 7, options: .curveEaseIn, animations: {
self.loginView.transform = CGAffineTransform(translationX: ScreenW, y: 0)
self.serverView.transform = CGAffineTransform(translationX: ScreenW, y: 0)
}, completion: nil)
}
///ๆญฃๅจ็ป้ไธญ็ๅจ็ป
fileprivate func loginAnim() {
UIView.animate(withDuration: animationDuration, animations: {
self.loginView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
self.logoBotDis.constant = self.logoAnimBotDis
self.view.layoutIfNeeded()
}, completion: { (_) in
self.setupLoginCircleAnim()
})
}
///่ฎพ็ฝฎ็ป้ๅๅๅจ็ป
fileprivate func setupLoginCircleAnim() {
loginAnimLayer = CAReplicatorLayer()
loginAnimLayer!.frame = logoView.bounds
logoView.layer.addSublayer(loginAnimLayer!)
//ๅฐๅๅlayer
let layer = CALayer()
layer.transform = CATransform3DMakeScale(0, 0, 0)
layer.position = CGPoint(x: loginView.bounds.size.width / 2, y: 20)
layer.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
layer.cornerRadius = 5
layer.backgroundColor = UIColor.green.cgColor
loginAnimLayer!.addSublayer(layer)
//่ฎพ็ฝฎ็ผฉๆพๅจ็ป
let anim = CABasicAnimation()
anim.keyPath = "transform.scale"
anim.fromValue = 1
anim.toValue = 0
anim.repeatCount = MAXFLOAT
let animDuration = 1
anim.duration = CFTimeInterval(animDuration)
layer.add(anim, forKey: nil)
//ๆทปๅ layer
let count : CGFloat = 20
let angle = CGFloat(M_PI * 2) / count
loginAnimLayer!.instanceCount = Int(count)
loginAnimLayer!.instanceTransform = CATransform3DMakeRotation(angle, 0, 0, 1)
loginAnimLayer!.instanceDelay = Double(animDuration) / Double(count)
//็ญๅพ
ไธ็งๅๅๆๅกๅจๅ้็ปๅฝ่ฏทๆฑ
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + Double(Int64(1000000000 * animationDuration)) / Double(NSEC_PER_SEC)) {
self.loginRequest(userName: self.userNameTF.text!, passWord: self.PwdTF.text!)
}
}
///็ป้ๅคฑ่ดฅ็ๅจ็ป
fileprivate func loginDefeatAnim() {
UIView.animate(withDuration: animationDuration, animations: {
self.loginAnimLayer!.removeFromSuperlayer()
self.loginAnimLayer = nil
self.loginView.transform = CGAffineTransform.identity
self.logoBotDis.constant = self.logoOriBotDis
self.view.layoutIfNeeded()
}, completion: { (_) in
})
}
///็ป้ๆๅ็ๅจ็ป
fileprivate func loginSuccessAnim() {
UIView.animate(withDuration: animationDuration, animations: {
self.logoView.transform = CGAffineTransform(scaleX: 2.0, y: 2.0)
self.logoView.alpha = 0.001
}, completion: { (_) in
//ๅญๅจ็ปๅฝๆฐๆฎ
UserDefaults.standard.set(self.severAddStr, forKey: severAddStrKey)
if self.remNameBtn.isSelected == true {
UserDefaults.standard.set(self.userNameStr, forKey: userNameStrKey)
}else {
UserDefaults.standard.set(nil, forKey: userNameStrKey)
}
if self.remPwdBtn.isSelected == true {
UserDefaults.standard.set(self.PWDStr, forKey: passWordStrKey)
}else {
UserDefaults.standard.set(nil, forKey: passWordStrKey)
}
UserDefaults.standard.synchronize()
//ๅๅปบๅ
จๅฑไฝฟ็จ็netWorkerๅไพ
let _ = SAMNetWorker.globalNetWorker(self.severAddStr!)
//ๅๅปบๅ
จๅฑไฝฟ็จ็ไธไผ ๅพ็netWorkerๅไพ
let _ = SAMNetWorker.globalUnloadImageNetWorker(self.severAddStr!)
//ๅๅบ็ปๅฝๆๅ็้็ฅ
NotificationCenter.default.post(name: Notification.Name(rawValue: LoginSuccessNotification), object: nil, userInfo: nil)
})
}
//MARK: - ๅฑๆง
///ๆๅกๅจๅฐๅ
fileprivate var severAddStr: String?
///็จๆทๅ
fileprivate var userNameStr: String?
///ๅฏ็
fileprivate var PWDStr: String?
///logoView็ๅๅงๅบ้จ่ท็ฆป
fileprivate var logoOriBotDis: CGFloat = 0
///logoView็ๅจ็ปๅบ้จ่ท็ฆป
fileprivate var logoAnimBotDis: CGFloat = 0
///็ปๅฝไธญๅฐ็ปฟๅๅจ็ปLayer
fileprivate var loginAnimLayer: CAReplicatorLayer?
//MARK: - xib้พๆฅๅฑๆง
@IBOutlet weak var loginView: UIView!
@IBOutlet weak var userNameTF: UITextField!
@IBOutlet weak var PwdTF: UITextField!
@IBOutlet weak var loginBtn: UIButton!
@IBOutlet weak var remNameBtn: UIButton!
@IBOutlet weak var remPwdBtn: UIButton!
@IBOutlet weak var serverView: UIView!
@IBOutlet weak var serverAddTF: UITextField!
@IBOutlet weak var confirmBtn: UIButton!
@IBOutlet weak var logoView: UIView!
@IBOutlet weak var logoBotDis: NSLayoutConstraint!
//MARK: - ๅ
ถไปๆนๆณ
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func loadView() {
view = Bundle.main.loadNibNamed("SAMLoginController", owner: self, options: nil)![0] as! UIView
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | b7bd22c8262ebf5fb3a573d9ac5a8beb | 32.840314 | 161 | 0.585983 | 4.731698 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker | Pods/HXPHPicker/Sources/HXPHPicker/Picker/Controller/PhotoPickerController+FetchAsset.swift | 1 | 12241 | //
// PhotoPickerController+FetchAsset.swift
// HXPHPicker
//
// Created by Slience on 2021/8/25.
//
import UIKit
import Photos
// MARK: fetch Asset
extension PhotoPickerController {
func fetchData(status: PHAuthorizationStatus) {
if status.rawValue >= 3 {
PHPhotoLibrary.shared().register(self)
// ๆๆ้
ProgressHUD.showLoading(addedTo: view, afterDelay: 0.15, animated: true)
fetchCameraAssetCollection()
}else if status.rawValue >= 1 {
// ๆ ๆ้
view.addSubview(deniedView)
}
}
/// ่ทๅ็ธๆบ่ถๅท่ตๆบ้ๅ
func fetchCameraAssetCollection() {
if !config.allowLoadPhotoLibrary {
if cameraAssetCollection == nil {
cameraAssetCollection = PhotoAssetCollection(
albumName: config.albumList.emptyAlbumName.localized,
coverImage: config.albumList.emptyCoverImageName.image
)
}
fetchCameraAssetCollectionCompletion?(cameraAssetCollection)
return
}
if config.creationDate {
options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: config.creationDate)]
}
PhotoManager.shared.fetchCameraAssetCollection(
for: selectOptions,
options: options
) { [weak self] (assetCollection) in
guard let self = self else { return }
if assetCollection.count == 0 {
self.cameraAssetCollection = PhotoAssetCollection(
albumName: self.config.albumList.emptyAlbumName.localized,
coverImage: self.config.albumList.emptyCoverImageName.image
)
}else {
// ่ทๅๅฐ้ข
self.cameraAssetCollection = assetCollection
}
if self.config.albumShowMode == .popup {
self.fetchAssetCollections()
}
self.fetchCameraAssetCollectionCompletion?(self.cameraAssetCollection)
}
}
/// ่ทๅ็ธๅ้ๅ
func fetchAssetCollections() {
cancelAssetCollectionsQueue()
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation] in
if self.config.creationDate {
self.options.sortDescriptors = [
NSSortDescriptor(
key: "creationDate",
ascending: self.config.creationDate
)
]
}
self.assetCollectionsArray = []
var localCount = self.localAssetArray.count + self.localCameraAssetArray.count
var coverImage = self.localCameraAssetArray.first?.originalImage
if coverImage == nil {
coverImage = self.localAssetArray.first?.originalImage
}
var firstSetImage = true
for phAsset in self.selectedAssetArray where
phAsset.phAsset == nil {
let inLocal = self.localAssetArray.contains(
where: {
$0.isEqual(phAsset)
})
let inLocalCamera = self.localCameraAssetArray.contains(
where: {
$0.isEqual(phAsset)
}
)
if !inLocal && !inLocalCamera {
if firstSetImage {
coverImage = phAsset.originalImage
firstSetImage = false
}
localCount += 1
}
}
if operation.isCancelled {
return
}
if !self.config.allowLoadPhotoLibrary {
DispatchQueue.main.async {
self.cameraAssetCollection?.realCoverImage = coverImage
self.cameraAssetCollection?.count += localCount
self.assetCollectionsArray.append(self.cameraAssetCollection!)
self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray)
}
return
}
PhotoManager.shared.fetchAssetCollections(
for: self.options,
showEmptyCollection: false
) { [weak self] (assetCollection, isCameraRoll, stop) in
guard let self = self else {
stop.pointee = true
return
}
if operation.isCancelled {
stop.pointee = true
return
}
if let assetCollection = assetCollection {
if let collection = assetCollection.collection,
let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssetCollections: collection) {
if !canAdd {
return
}
}
assetCollection.count += localCount
if isCameraRoll {
self.assetCollectionsArray.insert(assetCollection, at: 0)
}else {
self.assetCollectionsArray.append(assetCollection)
}
}else {
if let cameraAssetCollection = self.cameraAssetCollection {
self.cameraAssetCollection?.count += localCount
if coverImage != nil {
self.cameraAssetCollection?.realCoverImage = coverImage
}
if !self.assetCollectionsArray.isEmpty {
self.assetCollectionsArray[0] = cameraAssetCollection
}else {
self.assetCollectionsArray.append(cameraAssetCollection)
}
}
DispatchQueue.main.async {
self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray)
}
}
}
}
assetCollectionsQueue.addOperation(operation)
}
func cancelAssetCollectionsQueue() {
assetCollectionsQueue.cancelAllOperations()
}
private func getSelectAsset() -> ([PHAsset], [PhotoAsset]) {
var selectedAssets = [PHAsset]()
var selectedPhotoAssets: [PhotoAsset] = []
var localIndex = -1
for (index, photoAsset) in selectedAssetArray.enumerated() {
if config.selectMode == .single {
break
}
photoAsset.selectIndex = index
photoAsset.isSelected = true
if let phAsset = photoAsset.phAsset {
selectedAssets.append(phAsset)
selectedPhotoAssets.append(photoAsset)
}else {
let inLocal = localAssetArray
.contains {
if $0.isEqual(photoAsset) {
localAssetArray[localAssetArray.firstIndex(of: $0)!] = photoAsset
return true
}
return false
}
let inLocalCamera = localCameraAssetArray
.contains(where: {
if $0.isEqual(photoAsset) {
localCameraAssetArray[
localCameraAssetArray.firstIndex(of: $0)!
] = photoAsset
return true
}
return false
})
if !inLocal && !inLocalCamera {
if photoAsset.localIndex > localIndex {
localIndex = photoAsset.localIndex
localAssetArray.insert(photoAsset, at: 0)
}else {
if localIndex == -1 {
localIndex = photoAsset.localIndex
localAssetArray.insert(photoAsset, at: 0)
}else {
localAssetArray.insert(photoAsset, at: 1)
}
}
}
}
}
return (selectedAssets, selectedPhotoAssets)
}
/// ่ทๅ็ธๅ้็่ตๆบ
/// - Parameters:
/// - assetCollection: ็ธๅ
/// - completion: ๅฎๆๅ่ฐ
func fetchPhotoAssets(
assetCollection: PhotoAssetCollection?,
completion: (([PhotoAsset], PhotoAsset?, Int, Int) -> Void)?
) {
cancelFetchAssetsQueue()
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation] in
var photoCount = 0
var videoCount = 0
self.localAssetArray.forEach { $0.isSelected = false }
self.localCameraAssetArray.forEach { $0.isSelected = false }
let result = self.getSelectAsset()
let selectedAssets = result.0
let selectedPhotoAssets = result.1
var localAssets: [PhotoAsset] = []
if operation.isCancelled {
return
}
localAssets.append(contentsOf: self.localCameraAssetArray.reversed())
localAssets.append(contentsOf: self.localAssetArray)
var photoAssets = [PhotoAsset]()
photoAssets.reserveCapacity(assetCollection?.count ?? 10)
var lastAsset: PhotoAsset?
assetCollection?.enumerateAssets( usingBlock: { [weak self] (photoAsset, index, stop) in
guard let self = self,
let phAsset = photoAsset.phAsset
else {
stop.pointee = true
return
}
if operation.isCancelled {
stop.pointee = true
return
}
if let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssets: phAsset) {
if !canAdd {
return
}
}
if self.selectOptions.contains(.gifPhoto) {
if phAsset.isImageAnimated {
photoAsset.mediaSubType = .imageAnimated
}
}
if self.config.selectOptions.contains(.livePhoto) {
if phAsset.isLivePhoto {
photoAsset.mediaSubType = .livePhoto
}
}
switch photoAsset.mediaType {
case .photo:
if !self.selectOptions.isPhoto {
return
}
photoCount += 1
case .video:
if !self.selectOptions.isVideo {
return
}
videoCount += 1
}
var asset = photoAsset
if let index = selectedAssets.firstIndex(of: phAsset) {
let selectPhotoAsset = selectedPhotoAssets[index]
asset = selectPhotoAsset
lastAsset = selectPhotoAsset
}
photoAssets.append(asset)
})
if self.config.photoList.showAssetNumber {
localAssets.forEach {
if $0.mediaType == .photo {
photoCount += 1
}else {
videoCount += 1
}
}
}
photoAssets.append(contentsOf: localAssets.reversed())
if self.config.photoList.sort == .desc {
photoAssets.reverse()
}
if operation.isCancelled {
return
}
DispatchQueue.main.async {
completion?(photoAssets, lastAsset, photoCount, videoCount)
}
}
assetsQueue.addOperation(operation)
}
func cancelFetchAssetsQueue() {
assetsQueue.cancelAllOperations()
}
}
| mit | fc0553934e2ac436422e4487c3f80602 | 38.229032 | 119 | 0.491983 | 6.485867 | false | false | false | false |
carping/Postal | Postal/MailData+Decode.swift | 1 | 7122 | //
// The MIT License (MIT)
//
// Copyright (c) 2017 Snips
//
// 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 libetpan
extension MailData {
public var decodedData: Data {
switch encoding {
case .encoding7Bit, .encoding8Bit, .binary, .other: return rawData as Data
case .base64: return rawData.base64Decoded
case .quotedPrintable: return rawData.quotedPrintableDecoded
case .uuEncoding: return rawData.uudecoded
}
}
}
extension Data {
var base64Decoded: Data {
return decodeWithMechanism(MAILMIME_MECHANISM_BASE64, partial: false).decoded
}
var quotedPrintableDecoded: Data {
return decodeWithMechanism(MAILMIME_MECHANISM_QUOTED_PRINTABLE, partial: false).decoded
}
func decodeWithMechanism(_ mechanism: Int, partial: Bool) -> (decoded: Data, remaining: Data?) {
var curToken: size_t = 0
var decodedBytes: UnsafeMutablePointer<Int8>? = nil
var decodedLength: Int = 0
let decodeFunc = partial ? mailmime_part_parse_partial : mailmime_part_parse
let _ = withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
decodeFunc(bytes, count, &curToken, Int32(mechanism), &decodedBytes, &decodedLength)
}
let decodedData = Data(bytesNoCopy: UnsafeMutableRawPointer(decodedBytes!), count: decodedLength, deallocator: .free)
let remaining: Data?
if decodedLength < count {
remaining = withUnsafeBytes { bytes in
Data(bytes: UnsafeRawPointer(bytes + curToken), count: count - curToken)
}
} else {
remaining = nil
}
return (decoded: decodedData, remaining: remaining)
}
var uudecoded: Data {
return uudecode(partial: false).decoded
}
func uudecode(partial: Bool) -> (decoded: Data, remaining: Data?) {
return withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
var currentPosition = bytes
let accumulator = NSMutableData()
while true {
let (data, next) = getLine(currentPosition)
if let next = next { // line is complete
accumulator.append(data.uudecodedLine)
currentPosition = next
} else { // no new line
if !partial { // not partial, just decode remaining bytes
accumulator.append(data.uudecodedLine)
return (decoded: accumulator as Data, remaining: nil)
} else { // partial, return remaining bytes as remaining
let remainingBytesCopy: Data = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
return Data(bytes: bytes, count: data.count) // force copy of remaining data
}
return (decoded: accumulator as Data, remaining: remainingBytesCopy)
}
}
}
}
}
var uudecodedLine: Data {
return withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
var current = bytes
let end = current + count
let leadingCount = Int((current[0] & 0x7f) - 0x20)
current += 1
if leadingCount < 0 { // don't process lines without leading count character
return Data()
}
if strncasecmp(UnsafePointer<CChar>(bytes), "begin ", 6) == 0 || strncasecmp(UnsafePointer<CChar>(bytes), "end", 3) == 0 {
return Data()
}
let decoded = NSMutableData(capacity: leadingCount)! // if we can't allocate it, let's better crash
var buf = [Int8](repeating: 0, count: 3)
while current < end && decoded.length < leadingCount {
var v: Int8 = 0
(0..<4).forEach { _ in // pack decoded bytes in the int
let c = current.pointee
current += 1
v = v << 6 | ((c - 0x20) & 0x3F)
}
for i in stride(from: 2, through: 0, by: -1) { // unpack the int in buf
buf[i] = v & 0xF
v = v >> 8
}
decoded.append(&buf, length: buf.count)
}
return decoded as Data
}
}
func getLine(_ from: UnsafePointer<CChar>) -> (data: Data, next: UnsafePointer<CChar>?) {
return withUnsafeBytes { (bytes: UnsafePointer<Int8>) in
let from = UnsafeMutablePointer(mutating: from)
let bufferStart = UnsafeMutablePointer(mutating: bytes)
assert(from >= bufferStart && from - bufferStart <= count)
let cr: CChar = 13 //"\r".utf8.first!
let lf: CChar = 10 //"\n".utf8.first!
var lineStart = UnsafeMutablePointer<CChar>(from)
// skip eols at the beginning
while (lineStart - bufferStart < count) && (lineStart.pointee == cr || lineStart.pointee == lf) {
lineStart += 1
}
let remainingLength = count - (lineStart - bufferStart)
var lineSize: size_t = 0
while lineSize < remainingLength {
if lineStart[lineSize] == cr || lineStart[lineSize] == lf {
// found eol
let data = Data(bytesNoCopy: lineStart, count: lineSize, deallocator: .none)
let next = UnsafePointer<CChar>(lineStart+lineSize+1)
return (data: data, next: next)
} else {
lineSize += 1
}
}
let data = Data(bytesNoCopy: lineStart, count: lineSize - 1, deallocator: .none)
return (data: data, next: nil)
}
}
}
| mit | 6bd7f3f58a74eb13e93ac858c066b371 | 39.931034 | 134 | 0.562202 | 4.884774 | false | false | false | false |
Alberto-Vega/SwiftCodeChallenges | IntegerToWords.playground/Sources/NumberToTextConverter.swift | 1 | 4245 | import Foundation
public class NumberToTextConverter {
public init() {
}
let ones = [0 : "zero",
1 : "one",
2 : "two",
3 : "three",
4 : "four",
5 : "five",
6 : "Six",
7 : "seven",
8 : "eigth",
9 : "nine"]
let elevenToNineteen = [11 : "eleven",
12 : "twelve",
13 : "thirteen",
14 : "fourteen",
15 : "fifteen",
16 : "sixteen",
17 : "seventeen",
18 : "eighteen",
19 : "nineteen"]
let tens = [10: "ten",
20: "twenty",
30: "thirty",
40: "forty",
50: "fifty",
60: "sixty",
70: "seventy",
80: "eighty",
90: "ninety"]
func textFromSingleDigit(number: Int) -> String? {
var result: String?
result = ones[number] ?? "This number is not a single digit"
return result ?? nil
}
func textFromTwoDigit(number: Int) -> String? {
var result: String?
switch true {
case number < 20:
if number > 10 {
result = elevenToNineteen[number] ?? nil
}
else if number == 10 {
result = tens[number]
}
else {
result = ones[number] ?? nil
}
case number >= 20 && number <= 99 :
let onesDigit = number % 10
if onesDigit != 0 {
result = "\(tens[(number/10) * 10] ?? "nil") \(ones[onesDigit] ?? " ")"
} else {
result = "\(tens[(number/10) * 10] ?? "nil")"
}
default:
result = "Failed to map number to Textual Representation"
}
return result ?? nil
}
func textFromThreeDigit(number: Int) -> String? {
var result: String?
let hundredUnits = number/100
let lastTwoDigits = number % 100
if lastTwoDigits == 0 {
result = "\(textFromSingleDigit(number: hundredUnits) ?? "") hundred"
} else {
result = "\(textFromSingleDigit(number: hundredUnits) ?? "") hundred \(textFromTwoDigit(number: lastTwoDigits) ?? "")"
}
return result ?? nil
}
func textFromFourDigit(number: Int) -> String? {
var result: String?
let thousandUnits = number/1000
let lastThreeDigits = number % 1000
if lastThreeDigits == 0 {
result = "\(textFromSingleDigit(number: thousandUnits) ?? "") thousand"
} else {
result = "\(textFromSingleDigit(number: thousandUnits) ?? "") thousand \(textFromThreeDigit(number: lastThreeDigits) ?? "")"
}
return result ?? nil
}
func textFromFiveDigit(number: Int) -> String? {
var result: String?
let thousandUnits = number/1000
let lastThreeDigits = number % 1000
if lastThreeDigits == 0 {
result = "\(textFromTwoDigit(number: thousandUnits) ?? "") thousand"
} else {
result = "\(textFromTwoDigit(number: thousandUnits) ?? "") thousand \(textFromThreeDigit(number: lastThreeDigits) ?? "")"
}
return result ?? nil
}
public func textualRepresentation(ofInt: Int) -> String? {
var result: String?
switch true {
case ofInt < 10 :
result = textFromSingleDigit(number: ofInt)
case ofInt >= 10 && ofInt <= 99:
result = textFromTwoDigit(number: ofInt)
case ofInt >= 100 && ofInt <= 999:
result = textFromThreeDigit(number: ofInt)
case ofInt >= 1000 && ofInt <= 9000:
result = textFromFourDigit(number: ofInt)
case ofInt >= 10_000 && ofInt <= 99_999:
result = textFromFiveDigit(number: ofInt)
default:
result = "Failed to map number to Textual Representation"
}
return result ?? nil
}
}
| mit | a8f78d74de1ef2cbcc5a65f38162544b | 33.512195 | 136 | 0.469494 | 4.812925 | false | false | false | false |
khizkhiz/swift | benchmark/utils/DriverUtils.swift | 2 | 10738 | //===--- DriverUtils.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Darwin
struct BenchResults {
var delim: String = ","
var sampleCount: UInt64 = 0
var min: UInt64 = 0
var max: UInt64 = 0
var mean: UInt64 = 0
var sd: UInt64 = 0
var median: UInt64 = 0
init() {}
init(delim: String, sampleCount: UInt64, min: UInt64, max: UInt64, mean: UInt64, sd: UInt64, median: UInt64) {
self.delim = delim
self.sampleCount = sampleCount
self.min = min
self.max = max
self.mean = mean
self.sd = sd
self.median = median
// Sanity the bounds of our results
precondition(self.min <= self.max, "min should always be <= max")
precondition(self.min <= self.mean, "min should always be <= mean")
precondition(self.min <= self.median, "min should always be <= median")
precondition(self.max >= self.mean, "max should always be >= mean")
precondition(self.max >= self.median, "max should always be >= median")
}
}
extension BenchResults : CustomStringConvertible {
var description: String {
return "\(sampleCount)\(delim)\(min)\(delim)\(max)\(delim)\(mean)\(delim)\(sd)\(delim)\(median)"
}
}
struct Test {
let name: String
let index: Int
let f: (Int)->()
var run: Bool
init(name: String, n: Int, f: (Int)->()) {
self.name = name
self.index = n
self.f = f
run = true
}
}
public var precommitTests: [String : (Int)->()] = [:]
public var otherTests: [String : (Int)->()] = [:]
enum TestAction {
case Run
case ListTests
case Fail(String)
}
struct TestConfig {
/// The delimiter to use when printing output.
var delim: String = ","
/// The filters applied to our test names.
var filters = [String]()
/// The scalar multiple of the amount of times a test should be run. This
/// enables one to cause tests to run for N iterations longer than they
/// normally would. This is useful when one wishes for a test to run for a
/// longer amount of time to perform performance analysis on the test in
/// instruments.
var iterationScale: Int = 1
/// If we are asked to have a fixed number of iterations, the number of fixed
/// iterations.
var fixedNumIters: UInt = 0
/// The number of samples we should take of each test.
var numSamples: Int = 1
/// Is verbose output enabled?
var verbose: Bool = false
/// Should we only run the "pre-commit" tests?
var onlyPrecommit: Bool = true
/// After we run the tests, should the harness sleep to allow for utilities
/// like leaks that require a PID to run on the test harness.
var afterRunSleep: Int? = nil
/// The list of tests to run.
var tests = [Test]()
mutating func processArguments() -> TestAction {
let validOptions=["--iter-scale", "--num-samples", "--num-iters",
"--verbose", "--delim", "--run-all", "--list", "--sleep"]
let maybeBenchArgs: Arguments? = parseArgs(validOptions)
if maybeBenchArgs == nil {
return .Fail("Failed to parse arguments")
}
let benchArgs = maybeBenchArgs!
if let _ = benchArgs.optionalArgsMap["--list"] {
return .ListTests
}
if let x = benchArgs.optionalArgsMap["--iter-scale"] {
if x.isEmpty { return .Fail("--iter-scale requires a value") }
iterationScale = Int(x)!
}
if let x = benchArgs.optionalArgsMap["--num-iters"] {
if x.isEmpty { return .Fail("--num-iters requires a value") }
fixedNumIters = numericCast(Int(x)!)
}
if let x = benchArgs.optionalArgsMap["--num-samples"] {
if x.isEmpty { return .Fail("--num-samples requires a value") }
numSamples = Int(x)!
}
if let _ = benchArgs.optionalArgsMap["--verbose"] {
verbose = true
print("Verbose")
}
if let x = benchArgs.optionalArgsMap["--delim"] {
if x.isEmpty { return .Fail("--delim requires a value") }
delim = x
}
if let _ = benchArgs.optionalArgsMap["--run-all"] {
onlyPrecommit = false
}
if let x = benchArgs.optionalArgsMap["--sleep"] {
if x.isEmpty {
return .Fail("--sleep requires a non-empty integer value")
}
let v: Int? = Int(x)
if v == nil {
return .Fail("--sleep requires a non-empty integer value")
}
afterRunSleep = v!
}
filters = benchArgs.positionalArgs
return .Run
}
mutating func findTestsToRun() {
var i = 1
for benchName in precommitTests.keys.sorted() {
tests.append(Test(name: benchName, n: i, f: precommitTests[benchName]!))
i += 1
}
for benchName in otherTests.keys.sorted() {
tests.append(Test(name: benchName, n: i, f: otherTests[benchName]!))
i += 1
}
for i in 0..<tests.count {
if onlyPrecommit && precommitTests[tests[i].name] == nil {
tests[i].run = false
}
if !filters.isEmpty &&
!filters.contains(String(tests[i].index)) &&
!filters.contains(tests[i].name) {
tests[i].run = false
}
}
}
}
func internalMeanSD(inputs: [UInt64]) -> (UInt64, UInt64) {
// If we are empty, return 0, 0.
if inputs.isEmpty {
return (0, 0)
}
// If we have one element, return elt, 0.
if inputs.count == 1 {
return (inputs[0], 0)
}
// Ok, we have 2 elements.
var sum1: UInt64 = 0
var sum2: UInt64 = 0
for i in inputs {
sum1 += i
}
let mean: UInt64 = sum1 / UInt64(inputs.count)
for i in inputs {
sum2 = sum2 &+ UInt64((Int64(i) &- Int64(mean))&*(Int64(i) &- Int64(mean)))
}
return (mean, UInt64(sqrt(Double(sum2)/(Double(inputs.count) - 1))))
}
func internalMedian(inputs: [UInt64]) -> UInt64 {
return inputs.sorted()[inputs.count / 2]
}
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
@_silgen_name("swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafeMutablePointer<Void>) -> ()
@_silgen_name("swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafeMutablePointer<Void>) -> Int
#endif
class SampleRunner {
var info = mach_timebase_info_data_t(numer: 0, denom: 0)
init() {
mach_timebase_info(&info)
}
func run(name: String, fn: (Int) -> Void, num_iters: UInt) -> UInt64 {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
var str = name
startTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
#endif
let start_ticks = mach_absolute_time()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = mach_absolute_time()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
stopTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
#endif
// Compute the spent time and the scaling factor.
let elapsed_ticks = end_ticks - start_ticks
return elapsed_ticks * UInt64(info.numer) / UInt64(info.denom)
}
}
/// Invoke the benchmark entry point and return the run time in milliseconds.
func runBench(name: String, _ fn: (Int) -> Void, _ c: TestConfig) -> BenchResults {
var samples = [UInt64](repeating: 0, count: c.numSamples)
if c.verbose {
print("Running \(name) for \(c.numSamples) samples.")
}
let sampler = SampleRunner()
for s in 0..<c.numSamples {
let time_per_sample: UInt64 = 1_000_000_000 * UInt64(c.iterationScale)
var scale : UInt
var elapsed_time : UInt64 = 0
if c.fixedNumIters == 0 {
elapsed_time = sampler.run(name, fn: fn, num_iters: 1)
scale = UInt(time_per_sample / elapsed_time)
} else {
// Compute the scaling factor if a fixed c.fixedNumIters is not specified.
scale = c.fixedNumIters
}
// Rerun the test with the computed scale factor.
if scale > 1 {
if c.verbose {
print(" Measuring with scale \(scale).")
}
elapsed_time = sampler.run(name, fn: fn, num_iters: scale)
} else {
scale = 1
}
// save result in microseconds or k-ticks
samples[s] = elapsed_time / UInt64(scale) / 1000
if c.verbose {
print(" Sample \(s),\(samples[s])")
}
}
let (mean, sd) = internalMeanSD(samples)
// Return our benchmark results.
return BenchResults(delim: c.delim, sampleCount: UInt64(samples.count),
min: samples.min()!, max: samples.max()!,
mean: mean, sd: sd, median: internalMedian(samples))
}
func printRunInfo(c: TestConfig) {
if c.verbose {
print("--- CONFIG ---")
print("NumSamples: \(c.numSamples)")
print("Verbose: \(c.verbose)")
print("IterScale: \(c.iterationScale)")
if c.fixedNumIters != 0 {
print("FixedIters: \(c.fixedNumIters)")
}
print("Tests Filter: \(c.filters)")
print("Tests to run: ", terminator: "")
for t in c.tests {
if t.run {
print("\(t.name), ", terminator: "")
}
}
print("")
print("")
print("--- DATA ---")
}
}
func runBenchmarks(c: TestConfig) {
let units = "us"
print("#\(c.delim)TEST\(c.delim)SAMPLES\(c.delim)MIN(\(units))\(c.delim)MAX(\(units))\(c.delim)MEAN(\(units))\(c.delim)SD(\(units))\(c.delim)MEDIAN(\(units))")
var SumBenchResults = BenchResults()
SumBenchResults.sampleCount = 0
for t in c.tests {
if !t.run {
continue
}
let BenchIndex = t.index
let BenchName = t.name
let BenchFunc = t.f
let results = runBench(BenchName, BenchFunc, c)
print("\(BenchIndex)\(c.delim)\(BenchName)\(c.delim)\(results.description)")
fflush(stdout)
SumBenchResults.min += results.min
SumBenchResults.max += results.max
SumBenchResults.mean += results.mean
SumBenchResults.sampleCount += 1
// Don't accumulate SD and Median, as simple sum isn't valid for them.
// TODO: Compute SD and Median for total results as well.
// SumBenchResults.sd += results.sd
// SumBenchResults.median += results.median
}
print("")
print("Totals\(c.delim)\(SumBenchResults.description)")
}
public func main() {
var config = TestConfig()
switch (config.processArguments()) {
case let .Fail(msg):
// We do this since we need an autoclosure...
fatalError("\(msg)")
case .ListTests:
config.findTestsToRun()
print("Enabled Tests:")
for t in config.tests {
print(" \(t.name)")
}
case .Run:
config.findTestsToRun()
printRunInfo(config)
runBenchmarks(config)
if let x = config.afterRunSleep {
sleep(UInt32(x))
}
}
}
| apache-2.0 | e476c6429af0abf2906cfdcd2a659a95 | 27.788204 | 161 | 0.619948 | 3.778325 | false | true | false | false |
Duraiamuthan/HybridWebRTC_iOS | WebRTCSupport/Pods/XWebView/XWebView/XWVScriptObject.swift | 1 | 5475 | /*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import WebKit
public class XWVScriptObject : XWVObject {
// JavaScript object operations
public func construct(arguments arguments: [AnyObject]?, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
let exp = "new " + scriptForCallingMethod(nil, arguments: arguments)
evaluateExpression(exp, completionHandler: completionHandler)
}
public func call(arguments arguments: [AnyObject]?, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
let exp = scriptForCallingMethod(nil, arguments: arguments)
evaluateExpression(exp, completionHandler: completionHandler)
}
public func callMethod(name: String, withArguments arguments: [AnyObject]?, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
let exp = scriptForCallingMethod(name, arguments: arguments)
evaluateExpression(exp, completionHandler: completionHandler)
}
public func construct(arguments arguments: [AnyObject]?) throws -> AnyObject {
let exp = "new \(scriptForCallingMethod(nil, arguments: arguments))"
guard let result = try evaluateExpression(exp) else {
let code = WKErrorCode.JavaScriptExceptionOccurred.rawValue
throw NSError(domain: WKErrorDomain, code: code, userInfo: nil)
}
return result
}
public func call(arguments arguments: [AnyObject]?) throws -> AnyObject? {
return try evaluateExpression(scriptForCallingMethod(nil, arguments: arguments))
}
public func callMethod(name: String, withArguments arguments: [AnyObject]?) throws -> AnyObject? {
return try evaluateExpression(scriptForCallingMethod(name, arguments: arguments))
}
public func call(arguments arguments: [AnyObject]?, error: NSErrorPointer) -> AnyObject? {
return evaluateExpression(scriptForCallingMethod(nil, arguments: arguments), error: error)
}
public func callMethod(name: String, withArguments arguments: [AnyObject]?, error: NSErrorPointer) -> AnyObject? {
return evaluateExpression(scriptForCallingMethod(name, arguments: arguments), error: error)
}
public func defineProperty(name: String, descriptor: [String:AnyObject]) -> AnyObject? {
let exp = "Object.defineProperty(\(namespace), \(name), \(serialize(descriptor)))"
return try! evaluateExpression(exp)
}
public func deleteProperty(name: String) -> Bool {
let result: AnyObject? = try! evaluateExpression("delete \(scriptForFetchingProperty(name))")
return (result as? NSNumber)?.boolValue ?? false
}
public func hasProperty(name: String) -> Bool {
let result: AnyObject? = try! evaluateExpression("\(scriptForFetchingProperty(name)) != undefined")
return (result as? NSNumber)?.boolValue ?? false
}
public func value(forProperty name: String) -> AnyObject? {
return try! evaluateExpression(scriptForFetchingProperty(name))
}
public func setValue(value: AnyObject?, forProperty name:String) {
webView?.evaluateJavaScript(scriptForUpdatingProperty(name, value: value), completionHandler: nil)
}
public func value(atIndex index: UInt) -> AnyObject? {
return try! evaluateExpression("\(namespace)[\(index)]")
}
public func setValue(value: AnyObject?, atIndex index: UInt) {
webView?.evaluateJavaScript("\(namespace)[\(index)] = \(serialize(value))", completionHandler: nil)
}
private func scriptForFetchingProperty(name: String!) -> String {
if name == nil {
return namespace
} else if name.isEmpty {
return "\(namespace)['']"
} else if let idx = Int(name) {
return "\(namespace)[\(idx)]"
} else {
return "\(namespace).\(name)"
}
}
private func scriptForUpdatingProperty(name: String!, value: AnyObject?) -> String {
return scriptForFetchingProperty(name) + " = " + serialize(value)
}
private func scriptForCallingMethod(name: String!, arguments: [AnyObject]?) -> String {
let args = arguments?.map(serialize) ?? []
return scriptForFetchingProperty(name) + "(" + args.joinWithSeparator(", ") + ")"
}
}
extension XWVScriptObject {
// Subscript as property accessor
public subscript(name: String) -> AnyObject? {
get {
return value(forProperty: name)
}
set {
setValue(newValue, forProperty: name)
}
}
public subscript(index: UInt) -> AnyObject? {
get {
return value(atIndex: index)
}
set {
setValue(newValue, atIndex: index)
}
}
}
class XWVWindowObject: XWVScriptObject {
private let origin: XWVObject
init(webView: WKWebView) {
origin = XWVObject(namespace: "XWVPlugin.context", webView: webView)
super.init(namespace: "window", origin: origin)
}
}
| gpl-3.0 | 075a5c98a345c878e73f5ad990a7db0f | 41.773438 | 135 | 0.674155 | 5.069444 | false | false | false | false |
galacemiguel/bluehacks2017 | Project Civ-1/Project Civ/ProjectUpdateTitleCell.swift | 1 | 2566 | //
// ProjectUpdateTitleCell.swift
// Project Civ
//
// Created by Carlos Arcenas on 2/18/17.
// Copyright ยฉ 2017 Rogue Three. All rights reserved.
//
import UIKit
class ProjectUpdateTitleCell: UICollectionViewCell {
static let titleFont = UIFont(name: "Tofino-Bold", size: 25)!
static let authorFont = UIFont(name: "Tofino-Book", size: 14)!
static let commonInset = UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)
static func cellSize(width: CGFloat, titleString: String, authorString: String) -> CGSize {
let titleBounds = TextSize.size(titleString, font: ProjectUpdateTitleCell.titleFont, width: width, insets: commonInset)
let authorBounds = TextSize.size(authorString, font: ProjectUpdateTitleCell.authorFont, width: width, insets: ProjectUpdateTitleCell.commonInset)
return CGSize(width: width, height: titleBounds.height + authorBounds.height)
}
let titleLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.font = ProjectUpdateTitleCell.titleFont
label.textColor = UIColor(hex6: 0x387780)
return label
}()
let authorLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor.clear
label.numberOfLines = 0
label.font = ProjectUpdateTitleCell.authorFont
label.textColor = UIColor(hex6: 0x757780)
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(authorLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let authorLabelRect = TextSize.size(authorLabel.text!, font: ProjectUpdateTitleCell.authorFont, width: frame.width, insets: ProjectUpdateTitleCell.commonInset)
authorLabel.frame = UIEdgeInsetsInsetRect(authorLabelRect, ProjectUpdateTitleCell.commonInset)
authorLabel.frame.origin.y = frame.height - authorLabelRect.size.height
let titleLabelRect = TextSize.size(titleLabel.text!, font: ProjectUpdateTitleCell.titleFont, width: frame.width, insets: ProjectUpdateTitleCell.commonInset)
titleLabel.frame = UIEdgeInsetsInsetRect(titleLabelRect, ProjectUpdateTitleCell.commonInset)
titleLabel.frame.origin.y = authorLabel.frame.origin.y - titleLabel.frame.height
}
}
| mit | f4509b709498fa517590526159187bed | 40.370968 | 167 | 0.698246 | 4.794393 | false | false | false | false |
marty-suzuki/FluxCapacitor | FluxCapacitor/Internal/ValueNotifyCenter.swift | 1 | 1724 | //
// ValueNotifyCenter.swift
// FluxCapacitor
//
// Created by marty-suzuki on 2018/02/04.
// Copyright ยฉ 2018ๅนด marty-suzuki. All rights reserved.
//
import Foundation
/// Notify changes of values.
final class ValueNotifyCenter<Element> {
private struct Observer {
fileprivate struct Token {
let value = UUID().uuidString
}
fileprivate let token: Token
fileprivate let excuteQueue: ExecuteQueue
fileprivate let changes: (Element) -> ()
}
private var observers: [Observer] = []
private let mutex = PThreadMutex()
func addObserver(excuteQueue: ExecuteQueue, changes: @escaping (Element) -> Void) -> Dust {
mutex.lock()
let observer = Observer(token: .init(), excuteQueue: excuteQueue, changes: changes)
observers.append(observer)
let token = observer.token
mutex.unlock()
return Dust { [weak self] in
guard let me = self else { return }
defer { me.mutex.unlock() }; me.mutex.lock()
me.observers = me.observers.filter { $0.token.value != token.value }
}
}
func notifyChanges(value: Element) {
observers.forEach { observer in
let execute: () -> Void = {
observer.changes(value)
}
switch observer.excuteQueue {
case .current:
execute()
case .main:
if Thread.isMainThread {
execute()
} else {
DispatchQueue.main.async(execute: execute)
}
case .queue(let queue):
queue.async(execute: execute)
}
}
}
}
| mit | 3f927dcd510a8352d914654b47c78c12 | 26.758065 | 95 | 0.553167 | 4.651351 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/SecretsManager/SecretsManager_Error.swift | 1 | 4714 | //===----------------------------------------------------------------------===//
//
// 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
/// Error enum for SecretsManager
public struct SecretsManagerErrorType: AWSErrorType {
enum Code: String {
case decryptionFailure = "DecryptionFailure"
case encryptionFailure = "EncryptionFailure"
case internalServiceError = "InternalServiceError"
case invalidNextTokenException = "InvalidNextTokenException"
case invalidParameterException = "InvalidParameterException"
case invalidRequestException = "InvalidRequestException"
case limitExceededException = "LimitExceededException"
case malformedPolicyDocumentException = "MalformedPolicyDocumentException"
case preconditionNotMetException = "PreconditionNotMetException"
case publicPolicyException = "PublicPolicyException"
case resourceExistsException = "ResourceExistsException"
case resourceNotFoundException = "ResourceNotFoundException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize SecretsManager
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
/// Secrets Manager can't decrypt the protected secret text using the provided KMS key.
public static var decryptionFailure: Self { .init(.decryptionFailure) }
/// Secrets Manager can't encrypt the protected secret text using the provided KMS key. Check that the customer master key (CMK) is available, enabled, and not in an invalid state. For more information, see How Key State Affects Use of a Customer Master Key.
public static var encryptionFailure: Self { .init(.encryptionFailure) }
/// An error occurred on the server side.
public static var internalServiceError: Self { .init(.internalServiceError) }
/// You provided an invalid NextToken value.
public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) }
/// You provided an invalid value for a parameter.
public static var invalidParameterException: Self { .init(.invalidParameterException) }
/// You provided a parameter value that is not valid for the current state of the resource. Possible causes: You tried to perform the operation on a secret that's currently marked deleted. You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and you didn't include such an ARN as a parameter in this call.
public static var invalidRequestException: Self { .init(.invalidRequestException) }
/// The request failed because it would exceed one of the Secrets Manager internal limits.
public static var limitExceededException: Self { .init(.limitExceededException) }
/// The policy document that you provided isn't valid.
public static var malformedPolicyDocumentException: Self { .init(.malformedPolicyDocumentException) }
/// The request failed because you did not complete all the prerequisite steps.
public static var preconditionNotMetException: Self { .init(.preconditionNotMetException) }
/// The resource policy did not prevent broad access to the secret.
public static var publicPolicyException: Self { .init(.publicPolicyException) }
/// A resource with the ID you requested already exists.
public static var resourceExistsException: Self { .init(.resourceExistsException) }
/// We can't find the resource that you asked for.
public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) }
}
extension SecretsManagerErrorType: Equatable {
public static func == (lhs: SecretsManagerErrorType, rhs: SecretsManagerErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension SecretsManagerErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| apache-2.0 | 09478428ca0e87b86c9e5800088fc094 | 51.377778 | 360 | 0.71574 | 5.326554 | false | false | false | false |
prebid/prebid-mobile-ios | PrebidMobile/PrebidMobileRendering/SkadnParametersManager.swift | 1 | 3748 | /* Copyright 2018-2019 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import StoreKit
@objcMembers
public class SkadnParametersManager: NSObject {
private static func getFidelity(from skadnInfo: PBMORTBBidExtSkadn, fidelityType: NSNumber) -> PBMORTBSkadnFidelity? {
guard let fidelities = skadnInfo.fidelities else { return nil }
for fidelity in fidelities {
if fidelity.fidelity == fidelityType {
return fidelity
}
}
return nil
}
@available(iOS 14.5, *)
public static func getSkadnImpression(for skadnInfo: PBMORTBBidExtSkadn) -> SKAdImpression? {
guard let fidelity = SkadnParametersManager.getFidelity(from: skadnInfo, fidelityType: 0) else { return nil }
let imp = SKAdImpression()
if let itunesitem = skadnInfo.itunesitem,
let network = skadnInfo.network,
let campaign = skadnInfo.campaign,
let sourceapp = skadnInfo.sourceapp,
let nonce = fidelity.nonce,
let timestamp = fidelity.timestamp,
let signature = fidelity.signature,
let version = skadnInfo.version {
imp.sourceAppStoreItemIdentifier = sourceapp
imp.advertisedAppStoreItemIdentifier = itunesitem
imp.adNetworkIdentifier = network
imp.adCampaignIdentifier = campaign
imp.adImpressionIdentifier = nonce.uuidString
imp.timestamp = timestamp
imp.signature = signature
imp.version = version
return imp
}
return nil
}
public static func getSkadnProductParameters(for skadnInfo: PBMORTBBidExtSkadn) -> Dictionary<String, Any>? {
// >= SKAdNetwork 2.2
if #available(iOS 14.5, *) {
guard let fidelity = SkadnParametersManager.getFidelity(from: skadnInfo, fidelityType: 1) else { return nil }
var productParams = Dictionary<String, Any>()
if let itunesitem = skadnInfo.itunesitem,
let network = skadnInfo.network,
let campaign = skadnInfo.campaign,
let sourceapp = skadnInfo.sourceapp,
let version = skadnInfo.version,
let timestamp = fidelity.timestamp,
let nonce = fidelity.nonce,
let signature = fidelity.signature {
productParams[SKStoreProductParameterITunesItemIdentifier] = itunesitem
productParams[SKStoreProductParameterAdNetworkIdentifier] = network
productParams[SKStoreProductParameterAdNetworkCampaignIdentifier] = campaign
productParams[SKStoreProductParameterAdNetworkVersion] = version
productParams[SKStoreProductParameterAdNetworkSourceAppStoreIdentifier] = sourceapp
productParams[SKStoreProductParameterAdNetworkTimestamp] = timestamp
productParams[SKStoreProductParameterAdNetworkNonce] = nonce
productParams[SKStoreProductParameterAdNetworkAttributionSignature] = signature
return productParams
}
}
return nil
}
}
| apache-2.0 | 2279414fc40396cdeee2e5ca5f306b1b | 41.590909 | 122 | 0.65635 | 5.536189 | false | false | false | false |
937447974/YJCocoa | YJCocoa/Classes/AppFrameworks/UIKit/CollectionView/YJUICollectionViewManager.swift | 1 | 7658 | //
// YJUICollectionViewManager.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJๆๆฏๆฏๆ็พค:557445088
//
// Created by ้ณๅ on 2019/5/23.
// Copyright ยฉ 2016-็ฐๅจ YJCocoa. All rights reserved.
//
import UIKit
/** UICollectionView็ฎก็ๅจ*/
@objcMembers
open class YJUICollectionViewManager: NSObject {
/// header ๆฐๆฎๆบ
public var dataSourceHeader = Array<YJUICollectionCellObject>()
/// header ๆฐๆฎๆบ
public var dataSourceFooter = Array<YJUICollectionCellObject>()
/// cell ๆฐๆฎๆบ
public var dataSourceCell = Array<Array<YJUICollectionCellObject>>()
/// cell ็ฌฌไธ็ปๆฐๆฎๆบ
public var dataSourceCellFirst: Array<YJUICollectionCellObject> {
get {return self.dataSourceCell.first!}
set {
if self.dataSourceCell.count > 0 {
self.dataSourceCell[0] = newValue
} else {
self.dataSourceCell.append(newValue)
}
}
}
public weak private(set) var collectionView: UICollectionView!
public weak private(set) var flowLayout: UICollectionViewFlowLayout!
private var identifierSet = Set<String>()
public init(collectionView: UICollectionView) {
super.init()
self.collectionView = collectionView
self.flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
self.dataSourceCellFirst = Array()
}
}
extension YJUICollectionViewManager: UICollectionViewDataSource {
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.dataSourceCell.count
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard section < self.dataSourceCell.count else {
YJLogWarn("error:ๆฐ็ป่ถ็; selector:\(#function)")
return 0
}
return self.dataSourceCell[section].count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let co = self.cellObject(with: indexPath) else {
YJLogWarn("error:ๆฐ็ป่ถ็; selector:\(#function)")
return UICollectionViewCell(frame: CGRect.zero)
}
return self.dequeueReusableCell(withCellObject: co)
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let isHeader = UICollectionView.elementKindSectionHeader == kind
guard let co = isHeader ? self.cellHeaderObject(with: indexPath.section) : self.cellFooterObject(with: indexPath.section) else {
return UICollectionReusableView(frame: CGRect.zero)
}
return self.dequeueReusableSupplementaryView(ofKind: kind, for: co)
}
private func dequeueReusableCell(withCellObject cellObject: YJUICollectionCellObject) -> UICollectionViewCell {
if !self.identifierSet.contains(cellObject.reuseIdentifier) {
self.collectionView.register(cellObject.cellClass, forCellWithReuseIdentifier: cellObject.reuseIdentifier)
self.identifierSet.insert(cellObject.reuseIdentifier)
}
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: cellObject.reuseIdentifier, for: cellObject.indexPath)
cell.collectionViewManager(self, reloadWith: cellObject)
return cell
}
private func dequeueReusableSupplementaryView(ofKind elementKind: String, for cellObject: YJUICollectionCellObject) -> UICollectionReusableView {
let identifier = elementKind + cellObject.reuseIdentifier
if !self.identifierSet.contains(identifier) {
self.collectionView.register(cellObject.cellClass, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)
self.identifierSet.insert(identifier)
}
let reusableView = self.collectionView.dequeueReusableSupplementaryView(ofKind: elementKind, withReuseIdentifier: identifier, for: cellObject.indexPath)
reusableView.collectionViewManager(self, reloadWith: cellObject)
return reusableView
}
}
extension YJUICollectionViewManager: UICollectionViewDelegate {
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let co = self.cellObject(with: indexPath) {
co.didSelectClosure?(self, co)
}
}
}
extension YJUICollectionViewManager: UICollectionViewDelegateFlowLayout {
//MARK: UICollectionViewDelegateFlowLayout
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let co = self.cellObject(with: indexPath) else {
YJLogWarn("error:ๆฐ็ป่ถ็; selector:\(#function)")
return self.flowLayout.itemSize
}
return self.collectionView(collectionView, referenceSizeFor: "cell", in: co)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let co = self.cellHeaderObject(with: section) else {
return self.flowLayout.headerReferenceSize
}
return self.collectionView(collectionView, referenceSizeFor: UICollectionView.elementKindSectionHeader, in: co)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard let co = self.cellFooterObject(with: section) else {
return self.flowLayout.footerReferenceSize
}
return self.collectionView(collectionView, referenceSizeFor: UICollectionView.elementKindSectionFooter, in: co)
}
// MARK: private
private func cellObject(with indexPath: IndexPath) -> YJUICollectionCellObject? {
guard indexPath.section < self.dataSourceCell.count && indexPath.row < self.dataSourceCell[indexPath.section].count else {
return nil
}
let co = self.dataSourceCell[indexPath.section][indexPath.row]
co.indexPath = indexPath
return co
}
private func cellHeaderObject(with section: Int) -> YJUICollectionCellObject? {
guard section < self.dataSourceHeader.count else {
return nil
}
let co = self.dataSourceHeader[section]
co.indexPath = IndexPath(row: 0, section: section)
return co
}
private func cellFooterObject(with section: Int) -> YJUICollectionCellObject? {
guard section < self.dataSourceFooter.count else {
return nil
}
let co = self.dataSourceFooter[section]
co.indexPath = IndexPath(row: 0, section: section)
return co
}
private func collectionView(_ collectionView: UICollectionView, referenceSizeFor kind: String, in cellObject: YJUICollectionCellObject) -> CGSize {
if let size = cellObject.size {
return size
}
var size = CGSize.zero
if let cellType = cellObject.cellClass as? UICollectionViewCell.Type {
size = cellType.collectionViewManager(self, sizeWith: cellObject)
} else {
size = cellObject.cellClass.collectionViewManager(self, referenceSizeFor: kind, in: cellObject)
}
return size
}
}
| mit | 13bb6a317ad75c625598f855e2947947 | 41.340782 | 177 | 0.699037 | 5.668661 | false | false | false | false |
mapzen/ios | SampleApp/DemoMapViewController.swift | 1 | 4641 | //
// DemoMapViewController.swift
// ios-sdk
//
// Created by Matt Smollinger on 7/12/16.
// Copyright ยฉ 2016 Mapzen. All rights reserved.
//
import UIKit
import TangramMap
import Mapzen_ios_sdk
import CoreLocation
class DemoMapViewController: SampleMapViewController, MapMarkerSelectDelegate {
private var styleLoaded = false
lazy var activityIndicator : UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView.init(activityIndicatorStyle: .whiteLarge)
indicator.color = .black
indicator.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(indicator)
let xConstraint = indicator.centerXAnchor.constraint(equalTo: self.view.centerXAnchor)
let yConstraint = indicator.centerYAnchor.constraint(equalTo: self.view.centerYAnchor)
NSLayoutConstraint.activate([xConstraint, yConstraint])
return indicator
}()
override func viewDidLoad() {
super.viewDidLoad()
setupSwitchStyleBtn()
setupSwitchLocaleBtn()
setupStyleNotification()
markerSelectDelegate = self
locationManager.requestAlwaysAuthorization()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
try? loadStyleSheetAsync(appDelegate.selectedMapStyle) { (style) in
self.styleLoaded = true
let _ = self.showCurrentLocation(true)
self.showFindMeButon(true)
//Uncomment this to enable background location updates. However be aware that they are never cancelled so the sample app will just chew through your battery!
// if self.locationManager.canEnableBackgroundLocationUpdates() {
// _ = self.locationManager.enableBackgroundLocationUpdates(forType: .other, desiredAccuracy: kCLLocationAccuracyBest, pausesLocationAutomatically: false)
// }
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "displayStyleSelector" {
let destVC = segue.destination as! UINavigationController
let styleVC = destVC.viewControllers[0] as! StylePickerVC
styleVC.mapController = self
}
}
override func locationDidUpdate(_ location: CLLocation) {
super.locationDidUpdate(location)
print("Location update received!")
}
//MARK : MapSelectDelegate
func mapController(_ controller: MZMapViewController, didSelectMarker marker: GenericMarker, atScreenPosition position: CGPoint) {
let alert = UIAlertController(title: "Marker Selected", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
//MARK : Private
private func setupSwitchStyleBtn() {
let btn = UIBarButtonItem.init(title: "Map Style", style: .plain, target: self, action: #selector(openSettings))
self.navigationItem.rightBarButtonItem = btn
}
private func setupSwitchLocaleBtn() {
let btn = UIBarButtonItem.init(title: "Map Language", style: .plain, target: self, action: #selector(changeMapLanguage))
self.navigationItem.leftBarButtonItem = btn
}
@objc private func openSettings() {
performSegue(withIdentifier: "displayStyleSelector", sender: self)
}
@objc private func changeMapLanguage() {
let languageIdByActionSheetTitle = [
"English": "en_US",
"French": "fr_FR",
"Japanese": "ja_JP",
"Hindi": "hi_IN",
"Spanish": "es_ES",
"Korean": "ko_KR",
"Italian": "it_IT",
"OSM Default": "none",
]
let actionSheet = UIAlertController.init(title: "Map Language", message: "Choose a language", preferredStyle: .actionSheet)
for (actionTitle, languageIdentifier) in languageIdByActionSheetTitle {
if (languageIdentifier == "none") {
actionSheet.addAction(UIAlertAction.init(title: actionTitle, style: .default, handler: { [unowned self] (action) in
let update = TGSceneUpdate(path: "global.ux_language", value: "")
self.tgViewController.updateSceneAsync([update])
}))
continue
}
actionSheet.addAction(UIAlertAction.init(title: actionTitle, style: .default, handler: { [unowned self] (action) in
self.updateLocale(Locale.init(identifier: languageIdentifier))
}))
}
actionSheet.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: { [unowned self] (action) in
self.dismiss(animated: true, completion: nil)
}))
let presentationController = actionSheet.popoverPresentationController
presentationController?.barButtonItem = self.navigationItem.leftBarButtonItem
self.navigationController?.present(actionSheet, animated: true, completion: nil)
}
}
| apache-2.0 | f9052dcef3dae6f565906b50d11931af | 38.322034 | 161 | 0.724784 | 4.630739 | false | false | false | false |
douban/rexxar-ios | RexxarDemo/Library/FRDToast/LoadingView.swift | 2 | 6568 | //
// LoadingView.swift
// Frodo
//
// Created by ๆไฟ on 15/12/7.
// Copyright ยฉ 2015ๅนด Douban Inc. All rights reserved.
//
import UIKit
private let animationDuration: TimeInterval = 2.4
@objc class LoadingView: UIView {
var lineWidth: CGFloat = 5 {
didSet {
setNeedsLayout()
}
}
var strokeColor = UIColor(hex: 0x42BD56) {
didSet {
ringLayer.strokeColor = strokeColor.cgColor
rightPointLayer.strokeColor = strokeColor.cgColor
leftPointLayer.strokeColor = strokeColor.cgColor
}
}
fileprivate let ringLayer = CAShapeLayer()
fileprivate let pointSuperLayer = CALayer()
fileprivate let rightPointLayer = CAShapeLayer()
fileprivate let leftPointLayer = CAShapeLayer()
fileprivate var isAnimating = false
init(frame: CGRect, color: UIColor?) {
super.init(frame: frame)
strokeColor = color ?? strokeColor
ringLayer.contentsScale = UIScreen.main.scale
ringLayer.strokeColor = strokeColor.cgColor
ringLayer.fillColor = UIColor.clear.cgColor
ringLayer.lineCap = CAShapeLayerLineCap.round
ringLayer.lineJoin = CAShapeLayerLineJoin.bevel
layer.addSublayer(ringLayer)
layer.addSublayer(pointSuperLayer)
rightPointLayer.strokeColor = strokeColor.cgColor
rightPointLayer.lineCap = CAShapeLayerLineCap.round
pointSuperLayer.addSublayer(rightPointLayer)
leftPointLayer.strokeColor = strokeColor.cgColor
leftPointLayer.lineCap = CAShapeLayerLineCap.round
pointSuperLayer.addSublayer(leftPointLayer)
NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let centerPoint = CGPoint(x: bounds.width/2, y: bounds.height/2)
let radius = bounds.width/2 - lineWidth
let path = UIBezierPath(arcCenter: centerPoint, radius: radius, startAngle:CGFloat(-Double.pi), endAngle: CGFloat(Double.pi * 0.6), clockwise: true)
ringLayer.lineWidth = lineWidth
ringLayer.path = path.cgPath
ringLayer.frame = bounds
let x = bounds.width/2 - CGFloat(sin(Double.pi * 50.0/180.0)) * radius
let y = bounds.height/2 - CGFloat(sin(Double.pi * 40.0/180.0)) * radius
let rightPoint = CGPoint(x: bounds.width - x, y: y)
let leftPoint = CGPoint(x: x, y: y)
let rightPointPath = UIBezierPath()
rightPointPath.move(to: rightPoint)
rightPointPath.addLine(to: rightPoint)
rightPointLayer.path = rightPointPath.cgPath
rightPointLayer.lineWidth = lineWidth
let leftPointPath = UIBezierPath()
leftPointPath.move(to: leftPoint)
leftPointPath.addLine(to: leftPoint)
leftPointLayer.path = leftPointPath.cgPath
leftPointLayer.lineWidth = lineWidth
pointSuperLayer.frame = bounds
}
func startAnimation() {
if isAnimating { return }
pointSuperLayer.isHidden = false
let keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.216 as Double), NSNumber(value: 0.396 as Double), NSNumber(value: 0.8 as Double), NSNumber(value: 1 as Int32)]
// pointSuperLayer animation
let pointKeyAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
pointKeyAnimation.duration = animationDuration
pointKeyAnimation.repeatCount = Float.infinity
pointKeyAnimation.values = [0, (2 * Double.pi * 0.375 + 2 * Double.pi), (4 * Double.pi), (4 * Double.pi), (4 * Double.pi + 0.3 * Double.pi)]
pointKeyAnimation.keyTimes = keyTimes
pointSuperLayer.add(pointKeyAnimation, forKey: nil)
// ringLayer animation
let ringAnimationGroup = CAAnimationGroup()
let ringKeyRotationAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
ringKeyRotationAnimation.values = [0, (2 * Double.pi), (Double.pi/2 + 2 * Double.pi), (Double.pi/2 + 2 * Double.pi), (4 * Double.pi)]
ringKeyRotationAnimation.keyTimes = keyTimes
ringAnimationGroup.animations = [ringKeyRotationAnimation]
let ringKeyStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart")
ringKeyStartAnimation.values = [0, 0.25, 0.35, 0.35, 0]
ringKeyStartAnimation.keyTimes = keyTimes
ringAnimationGroup.animations?.append(ringKeyStartAnimation)
let ringKeyEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd")
ringKeyEndAnimation.values = [1, 1, 0.9, 0.9, 1]
ringKeyEndAnimation.keyTimes = keyTimes
ringAnimationGroup.animations?.append(ringKeyEndAnimation)
ringAnimationGroup.duration = animationDuration
ringAnimationGroup.repeatCount = Float.infinity
ringLayer.add(ringAnimationGroup, forKey: nil)
// pointAnimation
let rightPointKeyAnimation = CAKeyframeAnimation(keyPath: "lineWidth")
rightPointKeyAnimation.values = [lineWidth, lineWidth, lineWidth * 1.4, lineWidth * 1.4, lineWidth]
rightPointKeyAnimation.keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.21 as Double), NSNumber(value: 0.29 as Double), NSNumber(value: 0.88 as Double), NSNumber(value: 0.96 as Double)]
rightPointKeyAnimation.duration = animationDuration
rightPointKeyAnimation.repeatCount = Float.infinity
rightPointLayer.add(rightPointKeyAnimation, forKey: nil)
let leftPointKeyAnimation = CAKeyframeAnimation(keyPath: "lineWidth")
leftPointKeyAnimation.values = [lineWidth, lineWidth, lineWidth * 1.4, lineWidth * 1.4, lineWidth]
leftPointKeyAnimation.keyTimes = [NSNumber(value: 0 as Double), NSNumber(value: 0.31 as Double), NSNumber(value: 0.39 as Double), NSNumber(value: 0.8 as Double), NSNumber(value: 0.88 as Double)]
leftPointKeyAnimation.duration = animationDuration
leftPointKeyAnimation.repeatCount = Float.infinity
leftPointLayer.add(leftPointKeyAnimation, forKey: nil)
isAnimating = true
}
func stopAnimation() {
pointSuperLayer.removeAllAnimations()
ringLayer.removeAllAnimations()
rightPointLayer.removeAllAnimations()
leftPointLayer.removeAllAnimations()
isAnimating = false
}
func setPercentage(_ percent: CGFloat) {
pointSuperLayer.isHidden = true
ringLayer.strokeEnd = percent
}
@objc fileprivate func appWillEnterForeground() {
if isAnimating {
isAnimating = false
startAnimation()
}
}
override func willMove(toWindow newWindow: UIWindow?) {
if newWindow != nil && isAnimating {
isAnimating = false
startAnimation()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | fb80769791ebe0688f00941d776e3872 | 34.852459 | 200 | 0.73312 | 4.646601 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | Example/Pods/GRMustache.swift/Sources/TemplateCompiler.swift | 2 | 24418 | // The MIT License
//
// Copyright (c) 2015 Gwendal Rouรฉ
//
// 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
final class TemplateCompiler: TemplateTokenConsumer {
fileprivate var state: CompilerState
fileprivate let repository: TemplateRepository
fileprivate let templateID: TemplateID?
init(contentType: ContentType, repository: TemplateRepository, templateID: TemplateID?) {
self.state = .compiling(CompilationState(contentType: contentType))
self.repository = repository
self.templateID = templateID
}
func templateAST() throws -> TemplateAST {
switch(state) {
case .compiling(let compilationState):
switch compilationState.currentScope.type {
case .root:
return TemplateAST(nodes: compilationState.currentScope.templateASTNodes, contentType: compilationState.contentType)
case .section(openingToken: let openingToken, expression: _):
throw MustacheError(kind: .parseError, message: "Unclosed Mustache tag", templateID: openingToken.templateID, lineNumber: openingToken.lineNumber)
case .invertedSection(openingToken: let openingToken, expression: _):
throw MustacheError(kind: .parseError, message: "Unclosed Mustache tag", templateID: openingToken.templateID, lineNumber: openingToken.lineNumber)
case .partialOverride(openingToken: let openingToken, parentPartialName: _):
throw MustacheError(kind: .parseError, message: "Unclosed Mustache tag", templateID: openingToken.templateID, lineNumber: openingToken.lineNumber)
case .block(openingToken: let openingToken, blockName: _):
throw MustacheError(kind: .parseError, message: "Unclosed Mustache tag", templateID: openingToken.templateID, lineNumber: openingToken.lineNumber)
}
case .error(let compilationError):
throw compilationError
}
}
// MARK: - TemplateTokenConsumer
func parser(_ parser: TemplateParser, didFailWithError error: Error) {
state = .error(error)
}
func parser(_ parser: TemplateParser, shouldContinueAfterParsingToken token: TemplateToken) -> Bool {
switch(state) {
case .error:
return false
case .compiling(let compilationState):
do {
switch(token.type) {
case .setDelimiters:
// noop
break
case .comment:
// noop
break
case .pragma(content: let content):
let pragma = content.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if (try! NSRegularExpression(pattern: "^CONTENT_TYPE\\s*:\\s*TEXT$", options: NSRegularExpression.Options(rawValue: 0))).firstMatch(in: pragma, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, (pragma as NSString).length)) != nil {
switch compilationState.compilerContentType {
case .unlocked:
compilationState.compilerContentType = .unlocked(.text)
case .locked(_):
throw MustacheError(kind: .parseError, message:"CONTENT_TYPE:TEXT pragma tag must prepend any Mustache variable, section, or partial tag.", templateID: token.templateID, lineNumber: token.lineNumber)
}
} else if (try! NSRegularExpression(pattern: "^CONTENT_TYPE\\s*:\\s*HTML$", options: NSRegularExpression.Options(rawValue: 0))).firstMatch(in: pragma, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, (pragma as NSString).length)) != nil {
switch compilationState.compilerContentType {
case .unlocked:
compilationState.compilerContentType = .unlocked(.html)
case .locked(_):
throw MustacheError(kind: .parseError, message:"CONTENT_TYPE:HTML pragma tag must prepend any Mustache variable, section, or partial tag.", templateID: token.templateID, lineNumber: token.lineNumber)
}
}
case .text(text: let text):
switch compilationState.currentScope.type {
case .partialOverride:
// Text inside a partial override tag is not rendered.
//
// We could throw an error, like we do for illegal tags
// inside a partial override tag.
//
// But Hogan.js has an explicit test for "successfully"
// ignored text. So let's not throw.
//
// Ignore text inside a partial override tag:
break
default:
compilationState.currentScope.appendNode(TemplateASTNode.text(text: text))
}
case .escapedVariable(content: let content, tagDelimiterPair: _):
switch compilationState.currentScope.type {
case .partialOverride:
throw MustacheError(kind: .parseError, message:"Illegal tag inside a partial override tag.", templateID: token.templateID, lineNumber: token.lineNumber)
default:
var empty = false
do {
let expression = try ExpressionParser().parse(content, empty: &empty)
compilationState.currentScope.appendNode(TemplateASTNode.variable(expression: expression, contentType: compilationState.contentType, escapesHTML: true, token: token))
compilationState.compilerContentType = .locked(compilationState.contentType)
} catch let error as MustacheError {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
}
case .unescapedVariable(content: let content, tagDelimiterPair: _):
switch compilationState.currentScope.type {
case .partialOverride:
throw MustacheError(kind: .parseError, message: "Illegal tag inside a partial override tag: \(token.templateSubstring)", templateID: token.templateID, lineNumber: token.lineNumber)
default:
var empty = false
do {
let expression = try ExpressionParser().parse(content, empty: &empty)
compilationState.currentScope.appendNode(TemplateASTNode.variable(expression: expression, contentType: compilationState.contentType, escapesHTML: false, token: token))
compilationState.compilerContentType = .locked(compilationState.contentType)
} catch let error as MustacheError {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
}
case .section(content: let content, tagDelimiterPair: _):
switch compilationState.currentScope.type {
case .partialOverride:
throw MustacheError(kind: .parseError, message: "Illegal tag inside a partial override tag: \(token.templateSubstring)", templateID: token.templateID, lineNumber: token.lineNumber)
default:
var empty = false
do {
let expression = try ExpressionParser().parse(content, empty: &empty)
compilationState.pushScope(Scope(type: .section(openingToken: token, expression: expression)))
compilationState.compilerContentType = .locked(compilationState.contentType)
} catch let error as MustacheError {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
}
case .invertedSection(content: let content, tagDelimiterPair: _):
switch compilationState.currentScope.type {
case .partialOverride:
throw MustacheError(kind: .parseError, message: "Illegal tag inside a partial override tag: \(token.templateSubstring)", templateID: token.templateID, lineNumber: token.lineNumber)
default:
var empty = false
do {
let expression = try ExpressionParser().parse(content, empty: &empty)
compilationState.pushScope(Scope(type: .invertedSection(openingToken: token, expression: expression)))
compilationState.compilerContentType = .locked(compilationState.contentType)
} catch let error as MustacheError {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
}
case .block(content: let content):
var empty: Bool = false
let blockName = try blockNameFromString(content, inToken: token, empty: &empty)
compilationState.pushScope(Scope(type: .block(openingToken: token, blockName: blockName)))
compilationState.compilerContentType = .locked(compilationState.contentType)
case .partialOverride(content: let content):
var empty: Bool = false
let parentPartialName = try partialNameFromString(content, inToken: token, empty: &empty)
compilationState.pushScope(Scope(type: .partialOverride(openingToken: token, parentPartialName: parentPartialName)))
compilationState.compilerContentType = .locked(compilationState.contentType)
case .close(content: let content):
switch compilationState.currentScope.type {
case .root:
throw MustacheError(kind: .parseError, message: "Unmatched closing tag", templateID: token.templateID, lineNumber: token.lineNumber)
case .section(openingToken: let openingToken, expression: let closedExpression):
var empty: Bool = false
var expression: Expression?
do {
expression = try ExpressionParser().parse(content, empty: &empty)
} catch let error as MustacheError {
if empty == false {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
}
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
if expression != nil && expression != closedExpression {
throw MustacheError(kind: .parseError, message: "Unmatched closing tag", templateID: token.templateID, lineNumber: token.lineNumber)
}
let templateASTNodes = compilationState.currentScope.templateASTNodes
let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType)
// // TODO: uncomment and make it compile
// if token.templateString !== openingToken.templateString {
// fatalError("Not implemented")
// }
let templateString = token.templateString
let innerContentRange = openingToken.range.upperBound..<token.range.lowerBound
let sectionTag = TemplateASTNode.section(templateAST: templateAST, expression: closedExpression, inverted: false, openingToken: openingToken, innerTemplateString: templateString[innerContentRange])
compilationState.popCurrentScope()
compilationState.currentScope.appendNode(sectionTag)
case .invertedSection(openingToken: let openingToken, expression: let closedExpression):
var empty: Bool = false
var expression: Expression?
do {
expression = try ExpressionParser().parse(content, empty: &empty)
} catch let error as MustacheError {
if empty == false {
throw error.errorWith(templateID: token.templateID, lineNumber: token.lineNumber)
}
} catch {
throw MustacheError(kind: .parseError, templateID: token.templateID, lineNumber: token.lineNumber, underlyingError: error)
}
if expression != nil && expression != closedExpression {
throw MustacheError(kind: .parseError, message: "Unmatched closing tag", templateID: token.templateID, lineNumber: token.lineNumber)
}
let templateASTNodes = compilationState.currentScope.templateASTNodes
let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType)
// // TODO: uncomment and make it compile
// if token.templateString !== openingToken.templateString {
// fatalError("Not implemented")
// }
let templateString = token.templateString
let innerContentRange = openingToken.range.upperBound..<token.range.lowerBound
let sectionTag = TemplateASTNode.section(templateAST: templateAST, expression: closedExpression, inverted: true, openingToken: openingToken, innerTemplateString: templateString[innerContentRange])
compilationState.popCurrentScope()
compilationState.currentScope.appendNode(sectionTag)
case .partialOverride(openingToken: _, parentPartialName: let parentPartialName):
var empty: Bool = false
var partialName: String?
do {
partialName = try partialNameFromString(content, inToken: token, empty: &empty)
} catch {
if empty == false {
throw error
}
}
if partialName != nil && partialName != parentPartialName {
throw MustacheError(kind: .parseError, message: "Unmatched closing tag", templateID: token.templateID, lineNumber: token.lineNumber)
}
let parentTemplateAST = try repository.templateAST(named: parentPartialName, relativeToTemplateID:templateID)
switch parentTemplateAST.type {
case .undefined:
break
case .defined(nodes: _, contentType: let partialContentType):
if partialContentType != compilationState.contentType {
throw MustacheError(kind: .parseError, message: "Content type mismatch", templateID: token.templateID, lineNumber: token.lineNumber)
}
}
let templateASTNodes = compilationState.currentScope.templateASTNodes
let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType)
let partialOverrideNode = TemplateASTNode.partialOverride(childTemplateAST: templateAST, parentTemplateAST: parentTemplateAST, parentPartialName: parentPartialName)
compilationState.popCurrentScope()
compilationState.currentScope.appendNode(partialOverrideNode)
case .block(openingToken: _, blockName: let closedBlockName):
var empty: Bool = false
var blockName: String?
do {
blockName = try blockNameFromString(content, inToken: token, empty: &empty)
} catch {
if empty == false {
throw error
}
}
if blockName != nil && blockName != closedBlockName {
throw MustacheError(kind: .parseError, message: "Unmatched closing tag", templateID: token.templateID, lineNumber: token.lineNumber)
}
let templateASTNodes = compilationState.currentScope.templateASTNodes
let templateAST = TemplateAST(nodes: templateASTNodes, contentType: compilationState.contentType)
let blockNode = TemplateASTNode.block(innerTemplateAST: templateAST, name: closedBlockName)
compilationState.popCurrentScope()
compilationState.currentScope.appendNode(blockNode)
}
case .partial(content: let content):
var empty: Bool = false
let partialName = try partialNameFromString(content, inToken: token, empty: &empty)
let partialTemplateAST = try repository.templateAST(named: partialName, relativeToTemplateID: templateID)
let partialNode = TemplateASTNode.partial(templateAST: partialTemplateAST, name: partialName)
compilationState.currentScope.appendNode(partialNode)
compilationState.compilerContentType = .locked(compilationState.contentType)
}
return true
} catch {
state = .error(error)
return false
}
}
}
// MARK: - Private
fileprivate class CompilationState {
var currentScope: Scope {
return scopeStack[scopeStack.endIndex - 1]
}
var contentType: ContentType {
switch compilerContentType {
case .unlocked(let contentType):
return contentType
case .locked(let contentType):
return contentType
}
}
init(contentType: ContentType) {
self.compilerContentType = .unlocked(contentType)
self.scopeStack = [Scope(type: .root)]
}
func popCurrentScope() {
scopeStack.removeLast()
}
func pushScope(_ scope: Scope) {
scopeStack.append(scope)
}
enum CompilerContentType {
case unlocked(ContentType)
case locked(ContentType)
}
var compilerContentType: CompilerContentType
fileprivate var scopeStack: [Scope]
}
fileprivate enum CompilerState {
case compiling(CompilationState)
case error(Error)
}
fileprivate class Scope {
let type: Type
var templateASTNodes: [TemplateASTNode]
init(type:Type) {
self.type = type
self.templateASTNodes = []
}
func appendNode(_ node: TemplateASTNode) {
templateASTNodes.append(node)
}
enum `Type` {
case root
case section(openingToken: TemplateToken, expression: Expression)
case invertedSection(openingToken: TemplateToken, expression: Expression)
case partialOverride(openingToken: TemplateToken, parentPartialName: String)
case block(openingToken: TemplateToken, blockName: String)
}
}
fileprivate func blockNameFromString(_ string: String, inToken token: TemplateToken, empty: inout Bool) throws -> String {
let whiteSpace = CharacterSet.whitespacesAndNewlines
let blockName = string.trimmingCharacters(in: whiteSpace)
if blockName.characters.count == 0 {
empty = true
throw MustacheError(kind: .parseError, message: "Missing block name", templateID: token.templateID, lineNumber: token.lineNumber)
} else if (blockName.rangeOfCharacter(from: whiteSpace) != nil) {
empty = false
throw MustacheError(kind: .parseError, message: "Invalid block name", templateID: token.templateID, lineNumber: token.lineNumber)
}
return blockName
}
fileprivate func partialNameFromString(_ string: String, inToken token: TemplateToken, empty: inout Bool) throws -> String {
let whiteSpace = CharacterSet.whitespacesAndNewlines
let partialName = string.trimmingCharacters(in: whiteSpace)
if partialName.characters.count == 0 {
empty = true
throw MustacheError(kind: .parseError, message: "Missing template name", templateID: token.templateID, lineNumber: token.lineNumber)
} else if (partialName.rangeOfCharacter(from: whiteSpace) != nil) {
empty = false
throw MustacheError(kind: .parseError, message: "Invalid template name", templateID: token.templateID, lineNumber: token.lineNumber)
}
return partialName
}
}
| apache-2.0 | 3c4a9b616836af633e0a55b49cbb3a44 | 57.553957 | 290 | 0.570463 | 6.532103 | false | false | false | false |
Raizlabs/ios-template | PRODUCTNAME/app/Pods/BonMot/Sources/Image+Tinting.swift | 1 | 4149 | //
// Image+Tinting.swift
// BonMot
//
// Created by Zev Eisenberg on 9/28/16.
// Copyright ยฉ 2016 Raizlabs. All rights reserved.
//
import Foundation
#if os(OSX)
import AppKit
#else
import UIKit
#endif
public extension BONImage {
#if os(OSX)
/// Returns a copy of the receiver where the alpha channel is maintained,
/// but every pixel's color is replaced with `color`.
///
/// - note: The returned image does _not_ have the template flag set,
/// preventing further tinting.
///
/// - Parameter theColor: The color to use to tint the receiver.
/// - Returns: A tinted copy of the image.
@objc(bon_tintedImageWithColor:)
func tintedImage(color theColor: BONColor) -> BONImage {
let imageRect = CGRect(origin: .zero, size: size)
let image = NSImage(size: size)
let rep = NSBitmapImageRep(
bitmapDataPlanes: nil,
pixelsWide: Int(size.width),
pixelsHigh: Int(size.height),
bitsPerSample: 8,
samplesPerPixel: 4,
hasAlpha: true,
isPlanar: false,
colorSpaceName: theColor.colorSpaceName,
bytesPerRow: 0,
bitsPerPixel: 0
)!
image.addRepresentation(rep)
image.lockFocus()
let context = NSGraphicsContext.current!.cgContext
context.setBlendMode(.normal)
let cgImage = self.cgImage(forProposedRect: nil, context: nil, hints: nil)!
context.draw(cgImage, in: imageRect)
// .sourceIn: resulting color = source color * destination alpha
context.setBlendMode(.sourceIn)
context.setFillColor(theColor.cgColor)
context.fill(imageRect)
image.unlockFocus()
// Prevent further tinting
image.isTemplate = false
// Transfer accessibility description
image.accessibilityDescription = self.accessibilityDescription
return image
}
#else
/// Returns a copy of the receiver where the alpha channel is maintained,
/// but every pixel's color is replaced with `color`.
///
/// - note: The returned image does _not_ have the template flag set,
/// preventing further tinting.
///
/// - Parameter theColor: The color to use to tint the receiver.
/// - Returns: A tinted copy of the image.
@objc(bon_tintedImageWithColor:)
func tintedImage(color theColor: BONColor) -> BONImage {
let imageRect = CGRect(origin: .zero, size: size)
// Save original properties
let originalCapInsets = capInsets
let originalResizingMode = resizingMode
let originalAlignmentRectInsets = alignmentRectInsets
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()!
// Flip the context vertically
context.translateBy(x: 0.0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0)
// Image tinting mostly inspired by http://stackoverflow.com/a/22528426/255489
context.setBlendMode(.normal)
context.draw(cgImage!, in: imageRect)
// .sourceIn: resulting color = source color * destination alpha
context.setBlendMode(.sourceIn)
context.setFillColor(theColor.cgColor)
context.fill(imageRect)
// Get new image
var image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
// Prevent further tinting
image = image.withRenderingMode(.alwaysOriginal)
// Restore original properties
image = image.withAlignmentRectInsets(originalAlignmentRectInsets)
if originalCapInsets != image.capInsets || originalResizingMode != image.resizingMode {
image = image.resizableImage(withCapInsets: originalCapInsets, resizingMode: originalResizingMode)
}
// Transfer accessibility label (watchOS not included; does not have accessibilityLabel on UIImage).
#if os(iOS) || os(tvOS)
image.accessibilityLabel = self.accessibilityLabel
#endif
return image
}
#endif
}
| mit | c3203f685d45cc63c82808181efa2172 | 31.40625 | 110 | 0.645853 | 5.070905 | false | false | false | false |
narner/AudioKit | AudioKit/Common/User Interface/AKNodeFFTPlot.swift | 1 | 3263 | //
// AKNodeFFTPlot.swift
// AudioKitUI
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright ยฉ 2017 Aurelius Prochazka. All rights reserved.
//
#if !JAZZY_HACK
import AudioKit
#endif
/// Plot the FFT output from any node in an signal processing graph
@IBDesignable
open class AKNodeFFTPlot: EZAudioPlot, EZAudioFFTDelegate {
internal func setupNode(_ input: AKNode?) {
if fft == nil {
fft = EZAudioFFT(maximumBufferSize: vDSP_Length(bufferSize),
sampleRate: Float(AKSettings.sampleRate),
delegate: self)
}
input?.avAudioNode.installTap(onBus: 0,
bufferSize: bufferSize,
format: nil) { [weak self] (buffer, _) in
if let strongSelf = self {
buffer.frameLength = strongSelf.bufferSize
let offset = Int(buffer.frameCapacity - buffer.frameLength)
if let tail = buffer.floatChannelData?[0], let existingFFT = strongSelf.fft {
existingFFT.computeFFT(withBuffer: &tail[offset],
withBufferSize: strongSelf.bufferSize)
}
}
}
}
internal var bufferSize: UInt32 = 1_024
/// EZAudioFFT container
fileprivate var fft: EZAudioFFT?
/// The node whose output to graph
open var node: AKNode? {
willSet {
node?.avAudioNode.removeTap(onBus: 0)
}
didSet {
setupNode(node)
}
}
deinit {
node?.avAudioNode.removeTap(onBus: 0)
}
/// Required coder-based initialization (for use with Interface Builder)
///
/// - parameter coder: NSCoder
///
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupNode(nil)
}
/// Initialize the plot with the output from a given node and optional plot size
///
/// - Parameters:
/// - input: AKNode from which to get the plot data
/// - width: Width of the view
/// - height: Height of the view
///
@objc public init(_ input: AKNode?, frame: CGRect, bufferSize: Int = 1_024) {
super.init(frame: frame)
self.plotType = .buffer
self.backgroundColor = AKColor.white
self.shouldCenterYAxis = true
self.bufferSize = UInt32(bufferSize)
setupNode(input)
}
/// Callback function for FFT data:
///
/// - Parameters:
/// - fft: EZAudioFFT Reference
/// - updatedWithFFTData: A pointer to a c-style array of floats
/// - bufferSize: Number of elements in the FFT Data array
///
open func fft(_ fft: EZAudioFFT!,
updatedWithFFTData fftData: UnsafeMutablePointer<Float>,
bufferSize: vDSP_Length) {
DispatchQueue.main.async { () -> Void in
self.updateBuffer(fftData, withBufferSize: self.bufferSize)
}
}
}
| mit | 434164d2f518bd1156d8c40c52f91f92 | 32.979167 | 121 | 0.534641 | 5.169572 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/longest-harmonious-subsequence.swift | 2 | 489 | /**
* https://leetcode.com/problems/longest-harmonious-subsequence/
*
*
*/
// Date: Thu Feb 4 13:57:16 PST 2021
class Solution {
func findLHS(_ nums: [Int]) -> Int {
var map: [Int : Int] = [:]
for x in nums {
map[x, default: 0] += 1
}
var result = 0
for key in map.keys {
if let x = map[key], let y = map[key + 1] {
result = max(result, x + y)
}
}
return result
}
} | mit | a041c45a58b8e1a110f7b695375ae42a | 22.333333 | 64 | 0.453988 | 3.41958 | false | false | false | false |
zybug/firefox-ios | Client/Frontend/Reader/ReadabilityService.swift | 21 | 4078 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
private let ReadabilityServiceSharedInstance = ReadabilityService()
private let ReadabilityTaskDefaultTimeout = 15
private let ReadabilityServiceDefaultConcurrency = 1
enum ReadabilityOperationResult {
case Success(ReadabilityResult)
case Error(NSError)
case Timeout
}
class ReadabilityOperation: NSOperation, WKNavigationDelegate, ReadabilityBrowserHelperDelegate {
var url: NSURL
var semaphore: dispatch_semaphore_t
var result: ReadabilityOperationResult?
var browser: Browser!
init(url: NSURL) {
self.url = url
self.semaphore = dispatch_semaphore_create(0)
}
override func main() {
if self.cancelled {
return
}
// Setup a browser, attach a Readability helper. Kick all this off on the main thread since UIKit
// and WebKit are not safe from other threads.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let configuration = WKWebViewConfiguration()
self.browser = Browser(configuration: configuration)
self.browser.createWebview()
self.browser.navigationDelegate = self
if let readabilityBrowserHelper = ReadabilityBrowserHelper(browser: self.browser) {
readabilityBrowserHelper.delegate = self
self.browser.addHelper(readabilityBrowserHelper, name: ReadabilityBrowserHelper.name())
}
// Load the page in the webview. This either fails with a navigation error, or we get a readability
// callback. Or it takes too long, in which case the semaphore times out.
self.browser.loadRequest(NSURLRequest(URL: self.url))
})
if dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, Int64(Double(ReadabilityTaskDefaultTimeout) * Double(NSEC_PER_SEC)))) != 0 {
result = ReadabilityOperationResult.Timeout
}
// Maybe this is where we should store stuff in the cache / run a callback?
if let result = self.result {
switch result {
case .Timeout:
// Don't do anything on timeout
break
case .Success(let readabilityResult):
do {
try ReaderModeCache.sharedInstance.put(url, readabilityResult)
} catch let error as NSError {
print("Failed to store readability results in the cache: \(error.localizedDescription)")
// TODO Fail
}
case .Error(_):
// TODO Not entitely sure what to do on error. Needs UX discussion and followup bug.
break
}
}
}
func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
result = ReadabilityOperationResult.Error(error)
dispatch_semaphore_signal(semaphore)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
result = ReadabilityOperationResult.Error(error)
dispatch_semaphore_signal(semaphore)
}
func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult readabilityResult: ReadabilityResult) {
result = ReadabilityOperationResult.Success(readabilityResult)
dispatch_semaphore_signal(semaphore)
}
}
class ReadabilityService {
class var sharedInstance: ReadabilityService {
return ReadabilityServiceSharedInstance
}
var queue: NSOperationQueue
init() {
queue = NSOperationQueue()
queue.maxConcurrentOperationCount = ReadabilityServiceDefaultConcurrency
}
func process(url: NSURL) {
queue.addOperation(ReadabilityOperation(url: url))
}
} | mpl-2.0 | 0739616b947ca578649f68db78ddd5d7 | 36.081818 | 156 | 0.667729 | 5.518268 | false | false | false | false |
CYXiang/CYXSwiftDemo | CYXSwiftDemo/CYXSwiftDemo/Classes/Other/UIBarButtonItem+Extension.swift | 1 | 2224 | //
// UIBarButtonItem+Extension.swift
// CYXSwiftDemo
//
// Created by appleๅผๅ on 16/5/5.
// Copyright ยฉ 2016ๅนด cyx. All rights reserved.
//
import UIKit
enum ItemButtonType: Int {
case Left = 0
case Right = 1
}
extension UIBarButtonItem {
class func barButton(title: String, titleColor: UIColor, image: UIImage, hightLightImage: UIImage?, target: AnyObject?, action: Selector, type: ItemButtonType) -> UIBarButtonItem {
var btn:UIButton = UIButton()
if type == ItemButtonType.Left {
btn = ItemLeftButton(type: .Custom)
} else {
btn = ItemRightButton(type: .Custom)
}
btn.setTitle(title, forState: .Normal)
btn.setImage(image, forState: .Normal)
btn.setTitleColor(titleColor, forState: .Normal)
btn.setImage(hightLightImage, forState: .Highlighted)
btn.addTarget(target, action: action, forControlEvents: .TouchUpInside)
btn.frame = CGRectMake(0, 0, 60, 44)
btn.titleLabel?.font = UIFont.systemFontOfSize(10)
return UIBarButtonItem(customView: btn)
}
class func barButton(image: UIImage, target: AnyObject?, action: Selector) -> UIBarButtonItem {
let btn = ItemLeftImageButton(type: .Custom)
btn.setImage(image, forState: UIControlState.Normal)
btn.imageView?.contentMode = UIViewContentMode.Center
btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
btn.frame = CGRectMake(0, 0, 44, 44)
return UIBarButtonItem(customView: btn)
}
class func barButton(title: String, titleColor: UIColor, target: AnyObject?, action: Selector) -> UIBarButtonItem {
let btn = UIButton(frame: CGRectMake(0, 0, 60, 44))
btn.setTitle(title, forState: .Normal)
btn.setTitleColor(titleColor, forState: .Normal)
btn.addTarget(target, action: action, forControlEvents: UIControlEvents.TouchUpInside)
btn.titleLabel?.font = UIFont.systemFontOfSize(15)
if title.characters.count == 2 {
btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -25)
}
return UIBarButtonItem(customView: btn)
}
} | apache-2.0 | f46976f9b709242bd51b537ebc0fe022 | 37.912281 | 184 | 0.665313 | 4.390099 | false | false | false | false |
noahemmet/WorldKit | Sheep.playground/Contents.swift | 1 | 1953 | //: Playground - noun: a place where people can play
import XCPlayground
import WorldKit
let grassGrowthTime = 10
let sheepReproduceProbability = 0.5
let initialNumSheep = 50
let initialWorld = World(rows: 10, columns: 10, cellType: Grass.self)
let worldSequence = WorldSequence(initial: initialWorld)
let worldView = WorldView(worldSequence: worldSequence)
XCPlaygroundPage.currentPage.liveView = worldView
class Sheep: Agent {
// var color = NSColor.whiteColor()
var energy: Float = 100
func eatGrass(grass: Grass) -> Bool {
if grass.beEaten() {
energy = 100
return true
}
return false
}
func live() {
energy -= 35
}
override func update() {
live()
}
}
class Grass: Cell {
var growthInterval = Int(arc4random_uniform(70))
var regrowthTime = 50
override func update() {
grow()
}
func grow() {
if growthInterval < regrowthTime {
growthInterval += 1
color = .brownColor()
// color = color.colorWithAlphaComponent(color.alphaComponent - 0.05)
} else {
color = .greenColor()
// color = color.colorWithAlphaComponent(1)
}
}
func beEaten() -> Bool {
if growthInterval >= regrowthTime {
growthInterval = 0
return true
} else {
return false
}
}
}
worldSequence.current.addAgents(10, type: Sheep.self)
//sheep.position = CGPoint(x: 1, y: 1)
//sheep.color = .whiteColor()
worldSequence.updater = { world in
var sheep = worldSequence.current.agentsOfType(Sheep).first
if let sheep = sheep {
sheep.position.y += 0.1
sheep.position.x += 0.1
for nearbyGrass in world.cellsNearAgent(sheep) as! Set<Grass> {
if sheep.energy < 50 {
if sheep.eatGrass(nearbyGrass) {
break
}
}
}
if sheep.energy <= 0 {
print("Die")
sheep.color = .redColor()
worldSequence.current.removeAgent(sheep)
}
XCPlaygroundPage.currentPage.captureValue(sheep.energy, withIdentifier: "energy")
}
// print(world.agentsOfType(Sheep).count)
// print(sheep.position)
}
| apache-2.0 | 3e05a3d1865622285c1a309a89090e89 | 20.7 | 83 | 0.690732 | 3.196399 | false | false | false | false |
3squared/ios-charts | Charts/Classes/Renderers/ChartYAxisRenderer.swift | 1 | 16579 | //
// ChartYAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartYAxisRenderer: ChartAxisRendererBase
{
internal var _yAxis: ChartYAxis!
public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer)
_yAxis = yAxis
}
/// Computes the axis values.
public func computeAxis(var yMin yMin: Double, var yMax: Double)
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if (viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY)
{
let p1 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.getValueByTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
if (!_yAxis.isInverted)
{
yMin = Double(p2.y)
yMax = Double(p1.y)
}
else
{
yMin = Double(p1.y)
yMax = Double(p2.y)
}
}
computeAxisValues(min: yMin, max: yMax)
}
/// Sets up the y-axis labels. Computes the desired number of labels between
/// the two given extremes. Unlike the papareXLabels() method, this method
/// needs to be called upon every refresh of the view.
internal func computeAxisValues(min min: Double, max: Double)
{
let yMin = min
let yMax = max
let labelCount = _yAxis.labelCount
let range = abs(yMax - yMin)
if (labelCount == 0 || range <= 0)
{
_yAxis.entries = [Double]()
return
}
let rawInterval = range / Double(labelCount)
var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval))
if(_yAxis.valueFormatter?.maximumFractionDigits == 0)
{
interval = interval < 1 ? 1 : floor(interval)
}
let intervalMagnitude = pow(10.0, round(log10(interval)))
let intervalSigDigit = (interval / intervalMagnitude)
if (intervalSigDigit > 5)
{
// Use one order of magnitude higher, to avoid intervals like 0.9 or 90
interval = floor(10.0 * intervalMagnitude)
}
// force label count
if _yAxis.isForceLabelsEnabled
{
let step = Double(range) / Double(labelCount - 1)
if _yAxis.entries.count < labelCount
{
// Ensure stops contains at least numStops elements.
_yAxis.entries.removeAll(keepCapacity: true)
}
else
{
_yAxis.entries = [Double]()
_yAxis.entries.reserveCapacity(labelCount)
}
var v = yMin
for (var i = 0; i < labelCount; i++)
{
_yAxis.entries.append(v)
v += step
}
}
else
{
// no forced count
// if the labels should only show min and max
if (_yAxis.isShowOnlyMinMaxEnabled)
{
_yAxis.entries = [yMin, yMax]
}
else
{
let first = ceil(Double(yMin) / interval) * interval
let last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval)
var f: Double
var i: Int
var n = 0
for (f = first; f <= last; f += interval)
{
++n
}
if (_yAxis.entries.count < n)
{
// Ensure stops contains at least numStops elements.
_yAxis.entries = [Double](count: n, repeatedValue: 0.0)
}
else if (_yAxis.entries.count > n)
{
_yAxis.entries.removeRange(n..<_yAxis.entries.count)
}
for (f = first, i = 0; i < n; f += interval, ++i)
{
_yAxis.entries[i] = Double(f)
}
}
}
}
/// draws the y-axis labels to the screen
public override func renderAxisLabels(context context: CGContext?)
{
if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled)
{
return
}
let xoffset = _yAxis.xOffset
let yoffset = _yAxis.labelFont.lineHeight / 2.5 + _yAxis.yOffset
let dependency = _yAxis.axisDependency
let labelPosition = _yAxis.labelPosition
var xPos = CGFloat(0.0)
var textAlign: NSTextAlignment
if (dependency == .Left)
{
if (labelPosition == .OutsideChart)
{
textAlign = .Right
xPos = viewPortHandler.offsetLeft - xoffset
}
else
{
textAlign = .Left
xPos = viewPortHandler.offsetLeft + xoffset
}
}
else
{
if (labelPosition == .OutsideChart)
{
textAlign = .Left
xPos = viewPortHandler.contentRight + xoffset
}
else
{
textAlign = .Right
xPos = viewPortHandler.contentRight - xoffset
}
}
drawYLabels(context: context, fixedPosition: xPos, offset: yoffset - _yAxis.labelFont.lineHeight, textAlign: textAlign)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext?)
{
if (!_yAxis.isEnabled || !_yAxis.drawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _yAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, _yAxis.axisLineWidth)
if (_yAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _yAxis.axisLineDashPhase, _yAxis.axisLineDashLengths, _yAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (_yAxis.axisDependency == .Left)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
else
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
/// draws the y-labels on the specified x-position
internal func drawYLabels(context context: CGContext?, fixedPosition: CGFloat, offset: CGFloat, textAlign: NSTextAlignment)
{
let labelFont = _yAxis.labelFont
let labelTextColor = _yAxis.labelTextColor
let valueToPixelMatrix = transformer.valueToPixelMatrix
var pt = CGPoint()
for (var i = 0; i < _yAxis.entryCount; i++)
{
let text = _yAxis.getFormattedLabel(i)
if (!_yAxis.isDrawTopYLabelEntryEnabled && i >= _yAxis.entryCount - 1)
{
break
}
pt.x = 0
pt.y = CGFloat(_yAxis.entries[i])
pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix)
pt.x = fixedPosition
pt.y += offset
ChartUtils.drawText(context: context, text: text, point: pt, align: textAlign, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
private var _gridLineBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext?)
{
if (!_yAxis.isDrawGridLinesEnabled || !_yAxis.isEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _yAxis.gridColor.CGColor)
CGContextSetLineWidth(context, _yAxis.gridLineWidth)
if (_yAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _yAxis.gridLineDashPhase, _yAxis.gridLineDashLengths, _yAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
// draw the horizontal grid
for (var i = 0, count = _yAxis.entryCount; i < count; i++)
{
position.x = 0.0
position.y = CGFloat(_yAxis.entries[i])
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
_gridLineBuffer[0].x = viewPortHandler.contentLeft
_gridLineBuffer[0].y = position.y
_gridLineBuffer[1].x = viewPortHandler.contentRight
_gridLineBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineBuffer, 2)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext?)
{
var limitLines = _yAxis.limitLines
let padding = CGFloat(5)
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = 0; i < limitLines.count; i++)
{
let l = limitLines[i]
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft - padding
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight + padding
_limitLineSegmentsBuffer[1].y = position.y
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let add = CGFloat(4.0)
let xOffset: CGFloat = add
let yOffset: CGFloat = l.lineWidth + labelLineHeight
if (l.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else if (l.labelPosition == .LeftBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y + yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
let paragraphStyle = NSMutableParagraphStyle();
paragraphStyle.alignment = .Center;
let labelSize = (label as NSString).sizeWithAttributes([ NSFontAttributeName : l.valueFont ])
let labelInsetTopBottomSize = (l.labelInset.top + l.labelInset.bottom)
let labelInsetLeftRightSize = (l.labelInset.left + l.labelInset.right)
let qx = viewPortHandler.contentLeft - labelInsetLeftRightSize - labelSize.width - padding
let qy = position.y - yOffset + labelSize.height / 2 - (labelInsetTopBottomSize / 2)
let rect = CGRectMake(qx, qy, labelSize.width + labelInsetLeftRightSize, labelSize.height + labelInsetTopBottomSize)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
let path = UIBezierPath(roundedRect: rect, cornerRadius: (CGRectGetHeight(rect) / 2))
path.fill()
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: qx + (labelInsetLeftRightSize / 2),
y: qy + (labelInsetTopBottomSize / 2)),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor, NSParagraphStyleAttributeName : paragraphStyle]);
}
}
if let image = l.image {
let x = l.imagePosition == .End ? viewPortHandler.contentRight + padding : viewPortHandler.contentLeft - image.size.width - padding
let y = position.y - image.size.height / 2
ChartUtils.drawImage(context: context,
image: image,
point: CGPoint(
x: x,
y: y))
}
}
CGContextRestoreGState(context)
}
} | apache-2.0 | 7bd1da1078a98f84b55836bf1ffbf029 | 35.600442 | 184 | 0.529706 | 5.718869 | false | false | false | false |
AKIRA-MIYAKE/EasyBeacon | EasyBeacon/BeaconMonitor.swift | 1 | 6226 | //
// BeaconMonitor.swift
// EasyBeacon
//
// Created by MiyakeAkira on 2015/05/30.
// Copyright (c) 2015ๅนด Miyake Akira. All rights reserved.
//
import Foundation
import CoreLocation
import SwiftyEvents
class BeaconMonitor: NSObject, CLLocationManagerDelegate {
// MARK: - let
let available: Available
let enteringBeaconRegion: EnteringBeaconRegion
let rangedBeacons: RangedBeacons
let proximityBeacon: ProximityBeacon
private let locationManager: CLLocationManager
private let notificationCenter: NSNotificationCenter
private let beaconRegions: Set<BeaconRegion>
// MARK: - Variables
private var isRunning: Bool
// MARK: - Initialzie
init(beaconRegions: Set<BeaconRegion>) {
self.beaconRegions = beaconRegions
available = Available(value: false)
enteringBeaconRegion = EnteringBeaconRegion()
rangedBeacons = RangedBeacons()
proximityBeacon = ProximityBeacon()
locationManager = CLLocationManager()
notificationCenter = NSNotificationCenter.defaultCenter()
isRunning = false
super.init()
initialize()
}
private func initialize() {
// Setup location manager
locationManager.delegate = self
switch CLLocationManager.authorizationStatus() {
case .NotDetermined:
locationManager.requestAlwaysAuthorization()
case .AuthorizedAlways:
available.value = true
default:
break
}
clean()
// Setup notification center
notificationCenter.addObserver(
self,
selector: "handleDidBecomeActive:",
name: UIApplicationDidBecomeActiveNotification,
object: nil)
notificationCenter.addObserver(
self,
selector: "handleDidEnterBackground:",
name: UIApplicationDidEnterBackgroundNotification,
object: nil)
// Starting monitor
available.on(.Updated) { value in
if value {
self.startMonitoring()
}
}
if available.value {
startMonitoring()
}
}
deinit {
notificationCenter.removeObserver(self)
}
// MARK: - Private method
private func startMonitoring() {
if available.value && !isRunning {
for region in beaconRegions {
locationManager.startMonitoringForRegion(region.region)
}
isRunning = true
}
}
private func stopMonitoring() {
if isRunning {
clean()
isRunning = false
}
}
private func clean() {
if let ranged = locationManager.rangedRegions as? Set<CLBeaconRegion> {
for region in ranged {
locationManager.stopRangingBeaconsInRegion(region)
}
}
if let monitored = locationManager.monitoredRegions as? Set<CLBeaconRegion> {
for region in monitored {
locationManager.stopMonitoringForRegion(region)
}
}
}
// MARK: - Selector
func handleDidBecomeActive(notification: NSNotification) {
for region in beaconRegions {
locationManager.requestStateForRegion(region.region)
}
}
func handleDidEnterBackground(notification: NSNotification) {
for region in beaconRegions {
locationManager.stopRangingBeaconsInRegion(region.region)
}
}
// MARK: - Location manager delegate
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .AuthorizedAlways:
available.value = true
default:
available.value = false
}
}
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
locationManager.requestStateForRegion(region)
}
func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) {
if let region = region as? CLBeaconRegion {
switch state {
case .Inside:
enteringBeaconRegion.value = BeaconRegion(region: region)
locationManager.startRangingBeaconsInRegion(region)
default:
break
}
}
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
if let region = region as? CLBeaconRegion {
enteringBeaconRegion.value = BeaconRegion(region: region)
locationManager.startRangingBeaconsInRegion(region)
}
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
if let region = region as? CLBeaconRegion {
locationManager.stopRangingBeaconsInRegion(region)
enteringBeaconRegion.value = nil
}
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
if let beacons = beacons as? [CLBeacon] {
rangedBeacons.value = beacons.map { Beacon(beacon: $0) }
var proximity: CLBeacon? = nil
for beacon in beacons {
if beacon.proximity != .Unknown {
if let current = proximity {
if current.rssi < beacon.rssi {
proximity = beacon
}
} else {
proximity = beacon
}
}
}
if let proximity = proximity {
proximityBeacon.value = Beacon(beacon: proximity)
} else {
proximityBeacon.value = nil
}
}
}
} | mit | 1cdf3c998cad581114f318111b86953a | 27.424658 | 128 | 0.571497 | 6.463136 | false | false | false | false |
mdab121/swift-fcm | Sources/FCM/HTTPParser.swift | 1 | 1466 | // (c) 2017 Kajetan Michal Dabrowski
// This code is licensed under MIT license (see LICENSE for details)
import Foundation
internal enum CavemanResponseParserError: Error {
case networkError(message: String)
case invalidResponse
case invalidHeader
case invalidStatusCode
case invalidPayload
}
/// Ok so I know this is a caveman solution. It should be done by URLSession and URLResponse
/// However those are still not implemented on linux, so we're sticking with this parsing, until they're done
internal class CavemanHTTPResponseParser {
func parse(response: Data) throws -> (Data, Int) {
let responseParts = response.split { return CharacterSet.newlines.contains(UnicodeScalar($0)) }
guard responseParts.count >= 2 else {
let message = String(data: response, encoding: .utf8) ?? ""
throw CavemanResponseParserError.networkError(message: message)
}
guard let headerData = responseParts.first else {
throw CavemanResponseParserError.invalidHeader
}
let headerParts = headerData.split { return CharacterSet.whitespaces.contains(UnicodeScalar($0)) }
guard headerParts.count >= 3,
let responseStatusString = String(data: Data(headerParts[1]), encoding: .utf8),
let responseStatus = Int(responseStatusString) else {
throw CavemanResponseParserError.invalidHeader
}
guard let payloadData = responseParts.last else {
throw CavemanResponseParserError.invalidPayload
}
return (Data(payloadData), responseStatus)
}
}
| mit | a035af7cf9539bc17fa2ccd9e2e03546 | 34.756098 | 109 | 0.769441 | 4.236994 | false | false | false | false |
mattdaw/SwiftBoard | SwiftBoard/CollectionViews/ListViewModelDataSource.swift | 1 | 1662 | //
// ListViewModelDataSource.swift
// SwiftBoard
//
// Created by Matt Daw on 2014-10-21.
// Copyright (c) 2014 Matt Daw. All rights reserved.
//
import UIKit
class ListViewModelDataSource : NSObject, UICollectionViewDelegate, UICollectionViewDataSource {
var listViewModel: ListViewModel
init(_ initViewModel: ListViewModel) {
listViewModel = initViewModel
super.init()
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listViewModel.numberOfItems()
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell:UICollectionViewCell
var itemViewModel = listViewModel.itemAtIndex(indexPath.item)
switch itemViewModel {
case let appViewModel as AppViewModel:
let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("App", forIndexPath: indexPath) as AppCollectionViewCell
myCell.appViewModel = appViewModel
cell = myCell
case let folderViewModel as FolderViewModel:
let myCell = collectionView.dequeueReusableCellWithReuseIdentifier("Folder", forIndexPath: indexPath) as FolderCollectionViewCell
myCell.folderViewModel = folderViewModel
cell = myCell
default:
cell = UICollectionViewCell()
}
return cell
}
} | mit | 1b08332fbc3ed2e55e849fc04d4c1a4c | 31.607843 | 141 | 0.670277 | 6.343511 | false | false | false | false |
adelinofaria/Buildasaur | BuildaUtils/XcodeProjectParser.swift | 2 | 7622 | //
// XcodeProjectParser.swift
// Buildasaur
//
// Created by Honza Dvorsky on 24/01/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XcodeServerSDK
public class XcodeProjectParser {
private class func firstItemMatchingTestRecursive(url: NSURL, test: (itemUrl: NSURL) -> Bool) -> NSURL? {
let fm = NSFileManager.defaultManager()
if let path = url.path {
var isDir: ObjCBool = false
let exists = fm.fileExistsAtPath(path, isDirectory: &isDir)
if !exists {
return nil
}
if !isDir {
//not dir, test
return test(itemUrl: url) ? url : nil
}
var error: NSError?
if let contents = fm.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.allZeros, error: &error) as? [NSURL] {
for i in contents {
if let foundUrl = self.firstItemMatchingTestRecursive(i, test: test) {
return foundUrl
}
}
}
}
return nil
}
private class func firstItemMatchingTest(url: NSURL, test: (itemUrl: NSURL) -> Bool) -> NSURL? {
return self.allItemsMatchingTest(url, test: test).first
}
private class func allItemsMatchingTest(url: NSURL, test: (itemUrl: NSURL) -> Bool) -> [NSURL] {
let fm = NSFileManager.defaultManager()
var error: NSError?
if let contents = fm.contentsOfDirectoryAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.allZeros, error: &error) as? [NSURL] {
let filtered = contents.filter(test)
return filtered
}
return [NSURL]()
}
private class func findCheckoutUrl(workspaceUrl: NSURL) -> NSURL? {
return self.firstItemMatchingTestRecursive(workspaceUrl, test: { (itemUrl: NSURL) -> Bool in
return itemUrl.pathExtension == "xccheckout"
})
}
private class func parseCheckoutFile(url: NSURL) -> NSDictionary? {
return NSDictionary(contentsOfURL: url)
}
public class func parseRepoMetadataFromProjectOrWorkspaceURL(url: NSURL) -> (NSDictionary?, NSError?) {
let workspaceUrl = url
if let checkoutUrl = self.findCheckoutUrl(workspaceUrl) {
//we have the checkout url
if let parsed = self.parseCheckoutFile(checkoutUrl) {
return (parsed, nil)
} else {
let error = Error.withInfo("Cannot parse the checkout file at path \(checkoutUrl)")
return (nil, error)
}
}
//no checkout, what to do?
let error = Error.withInfo("Cannot find the Checkout file, please make sure to open this project in Xcode at least once (it will generate the required Checkout file). Then try again.")
return (nil, error)
}
public class func sharedSchemeUrlsFromProjectOrWorkspaceUrl(url: NSURL) -> [NSURL] {
var projectUrls: [NSURL]
if self.isWorkspaceUrl(url) {
//first parse project urls from workspace contents
projectUrls = self.projectUrlsFromWorkspace(url) ?? [NSURL]()
//also add the workspace's url, it might own some schemes as well
projectUrls.append(url)
} else {
//this already is a project url, take just that
projectUrls = [url]
}
//we have the project urls, now let's parse schemes from each of them
let schemeUrls = projectUrls.map {
self.sharedSchemeUrlsFromProjectUrl($0)
}.reduce([NSURL](), combine: { (arr, newUrls) -> [NSURL] in
arr + newUrls
})
return schemeUrls
}
private class func sharedSchemeUrlsFromProjectUrl(url: NSURL) -> [NSURL] {
//the structure is
//in a project file, if there are any shared schemes, they will be in
//xcshareddata/xcschemes/*
if let sharedDataFolder = self.firstItemMatchingTest(url,
test: { (itemUrl: NSURL) -> Bool in
return itemUrl.lastPathComponent == "xcshareddata"
}) {
if let schemesFolder = self.firstItemMatchingTest(sharedDataFolder,
test: { (itemUrl: NSURL) -> Bool in
return itemUrl.lastPathComponent == "xcschemes"
}) {
//we have the right folder, yay! just filter all files ending with xcscheme
let schemes = self.allItemsMatchingTest(schemesFolder, test: { (itemUrl: NSURL) -> Bool in
let ext = itemUrl.pathExtension ?? ""
return ext == "xcscheme"
})
return schemes
}
}
return [NSURL]()
}
private class func isProjectUrl(url: NSURL) -> Bool {
return url.absoluteString!.hasSuffix(".xcodeproj")
}
private class func isWorkspaceUrl(url: NSURL) -> Bool {
return url.absoluteString!.hasSuffix(".xcworkspace")
}
private class func projectUrlsFromWorkspace(url: NSURL) -> [NSURL]? {
assert(self.isWorkspaceUrl(url), "Url \(url) is not a workspace url")
//parse the workspace contents url and get the urls of the contained projects
let contentsUrl = url.URLByAppendingPathComponent("contents.xcworkspacedata")
var readingError: NSError?
if let contentsData = NSFileManager.defaultManager().contentsAtPath(contentsUrl.path!) {
if let stringContents = NSString(data: contentsData, encoding: NSUTF8StringEncoding) {
//parse by lines
let components = stringContents.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as! [String]
let projectRelativePaths = components.map {
(line: String) -> String? in
let range1 = line.rangeOfString("group:")
let range2 = line.rangeOfString("\">", options: NSStringCompareOptions.BackwardsSearch)
if let range1 = range1, let range2 = range2 {
let start = range1.endIndex
let end = range2.startIndex
return line.substringWithRange(Range<String.Index>(start: start, end: end))
}
return nil
}.filter {
return $0 != nil
}.map {
return $0!
}
//we now have relative paths, let's make them absolute
let absolutePaths = projectRelativePaths.map {
return url.URLByAppendingPathComponent("..").URLByAppendingPathComponent($0)
}
//ok, we're done, return
return absolutePaths
}
}
Log.error("Couldn't load contents of workspace \(url)")
return nil
}
private class func parseSharedSchemesFromProjectURL(url: NSURL) -> (schemeUrls: [NSURL]?, error: NSError?) {
return (schemeUrls: [NSURL](), error: nil)
}
}
| mit | 96907c1afde9cbf1118c76ed0bb2ec7d | 36.180488 | 192 | 0.556809 | 5.304106 | false | true | false | false |
boycechang/BCColor | BCColor/PickColorsFromImageViewController.swift | 1 | 1439 | //
// PickColorsFromImageViewController.swift
// BCColorDemo
//
// Created by Boyce on 3/24/16.
// Copyright ยฉ 2016 Boyce. All rights reserved.
//
import UIKit
class PickColorsFromImageViewController: UIViewController {
@IBOutlet fileprivate weak var imageView: UIImageView!
@IBOutlet fileprivate weak var titleLabel: UILabel!
@IBOutlet fileprivate weak var subtitleLabel: UILabel!
@IBOutlet fileprivate weak var detailLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let colors = imageView.image?.getColors() {
self.view.backgroundColor = colors.backgroundColor
titleLabel.textColor = colors.primaryColor
subtitleLabel.textColor = colors.secondaryColor
detailLabel.textColor = colors.minorColor
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 29f0d188581c1ed281a9f248ca475356 | 30.955556 | 106 | 0.684284 | 5.267399 | false | false | false | false |
practicalswift/swift | test/Driver/Dependencies/bindings-build-record.swift | 6 | 4134 | // REQUIRES: shell
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/bindings-build-record/* %t
// RUN: %{python} %S/Inputs/touch.py 443865900 %t/*
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=MUST-EXEC
// MUST-EXEC-NOT: warning
// MUST-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// MUST-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// MUST-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": [443865900, 0], "./yet-another.swift": [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=NO-EXEC
// NO-EXEC: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// NO-EXEC: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// NO-EXEC: inputs: ["./yet-another.swift"], output: {{[{].*[}]}}, condition: check-dependencies
// RUN: echo '{version: "'$(%swiftc_driver_plain -version | head -n1)'", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}, build_time: [443865901, 0]}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=BUILD-RECORD
// BUILD-RECORD: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: check-dependencies{{$}}
// BUILD-RECORD: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}}
// BUILD-RECORD: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift ./added.swift -incremental -output-file-map %t/output.json 2>&1 > %t/added.txt
// RUN: %FileCheck %s -check-prefix=BUILD-RECORD < %t/added.txt
// RUN: %FileCheck %s -check-prefix=FILE-ADDED < %t/added.txt
// FILE-ADDED: inputs: ["./added.swift"], output: {{[{].*[}]}}, condition: newly-added{{$}}
// RUN: %{python} %S/Inputs/touch.py 443865960 %t/main.swift
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=BUILD-RECORD-PLUS-CHANGE
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./main.swift"], output: {{[{].*[}]}}, condition: run-without-cascading
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./other.swift"], output: {{[{].*[}]}}, condition: run-without-cascading{{$}}
// BUILD-RECORD-PLUS-CHANGE: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
// RUN: %{python} %S/Inputs/touch.py 443865900 %t/*
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=FILE-REMOVED
// FILE-REMOVED: inputs: ["./main.swift"], output: {{[{].*[}]$}}
// FILE-REMOVED: inputs: ["./other.swift"], output: {{[{].*[}]$}}
// FILE-REMOVED-NOT: yet-another.swift
// RUN: echo '{version: "bogus", inputs: {"./main.swift": [443865900, 0], "./other.swift": !private [443865900, 0], "./yet-another.swift": !dirty [443865900, 0]}}' > %t/main~buildrecord.swiftdeps
// RUN: cd %t && %swiftc_driver -driver-print-bindings ./main.swift ./other.swift ./yet-another.swift -incremental -output-file-map %t/output.json 2>&1 | %FileCheck %s -check-prefix=INVALID-RECORD
// INVALID-RECORD-NOT: warning
// INVALID-RECORD: inputs: ["./main.swift"], output: {{[{].*[}]$}}
// INVALID-RECORD: inputs: ["./other.swift"], output: {{[{].*[}]$}}
// INVALID-RECORD: inputs: ["./yet-another.swift"], output: {{[{].*[}]$}}
| apache-2.0 | c7a94daccf0950c15afc3c00d8691af3 | 77 | 263 | 0.641509 | 3.422185 | false | false | false | false |
practicalswift/swift | test/Generics/sr7275.swift | 34 | 345 | // RUN: %target-typecheck-verify-swift -swift-version 4
extension Sequence where Element: AnyObject {
public func f1(to object: AnyObject) -> Bool {
return contains { $0 === object }
}
}
extension Sequence where Iterator.Element: AnyObject {
public func f2(to object: AnyObject) -> Bool {
return contains { $0 === object }
}
}
| apache-2.0 | 898e2d0b45a69c6ead769f1f8c73970b | 25.538462 | 55 | 0.678261 | 3.791209 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Utilities/DOTJobGraphSerializer.swift | 1 | 2549 | //===--------------- DOTJobGraphSerializer.swift - Swift GraphViz ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
/// Serializes the job graph to a .dot file
@_spi(Testing) public struct DOTJobGraphSerializer {
var kindCounter = [Job.Kind: Int]()
var hasEmittedStyling = Set<String>()
let jobs: [Job]
/// Creates a serializer that will serialize the given set of top level jobs.
public init(jobs: [Job]) {
self.jobs = jobs
}
/// Gets the name of the tool that's being invoked from a job
func findToolName(_ path: VirtualPath) -> String {
switch path {
case .absolute(let abs): return abs.components.last!
case .relative(let rel): return rel.components.last!
default: fatalError("no tool for kind \(path)")
}
}
/// Gets a unique label for a job name
mutating func label(for job: Job) -> String {
var label = "\(job.kind)"
if let count = kindCounter[job.kind] {
label += " \(count)"
}
label += " (\(findToolName(job.tool)))"
kindCounter[job.kind, default: 0] += 1
return label
}
/// Quote the name and escape the quotes
func quoteName(_ name: String) -> String {
return "\"" + name.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
public mutating func writeDOT<Stream: TextOutputStream>(to stream: inout Stream) {
stream.write("digraph Jobs {\n")
for job in jobs {
let jobName = quoteName(label(for: job))
if !hasEmittedStyling.contains(jobName) {
stream.write(" \(jobName) [style=bold];\n")
}
for input in job.inputs {
let inputName = quoteName(input.file.name)
if hasEmittedStyling.insert(inputName).inserted {
stream.write(" \(inputName) [fontsize=12];\n")
}
stream.write(" \(inputName) -> \(jobName) [color=blue];\n")
}
for output in job.outputs {
let outputName = quoteName(output.file.name)
if hasEmittedStyling.insert(outputName).inserted {
stream.write(" \(outputName) [fontsize=12];\n")
}
stream.write(" \(jobName) -> \(outputName) [color=green];\n")
}
}
stream.write("}\n")
}
}
| apache-2.0 | 556e39ce8014bf9d43017568c7a96826 | 33.917808 | 84 | 0.607297 | 4.020505 | false | false | false | false |
jamming/FrameworkBenchmarks | frameworks/Swift/vapor/vapor-fluent/Sources/main.swift | 8 | 1370 | import Fluent
import FluentPostgresDriver
import Vapor
var env = try Environment.detect()
try LoggingSystem.bootstrap(from: &env)
let app = Application(env)
defer { app.shutdown() }
app.http.server.configuration.serverName = "Vapor"
app.logger.notice("๐ง VAPOR")
app.logger.notice("System.coreCount: \(System.coreCount)")
app.logger.notice("System.maxConnectionsPerEventLoop: \(System.maxConnectionsPerEventLoop)")
app.databases.use(.postgres(
hostname: "tfb-database",
username: "benchmarkdbuser",
password: "benchmarkdbpass",
database: "hello_world",
maxConnectionsPerEventLoop: System.maxConnectionsPerEventLoop
), as: .psql)
app.get("db") { req async throws -> World in
guard let world = try await World.find(.random(in: 1...10_000), on: req.db) else {
throw Abort(.notFound)
}
return world
}
app.get("queries") { req async throws -> [World] in
let queries = (req.query["queries"] ?? 1).bounded(to: 1...500)
var worlds: [World] = []
for _ in queries {
guard let world = try await World.find(.random(in: 1...10_000), on: req.db) else {
throw Abort(.notFound)
}
worlds.append(world)
}
return worlds
}
extension Int: Sequence {
public func makeIterator() -> CountableRange<Int>.Iterator {
return (0..<self).makeIterator()
}
}
try app.run()
| bsd-3-clause | a5a4acdfd29cd56cd3ee9a76a9f5bfac | 23.410714 | 92 | 0.666423 | 3.625995 | false | false | false | false |
fthomasmorel/insapp-iOS | Insapp/Notification+CoreDataClass.swift | 1 | 3658 | //
// Notification+CoreDataClass.swift
// Insapp
//
// Created by Florent THOMAS-MOREL on 10/3/16.
// Copyright ยฉ 2016 Florent THOMAS-MOREL. All rights reserved.
//
import Foundation
import CoreData
public class Notification: NSManagedObject {
static let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
static let entityDescription = NSEntityDescription.entity(forEntityName: "Notification", in:managedContext)
@objc
private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
super.init(entity: entity, insertInto: context)
}
public func encode(with aCoder: NSCoder) { }
required public init?(coder aDecoder: NSCoder) {
super.init(entity: Notification.entityDescription!, insertInto: Notification.managedContext)
}
init(id: String, sender: String, receiver: String, content: String, type: String, message: String, seen: Bool, date: NSDate){
super.init(entity: Notification.entityDescription!, insertInto: Notification.managedContext)
self.id = id
self.sender = sender
self.receiver = receiver
self.content = content
self.type = type
self.message = message
self.seen = seen
self.date = date
}
static func parseJson(_ json:Dictionary<String, AnyObject>) -> Optional<Notification>{
guard let id = json[kNotificationId] as? String else { return .none }
guard let sender = json[kNotificationSender] as? String else { return .none }
guard let receiver = json[kNotificationReceiver] as? String else { return .none }
guard let content = json[kNotificationContent] as? String else { return .none }
guard let type = json[kNotificationType] as? String else { return .none }
guard let message = json[kNotificationMessage] as? String else { return .none }
guard let seen = json[kNotificationSeen] as? Bool else { return .none }
guard let dateStr = json[kNotificationDate] as? String else { return .none }
guard let date = dateStr.dateFromISO8602 else { return .none }
guard type == kNotificationTypeEvent ||
type == kNotificationTypePost ||
type == kNotificationTypeTag ||
type == kNotificationTypeEventTag else { return .none }
let notification = Notification(id: id, sender: sender, receiver: receiver, content: content, type: type, message: message, seen: seen, date: date as NSDate)
if type == kNotificationTypeTag || type == kNotificationTypeEventTag {
guard let commentJson = json[kNotificationComment] as? Dictionary<String, AnyObject> else { return .none }
guard let comment = Comment.parseJson(commentJson) else { return .none }
notification.comment = comment
}
return notification
}
static func parseArray(_ array: [Dictionary<String, AnyObject>]) -> [Notification] {
let notificationsJson = array.filter({ (json) -> Bool in
if let tag = Notification.parseJson(json) {
Notification.managedContext.delete(tag)
return true
}else{
return false
}
})
let notifications = notificationsJson.map { (json) -> Notification in
return Notification.parseJson(json)!
}
return notifications
}
}
| mit | 89febbe6eb5a643b0dd54ba72d80da14 | 44.148148 | 165 | 0.627017 | 5.023352 | false | false | false | false |
JesusAntonioGil/MemeMe | MemeMe/Model/CameraManager.swift | 1 | 1835 | //
// CameraManager.swift
// MemeMe
//
// Created by Jesus Antonio Gil on 13/2/16.
// Copyright ยฉ 2016 Jesus Antonio Gil. All rights reserved.
//
import UIKit
@objc protocol CameraManagerDelegate {
optional func cameraDidPhotoWithImage(image: UIImage, editingInfo: [String : AnyObject]?)
}
class CameraManager: NSObject {
//Injected
var viewController: UIViewController!
var delegate: CameraManagerDelegate!
private var imagePickerController = UIImagePickerController()
//MARK: PUBLIC
func presentCamera(sourceType: UIImagePickerControllerSourceType) {
imagePickerController.delegate = self
imagePickerController.allowsEditing = false
imagePickerController.sourceType = sourceType
if(sourceType == .Camera) {
imagePickerController.cameraCaptureMode = .Photo
}
viewController.presentViewController(imagePickerController, animated: true, completion: nil)
}
class func checkCameraAvailable() -> Bool {
return UIImagePickerController.isSourceTypeAvailable(.Camera)
}
}
//MARK: UIImagePickerController & UINavigationController Delegate
extension CameraManager: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
if(delegate != nil) {
delegate.cameraDidPhotoWithImage!(image, editingInfo: editingInfo)
}
viewController.dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
if(delegate != nil) {
viewController.dismissViewControllerAnimated(true, completion: nil)
}
}
}
| mit | f2182ca3ae4212fcf040741770e39237 | 29.065574 | 139 | 0.711014 | 5.973941 | false | false | false | false |
the-grid/Portal | Portal/Models/Extensions/Color.swift | 1 | 2870 | import Argo
import Curry
import Ogra
#if os(iOS)
import UIKit
public typealias Color = UIColor
#elseif os(OSX)
import AppKit
public typealias Color = NSColor
#endif
extension Color {
convenience init?(hex: String) {
let hexString = hex.substringFromIndex(hex.startIndex.advancedBy(1))
var hexInt: UInt32 = 0
NSScanner(string: hexString).scanHexInt(&hexInt)
let divisor: CGFloat = 255
let red = CGFloat((hexInt & 0xff0000) >> 16) / divisor
let green = CGFloat((hexInt & 0x00ff00) >> 8) / divisor
let blue = CGFloat(hexInt & 0x0000ff) / divisor
let alpha: CGFloat = 1
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
func hexString() -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return String(format: "#%02x%02x%02x", Int(red * 255), Int(green * 255), Int(blue * 255))
}
}
// MARK: - Decodable
extension Color: Decodable {
public typealias DecodedType = Color
public static func decode(json: JSON) -> Decoded<Color> {
switch json {
case let .String(s):
return Color(hex: s).map(pure) ?? .customError("Unable to decode Hex value: \(s)")
case .Array:
let components: Decoded<[CGFloat]> = [Float]
.decode(json)
.map {
$0.map { component in
CGFloat(component) / CGFloat(255)
}
}
switch components {
case let .Success(rgb):
guard rgb.count >= 3 else { return .customError("Insufficient number of RGB color components.") }
let red = rgb[0], green = rgb[1], blue = rgb[2]
let color = Color(red: red, green: green, blue: blue, alpha: 1)
return pure(color) ?? .customError("Unable to decode RGB value: \(rgb)")
case let .Failure(error):
return .Failure(error)
}
default:
return .typeMismatch("Color", actual: json)
}
}
}
// MARK: - Encoding
extension Color {
public func toHex() -> JSON {
return hexString().encode()
}
public func toRgb() -> JSON {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
getRed(&red, green: &green, blue: &blue, alpha: &alpha)
return [ red, green, blue ].map({ Float($0) * 255 }).encode()
}
}
public func toHex(color: Color) -> JSON {
return color.toHex()
}
public func toRgb(color: Color) -> JSON {
return color.toRgb()
}
| mit | babbc6e660657232d1deb7455a980aba | 27.415842 | 113 | 0.537631 | 4.15942 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Classes/Dynamic/YSDynamicViewController.swift | 1 | 2337 | //
// YSDynamicViewController.swift
// ysbilibili
//
// Created by MOLBASE on 2017/7/31.
// Copyright ยฉ 2017ๅนด YangShen. All rights reserved.
//
import UIKit
class YSDynamicViewController: YSBaseViewController {
fileprivate var searchButton: UIButton = {
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "home_search_white_22x22_"), for: .normal)
searchButton.backgroundColor = UIColor.clear
return searchButton
}()
fileprivate lazy var tableView: UITableView = { [unowned self] in
var tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView.tableFooterView = UIView()
tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0)
tableView.backgroundColor = kHomeBackColor
return tableView
}()
fileprivate lazy var noLoginImageview: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "login_forbidden")
return imageView
}()
fileprivate lazy var loginButton: UIButton = {
let loginButton = UIButton()
loginButton.setTitleColor(UIColor.white, for: .normal)
loginButton.backgroundColor = kNavBarColor
loginButton.setTitle("็ปๅฝ", for: .normal)
loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 15)
loginButton.layer.cornerRadius = kCellCornerRadius
return loginButton
}()
override func viewDidLoad() {
super.viewDidLoad()
naviBar.titleLabel.text = "ๅจๆ"
naviBar.rightItem = searchButton
view.addSubview(tableView)
tableView.addSubview(noLoginImageview)
tableView.addSubview(loginButton)
tableView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(view)
make.top.equalTo(view).offset(64)
}
noLoginImageview.snp.makeConstraints { (make) in
make.centerX.equalTo(tableView)
make.centerY.equalTo(tableView).offset(-150)
}
loginButton.snp.makeConstraints { (make) in
make.centerX.equalTo(tableView)
make.top.equalTo(noLoginImageview.snp.bottom).offset(10)
make.size.equalTo(CGSize(width: 80, height: 24))
}
}
}
| mit | 3dcb933d89a0ab774c5a2d0b2c10b5ce | 30.863014 | 87 | 0.636715 | 4.756646 | false | false | false | false |
jovito-royeca/Decktracker | ios/Pods/Eureka/Source/Rows/Common/DecimalFormatter.swift | 5 | 1404 | //
// DecimalFormatter.swift
// Eureka
//
// Created by Martin Barreto on 2/24/16.
// Copyright ยฉ 2016 Xmartlabs. All rights reserved.
//
import Foundation
public class DecimalFormatter : NSNumberFormatter, FormatterProtocol {
public override init() {
super.init()
locale = .currentLocale()
numberStyle = .DecimalStyle
minimumFractionDigits = 2
maximumFractionDigits = 2
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
guard obj != nil else { return false }
let str = string.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("")
obj.memory = NSNumber(double: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits))))
return true
}
public func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition {
return textInput.positionFromPosition(position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position
}
} | apache-2.0 | b6ca9063a2ca6dd15f17f1989ae31575 | 39.114286 | 197 | 0.702067 | 5.196296 | false | false | false | false |
yuzushioh/GithubShokunin | Sources/App/PullRequest.swift | 1 | 799 | //
// PullRequest.swift
// GithubShokunin
//
// Created by yuzushioh on 2016/12/20.
//
//
import Vapor
struct PullRequest {
let author: GithubUser
let title: String
let url: String
let number: Int
let state: String
let assignee: GithubUser?
let labels: [String]
}
extension PullRequest: NodeInitializable {
init(node: Node, in context: Context) throws {
author = try node.extract("user")
title = try node.extract("title")
url = try node.extract("html_url")
number = try node.extract("number")
state = try node.extract("state")
assignee = try node.extract("assign")
let labelsNode = node["labels"]?.nodeArray
labels = try labelsNode?.flatMap { try $0.extract("name") ?? "" } ?? []
}
}
| mit | 88e5ae8a174c30d2193243109c98f7d3 | 23.212121 | 79 | 0.609512 | 3.878641 | false | false | false | false |
alberttra/A-Framework | Pod/Classes/NetworkServices.swift | 1 | 5431 | //
// Network.swift
// Pods
//
// Created by Albert Tra on 27/01/16.
//
//
import Foundation
import Alamofire /// How to setup dependencies: 3CC09F7B-ABAC-42AE-B84E-0831D1F0371B
import SwiftyJSON /// How to setup dependencies: 3CC09F7B-ABAC-42AE-B84E-0831D1F0371B
import Haneke
public class NetworkServices {
// static let sharedInstance = Network() /// Single ton BB99C1B5-0355-4BF7-A6AE-C47FCDE8F0DC
var credential: NSURLCredential!
let cache = Shared.dataCache
let logger = Logger()
var rawJSON: SwiftyJSON.JSON?
var id: String = ""
/**
Custom configuration
*/
let networkManager: Alamofire.Manager = {
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"api.werdenktwas.de": .DisableEvaluation /// Disable Server Trust Policies for this domain
// "https://dacityapp.werdenktwas.de": ServerTrustPolicy.DisableEvaluation
// "https://api.werdenktwas.de": .PinCertificates (
]
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
return Alamofire.Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)
}()
// func postRequest(url: String, parameters: [String: String], completion: (rawJSON: JSON) -> Void) {
// networkManager.request(.POST, url, parameters: parameters)
// .responseJSON { data in
// if data.result.error == nil {
// completion(rawJSON: JSON(data.result.value!))
// } else {
// print(data.result.error)
// }
// }
// }
init() {
self.credential = NSURLCredential(user: "", password: "", persistence: .ForSession)
// let url = "http://api.werdenktwas.de/bmsapi/find_duplicates?lang=de&categoryid=67&lat=49.863044&appid=1&domainid=32&long=8.632512"
// let url = "https://dacityapp.werdenktwas.de/cityapp"
// let url = "https://api.werdenktwas.de/bmsapi/get_message_detail?id=" + "12116"
// self.getRawJSON(url) { (json) -> Void in
// print(json)
// }
}
/**
Return JSON Object
:Author: Albert Tra
*/
public func getRawJSON(url: String, completion: (json: SwiftyJSON.JSON) -> Void) {
networkManager.request(Alamofire.Method.GET, url) /// Using this networkManager for special configurations, which are set above in let networkManager: Alamofire.Manager = { ... }
// Alamofire.request(Alamofire.Method.GET, url) /// Using this for default configuration
.authenticate(usingCredential: credential)
.responseJSON { response in
print("Query URL: ", url)
// print("=== Request: ", response.request) // original URL request
// print("=== Response: ", response.response) // URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
if let _ = response.result.value {
self.rawJSON = SwiftyJSON.JSON(response.result.value!)
completion(json: self.rawJSON!)
} else {
print("Some thing wrong")
print(response.debugDescription)
}
}
}
public func getRawJSON(url: String, parameters: [String: String], completion: (json: SwiftyJSON.JSON) -> Void) {
networkManager.request(Alamofire.Method.GET, url, parameters: parameters) /// Using this networkManager for special configurations, which are set above in let networkManager: Alamofire.Manager = { ... }
// Alamofire.request(Alamofire.Method.GET, url) /// Using this for default configuration
.authenticate(usingCredential: credential)
.responseJSON { response in
// var message = "Query URL: " + url + "\n"
// message = message + Parameters
self.logger.log(self, uuid: "5033D3A1-F834-4D38-A9F3-9E1BF2FB7454", message: nil)
print("Query URL: ", url)
print("Parameters: ", parameters)
// print("=== Request: ", response.request) // original URL request
// print("=== Response: ", response.response) // URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
if let _ = response.result.value {
self.rawJSON = SwiftyJSON.JSON(response.result.value!)
completion(json: self.rawJSON!)
} else {
print("\n80DF8EF6-90EB-440E-B7DC-7FBE4CB11C3A \t", response.debugDescription)
}
}
}
/**
Return as NSData
:Author: Albert Tra
*/
public func getRawData(url: String!, completion: (data: NSData) -> Void) {
if url != nil {
let URL = NSURL(string: url)
self.cache.fetch(URL: URL!).onSuccess { (data) -> () in
completion(data: data)
}
} else {
print("invalue URL")
}
}
}
| mit | 4a69cf5b552b34eeaf69209dfb63ee98 | 40.458015 | 210 | 0.568035 | 4.422638 | false | true | false | false |
MakeSchool/TripPlanner | Carthage/Checkouts/DVR/DVR/Interaction.swift | 1 | 3297 | import Foundation
struct Interaction {
// MARK: - Properties
let request: NSURLRequest
let response: NSURLResponse
let responseData: NSData?
let recordedAt: NSDate
// MARK: - Initializers
init(request: NSURLRequest, response: NSURLResponse, responseData: NSData? = nil, recordedAt: NSDate = NSDate()) {
self.request = request
self.response = response
self.responseData = responseData
self.recordedAt = recordedAt
}
// MARK: - Encoding
static func encodeBody(body: NSData, headers: [String: String]? = nil) -> AnyObject? {
if let contentType = headers?["Content-Type"] {
// Text
if contentType.hasPrefix("text/") {
// TODO: Use encoding if specified in headers
return String(NSString(data: body, encoding: NSUTF8StringEncoding))
}
// JSON
if contentType.hasPrefix("application/json") {
do {
return try NSJSONSerialization.JSONObjectWithData(body, options: [])
} catch {
return nil
}
}
}
// Base64
return body.base64EncodedStringWithOptions([])
}
static func dencodeBody(body: AnyObject?, headers: [String: String]? = nil) -> NSData? {
guard let body = body else { return nil }
if let contentType = headers?["Content-Type"] {
// Text
if let string = body as? String where contentType.hasPrefix("text/") {
// TODO: Use encoding if specified in headers
return string.dataUsingEncoding(NSUTF8StringEncoding)
}
// JSON
if contentType.hasPrefix("application/json") {
do {
return try NSJSONSerialization.dataWithJSONObject(body, options: [])
} catch {
return nil
}
}
}
// Base64
if let base64 = body as? String {
return NSData(base64EncodedString: base64, options: [])
}
return nil
}
}
extension Interaction {
var dictionary: [String: AnyObject] {
var dictionary: [String: AnyObject] = [
"request": request.dictionary,
"recorded_at": recordedAt.timeIntervalSince1970
]
var response = self.response.dictionary
if let data = responseData, body = Interaction.encodeBody(data, headers: response["headers"] as? [String: String]) {
response["body"] = body
}
dictionary["response"] = response
return dictionary
}
init?(dictionary: [String: AnyObject]) {
guard let request = dictionary["request"] as? [String: AnyObject],
response = dictionary["response"] as? [String: AnyObject],
recordedAt = dictionary["recorded_at"] as? Int else { return nil }
self.request = NSMutableURLRequest(dictionary: request)
self.response = URLHTTPResponse(dictionary: response)
self.recordedAt = NSDate(timeIntervalSince1970: NSTimeInterval(recordedAt))
self.responseData = Interaction.dencodeBody(response["body"], headers: response["headers"] as? [String: String])
}
}
| mit | a3d6c98953a546c46c286eafbbe51a1d | 31.009709 | 124 | 0.577798 | 5.143526 | false | false | false | false |
paketehq/ios | Pakete/API.swift | 1 | 3394 | //
// API.swift
// Pakete
//
// Created by Royce Albert Dy on 13/03/2016.
// Copyright ยฉ 2016 Pakete. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
struct Pakete {
enum Router: URLRequestConvertible {
static let baseURLString = "https://pakete-api-staging.herokuapp.com/v1"
case trackPackage(courier: Courier, trackingNumber: String)
case couriers
var method: HTTPMethod {
return .get
}
var path: String {
switch self {
case .trackPackage:
return "/track"
case .couriers:
return "/couriers"
}
}
// MARK: URLRequestConvertible
func asURLRequest() throws -> URLRequest {
let result: (path: String, parameters: Parameters) = {
switch self {
case .trackPackage(let courier, let trackingNumber):
return ("/track", ["courier": courier.code, "tracking_number": trackingNumber])
case .couriers:
return ("/couriers", [:])
}
}()
let url = try Router.baseURLString.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(result.path))
urlRequest.httpMethod = method.rawValue
urlRequest.setValue("compress, gzip", forHTTPHeaderField: "Accept-Encoding")
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.setValue(Token().tokenString(), forHTTPHeaderField: "pakete-api-key")
return try URLEncoding.default.encode(urlRequest, with: result.parameters)
}
}
}
extension DataRequest {
public func responseSwiftyJSON(_ completionHandler: @escaping (_ request: URLRequest, _ response: HTTPURLResponse?, _ json: SwiftyJSON.JSON, _ error: NSError?) -> Void) -> Self {
return response(queue: nil, responseSerializer: DataRequest.jsonResponseSerializer(options: .allowFragments), completionHandler: { (response) -> Void in
DispatchQueue.global(qos: .default).async(execute: {
var responseJSON = JSON.null
var responseError: NSError?
if let originalRequest = response.request {
switch response.result {
case .success(let value):
if let httpURLResponse = response.response {
responseJSON = SwiftyJSON.JSON(value)
// if not 200 then it's a problem
if httpURLResponse.statusCode != 200 {
responseError = NSError(domain: originalRequest.url?.absoluteString ?? "", code: httpURLResponse.statusCode, userInfo: [NSLocalizedFailureReasonErrorKey: responseJSON["message"].stringValue])
}
}
case .failure(let error):
responseError = error as NSError
}
DispatchQueue.main.async(execute: {
completionHandler(originalRequest, response.response, responseJSON, responseError)
})
} else {
fatalError("original request is nil")
}
})
})
}
}
| mit | 7a8d9bfd4149c08b32c20f301e706f99 | 38 | 223 | 0.560566 | 5.608264 | false | false | false | false |
miktap/pepe-p06 | PePeP06/PePeP06Tests/DataServiceTests.swift | 1 | 12020 | //
// DataServiceTests.swift
// PePeP06Tests
//
// Created by Mikko Tapaninen on 28/12/2017.
//
import Foundation
import Quick
import Nimble
@testable import PePeP06
class DataServiceTests: QuickSpec {
override func spec() {
describe("DataService") {
var dataService: DataService!
var mockTasoClient: MockTasoClient!
var mockDelegate: MockDataServiceDelegate!
beforeEach {
mockTasoClient = MockTasoClient()
mockDelegate = MockDataServiceDelegate()
dataService = DataService(client: mockTasoClient)
dataService.addDelegate(delegate: mockDelegate)
}
describe("populateClub") {
context("when promise rejects") {
it("notifies delegates with an error") {
mockTasoClient.rejectPromise = true
dataService.populateClub()
expect(mockDelegate.clubPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.clubPopulatedClub).toEventually(beNil())
expect(mockDelegate.clubPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response has no data") {
it("notifies delegates with an error") {
mockTasoClient.webResponse = WebResponse(data: nil, statusCode: 200)
dataService.populateClub()
expect(mockDelegate.clubPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.clubPopulatedClub).toEventually(beNil())
expect(mockDelegate.clubPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response cannot be parsed to 'ClubListing'") {
it("notifies delegates with an error") {
let json = """
{
"club": {
"name": "PERTTELIN PEIKOT",
"abbrevation": "PePe"
}
}
"""
mockTasoClient.webResponse = WebResponse(data: json.data(using: .utf8)!, statusCode: 200)
dataService.populateClub()
expect(mockDelegate.clubPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.clubPopulatedClub).toEventually(beNil())
expect(mockDelegate.clubPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response is valid") {
it("notifies delegates with categories") {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "Club", ofType: "json")!
let url = URL(fileURLWithPath: path)
let clubJSON = try! String(contentsOf: url, encoding: .utf8)
mockTasoClient.webResponse = WebResponse(data: clubJSON.data(using: .utf8)!, statusCode: 200)
dataService.populateClub()
expect(mockDelegate.clubPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.clubPopulatedClub?.club_id).toEventually(equal("3077"))
expect(mockDelegate.clubPopulatedError).toEventually(beNil())
}
}
}
describe("populateTeams") {
context("when promise rejects") {
it("notifies delegates with an error") {
mockTasoClient.rejectPromise = true
dataService.populateTeams(team_ids: ["1","2"])
expect(mockDelegate.teamsPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamsPopulatedTeams).toEventually(beNil())
expect(mockDelegate.teamsPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response has no data") {
it("notifies delegates with an error") {
mockTasoClient.webResponse = WebResponse(data: nil, statusCode: 200)
dataService.populateTeams(team_ids: ["1","2"])
expect(mockDelegate.teamsPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamsPopulatedTeams).toEventually(beNil())
expect(mockDelegate.teamsPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response cannot be parsed to 'TeamListing'") {
it("notifies delegates with an error") {
let json = """
{
"team": {
"team_name": "pepe"
}
}
"""
mockTasoClient.webResponse = WebResponse(data: json.data(using: .utf8)!, statusCode: 200)
dataService.populateTeams(team_ids: ["1","2"])
expect(mockDelegate.teamsPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamsPopulatedTeams).toEventually(beNil())
expect(mockDelegate.teamsPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response is valid") {
it("notifies delegates with categories") {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "Team", ofType: "json")!
let url = URL(fileURLWithPath: path)
let teamJSON = try! String(contentsOf: url, encoding: .utf8)
mockTasoClient.webResponse = WebResponse(data: teamJSON.data(using: .utf8)!, statusCode: 200)
dataService.populateTeams(team_ids: ["1","2"])
expect(mockDelegate.teamsPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamsPopulatedTeams?.count).toEventually(equal(2))
expect(mockDelegate.teamsPopulatedError).toEventually(beNil())
}
}
}
describe("populateTeamWithCategory") {
context("when promise rejects") {
it("notifies delegates with an error") {
mockTasoClient.rejectPromise = true
dataService.populateTeamWithCategory(team_id: "1", competition_id: "3", category_id: "2")
expect(mockDelegate.teamWithCategoryPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamWithCategoryPopulatedTeam).toEventually(beNil())
expect(mockDelegate.teamWithCategoryPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response has no data") {
it("notifies delegates with an error") {
mockTasoClient.webResponse = WebResponse(data: nil, statusCode: 200)
dataService.populateTeamWithCategory(team_id: "1", competition_id: "3", category_id: "2")
expect(mockDelegate.teamWithCategoryPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamWithCategoryPopulatedTeam).toEventually(beNil())
expect(mockDelegate.teamWithCategoryPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response cannot be parsed to 'TeamListing'") {
it("notifies delegates with an error") {
let json = """
{
"team": {
"team_name": "pepe"
}
}
"""
mockTasoClient.webResponse = WebResponse(data: json.data(using: .utf8)!, statusCode: 200)
dataService.populateTeamWithCategory(team_id: "1", competition_id: "3", category_id: "2")
expect(mockDelegate.teamWithCategoryPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamWithCategoryPopulatedTeam).toEventually(beNil())
expect(mockDelegate.teamWithCategoryPopulatedError).toEventually(beAnInstanceOf(DataServiceError.self))
}
}
context("when response is valid") {
it("notifies delegates with team") {
let bundle = Bundle(for: type(of: self))
let path = bundle.path(forResource: "Team", ofType: "json")!
let url = URL(fileURLWithPath: path)
let teamJSON = try! String(contentsOf: url, encoding: .utf8)
mockTasoClient.webResponse = WebResponse(data: teamJSON.data(using: .utf8)!, statusCode: 200)
dataService.populateTeamWithCategory(team_id: "1", competition_id: "3", category_id: "2")
expect(mockDelegate.teamWithCategoryPopulatedCalled).toEventually(beTrue())
expect(mockDelegate.teamWithCategoryPopulatedTeam?.team_id).toEventually(equal("141460"))
expect(mockDelegate.teamWithCategoryPopulatedError).toEventually(beNil())
}
}
}
describe("tasoClientReady") {
it("notifies delegates that service is ready") {
dataService.tasoClientReady()
expect(dataService.isReady).to(beTrue())
expect(mockDelegate.dataServiceReadyCalled).to(beTrue())
}
}
}
}
}
class MockDataServiceDelegate: DataServiceDelegate {
var id: String = "MockDataServiceDelegate"
var dataServiceReadyCalled = false
var clubPopulatedCalled = false
var clubPopulatedClub: TasoClub?
var clubPopulatedError: Error?
var teamsPopulatedCalled = false
var teamsPopulatedTeams: [TasoTeam]?
var teamsPopulatedError: Error?
var teamWithCategoryPopulatedCalled = false
var teamWithCategoryPopulatedTeam: TasoTeam?
var teamWithCategoryPopulatedError: Error?
func dataServiceReady() {
dataServiceReadyCalled = true
}
func clubPopulated(club: TasoClub?, error: Error?) {
clubPopulatedCalled = true
clubPopulatedClub = club
clubPopulatedError = error
}
func teamsPopulated(teams: [TasoTeam]?, error: Error?) {
teamsPopulatedCalled = true
teamsPopulatedTeams = teams
teamsPopulatedError = error
}
func teamWithCategoryPopulated(team: TasoTeam?, error: Error?) {
teamWithCategoryPopulatedCalled = true
teamWithCategoryPopulatedTeam = team
teamWithCategoryPopulatedError = error
}
}
| mit | a27b9bdd9807120fd4d134103b90463a | 44.358491 | 127 | 0.524626 | 6.455424 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/views/SLVRequiredItemGroupCell.swift | 1 | 4076 | //
// SLVRequiredItemGroupCell.swift
// selluv-ios
//
// Created by ์กฐ๋ฐฑ๊ทผ on 2016. 12. 22..
// Copyright ยฉ 2016๋
BitBoy Labs. All rights reserved.
//
import UIKit
let RequiredItem_SizeSelectButtonTag = 2001
let RequiredItem_NoneButtonTag = 2002
let RequiredItem_AddButtonTag = 2010
class SLVRequiredItemGroupCell: UICollectionReusableView {
@IBOutlet weak var itemLabel: UILabel!
@IBOutlet weak var sizeLabel: UILabel!
@IBOutlet weak var otherAddView: UIView!
@IBOutlet weak var sizeAddView: UIView!
@IBOutlet weak var noneButton: UIButton!
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var sizeSelectButton: UIButton!
@IBOutlet weak var bottomLine: UIView!
var touchBlock: TouchRequiredItemButtonBlock?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
self.sizeSelectButton.tag = RequiredItem_SizeSelectButtonTag
// self.noneButton.tag = RequiredItem_NoneButtonTag
self.addButton.tag = RequiredItem_AddButtonTag
}
override func layoutSubviews() {
super.layoutSubviews()
}
func onTouchBlock(_ block: @escaping TouchRequiredItemButtonBlock) {
self.touchBlock = block
}
func setupRequiredName(korea: String, english: String) {
let text = "\(korea) \(english)"
let nmLen = korea.distance(from: korea.startIndex, to: korea.endIndex)
let myMutableString = NSMutableAttributedString(string: text, attributes: [
NSFontAttributeName:UIFont.systemFont(ofSize: 13, weight: UIFontWeightRegular),
NSForegroundColorAttributeName: text_color_g153]
)
myMutableString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 17, weight: UIFontWeightMedium), range: NSRange(location:0,length:nmLen))
myMutableString.addAttribute(NSForegroundColorAttributeName, value: text_color_bl51, range: NSRange(location:0,length:nmLen))
self.itemLabel.attributedText = myMutableString
}
func setupRightView(isSize: Bool) {
self.otherAddView.isHidden = isSize
self.sizeAddView.isHidden = !isSize
}
func setupBottomLine(isRow: Bool) {
self.bottomLine.isHidden = isRow
}
func checkNoneDemage() {//self.noneButton ์ผ๋ก ์ ๊ทผํ๋ฉด ๋ค๋ฅธ ์น์
์ ๋์ผ ๋ฒํผ๋ ์ํฅ์ ๋ฐ์..ใ
กใ
ก;;
if TempInputInfoModel.shared.currentModel.noDemage == true {
let button = self.viewWithTag(RequiredItem_NoneButtonTag + 1) as? UIButton
if button != nil && button!.isSelected == false {
button!.isSelected = true
}
}
}
func checkNoneAccessory() {
if TempInputInfoModel.shared.currentModel.noAccessory == true {
let button = self.viewWithTag(RequiredItem_NoneButtonTag + 2) as? UIButton
if button != nil && button!.isSelected == false {
button!.isSelected = true
}
}
}
@IBAction func touchSize2(_ sender: Any) {
let button = sender as! UIButton
DispatchQueue.main.async {
self.sizeSelectButton.isHighlighted = button.isHighlighted
}
self.sizeSelectButton.sendActions(for: .touchUpInside)
}
@IBAction func touchNoneButton(_ sender: Any) {
let button = sender as! UIButton
let selected = !button.isSelected
button.isSelected = selected
if self.touchBlock != nil {
self.touchBlock!(sender as! UIButton)
}
}
@IBAction func touchAddButton(_ sender: Any) {
if self.touchBlock != nil {
self.touchBlock!(sender as! UIButton)
}
}
@IBAction func touchSizeButton(_ sender: Any) {
if self.touchBlock != nil {
self.touchBlock!(sender as! UIButton)
}
}
}
| mit | 583edf7629cc83dc67c6f74bae4dab91 | 31.691057 | 164 | 0.645113 | 4.564132 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Tests/EurofurenceKitTests/Model Ingestion/SynchronizedStoreAssertion.swift | 1 | 4057 | import CoreData
@testable import EurofurenceKit
import EurofurenceWebAPI
import XCTest
extension SynchronizationPayload {
func image(identifiedBy id: EurofurenceWebAPI.Image.ID) throws -> EurofurenceWebAPI.Image {
try XCTUnwrap(images.changed.first(where: { $0.id == id }))
}
}
struct SynchronizedStoreAssertion {
var managedObjectContext: NSManagedObjectContext
var synchronizationPayload: SynchronizationPayload
func assert() throws {
var assertionError: Error?
managedObjectContext.performAndWait {
do {
try assertDays()
try assertTracks()
try assertRooms()
try assertEvents()
try assertKnowledgeGroups()
try assertKnowledgeEntries()
try assertDealers()
try assertAnnouncements()
try assertMaps()
} catch {
assertionError = error
}
}
if let assertionError = assertionError {
throw assertionError
}
}
private func assertDays() throws {
for day in synchronizationPayload.days.changed {
let entity: EurofurenceKit.Day = try managedObjectContext.entity(withIdentifier: day.id)
day.assert(against: entity)
}
}
private func assertTracks() throws {
for track in synchronizationPayload.tracks.changed {
let entity: EurofurenceKit.Track = try managedObjectContext.entity(withIdentifier: track.id)
track.assert(against: entity)
}
}
private func assertRooms() throws {
for room in synchronizationPayload.rooms.changed {
let entity: EurofurenceKit.Room = try managedObjectContext.entity(withIdentifier: room.id)
room.assert(against: entity)
}
}
private func assertEvents() throws {
for event in synchronizationPayload.events.changed {
let entity: EurofurenceKit.Event = try managedObjectContext.entity(withIdentifier: event.id)
try event.assert(against: entity, in: managedObjectContext, from: synchronizationPayload)
}
}
private func assertKnowledgeGroups() throws {
for knowledgeGroup in synchronizationPayload.knowledgeGroups.changed {
let entity: EurofurenceKit.KnowledgeGroup = try managedObjectContext.entity(
withIdentifier: knowledgeGroup.id
)
try knowledgeGroup.assert(against: entity)
}
}
private func assertKnowledgeEntries() throws {
for knowledgeEntry in synchronizationPayload.knowledgeEntries.changed {
let entity: EurofurenceKit.KnowledgeEntry = try managedObjectContext.entity(
withIdentifier: knowledgeEntry.id
)
try knowledgeEntry.assert(against: entity, in: managedObjectContext, from: synchronizationPayload)
}
}
private func assertDealers() throws {
for dealer in synchronizationPayload.dealers.changed {
let entity: EurofurenceKit.Dealer = try managedObjectContext.entity(withIdentifier: dealer.id)
try dealer.assert(against: entity, in: managedObjectContext, from: synchronizationPayload)
}
}
private func assertAnnouncements() throws {
for announcement in synchronizationPayload.announcements.changed {
let entity: EurofurenceKit.Announcement = try managedObjectContext.entity(withIdentifier: announcement.id)
try announcement.assert(against: entity, in: managedObjectContext, from: synchronizationPayload)
}
}
private func assertMaps() throws {
for map in synchronizationPayload.maps.changed {
let entity: EurofurenceKit.Map = try managedObjectContext.entity(withIdentifier: map.id)
try map.assert(against: entity, in: managedObjectContext, from: synchronizationPayload)
}
}
}
| mit | 9f5f08f3188eab766469402fe2307ca0 | 35.54955 | 118 | 0.646783 | 5.957416 | false | false | false | false |
christophhagen/Signal-iOS | SignalMessaging/attachments/MediaMessageView.swift | 1 | 17872 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import MediaPlayer
import YYImage
import SignalServiceKit
@objc
public enum MediaMessageViewMode: UInt {
case large
case small
case attachmentApproval
}
@objc
public class MediaMessageView: UIView, OWSAudioAttachmentPlayerDelegate {
let TAG = "[MediaMessageView]"
// MARK: Properties
@objc
public let mode: MediaMessageViewMode
@objc
public let attachment: SignalAttachment
@objc
public var videoPlayer: MPMoviePlayerController?
@objc
public var audioPlayer: OWSAudioAttachmentPlayer?
@objc
public var audioPlayButton: UIButton?
@objc
public var videoPlayButton: UIImageView?
@objc
public var playbackState = AudioPlaybackState.stopped {
didSet {
AssertIsOnMainThread()
ensureButtonState()
}
}
@objc
public var audioProgressSeconds: CGFloat = 0
@objc
public var audioDurationSeconds: CGFloat = 0
@objc
public var contentView: UIView?
// MARK: Initializers
@available(*, unavailable, message:"use other constructor instead.")
required public init?(coder aDecoder: NSCoder) {
fatalError("\(#function) is unimplemented.")
}
@objc
public required init(attachment: SignalAttachment, mode: MediaMessageViewMode) {
assert(!attachment.hasError)
self.mode = mode
self.attachment = attachment
super.init(frame: CGRect.zero)
createViews()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: View Lifecycle
@objc
public func viewWillAppear(_ animated: Bool) {
OWSAudioAttachmentPlayer.setAudioIgnoresHardwareMuteSwitch(true)
}
@objc
public func viewWillDisappear(_ animated: Bool) {
OWSAudioAttachmentPlayer.setAudioIgnoresHardwareMuteSwitch(false)
}
// MARK: - Create Views
private func createViews() {
if attachment.isAnimatedImage {
createAnimatedPreview()
} else if attachment.isImage {
createImagePreview()
} else if attachment.isVideo {
createVideoPreview()
} else if attachment.isAudio {
createAudioPreview()
} else {
createGenericPreview()
}
}
private func wrapViewsInVerticalStack(subviews: [UIView]) -> UIView {
assert(subviews.count > 0)
let stackView = UIView()
var lastView: UIView?
for subview in subviews {
stackView.addSubview(subview)
subview.autoHCenterInSuperview()
if lastView == nil {
subview.autoPinEdge(toSuperviewEdge: .top)
} else {
subview.autoPinEdge(.top, to: .bottom, of: lastView!, withOffset: stackSpacing())
}
lastView = subview
}
lastView?.autoPinEdge(toSuperviewEdge: .bottom)
return stackView
}
private func stackSpacing() -> CGFloat {
switch mode {
case .large, .attachmentApproval:
return CGFloat(10)
case .small:
return CGFloat(5)
}
}
private func createAudioPreview() {
guard let dataUrl = attachment.dataUrl else {
createGenericPreview()
return
}
audioPlayer = OWSAudioAttachmentPlayer(mediaUrl: dataUrl, delegate: self)
var subviews = [UIView]()
let audioPlayButton = UIButton()
self.audioPlayButton = audioPlayButton
setAudioIconToPlay()
audioPlayButton.imageView?.layer.minificationFilter = kCAFilterTrilinear
audioPlayButton.imageView?.layer.magnificationFilter = kCAFilterTrilinear
audioPlayButton.addTarget(self, action: #selector(audioPlayButtonPressed), for: .touchUpInside)
let buttonSize = createHeroViewSize()
audioPlayButton.autoSetDimension(.width, toSize: buttonSize)
audioPlayButton.autoSetDimension(.height, toSize: buttonSize)
subviews.append(audioPlayButton)
let fileNameLabel = createFileNameLabel()
if let fileNameLabel = fileNameLabel {
subviews.append(fileNameLabel)
}
let fileSizeLabel = createFileSizeLabel()
subviews.append(fileSizeLabel)
let stackView = wrapViewsInVerticalStack(subviews: subviews)
self.addSubview(stackView)
fileNameLabel?.autoPinWidthToSuperview(withMargin: 32)
// We want to center the stackView in it's superview while also ensuring
// it's superview is big enough to contain it.
stackView.autoPinWidthToSuperview()
stackView.autoVCenterInSuperview()
NSLayoutConstraint.autoSetPriority(UILayoutPriorityDefaultLow) {
stackView.autoPinHeightToSuperview()
}
stackView.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual)
stackView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual)
}
private func createAnimatedPreview() {
guard attachment.isValidImage else {
createGenericPreview()
return
}
guard let dataUrl = attachment.dataUrl else {
createGenericPreview()
return
}
guard let image = YYImage(contentsOfFile: dataUrl.path) else {
createGenericPreview()
return
}
guard image.size.width > 0 && image.size.height > 0 else {
createGenericPreview()
return
}
let animatedImageView = YYAnimatedImageView()
animatedImageView.image = image
let aspectRatio = image.size.width / image.size.height
addSubviewWithScaleAspectFitLayout(view:animatedImageView, aspectRatio:aspectRatio)
contentView = animatedImageView
animatedImageView.isUserInteractionEnabled = true
animatedImageView.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(imageTapped)))
}
private func addSubviewWithScaleAspectFitLayout(view: UIView, aspectRatio: CGFloat) {
self.addSubview(view)
// This emulates the behavior of contentMode = .scaleAspectFit using
// iOS auto layout constraints.
//
// This allows ConversationInputToolbar to place the "cancel" button
// in the upper-right hand corner of the preview content.
view.autoCenterInSuperview()
view.autoPin(toAspectRatio:aspectRatio)
view.autoMatch(.width, to: .width, of: self, withMultiplier: 1.0, relation: .lessThanOrEqual)
view.autoMatch(.height, to: .height, of: self, withMultiplier: 1.0, relation: .lessThanOrEqual)
}
private func createImagePreview() {
guard let image = attachment.image() else {
createGenericPreview()
return
}
guard image.size.width > 0 && image.size.height > 0 else {
createGenericPreview()
return
}
let imageView = UIImageView(image: image)
imageView.layer.minificationFilter = kCAFilterTrilinear
imageView.layer.magnificationFilter = kCAFilterTrilinear
let aspectRatio = image.size.width / image.size.height
addSubviewWithScaleAspectFitLayout(view:imageView, aspectRatio:aspectRatio)
contentView = imageView
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(imageTapped)))
}
private func createVideoPreview() {
guard let image = attachment.videoPreview() else {
createGenericPreview()
return
}
guard image.size.width > 0 && image.size.height > 0 else {
createGenericPreview()
return
}
let imageView = UIImageView(image: image)
imageView.layer.minificationFilter = kCAFilterTrilinear
imageView.layer.magnificationFilter = kCAFilterTrilinear
let aspectRatio = image.size.width / image.size.height
addSubviewWithScaleAspectFitLayout(view:imageView, aspectRatio:aspectRatio)
contentView = imageView
// attachment approval provides it's own play button to keep it
// at the proper zoom scale.
if mode != .attachmentApproval {
let videoPlayIcon = UIImage(named:"play_button")!
let videoPlayButton = UIImageView(image: videoPlayIcon)
self.videoPlayButton = videoPlayButton
videoPlayButton.contentMode = .scaleAspectFit
self.addSubview(videoPlayButton)
videoPlayButton.autoCenterInSuperview()
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(UITapGestureRecognizer(target:self, action:#selector(videoTapped)))
}
}
private func createGenericPreview() {
var subviews = [UIView]()
let imageView = createHeroImageView(imageName: "file-thin-black-filled-large")
subviews.append(imageView)
let fileNameLabel = createFileNameLabel()
if let fileNameLabel = fileNameLabel {
subviews.append(fileNameLabel)
}
let fileSizeLabel = createFileSizeLabel()
subviews.append(fileSizeLabel)
let stackView = wrapViewsInVerticalStack(subviews: subviews)
self.addSubview(stackView)
fileNameLabel?.autoPinWidthToSuperview(withMargin: 32)
// We want to center the stackView in it's superview while also ensuring
// it's superview is big enough to contain it.
stackView.autoPinWidthToSuperview()
stackView.autoVCenterInSuperview()
NSLayoutConstraint.autoSetPriority(UILayoutPriorityDefaultLow) {
stackView.autoPinHeightToSuperview()
}
stackView.autoPinEdge(toSuperviewEdge: .top, withInset: 0, relation: .greaterThanOrEqual)
stackView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 0, relation: .greaterThanOrEqual)
}
private func createHeroViewSize() -> CGFloat {
switch mode {
case .large:
return ScaleFromIPhone5To7Plus(175, 225)
case .attachmentApproval:
return ScaleFromIPhone5(100)
case .small:
return ScaleFromIPhone5To7Plus(80, 80)
}
}
private func createHeroImageView(imageName: String) -> UIView {
let imageSize = createHeroViewSize()
let image = UIImage(named: imageName)
assert(image != nil)
let imageView = UIImageView(image: image)
imageView.layer.minificationFilter = kCAFilterTrilinear
imageView.layer.magnificationFilter = kCAFilterTrilinear
imageView.layer.shadowColor = UIColor.black.cgColor
let shadowScaling = 5.0
imageView.layer.shadowRadius = CGFloat(2.0 * shadowScaling)
imageView.layer.shadowOpacity = 0.25
imageView.layer.shadowOffset = CGSize(width: 0.75 * shadowScaling, height: 0.75 * shadowScaling)
imageView.autoSetDimension(.width, toSize: imageSize)
imageView.autoSetDimension(.height, toSize: imageSize)
return imageView
}
private func labelFont() -> UIFont {
switch mode {
case .large, .attachmentApproval:
return UIFont.ows_regularFont(withSize: ScaleFromIPhone5To7Plus(18, 24))
case .small:
return UIFont.ows_regularFont(withSize: ScaleFromIPhone5To7Plus(14, 14))
}
}
private var controlTintColor: UIColor {
switch mode {
case .small, .large:
return UIColor.ows_materialBlue
case .attachmentApproval:
return UIColor.white
}
}
private func formattedFileExtension() -> String? {
guard let fileExtension = attachment.fileExtension else {
return nil
}
return String(format: NSLocalizedString("ATTACHMENT_APPROVAL_FILE_EXTENSION_FORMAT",
comment: "Format string for file extension label in call interstitial view"),
fileExtension.uppercased())
}
public func formattedFileName() -> String? {
guard let sourceFilename = attachment.sourceFilename else {
return nil
}
let filename = sourceFilename.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
guard filename.count > 0 else {
return nil
}
return filename
}
private func createFileNameLabel() -> UIView? {
let filename = formattedFileName() ?? formattedFileExtension()
guard filename != nil else {
return nil
}
let label = UILabel()
label.text = filename
label.textColor = controlTintColor
label.font = labelFont()
label.textAlignment = .center
label.lineBreakMode = .byTruncatingMiddle
return label
}
private func createFileSizeLabel() -> UIView {
let label = UILabel()
let fileSize = attachment.dataLength
label.text = String(format: NSLocalizedString("ATTACHMENT_APPROVAL_FILE_SIZE_FORMAT",
comment: "Format string for file size label in call interstitial view. Embeds: {{file size as 'N mb' or 'N kb'}}."),
OWSFormat.formatFileSize(UInt(fileSize)))
label.textColor = controlTintColor
label.font = labelFont()
label.textAlignment = .center
return label
}
// MARK: - Event Handlers
@objc
func audioPlayButtonPressed(sender: UIButton) {
audioPlayer?.togglePlayState()
}
// MARK: - OWSAudioAttachmentPlayerDelegate
public func audioPlaybackState() -> AudioPlaybackState {
return playbackState
}
public func setAudioPlaybackState(_ value: AudioPlaybackState) {
playbackState = value
}
private func ensureButtonState() {
if playbackState == .playing {
setAudioIconToPause()
} else {
setAudioIconToPlay()
}
}
public func setAudioProgress(_ progress: CGFloat, duration: CGFloat) {
audioProgressSeconds = progress
audioDurationSeconds = duration
}
private func setAudioIconToPlay() {
let image = UIImage(named: "audio_play_black_large")?.withRenderingMode(.alwaysTemplate)
assert(image != nil)
audioPlayButton?.setImage(image, for: .normal)
audioPlayButton?.imageView?.tintColor = controlTintColor
}
private func setAudioIconToPause() {
let image = UIImage(named: "audio_pause_black_large")?.withRenderingMode(.alwaysTemplate)
assert(image != nil)
audioPlayButton?.setImage(image, for: .normal)
audioPlayButton?.imageView?.tintColor = controlTintColor
}
// MARK: - Full Screen Image
@objc
func imageTapped(sender: UIGestureRecognizer) {
// Approval view handles it's own zooming gesture
guard mode != .attachmentApproval else {
return
}
guard sender.state == .recognized else {
return
}
guard let fromView = sender.view else {
return
}
guard let fromViewController = CurrentAppContext().frontmostViewController() else {
return
}
let window = CurrentAppContext().rootReferenceView
let convertedRect = fromView.convert(fromView.bounds, to:window)
let viewController = FullImageViewController(attachment:attachment, from:convertedRect)
viewController.present(from:fromViewController)
}
// MARK: - Video Playback
@objc
func videoTapped(sender: UIGestureRecognizer) {
// Approval view handles it's own play gesture
guard mode != .attachmentApproval else {
return
}
guard sender.state == .recognized else {
return
}
playVideo()
}
@objc
public func playVideo() {
guard let dataUrl = attachment.dataUrl else {
owsFail("\(self.logTag) attachment is missing dataUrl")
return
}
let filePath = dataUrl.path
guard FileManager.default.fileExists(atPath: filePath) else {
owsFail("\(self.logTag) file at \(filePath) doesn't exist")
return
}
guard let videoPlayer = MPMoviePlayerController(contentURL: dataUrl) else {
owsFail("\(self.logTag) unable to build moview player controller")
return
}
videoPlayer.prepareToPlay()
NotificationCenter.default.addObserver(forName: .MPMoviePlayerWillExitFullscreen, object: nil, queue: nil) { [weak self] _ in
self?.moviePlayerWillExitFullscreen()
}
NotificationCenter.default.addObserver(forName: .MPMoviePlayerDidExitFullscreen, object: nil, queue: nil) { [weak self] _ in
self?.moviePlayerDidExitFullscreen()
}
videoPlayer.controlStyle = .default
videoPlayer.shouldAutoplay = true
self.addSubview(videoPlayer.view)
videoPlayer.view.frame = self.bounds
self.videoPlayer = videoPlayer
videoPlayer.view.autoPinToSuperviewEdges()
OWSAudioAttachmentPlayer.setAudioIgnoresHardwareMuteSwitch(true)
videoPlayer.setFullscreen(true, animated:false)
}
private func moviePlayerWillExitFullscreen() {
clearVideoPlayer()
}
private func moviePlayerDidExitFullscreen() {
clearVideoPlayer()
}
private func clearVideoPlayer() {
videoPlayer?.stop()
videoPlayer?.view.removeFromSuperview()
videoPlayer = nil
OWSAudioAttachmentPlayer.setAudioIgnoresHardwareMuteSwitch(false)
}
}
| gpl-3.0 | 549f4b2be6974441780f92f314ddb301 | 31.913444 | 169 | 0.647269 | 5.539988 | false | false | false | false |
couchbits/iOSToolbox | Sources/Extensions/Foundation/FloatExtensions.swift | 1 | 1217 | //
// CGFloat.swift
// iOSToolbox
//
// Created by Dominik Gauggel on 01.02.18.
//
import Foundation
public extension Float {
func equal(other: Float) -> Bool {
return Double(self).equal(other: Double(other))
}
static func equal(lhs: Float?, rhs: Float?) -> Bool {
if let lhs = lhs, let rhs = rhs {
return lhs.equal(other: rhs)
} else if lhs != nil {
return false
} else if rhs != nil {
return false
} else {
return true
}
}
}
public extension Optional where Wrapped == Float {
func equal(other: Float?) -> Bool {
guard let other = other else {
return self == nil
}
return self?.equal(other: other) ?? false
}
}
public extension CGFloat {
func equal(other: CGFloat) -> Bool {
return Float(self).equal(other: Float(other))
}
static func equal(lhs: Float?, rhs: Float?) -> Bool {
if let lhs = lhs, let rhs = rhs {
return lhs.equal(other: rhs)
} else if lhs != nil {
return false
} else if rhs != nil {
return false
} else {
return true
}
}
}
| mit | f4ab74007097b5d3091bd13832a61647 | 21.962264 | 57 | 0.520131 | 4.056667 | false | false | false | false |
mzyy94/TesSoMe | TesSoMe/PostDrawingViewController.swift | 1 | 6116 | //
// PostDrawingViewController.swift
// TesSoMe
//
// Created by Yuki Mizuno on 2014/10/09.
// Copyright (c) 2014ๅนด Yuki Mizuno. All rights reserved.
//
import UIKit
class DrawingPath: NSObject {
var path: UIBezierPath! = nil
var color: UIColor! = nil
init(path aPath: UIBezierPath, color aColor: UIColor) {
self.path = aPath
self.color = aColor
}
}
class PostDrawingViewController: UIViewController {
let imageSize = CGSize(width: 250, height: 85)
let imageRect = CGRect(origin: CGPointZero, size: CGSize(width: 250, height: 85))
var path:UIBezierPath! = nil
var undoStack:[DrawingPath] = []
var redoStack:[DrawingPath] = []
var drawing = false
var color = UIColor.blackColor()
var size: CGFloat = 5.0
var initialImage: UIImage! = nil
@IBOutlet weak var drawingImage: UIImageView!
@IBOutlet weak var undoBtn: UIBarButtonItem!
@IBOutlet weak var redoBtn: UIBarButtonItem!
@IBAction func undoBtnPressed(sender: UIBarButtonItem) {
undo()
}
@IBAction func redoBtnPressed(sender: UIBarButtonItem) {
redo()
}
@IBAction func toolBtnPressed(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("ShowColorPicker", sender: self)
}
func undo() {
redoStack.append(undoStack.removeLast())
drawingImage.image = initialImage
for undo in undoStack {
drawLine(path: undo.path, color: undo.color)
}
self.undoBtn.enabled = !undoStack.isEmpty
self.redoBtn.enabled = true
let postMainViewController = self.presentingViewController as PostMainViewController
postMainViewController.drawingImage = self.drawingImage.image
}
func redo() {
let redo = redoStack.removeLast()
undoStack.append(redo)
drawLine(path: redo.path, color: redo.color)
self.undoBtn.enabled = true
self.redoBtn.enabled = !redoStack.isEmpty
let postMainViewController = self.presentingViewController as PostMainViewController
postMainViewController.drawingImage = self.drawingImage.image
}
override func viewDidLoad() {
super.viewDidLoad()
UIGraphicsBeginImageContext(imageSize)
let rect = imageRect
if initialImage != nil {
initialImage.drawInRect(rect)
} else {
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextFillRect(context, rect)
}
initialImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
drawingImage.image = initialImage
drawingImage.contentMode = UIViewContentMode.ScaleToFill
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if undoStack.count > 16 {
UIGraphicsBeginImageContext(imageSize)
initialImage.drawInRect(imageRect)
for _ in 0..<(undoStack.count - 16) {
let undo = undoStack.removeAtIndex(0)
undo.color.setStroke()
undo.path.stroke()
}
initialImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.parentViewController?.presentingViewController?.navigationController?.setNavigationBarHidden(true, animated: true)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.parentViewController?.presentingViewController?.navigationController?.setNavigationBarHidden(false, animated: true)
}
func drawLine(path aPath: UIBezierPath, color aColor: UIColor) {
UIGraphicsBeginImageContext(imageSize)
self.drawingImage.image!.drawInRect(imageRect)
aColor.setStroke()
aPath.stroke()
self.drawingImage.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let viewPoint = touches.anyObject()!.locationInView(self.view)
if !CGRectContainsPoint(self.drawingImage.frame, viewPoint) {
drawing = false
return
}
path = UIBezierPath()
path.lineWidth = size
path.lineCapStyle = kCGLineCapRound
let currentPoint = touches.anyObject()!.locationInView(self.drawingImage)
let scale: CGFloat = self.drawingImage.bounds.size.width / self.imageSize.width
let scaledPoint = CGPoint(x: currentPoint.x / scale, y: currentPoint.y / scale)
path.moveToPoint(scaledPoint)
drawing = true
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
if (!drawing) {
return
}
let currentPoint = touches.anyObject()!.locationInView(self.drawingImage)
let scale: CGFloat = self.drawingImage.bounds.size.width / self.imageSize.width
let scaledPoint = CGPoint(x: currentPoint.x / scale, y: currentPoint.y / scale)
path.addLineToPoint(scaledPoint)
drawLine(path: path, color: color)
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
if (!drawing) {
return
}
let currentPoint = touches.anyObject()!.locationInView(self.drawingImage)
let scale: CGFloat = self.drawingImage.bounds.size.width / self.imageSize.width
let scaledPoint = CGPoint(x: currentPoint.x / scale, y: currentPoint.y / scale)
path.addLineToPoint(scaledPoint)
drawLine(path: path, color: color)
undoStack.append(DrawingPath(path: path, color: color))
if undoStack.count > 32 {
let undo = undoStack.removeAtIndex(0)
UIGraphicsBeginImageContext(imageSize)
initialImage.drawInRect(imageRect)
undo.color.setStroke()
undo.path.stroke()
initialImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
undo()
redo()
undoBtn.enabled = true
redoStack.removeAll(keepCapacity: false)
redoBtn.enabled = false
drawing = false
path = nil
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
self.touchesEnded(touches, withEvent: event)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowColorPicker" {
let colorPickerViewController = segue.destinationViewController as ColorPickerViewController
colorPickerViewController.color = self.color
colorPickerViewController.size = self.size
}
}
}
| gpl-3.0 | e6b4686640a6b687e99941b09d89659e | 27.175115 | 122 | 0.747956 | 4.147897 | false | false | false | false |
Tarovk/Mundus_Client | Pods/Aldo/Aldo/Aldo.swift | 2 | 12962 | //
// Aldo.swift
// Pods
//
// Created by Team Aldo on 29/12/2016.
//
//
import Foundation
import Alamofire
/**
All core URI requests that are being processed by the Aldo Framework.
*/
public enum RequestURI: String {
/// Dummy URI.
case REQUEST_EMPTY = "/"
/// URI to request and authorization token.
case REQUEST_AUTH_TOKEN = "/token"
/// URI template to create a session.
case SESSION_CREATE = "/session/username/%@"
/// URI template to join a session.
case SESSION_JOIN = "/session/join/%@/username/%@"
/// URI to get the information about the session.
case SESSION_INFO = "/session"
/// URI to get the players that have joined the session.
case SESSION_PLAYERS = "/session/players"
/// URI to resume the session.
case SESSION_STATE_PLAY = "/session/play"
/// URI to pause the session.
case SESSION_STATE_PAUSE = "/session/pause"
/// URI to stop and delete the session.
case SESSION_DELETE = "/session/delete"
/// URI to get all players linked to the device.
case PLAYER_ALL = "/player/all"
/// URI to get information of the active player.
case PLAYER_INFO = "/player"
/// URI template to update the username of the active player.
case PLAYER_USERNAME_UPDATE = "/player/username/%@"
/**
Converts the rawValue to one containing regular expression for comparison.
- Returns: A *String* representation as regular expression.
*/
public func regex() -> String {
var regex: String = "(.)+?"
if self == .PLAYER_USERNAME_UPDATE {
regex = "(.)+?$"
}
return "\(self.rawValue.replacingOccurrences(of: "%@", with: regex))$"
}
}
/**
Protocol for sending a request to the Aldo Framework.
*/
public protocol AldoRequester {
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
static func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback?)
}
/**
Class containing static methods to communicate with the Aldo Framework.
*/
public class Aldo: AldoRequester {
/// Keys for data storage
public enum Keys: String {
case AUTH_TOKEN
case SESSION
}
static let storage = UserDefaults.standard
static var hostAddress: String = "127.0.0.1"
static var baseAddress: String = "127.0.0.1"
static let id: String = UIDevice.current.identifierForVendor!.uuidString
/**
Define the address of the server running the Aldo Framework.
- Parameters:
- address: the address of the server running the Aldo Framework
including port and **without** a / at the end.
*/
public class func setHostAddress(address: String) {
if let url = URL(string: address) {
let host = url.host != nil ? url.host! : address
let port = url.port != nil ? ":\(url.port!)" : ""
hostAddress = address
baseAddress = "\(host)\(port)"
}
//hostAddress.asURL().s
//baseAddress =
}
/**
Checks whether the device already has an authorization token or not.
- Returns: *true* if having a token, otherwise *false*.
*/
public class func hasAuthToken() -> Bool {
return storage.object(forKey: Keys.AUTH_TOKEN.rawValue) != nil
}
/**
Checks wether the device has a information about a player in a session.
- Returns: *true* if having information about a player, otherwise *false*.
*/
public class func hasActivePlayer() -> Bool {
return storage.object(forKey: Keys.SESSION.rawValue) != nil
}
/**
Retrieves the storage where the information retrieved from the Aldo Framework is stored.
- Returns: an instance of *UserDefaults*
*/
public class func getStorage() -> UserDefaults {
return storage
}
/**
Retrieves the stored information about an active player.
- Returns: an instance of *Player* if available, otherwise *nil*
*/
public class func getPlayer() -> Player? {
if let objSession = storage.object(forKey: Keys.SESSION.rawValue) {
let sessionData = objSession as! Data
let session: Player = NSKeyedUnarchiver.unarchiveObject(with: sessionData) as! Player
return session
}
return nil
}
/// Stores information about an active player.
public class func setPlayer(player: Player) {
let playerData: Data = NSKeyedArchiver.archivedData(withRootObject: player)
Aldo.getStorage().set(playerData, forKey: Aldo.Keys.SESSION.rawValue)
}
/// Helper method creating the value of the Authorization header used for a request.
class func getAuthorizationHeaderValue() -> String {
let objToken = storage.object(forKey: Keys.AUTH_TOKEN.rawValue)
let token: String = (objToken != nil) ? ":\(objToken as! String)" : ""
var playerId: String = ""
if let player = Aldo.getPlayer() {
playerId = ":\(player.getId())"
}
return "\(id)\(token)\(playerId)"
}
/**
Senda a request to the server running the Aldo Framework.
- Parameters:
- uri: The request to be send.
- method: The HTTP method to be used for the request.
- parameters: The information that should be passed in the body
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
open class func request(uri: String, method: HTTPMethod, parameters: Parameters, callback: Callback? = nil) {
let headers = [
"Authorization": getAuthorizationHeaderValue()
]
Alamofire.request("\(hostAddress)\(uri)", method: method,
parameters: parameters, encoding: AldoEncoding(),
headers: headers).responseJSON { response in
var result: NSDictionary = [:]
if let JSON = response.result.value {
result = JSON as! NSDictionary
}
var responseCode: Int = 499
if let httpResponse = response.response {
responseCode = httpResponse.statusCode
}
AldoMainCallback(callback: callback).onResponse(request: uri,
responseCode: responseCode, response: result)
}
}
/**
Opens a websocket connection with the Aldo Framework.
- Parameters:
- path: The path to subscribe to
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
- Returns: An instance of *AldoWebSocket* representing the connection or
*nil* if the connection could not be made.
*/
public class func subscribe(path: String, callback: Callback) -> AldoWebSocket? {
if let url = URL(string: "ws://\(baseAddress)\(path)") {
let socket = AldoWebSocket(path: path, url: url, callback: callback)
socket.connect()
return socket
}
return nil
}
/**
Sends a request to obtain an authorization token.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestAuthToken(callback: Callback? = nil) {
let command: String = RequestURI.REQUEST_AUTH_TOKEN.rawValue
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to create a session.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func createSession(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_CREATE.rawValue, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to join a session.
- Parameters:
- username: The username to be used.
- token: The token to join a session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func joinSession(username: String, token: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.SESSION_JOIN.rawValue, token, username)
request(uri: command, method: .post, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionInfo(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players in the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestSessionPlayers(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_PLAYERS.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the status of the session.
- Parameters:
- newStatus: The new status of the session.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func changeSessionStatus(newStatus: Session.Status, callback: Callback? = nil) {
var command: String = RequestURI.SESSION_STATE_PLAY.rawValue
if newStatus == Session.Status.PAUSED {
command = RequestURI.SESSION_STATE_PAUSE.rawValue
}
request(uri: command, method: .put, parameters: [:], callback: callback)
}
/**
Sends a request to delete the session.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func deleteSession(callback: Callback? = nil) {
let command: String = RequestURI.SESSION_DELETE.rawValue
request(uri: command, method: .delete, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve the players linked to the device.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestDevicePlayers(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_ALL.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to retrieve information about the player.
- Parameter callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func requestPlayerInfo(callback: Callback? = nil) {
let command: String = RequestURI.PLAYER_INFO.rawValue
request(uri: command, method: .get, parameters: [:], callback: callback)
}
/**
Sends a request to change the username of the player.
- Parameters:
- username: The username to be used.
- callback: A realization of the Callback protocol to be called
when a response is returned from the Aldo Framework.
*/
public class func updateUsername(username: String, callback: Callback? = nil) {
let command: String = String(format: RequestURI.PLAYER_USERNAME_UPDATE.rawValue, username)
request(uri: command, method: .put, parameters: [:], callback: callback)
}
}
| mit | 5d6f2b2f8a11e079bded308d4f9d2aa3 | 35.206704 | 113 | 0.612251 | 4.951108 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/ios-sdk/WatsonDeveloperCloud/TextToSpeech/TextToSpeechConstants.swift | 1 | 1050 | /**
* Copyright IBM Corporation 2015
*
* 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
extension TextToSpeech {
internal struct Constants {
static let serviceURL = "https://stream.watsonplatform.net/text-to-speech/api"
static let tokenURL = "https://stream.watsonplatform.net/authorization/api/v1/token"
static let errorDomain = "com.watsonplatform.texttospeech"
static let synthesize = "/v1/synthesize"
static let voices = "/v1/voices"
}
} | mit | babb97fb796471017da7376d515561d5 | 32.903226 | 92 | 0.700952 | 4.356846 | false | false | false | false |
svanimpe/around-the-table | Sources/AroundTheTable/Forms/EditActivityDateTimeForm.swift | 1 | 855 | import Foundation
/**
Form for editing an activity's date and time.
*/
struct EditActivityDateTimeForm: Codable {
let day: Int
let month: Int
let year: Int
let hour: Int
let minute: Int
/// The new date.
/// Returns `nil` if the form's fields do not represent a valid date,
/// or if the date is not in the future.
var date: Date? {
var components = DateComponents()
components.calendar = Settings.calendar
components.day = day
components.month = month
components.year = year
components.hour = hour
components.minute = minute
components.timeZone = Settings.timeZone
guard components.isValidDate,
let date = components.date,
date > Date() else {
return nil
}
return date
}
}
| bsd-2-clause | 06456e33671842e6c1cd76dae2bb3c2f | 24.909091 | 73 | 0.591813 | 4.697802 | false | false | false | false |
tardieu/swift | stdlib/public/SDK/Foundation/NSDate.swift | 7 | 863 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSDate : CustomPlaygroundQuickLookable {
var summary: String {
let df = DateFormatter()
df.dateStyle = .medium
df.timeStyle = .short
return df.string(from: self as Date)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(summary)
}
}
| apache-2.0 | ca247290762b2edf9946c72d16a70a9e | 32.192308 | 80 | 0.590962 | 5.198795 | false | false | false | false |
minggangw/ios-extensions-crosswalk | extensions/Presentation/Presentation/Presentation.swift | 2 | 3427 | // Copyright (c) 2015 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import Foundation
import XWalkView
public class Presentation: XWalkExtension {
var remoteWindow: UIWindow? = nil
var remoteViewController: RemoteViewController? = nil
var sessions: Dictionary<String, PresentationSessionHost> = [:]
override init() {
super.init()
if UIScreen.screens().count == 2 {
print("external display connected. count:\(UIScreen.screens().count)")
let remoteScreen: UIScreen = UIScreen.screens()[1];
createWindowForScreen(remoteScreen)
sendAvailableChangeEvent(true)
}
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "screenDidConnect:", name: UIScreenDidConnectNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "screenDidDisconnect:", name: UIScreenDidDisconnectNotification, object: nil)
}
public override func didBindExtension(channel: XWalkChannel!, instance: Int) {
super.didBindExtension(channel, instance: instance)
let extensionName = "navigator.presentation.PresentationSession"
PresentationSessionHost.presentation = self
if let ext: PresentationSessionHost = XWalkExtensionFactory.createExtension(extensionName) as? PresentationSessionHost {
channel.webView?.loadExtension(ext, namespace: extensionName)
}
}
func createWindowForScreen(screen: UIScreen) {
assert(remoteWindow == nil, "remoteWindow should be nil before it is created.")
remoteWindow = UIWindow(frame: screen.bounds)
remoteWindow?.screen = screen
remoteViewController = RemoteViewController()
remoteWindow?.rootViewController = remoteViewController
remoteWindow?.hidden = false
}
func sendAvailableChangeEvent(isAvailable: Bool) {
var js = "var ev = new Event(\"change\"); ev.value = \(isAvailable);";
js += " dispatchEvent(ev);";
self.evaluateJavaScript(js)
}
func screenDidConnect(notification: NSNotification) {
if let screen = notification.object as? UIScreen {
createWindowForScreen(screen)
sendAvailableChangeEvent(true)
}
}
func screenDidDisconnect(notification: NSNotification) {
if let _ = notification.object as? UIScreen {
sendAvailableChangeEvent(false)
remoteWindow?.hidden = true
remoteViewController?.willDisconnect()
remoteViewController = nil
remoteWindow = nil
}
}
func registerSession(sessionHost: PresentationSessionHost, id: String) {
sessions[id] = sessionHost
}
func unregisterSession(id: String) {
sessions[id] = nil
}
func jsfunc_startSession(cid: UInt32, url: String, presentationId: String, _Promise: UInt32) {
if let sessionHost = sessions[presentationId] {
remoteViewController?.attachSession(sessionHost)
}
}
func jsfunc_joinSession(cid: UInt32, url: String, presentationId: String, _Promise: UInt32) {
}
func jsfunc_getAvailability(cid: UInt32, _Promise: UInt32) {
invokeCallback(_Promise, key: "resolve", arguments: [UIScreen.screens().count == 2]);
}
}
| bsd-3-clause | 7896dcdbcafc7888ff8b3deaaed9c6c9 | 36.25 | 128 | 0.674643 | 5.032305 | false | false | false | false |
Yummypets/YPImagePicker | Source/SelectionsGallery/YPSelectionsGalleryView.swift | 1 | 3281 | //
// YPSelectionsGalleryView.swift
// YPImagePicker
//
// Created by Sacha DSO on 13/06/2018.
// Copyright ยฉ 2018 Yummypets. All rights reserved.
//
import UIKit
import Stevia
class YPSelectionsGalleryView: UIView {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: YPGalleryCollectionViewFlowLayout())
convenience init() {
self.init(frame: .zero)
subviews(
collectionView
)
// Layout collectionView
collectionView.heightEqualsWidth()
if #available(iOS 11.0, *) {
collectionView.Right == safeAreaLayoutGuide.Right
collectionView.Left == safeAreaLayoutGuide.Left
} else {
|collectionView|
}
collectionView.CenterY == CenterY - 30
// Apply style
backgroundColor = YPConfig.colors.selectionsBackgroundColor
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
}
}
class YPGalleryCollectionViewFlowLayout: UICollectionViewFlowLayout {
override init() {
super.init()
scrollDirection = .horizontal
let sideMargin: CGFloat = 24
let spacing: CGFloat = 12
let overlapppingNextPhoto: CGFloat = 37
minimumLineSpacing = spacing
minimumInteritemSpacing = spacing
let screenWidth = YPImagePickerConfiguration.screenWidth
let size = screenWidth - (sideMargin + overlapppingNextPhoto)
itemSize = CGSize(width: size, height: size)
sectionInset = UIEdgeInsets(top: 0, left: sideMargin, bottom: 0, right: sideMargin)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// This makes so that Scrolling the collection view always stops with a centered image.
// This is heavily inpired form :
// https://stackoverflow.com/questions/13492037/targetcontentoffsetforproposedcontentoffsetwithscrollingvelocity
// -without-subcla
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint,
withScrollingVelocity velocity: CGPoint) -> CGPoint {
let spacing: CGFloat = 12
let overlapppingNextPhoto: CGFloat = 37
var offsetAdjustment = CGFloat.greatestFiniteMagnitude// MAXFLOAT
let horizontalOffset = proposedContentOffset.x + spacing + overlapppingNextPhoto/2 // + 5
guard let collectionView = collectionView else {
return proposedContentOffset
}
let targetRect = CGRect(x: proposedContentOffset.x,
y: 0,
width: collectionView.bounds.size.width,
height: collectionView.bounds.size.height)
guard let array = super.layoutAttributesForElements(in: targetRect) else {
return proposedContentOffset
}
for layoutAttributes in array {
let itemOffset = layoutAttributes.frame.origin.x
if abs(itemOffset - horizontalOffset) < abs(offsetAdjustment) {
offsetAdjustment = itemOffset - horizontalOffset
}
}
return CGPoint(x: proposedContentOffset.x + offsetAdjustment, y: proposedContentOffset.y)
}
}
| mit | 0f137f913bbb0e322d8eee66423766ef | 35.444444 | 116 | 0.666463 | 5.521886 | false | false | false | false |
mortorqrobotics/morscout-ios | MorScout/Supporting Files/Reachability.swift | 1 | 1188 | //
// Reachability.swift
// MorScout
//
// Created by Farbod Rafezy on 3/1/16.
// Copyright ยฉ 2016 MorTorq. All rights reserved.
//
import Foundation
import SystemConfiguration
open class Reachability {
/**
Checks to see if client is connected to the internet.
*/
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
| mit | 51a0957c68a8e01e527286d749d93322 | 31.972222 | 95 | 0.656276 | 4.805668 | false | false | false | false |
mflint/ios-tldr-viewer | tldr-viewer/FavouriteDataSourceDecorator.swift | 1 | 3884 | //
// FavouriteDataSourceDecorator.swift
// tldr-viewer
//
// Created by Matthew Flint on 04/08/2019.
// Copyright ยฉ 2019 Green Light. All rights reserved.
//
import Foundation
class FavouriteDataSourceDecorator: DataSourcing, SwitchableDataSourceDecorator {
private var underlyingDataSource: DataSourcing
private(set) var commands = [Command]()
let isSearchable = false
let isRefreshable = false
let name = Localizations.CommandList.DataSources.Favourites
let type = DataSourceType.favourites
private var delegates = WeakCollection<DataSourceDelegate>()
var favouriteCommandNames: [String] {
didSet {
update()
// save to preferences/iCloud in the background
DispatchQueue.global().async {
self.save()
}
}
}
init(underlyingDataSource: DataSourcing) {
// default value comes from local Preferences
favouriteCommandNames = Preferences.sharedInstance.favouriteCommandNames()
self.underlyingDataSource = underlyingDataSource
underlyingDataSource.add(delegate: self)
// listen for iCloud updates
let keyValueStore = NSUbiquitousKeyValueStore.default
NotificationCenter.default.addObserver(self, selector: #selector(FavouriteDataSourceDecorator.onCloudKeyValueStoreUpdate), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: keyValueStore)
keyValueStore.synchronize()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func add(delegate: DataSourceDelegate) {
delegates.add(delegate)
}
@objc private func onCloudKeyValueStoreUpdate(notification: Notification) {
guard let changeReason = notification.userInfo?[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int else { return }
guard let changedKeys = notification.userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] else { return }
if changeReason == NSUbiquitousKeyValueStoreInitialSyncChange || changeReason == NSUbiquitousKeyValueStoreServerChange && changedKeys.contains(Constant.iCloudKey.favouriteCommandNames) {
let keyValueStore = NSUbiquitousKeyValueStore.default
if let incomingFavouriteNames = keyValueStore.array(forKey: Constant.iCloudKey.favouriteCommandNames) as? [String] {
favouriteCommandNames = incomingFavouriteNames
}
}
}
func add(commandName: String) {
favouriteCommandNames.append(commandName)
}
func remove(commandName: String) {
if let index = favouriteCommandNames.firstIndex(of: commandName) {
favouriteCommandNames.remove(at: index)
}
}
func isFavourite(commandName: String) -> Bool {
favouriteCommandNames.contains(commandName)
}
private func save() {
Preferences.sharedInstance.setFavouriteCommandNames(favouriteCommandNames)
postNotification()
let keyValueStore = NSUbiquitousKeyValueStore.default
keyValueStore.set(favouriteCommandNames, forKey: Constant.iCloudKey.favouriteCommandNames)
keyValueStore.synchronize()
}
private func postNotification() {
NotificationCenter.default.post(name: Constant.FavouriteChangeNotification.name, object:self)
}
private func update() {
commands = underlyingDataSource.commands.filter({ (command) -> Bool in
self.isFavourite(commandName: command.name)
})
delegates.forEach { (delegate) in
delegate.dataSourceDidUpdate(dataSource: self)
}
}
}
extension FavouriteDataSourceDecorator: DataSourceDelegate {
func dataSourceDidUpdate(dataSource: DataSourcing) {
update()
}
}
| mit | 4c041c64ccec76c2a7548c0892a22eed | 34.3 | 218 | 0.687355 | 5.744083 | false | false | false | false |
athiercelin/Localizations | Localizations/Project Details/FileDataSource.swift | 1 | 3314 | //
// FileDataSource.swift
// Localizations
//
// Created by Arnaud Thiercelin on 2/7/16.
// Copyright ยฉ 2016 Arnaud Thiercelin. 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 Cocoa
class FileDataSource: NSObject, NSOutlineViewDataSource {
var regions = [Region]()
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return self.regions.count
} else {
return (item as! Region).files.count
}
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil {
return self.regions[index]
} else {
return (item as! Region).files[index]
}
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if item is Region {
return true
}
return false
}
func regionWithCode(code: String?) -> Region? {
guard code != nil else {
return nil
}
for region in self.regions {
if region.code == code {
return region
}
}
return nil
}
func buildDatasource(projectRoot: String, devRegion: String, knownRegions: [String], combinedFiles: [File]) {
// Build regions based on devRegion & knownRegions
for knownRegion in knownRegions {
if let matchingRegion = Region.regionMatchingString(string: knownRegion) {
self.regions.append(matchingRegion)
}
}
for file in combinedFiles {
if file.folder.characters.count != 0 {
// Assign files with their respective region
if let region = self.regionWithCode(code: Region.regionMatchingString(string: file.languageCode)?.code) {
region.files.append(file)
} else {
let newRegion = Region.regionMatchingString(string: file.languageCode)
if newRegion != nil {
newRegion!.files.append(file)
self.regions.append(newRegion!)
} else {
NSLog("Missing Region for file \(file), and could not recognize it and recover")
}
}
} else {
// Duplicate those without to each regions.
for region in regions {
let newFile = file.mutableCopy() as! File
newFile.folder = "\(region.code).lproj"
newFile.path = "\(projectRoot)/\(newFile.folder)/\(newFile.name)"
region.files.append(newFile)
}
}
}
}
}
| mit | 20f0cbfa3ed9b0da7d2d4324ae0a3a15 | 31.480392 | 112 | 0.698159 | 3.934679 | false | false | false | false |
yrchen/edx-app-ios | Source/CourseOutlineModeController.swift | 1 | 3335 | //
// CourseOutlineModeController.swift
// edX
//
// Created by Akiva Leffert on 5/28/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
public enum CourseOutlineMode : String {
case Full = "full"
case Video = "video"
public var isVideo : Bool {
switch self {
case .Video:
return true
default:
return false
}
}
}
public protocol CourseOutlineModeControllerDelegate : class {
func viewControllerForCourseOutlineModeChange() -> UIViewController
func courseOutlineModeChanged(courseMode : CourseOutlineMode)
}
public protocol CourseOutlineModeControllerDataSource : class {
var currentOutlineMode : CourseOutlineMode { get set }
var modeChangedNotificationName : String { get }
}
class CourseOutlineModeController : NSObject {
let barItem : UIBarButtonItem
private let dataSource : CourseOutlineModeControllerDataSource
weak var delegate : CourseOutlineModeControllerDelegate?
init(dataSource : CourseOutlineModeControllerDataSource) {
self.dataSource = dataSource
let button = UIButton(type: .System)
self.barItem = UIBarButtonItem(customView: button)
self.barItem.accessibilityLabel = Strings.courseModePickerDescription
super.init()
self.updateIconForButton(button)
button.oex_addAction({[weak self] _ in
self?.showModeChanger()
}, forEvents: .TouchUpInside)
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: dataSource.modeChangedNotificationName) { (_, owner, _) -> Void in
owner.updateIconForButton(button)
owner.delegate?.courseOutlineModeChanged(owner.dataSource.currentOutlineMode)
}
}
private func updateIconForButton(button : UIButton) {
let icon : Icon
let insets : UIEdgeInsets
// The icon should show the *next* mode, not the current one
switch dataSource.currentOutlineMode {
case .Full:
icon = Icon.CourseModeVideo
insets = UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)
case .Video:
icon = Icon.CourseModeFull
insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
button.imageEdgeInsets = insets
button.setImage(icon.barButtonImage(), forState: .Normal)
button.sizeToFit()
button.bounds = CGRectMake(0, 0, 20, button.bounds.size.height)
}
var currentMode : CourseOutlineMode {
return dataSource.currentOutlineMode
}
func showModeChanger() {
let items : [(title : String, value : CourseOutlineMode)] = [
(title :Strings.courseModeFull, value : CourseOutlineMode.Full),
(title : Strings.courseModeVideo, value : CourseOutlineMode.Video)
]
let controller = UIAlertController.actionSheetWithItems(items, currentSelection: self.currentMode) {[weak self] mode in
self?.dataSource.currentOutlineMode = mode
}
controller.addCancelAction()
let presenter = delegate?.viewControllerForCourseOutlineModeChange()
presenter?.presentViewController(controller, animated: true, completion: nil)
}
} | apache-2.0 | 1a99bed47be3880cea3bbda8180e894c | 32.36 | 139 | 0.653673 | 5.302067 | false | false | false | false |
orta/SignalKit | SignalKit/Utilities/CompoundObserver.swift | 1 | 1507 | //
// CompoundObserver.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/14/15.
// Copyright ยฉ 2015 Yanko Dimitrov. All rights reserved.
//
import Foundation
internal final class CompoundObserver<T: Observable, U: Observable>: Disposable {
private let observableA: T
private let observableB: U
private var latestA: T.Item?
private var latestB: U.Item?
private var subscriptionA: Disposable?
private var subscriptionB: Disposable?
private let callback: ((T.Item, U.Item)) -> Void
init(observableA: T, observableB: U, callback: ( (T.Item, U.Item) ) -> Void) {
self.observableA = observableA
self.observableB = observableB
self.callback = callback
observe()
}
deinit {
dispose()
}
private func observe() {
subscriptionA = observableA.addObserver { [weak self] in
self?.latestA = $0
self?.dispatchLatest()
}
subscriptionB = observableB.addObserver { [weak self] in
self?.latestB = $0
self?.dispatchLatest()
}
}
private func dispatchLatest() {
if let a = latestA, b = latestB {
callback( (a, b) )
}
}
func dispose() {
subscriptionA?.dispose()
subscriptionB?.dispose()
latestA = nil
latestB = nil
}
}
| mit | 52df2d92fc232a9d8ef914a34110c0d3 | 21.147059 | 82 | 0.535857 | 4.577508 | false | true | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/NewChatControllers/SelectChatTableViewController.swift | 1 | 8517 | //
// SelectChatTableViewController.swift
// Pigeon-project
//
// Created by Roman Mizin on 3/6/18.
// Copyright ยฉ 2018 Roman Mizin. All rights reserved.
//
import UIKit
import Firebase
import PhoneNumberKit
import SDWebImage
import Contacts
private let falconUsersCellID = "falconUsersCellID"
private let newGroupCellID = "newGroupCellID"
class SelectChatTableViewController: UITableViewController {
let newGroupAction = "New Group"
var actions = ["New Group"]
var users = [User]()
var filteredUsers = [User]()
var filteredUsersWithSection = [[User]]()
var collation = UILocalizedIndexedCollation.current()
var sectionTitles = [String]()
var searchBar: UISearchBar?
var phoneNumberKit = PhoneNumberKit()
let viewPlaceholder = ViewPlaceholder()
override func viewDidLoad() {
super.viewDidLoad()
configureController()
setupSearchController()
}
@objc fileprivate func updateUsers() {
self.users = RealmKeychain.realmUsersArray()
self.filteredUsers = RealmKeychain.realmUsersArray()
if !(RealmKeychain.realmUsersArray().count == 0) {
self.viewPlaceholder.remove(from: self.view, priority: .high)
}
if self.searchBar != nil && !self.searchBar!.isFirstResponder {
self.setUpCollation()
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
deinit {
print("new chat deinit")
NotificationCenter.default.removeObserver(self)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return ThemeManager.currentTheme().statusBarStyle
}
fileprivate func configureController() {
navigationItem.title = "New Message"
if #available(iOS 11.0, *) {
navigationItem.largeTitleDisplayMode = .always
navigationController?.navigationBar.prefersLargeTitles = true
}
extendedLayoutIncludesOpaqueBars = true
definesPresentationContext = true
edgesForExtendedLayout = [UIRectEdge.top, UIRectEdge.bottom]
view.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
tableView.indicatorStyle = ThemeManager.currentTheme().scrollBarStyle
tableView.sectionIndexBackgroundColor = view.backgroundColor
tableView.backgroundColor = view.backgroundColor
tableView.register(FalconUsersTableViewCell.self, forCellReuseIdentifier: falconUsersCellID)
tableView.separatorStyle = .none
}
fileprivate func deselectItem() {
guard DeviceType.isIPad else { return }
if let indexPath = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: indexPath, animated: true)
}
}
@objc fileprivate func dismissNavigationController() {
dismiss(animated: true, completion: nil)
}
fileprivate func setupSearchController() {
searchBar = UISearchBar()
searchBar?.delegate = self
searchBar?.searchBarStyle = .minimal
searchBar?.changeBackgroundColor(to: ThemeManager.currentTheme().searchBarColor)
searchBar?.placeholder = "Search"
searchBar?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
tableView.tableHeaderView = searchBar
}
func checkContactsAuthorizationStatus() -> Bool {
let contactsAuthorityCheck = CNContactStore.authorizationStatus(for: CNEntityType.contacts)
switch contactsAuthorityCheck {
case .denied, .notDetermined, .restricted:
viewPlaceholder.add(for: self.view, title: .denied, subtitle: .denied, priority: .high, position: .center)
return false
case .authorized:
viewPlaceholder.remove(from: self.view, priority: .high)
return true
@unknown default:
fatalError()
}
}
func checkNumberOfContacts() {
guard users.count == 0 else { return }
viewPlaceholder.add(for: self.view, title: .empty, subtitle: .empty, priority: .low, position: .center)
}
fileprivate func correctSearchBarForCurrentIOSVersion() -> UISearchBar {
var searchBar: UISearchBar!
searchBar = self.searchBar
return searchBar
}
@objc func setUpCollation() {
let (arrayContacts, arrayTitles) = collation.partitionObjects(array: self.filteredUsers,
collationStringSelector: #selector(getter: User.name))
guard let contacts = arrayContacts as? [[User]] else { return }
filteredUsersWithSection = contacts
sectionTitles = arrayTitles
setupHeaderSectionWithControls()
}
fileprivate func setupHeaderSectionWithControls() {
sectionTitles.insert("", at: 0)
filteredUsersWithSection.insert([User](), at: 0)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return actions.count
} else {
return filteredUsersWithSection[section].count
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 65
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionTitles[section]
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return sectionTitles
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = ThemeManager.currentTheme().generalBackgroundColor
if let headerTitle = view as? UITableViewHeaderFooterView {
headerTitle.textLabel?.textColor = ThemeManager.currentTheme().generalTitleColor
headerTitle.textLabel?.font = UIFont.boldSystemFont(ofSize: 12)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 25
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return selectCell(for: indexPath)
}
func selectCell(for indexPath: IndexPath) -> UITableViewCell {
let headerSection = 0
if indexPath.section == headerSection {
let defaultCell = UITableViewCell(style: .default, reuseIdentifier: newGroupCellID)
let cell = tableView.dequeueReusableCell(withIdentifier: newGroupCellID) ?? defaultCell
cell.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor
cell.imageView?.image = UIImage(named: "groupChat")
cell.imageView?.contentMode = .scaleAspectFit
cell.textLabel?.font = UIFont.systemFont(ofSize: 17)
cell.textLabel?.text = actions[indexPath.row]
cell.textLabel?.textColor = ThemeManager.currentTheme().controlButtonTintColor
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: falconUsersCellID,
for: indexPath) as? FalconUsersTableViewCell ?? FalconUsersTableViewCell()
let falconUser = filteredUsersWithSection[indexPath.section][indexPath.row]
cell.configureCell(for: falconUser)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
searchBar?.resignFirstResponder()
if indexPath.section == 0 {
let destination = SelectGroupMembersController()
let users = blacklistManager.removeBannedUsers(users: RealmKeychain.realmUsersArray())
destination.users = users
destination.filteredUsers = users
destination.setUpCollation()
self.navigationController?.pushViewController(destination, animated: true)
} else {
let falconUser = filteredUsersWithSection[indexPath.section][indexPath.row]
guard let currentUserID = Auth.auth().currentUser?.uid else { return }
guard let id = falconUser.id, let conversation = RealmKeychain.defaultRealm.objects(Conversation.self).filter("chatID == %@", id).first else {
let conversationDictionary = ["chatID": falconUser.id as AnyObject,
"chatName": falconUser.name as AnyObject,
"isGroupChat": false as AnyObject,
"chatOriginalPhotoURL": falconUser.photoURL as AnyObject,
"chatThumbnailPhotoURL": falconUser.thumbnailPhotoURL as AnyObject,
"chatParticipantsIDs": [falconUser.id, currentUserID] as AnyObject]
let conversation = Conversation(dictionary: conversationDictionary)
chatLogPresenter.open(conversation, controller: self)
return
}
chatLogPresenter.open(conversation, controller: self)
}
}
}
| gpl-3.0 | 66e2ded13bbefc09001f4b8afe7d3eda | 35.706897 | 145 | 0.716416 | 5.170613 | false | false | false | false |
iOkay/MiaoWuWu | Pods/Material/Sources/iOS/Layout.swift | 1 | 40375 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public class Layout {
/// Parent UIView context.
internal weak var parent: UIView?
/// Child UIView context.
internal weak var child: UIView?
/**
An initializer that takes in a parent context.
- Parameter parent: An optional parent UIView.
*/
public init(parent: UIView?) {
self.parent = parent
}
/**
An initializer that takes in a parent context and child context.
- Parameter parent: An optional parent UIView.
- Parameter child: An optional child UIView.
*/
public init(parent: UIView?, child: UIView?) {
self.parent = parent
self.child = child
}
/**
Prints a debug message when the parent context is not available.
- Parameter function: A String representation of the function that
caused the issue.
- Returns: The current Layout instance.
*/
internal func debugParentNotAvailableMessage(function: String = #function) -> Layout {
debugPrint("[Material Layout Error: Parent view context is not available for \(function).")
return self
}
/**
Prints a debug message when the child context is not available.
- Parameter function: A String representation of the function that
caused the issue.
- Returns: The current Layout instance.
*/
internal func debugChildNotAvailableMessage(function: String = #function) -> Layout {
debugPrint("[Material Layout Error: Child view context is not available for \(function).")
return self
}
/**
Sets the width of a view.
- Parameter child: A child UIView to layout.
- Parameter width: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func width(_ child: UIView, width: CGFloat) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.width(parent: v, child: child, width: width)
return self
}
/**
Sets the width of a view assuming a child context view.
- Parameter width: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func width(_ width: CGFloat) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.width(v, width: width)
}
/**
Sets the height of a view.
- Parameter child: A child UIView to layout.
- Parameter height: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func height(_ child: UIView, height: CGFloat) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.height(parent: v, child: child, height: height)
return self
}
/**
Sets the height of a view assuming a child context view.
- Parameter height: A CGFloat value.
- Returns: The current Layout instance.
*/
@discardableResult
public func height(_ height: CGFloat) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.height(v, height: height)
}
/**
Sets the width and height of a view.
- Parameter child: A child UIView to layout.
- Parameter size: A CGSize value.
- Returns: The current Layout instance.
*/
@discardableResult
public func size(_ child: UIView, size: CGSize) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.size(parent: v, child: child, size: size)
return self
}
/**
Sets the width and height of a view assuming a child context view.
- Parameter size: A CGSize value.
- Returns: The current Layout instance.
*/
@discardableResult
public func size(_ size: CGSize = CGSize.zero) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.size(v, size: size)
}
/**
A collection of children views are horizontally stretched with optional left,
right padding and interim interimSpace.
- Parameter children: An Array UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(_ children: [UIView], left: CGFloat = 0, right: CGFloat = 0, interimSpace: InterimSpace = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
Layout.horizontally(parent: v, children: children, left: left, right: right, interimSpace: interimSpace)
return self
}
/**
A collection of children views are vertically stretched with optional top,
bottom padding and interim interimSpace.
- Parameter children: An Array UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(_ children: [UIView], top: CGFloat = 0, bottom: CGFloat = 0, interimSpace: InterimSpace = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
Layout.vertically(parent: v, children: children, top: top, bottom: bottom, interimSpace: interimSpace)
return self
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(_ child: UIView, left: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.horizontally(parent: v, child: child, left: left, right: right)
return self
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func horizontally(left: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return horizontally(v, left: left, right: right)
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(_ child: UIView, top: CGFloat = 0, bottom: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.vertically(parent: v, child: child, top: top, bottom: bottom)
return self
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func vertically(top: CGFloat = 0, bottom: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return vertically(v, top: top, bottom: bottom)
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func edges(_ child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.edges(parent: v, child: child, top: top, left: left, bottom: bottom, right: right)
return self
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func edges(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return edges(v, top: top, left: left, bottom: bottom, right: right)
}
/**
A child view is aligned from the top with optional top padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
@discardableResult
public func top(_ child: UIView, top: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.top(parent: v, child: child, top: top)
return self
}
/**
A child view is aligned from the top with optional top padding.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
@discardableResult
public func top(_ top: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.top(v, top: top)
}
/**
A child view is aligned from the left with optional left padding.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func left(_ child: UIView, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.left(parent: v, child: child, left: left)
return self
}
/**
A child view is aligned from the left with optional left padding.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func left(_ left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.left(v, left: left)
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottom(_ child: UIView, bottom: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottom(parent: v, child: child, bottom: bottom)
return self
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottom(_ bottom: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.bottom(v, bottom: bottom)
}
/**
A child view is aligned from the right with optional right padding.
- Parameter child: A child UIView to layout.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func right(_ child: UIView, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.right(parent: v, child: child, right: right)
return self
}
/**
A child view is aligned from the right with optional right padding.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func right(_ right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return self.right(v, right: right)
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topLeft(_ child: UIView, top: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.topLeft(parent: v, child: child, top: top, left: left)
return self
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topLeft(top: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return topLeft(v, top: top, left: left)
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topRight(_ child: UIView, top: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.topRight(parent: v, child: child, top: top, right: right)
return self
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func topRight(top: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return topRight(v, top: top, right: right)
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomLeft(_ child: UIView, bottom: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottomLeft(parent: v, child: child, bottom: bottom, left: left)
return self
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomLeft(bottom: CGFloat = 0, left: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return bottomLeft(v, bottom: bottom, left: left)
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomRight(_ child: UIView, bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.bottomRight(parent: v, child: child, bottom: bottom, right: right)
return self
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
@discardableResult
public func bottomRight(bottom: CGFloat = 0, right: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return bottomRight(v, bottom: bottom, right: right)
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter child: A child UIView to layout.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func center(_ child: UIView, offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.center(parent: v, child: child, offsetX: offsetX, offsetY: offsetY)
return self
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func center(offsetX: CGFloat = 0, offsetY: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return center(v, offsetX: offsetX, offsetY: offsetY)
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the x axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerHorizontally(_ child: UIView, offset: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.centerHorizontally(parent: v, child: child, offset: offset)
return self
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter offset: A CGFloat value for the offset along the x axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerHorizontally(offset: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return centerHorizontally(v, offset: offset)
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerVertically(_ child: UIView, offset: CGFloat = 0) -> Layout {
guard let v = parent else {
return debugParentNotAvailableMessage()
}
self.child = child
Layout.centerVertically(parent: v, child: child, offset: offset)
return self
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
@discardableResult
public func centerVertically(offset: CGFloat = 0) -> Layout {
guard let v = child else {
return debugChildNotAvailableMessage()
}
return centerVertically(v, offset: offset)
}
}
/// Layout
extension Layout {
/**
Sets the width of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter width: A CGFloat value.
*/
public class func width(parent: UIView, child: UIView, width: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: width))
}
/**
Sets the height of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter height: A CGFloat value.
*/
public class func height(parent: UIView, child: UIView, height: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: height))
}
/**
Sets the width and height of a view.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter size: A CGSize value.
*/
public class func size(parent: UIView, child: UIView, size: CGSize = CGSize.zero) {
Layout.width(parent: parent, child: child, width: size.width)
Layout.height(parent: parent, child: child, height: size.height)
}
/**
A collection of children views are horizontally stretched with optional left,
right padding and interim interimSpace.
- Parameter parent: A parent UIView context.
- Parameter children: An Array UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
*/
public class func horizontally(parent: UIView, children: [UIView], left: CGFloat = 0, right: CGFloat = 0, interimSpace: InterimSpace = 0) {
prepareForConstraint(parent, children: children)
if 0 < children.count {
parent.addConstraint(NSLayoutConstraint(item: children[0], attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
for i in 1..<children.count {
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .left, relatedBy: .equal, toItem: children[i - 1], attribute: .right, multiplier: 1, constant: interimSpace))
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .width, relatedBy: .equal, toItem: children[0], attribute: .width, multiplier: 1, constant: 0))
}
parent.addConstraint(NSLayoutConstraint(item: children[children.count - 1], attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
}
}
/**
A collection of children views are vertically stretched with optional top,
bottom padding and interim interimSpace.
- Parameter parent: A parent UIView context.
- Parameter children: An Array UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter interimSpace: A CGFloat value for interim interimSpace.
*/
public class func vertically(parent: UIView, children: [UIView], top: CGFloat = 0, bottom: CGFloat = 0, interimSpace: InterimSpace = 0) {
prepareForConstraint(parent, children: children)
if 0 < children.count {
parent.addConstraint(NSLayoutConstraint(item: children[0], attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
for i in 1..<children.count {
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .top, relatedBy: .equal, toItem: children[i - 1], attribute: .bottom, multiplier: 1, constant: interimSpace))
parent.addConstraint(NSLayoutConstraint(item: children[i], attribute: .height, relatedBy: .equal, toItem: children[0], attribute: .height, multiplier: 1, constant: 0))
}
parent.addConstraint(NSLayoutConstraint(item: children[children.count - 1], attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
}
}
/**
A child view is horizontally stretched with optional left and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Parameter right: A CGFloat value for padding the right side.
*/
public class func horizontally(parent: UIView, child: UIView, left: CGFloat = 0, right: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
}
/**
A child view is vertically stretched with optional left and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter bottom: A CGFloat value for padding the bottom side.
*/
public class func vertically(parent: UIView, child: UIView, top: CGFloat = 0, bottom: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
}
/**
A child view is vertically and horizontally stretched with optional top, left, bottom and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
*/
public class func edges(parent: UIView, child: UIView, top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {
horizontally(parent: parent, child: child, left: left, right: right)
vertically(parent: parent, child: child, top: top, bottom: bottom)
}
/**
A child view is aligned from the top with optional top padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Returns: The current Layout instance.
*/
public class func top(parent: UIView, child: UIView, top: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1, constant: top))
}
/**
A child view is aligned from the left with optional left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func left(parent: UIView, child: UIView, left: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .left, relatedBy: .equal, toItem: parent, attribute: .left, multiplier: 1, constant: left))
}
/**
A child view is aligned from the bottom with optional bottom padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Returns: The current Layout instance.
*/
public class func bottom(parent: UIView, child: UIView, bottom: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1, constant: -bottom))
}
/**
A child view is aligned from the right with optional right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func right(parent: UIView, child: UIView, right: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .right, relatedBy: .equal, toItem: parent, attribute: .right, multiplier: 1, constant: -right))
}
/**
A child view is aligned from the top left with optional top and left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func topLeft(parent: UIView, child: UIView, top t: CGFloat = 0, left l: CGFloat = 0) {
top(parent: parent, child: child, top: t)
left(parent: parent, child: child, left: l)
}
/**
A child view is aligned from the top right with optional top and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter top: A CGFloat value for padding the top side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func topRight(parent: UIView, child: UIView, top t: CGFloat = 0, right r: CGFloat = 0) {
top(parent: parent, child: child, top: t)
right(parent: parent, child: child, right: r)
}
/**
A child view is aligned from the bottom left with optional bottom and left padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter left: A CGFloat value for padding the left side.
- Returns: The current Layout instance.
*/
public class func bottomLeft(parent: UIView, child: UIView, bottom b: CGFloat = 0, left l: CGFloat = 0) {
bottom(parent: parent, child: child, bottom: b)
left(parent: parent, child: child, left: l)
}
/**
A child view is aligned from the bottom right with optional bottom and right padding.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter bottom: A CGFloat value for padding the bottom side.
- Parameter right: A CGFloat value for padding the right side.
- Returns: The current Layout instance.
*/
public class func bottomRight(parent: UIView, child: UIView, bottom b: CGFloat = 0, right r: CGFloat = 0) {
bottom(parent: parent, child: child, bottom: b)
right(parent: parent, child: child, right: r)
}
/**
A child view is aligned at the center with an optional offsetX and offsetY value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offsetX: A CGFloat value for the offset along the x axis.
- Parameter offsetX: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func center(parent: UIView, child: UIView, offsetX: CGFloat = 0, offsetY: CGFloat = 0) {
centerHorizontally(parent: parent, child: child, offset: offsetX)
centerVertically(parent: parent, child: child, offset: offsetY)
}
/**
A child view is aligned at the center horizontally with an optional offset value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func centerHorizontally(parent: UIView, child: UIView, offset: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .centerX, relatedBy: .equal, toItem: parent, attribute: .centerX, multiplier: 1, constant: offset))
}
/**
A child view is aligned at the center vertically with an optional offset value.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
- Parameter offset: A CGFloat value for the offset along the y axis.
- Returns: The current Layout instance.
*/
public class func centerVertically(parent: UIView, child: UIView, offset: CGFloat = 0) {
prepareForConstraint(parent, child: child)
parent.addConstraint(NSLayoutConstraint(item: child, attribute: .centerY, relatedBy: .equal, toItem: parent, attribute: .centerY, multiplier: 1, constant: offset))
}
/**
Creats an Array with a NSLayoutConstraint value.
- Parameter format: The VFL format string.
- Parameter options: Additional NSLayoutFormatOptions.
- Parameter metrics: An optional Dictionary<String, Any> of metric key / value pairs.
- Parameter views: A Dictionary<String, Any> of view key / value pairs.
- Returns: The Array<NSLayoutConstraint> instance.
*/
public class func constraint(format: String, options: NSLayoutFormatOptions, metrics: [String: Any]?, views: [String: Any]) -> [NSLayoutConstraint] {
for (_, a) in views {
if let v = a as? UIView {
v.translatesAutoresizingMaskIntoConstraints = false
}
}
return NSLayoutConstraint.constraints(
withVisualFormat: format,
options: options,
metrics: metrics,
views: views
)
}
/**
Prepares the relationship between the parent view context and child view
to layout. If the child is not already added to the view hierarchy as the
parent's child, then it is added.
- Parameter parent: A parent UIView context.
- Parameter child: A child UIView to layout.
*/
private class func prepareForConstraint(_ parent: UIView, child: UIView) {
if parent != child.superview {
child.removeFromSuperview()
parent.addSubview(child)
}
child.translatesAutoresizingMaskIntoConstraints = false
}
/**
Prepares the relationship between the parent view context and an Array of
child UIViews.
- Parameter parent: A parent UIView context.
- Parameter children: An Array of UIViews.
*/
private class func prepareForConstraint(_ parent: UIView, children: [UIView]) {
for v in children {
prepareForConstraint(parent, child: v)
}
}
}
/// A memory reference to the LayoutKey instance for UIView extensions.
private var LayoutKey: UInt8 = 0
/// Layout extension for UIView.
extension UIView {
/// Layout reference.
public private(set) var layout: Layout {
get {
return AssociatedObject(base: self, key: &LayoutKey) {
return Layout(parent: self)
}
}
set(value) {
AssociateObject(base: self, key: &LayoutKey, value: value)
}
}
/**
Used to chain layout constraints on a child context.
- Parameter child: A child UIView to layout.
- Returns: The current Layout instance.
*/
public func layout(_ child: UIView) -> Layout {
return Layout(parent: self, child: child)
}
}
| gpl-3.0 | bb61840db35708f24403c40b589ed7e6 | 41.057292 | 197 | 0.655282 | 4.781502 | false | false | false | false |
techmehra/AJCountryPicker | AJCountryPicker/ViewController.swift | 1 | 1585 | //
// ViewController.swift
// AjCountryPicker
//
// Created by Ajay Mehra on 06/08/18.
// Copyright ยฉ 2018 Aisha Technologies. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet private var displayLabel: UILabel!
@IBAction private func selectCountry(_ sender: UIButton) {
let countryPicker = AJCountryPicker()
countryPicker.showSearchBar = true
countryPicker.showCallingCodes = true
countryPicker.country = {
self.displayLabel.text = "You have selected " + $0.name + "with ISO Code" + $0.ISOCode + "Your Calling code is " + $0.callingCode
}
navigationController?.pushViewController(countryPicker, animated: true)
}
@IBAction private func selectCountryWithCustomCodes(_ sender: UIButton) {
let countryPicker = AJCountryPicker()
countryPicker.showSearchBar = true
countryPicker.customCountriesCodes = ["IN", "US"]
countryPicker.showCallingCodes = true
countryPicker.country = {
self.displayLabel.text = "You have selected " + $0.name + "with ISO Code" + $0.ISOCode + "Your Calling code is " + $0.callingCode
}
navigationController?.pushViewController(countryPicker, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | fd65632e0dac90e3399b3f62c7fd61e5 | 32 | 141 | 0.669823 | 4.785498 | false | false | false | false |
richardpiazza/SOSwift | Sources/SOSwift/ItemAvailability.swift | 1 | 960 | import Foundation
/// A list of possible product availability options.
public enum ItemAvailability: String, CaseIterable, Codable {
case discontinued = "Discontinued"
case inStock = "InStock"
case inStoreOnly = "InStoreOnly"
case limitedAvailability = "LimitedAvailability"
case onlineOnly = "OnlineOnly"
case outOfStock = "OutOfStock"
case preOrder = "PreOrder"
case preSale = "PreSale"
case soldOut = "SoldOut"
public var displayValue: String {
switch self {
case .discontinued: return "Discontinued"
case .inStock: return "In Stock"
case .inStoreOnly: return "In Store Only"
case .limitedAvailability: return "Limited Availability"
case .onlineOnly: return "Online Only"
case .outOfStock: return "Out of Stock"
case .preOrder: return "Pre-Order"
case .preSale: return "Pre-Sale"
case .soldOut: return "Sold Out"
}
}
}
| mit | 44d9b3c2671c8dff6324d097f6ed7216 | 33.285714 | 64 | 0.661458 | 4.210526 | false | false | false | false |
allbto/ios-swiftility | Swiftility/Sources/Extensions/UIKit/UIViewControllerExtensions.swift | 2 | 9094 | //
// UIViewControllerExtensions.swift
// Swiftility
//
// Created by Allan Barbato on 9/25/15.
// Copyright ยฉ 2015 Allan Barbato. All rights reserved.
//
import UIKit
import ObjectiveC
// MARK: - Alert
extension UIViewController
{
public typealias UIAlertControllerButtonHandler = ((UIAlertAction) -> Void)
public func alert(_ message: String,
title: String? = nil,
cancelTitle: String = "OK",
cancelHandler: UIAlertControllerButtonHandler? = nil)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: cancelHandler)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
public func ask(_ message: String,
title: String? = nil,
okTitle: String = "OK",
cancelTitle: String = "Cancel",
okHandler: UIAlertControllerButtonHandler? = nil,
cancelHandler: UIAlertControllerButtonHandler? = nil)
{
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: cancelHandler)
alertController.addAction(cancelAction)
let okAction = UIAlertAction(title: okTitle, style: .default, handler: okHandler)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
// MARK: - Keyboard
extension UIViewController
{
public typealias KeyboardUpdateClosure = ((_ size: CGSize, _ notification: Notification) -> Void)
/**
Subscribe to keyboard updates notifications.
- parameter update: Closure called when keyboard change frame or hide. One can update constraints and then call self.animate(withKeyboardNotification:)
*/
public func observeKeyboardChanges(_ update: @escaping KeyboardUpdateClosure) -> [NSObjectProtocol]
{
return NotificationCenter
.default
.addObserver(withNames: [NSNotification.Name.UIKeyboardWillChangeFrame, NSNotification.Name.UIKeyboardWillHide]) { n in
guard
let userInfo = n.userInfo,
let keyboardSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size
else { return }
update(keyboardSize, n)
}
}
/**
Perform animations with the same settings as the notification's animation settings.
Performs animations only if `notification` is a valid UIKeyboardXXXNotification.
- parameter notification: UIKeyboardXXXNotification. Such as UIKeyboardWillChangeFrameNotification for example
- parameter animations: Optional custom animations to perform. Default is { self.view.layoutIfNeeded() }
- parameter completion: Optional completion handler to animations
*/
public func animate(withKeyboardNotification notification: Notification,
animations: (() -> Void)? = nil,
completion: ((Bool) -> Void)? = nil)
{
guard
let userInfo = notification.userInfo,
let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let curve = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uint32Value
else { return }
let options = UIViewAnimationOptions(rawValue: UInt(curve) << 16)
UIView.animate(
withDuration: duration,
delay: 0,
options: options,
animations: {
if let animations = animations {
animations()
} else {
self.view.layoutIfNeeded()
}
},
completion: completion
)
}
/*
Usage example:
let observers = self.observeKeyboardChanges { [weak self] keyboardSize, n in
self?.someConstraints.constant = keyboardSize.height
self?.animate(withKeyboardNotification: n)
}
*/
}
// MARK: - Convenience setup
private var NotificationObserversKey: StaticString = "SW_NotificationObserversKey"
private var PermanentNotificationObserversKey: StaticString = "SW_PermanentNotificationObserversKey"
private var ViewHasLoadedObserversKey: StaticString = "SW_ViewHasLoadedObserversKey"
private var ViewHasAppearedObserversKey: StaticString = "SW_ViewHasAppearedObserversKey"
extension UIViewController
{
// MARK: - Private Properties
fileprivate var _notificationObservers: [NSObjectProtocol]? {
get { return objc_getAssociatedObject(self, &NotificationObserversKey) as? [NSObjectProtocol] }
set { objc_setAssociatedObject(self, &NotificationObserversKey, newValue as [NSObjectProtocol]?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
fileprivate var _permanentNotificationObservers: [NSObjectProtocol]? {
get { return objc_getAssociatedObject(self, &PermanentNotificationObserversKey) as? [NSObjectProtocol] }
set { objc_setAssociatedObject(self, &PermanentNotificationObserversKey, newValue as [NSObjectProtocol]?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
// MARK: - Public Properties
public fileprivate(set) var viewHasLoaded: Bool {
get { return (objc_getAssociatedObject(self, &ViewHasLoadedObserversKey) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &ViewHasLoadedObserversKey, newValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
public fileprivate(set) var viewHasAppeared: Bool {
get { return (objc_getAssociatedObject(self, &ViewHasAppearedObserversKey) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &ViewHasAppearedObserversKey, newValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
// MARK: - Life cycle
internal static func _setupSwizzle()
{
guard self === UIViewController.self else { return }
once(token: "com.swiftility.UIViewControllerInitialize") {
swizzle(#selector(UIViewController.viewDidLoad), with: #selector(UIViewController.sw_viewDidLoad), on: self)
swizzle(#selector(UIViewController.viewWillAppear(_:)), with: #selector(UIViewController.sw_viewWillAppear(_:)), on: self)
swizzle(#selector(UIViewController.viewWillDisappear(_:)), with: #selector(UIViewController.sw_viewWillDisappear(_:)), on: self)
swizzle(#selector(UIViewController.viewDidAppear(_:)), with: #selector(UIViewController.sw_viewDidAppear(_:)), on: self)
swizzle(#selector(UIViewController.viewDidDisappear(_:)), with: #selector(UIViewController.sw_viewDidDisappear(_:)), on: self)
}
}
@objc private func sw_viewDidLoad()
{
viewHasLoaded = true
self.sw_viewDidLoad()
let observers = self.sw_setupPermanentNotificationObservers()
if !observers.isEmpty {
_permanentNotificationObservers = observers
}
}
@objc private func sw_viewWillAppear(_ animated: Bool)
{
self.sw_viewWillAppear(animated)
let observers = self.sw_setupActiveNotificationObservers()
if !observers.isEmpty {
_notificationObservers = observers
}
}
@objc private func sw_viewWillDisappear(_ animated: Bool)
{
self.sw_viewWillDisappear(animated)
if let observers = _notificationObservers, !observers.isEmpty {
NotificationCenter.default.removeObservers(observers)
}
}
@objc private func sw_viewDidAppear(_ animated: Bool)
{
viewHasAppeared = true
self.sw_viewDidAppear(animated)
}
@objc private func sw_viewDidDisappear(_ animated: Bool)
{
viewHasAppeared = false
self.sw_viewDidDisappear(animated)
}
// MARK: - Open methods
/// Notification observers setup when view appears and removed when view disappears
@objc open func sw_setupActiveNotificationObservers() -> [NSObjectProtocol]
{
return [] // To be overriden
}
/// Notification observers setup on view load and removed on deinit
/// Don't forget to call self.sw_removePermanentObservers() on class deinit
@objc open func sw_setupPermanentNotificationObservers() -> [NSObjectProtocol]
{
return [] // To be overriden
}
// MARK: - Utils
public func sw_removePermanentObservers()
{
if let observers = _permanentNotificationObservers, !observers.isEmpty {
NotificationCenter.default.removeObservers(observers)
}
}
}
| mit | 89a788a78ebc796f3f01254229a7d1ee | 37.046025 | 156 | 0.646541 | 5.595692 | false | false | false | false |
vipu1212/GhostPrompt | Example/GhostPrompt/SampleViewController.swift | 1 | 872 | //
// SampleViewController.swift
// GhostPrompt
//
// Created by Divyansh Singh on 24/02/16.
// Copyright ยฉ 2016 Servify. All rights reserved.
//
import UIKit
import GhostPrompt
class SampleViewController: UIViewController {
@IBOutlet weak var firstView: UIView!
override func viewDidLoad() {
}
@IBAction func clickedDirection(sender : UIButton) {
var direction = UIView.Direction.Bottom
switch sender.restorationIdentifier! {
case "top" : direction = .Top
case "bottom" : direction = .Bottom
case "left" : direction = .Left
case "right" : direction = .Right
default : break
}
let prompt = GhostPrompt(height: 55, ParentView: self.view)
prompt.appearingDirection = direction
prompt.showMessage(Message: "Boooo")
}
} | mit | e3634617033603b0208dec4e4ea00633 | 23.914286 | 67 | 0.621125 | 4.536458 | false | false | false | false |
luckymarmot/ThemeKit | Demo/Demo/WindowController.swift | 1 | 5058 | //
// WindowController.swift
// Demo
//
// Created by Nuno Grilo on 29/09/2016.
// Copyright ยฉ 2016 Paw & Nuno Grilo. All rights reserved.
//
import Cocoa
import ThemeKit
class WindowController: NSWindowController {
@objc public var themeKit: ThemeManager = ThemeManager.shared
override func windowDidLoad() {
// Observe note selection change notifications
NotificationCenter.default.addObserver(forName: .didChangeNoteSelection, object: nil, queue: nil) { (notification) in
let obj = notification.object
if let note = notification.userInfo?["note"] as? Note,
let viewController = obj as? NSViewController,
viewController.view.window == self.window {
self.updateTitle(note)
}
}
// Observe note text edit notifications
NotificationCenter.default.addObserver(forName: .didEditNoteText, object: nil, queue: nil) { (notification) in
let obj = notification.object
if let note = notification.userInfo?["note"] as? Note,
let viewController = obj as? NSViewController,
viewController.view.window == self.window {
self.updateTitle(note)
}
}
// Observe theme change notifications
NotificationCenter.default.addObserver(forName: .didChangeTheme, object: nil, queue: nil) { (_) in
// update KVO property
self.willChangeValue(forKey: "canEditTheme")
self.didChangeValue(forKey: "canEditTheme")
}
}
/// Add titlebar overlay view.
override func awakeFromNib() {
super.awakeFromNib()
if let titlebarView = self.titlebarView {
// create titlebar background overlay view
let overlayView = TitleBarOverlayView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
overlayView.translatesAutoresizingMaskIntoConstraints = false
// add overlay view below everything else
titlebarView.addSubview(overlayView, positioned: .below, relativeTo: nil)
// add constraints
let constraintViews = ["view": overlayView]
titlebarView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[view]-0-|", options: [NSLayoutConstraint.FormatOptions.directionLeadingToTrailing], metrics: nil, views: constraintViews))
titlebarView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]-0-|", options: [NSLayoutConstraint.FormatOptions.directionLeadingToTrailing], metrics: nil, views: constraintViews))
// refresh it when key flag changes
NotificationCenter.default.addObserver(forName: NSWindow.didBecomeKeyNotification, object: window, queue: nil, using: { _ in
overlayView.needsDisplay = true
})
NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: nil, using: { _ in
overlayView.needsDisplay = true
})
}
}
/// Find `NSTitlebarContainerView` view.
private var titlebarView: NSView? {
if let themeFrame = self.window?.contentView?.superview {
for subview in themeFrame.subviews where subview.className == "NSTitlebarContainerView" {
return subview.subviews.first { $0.className == "NSTitlebarView" }
}
}
return nil
}
/// Update window title with current note title.
@objc func updateTitle(_ note: Note) {
self.window?.title = "\(note.title) - ThemeKit Demo"
}
/// Can edit current theme (must be a `UserTheme`).
@objc var canEditTheme: Bool {
return ThemeManager.shared.theme.isUserTheme
}
/// Edit current (`UserTheme`) theme.
@IBAction func editTheme(_ sender: Any) {
if ThemeManager.shared.theme.isUserTheme,
let userTheme = ThemeManager.shared.theme as? UserTheme,
let userThemeURL = userTheme.fileURL {
guard FileManager.default.isWritableFile(atPath: userThemeURL.path) else {
let alert = NSAlert()
alert.messageText = "Theme file is not writable."
alert.informativeText = "If you're lunching Demo from the Downloads folder, move it to another place and try again."
alert.alertStyle = NSAlert.Style.critical
alert.addButton(withTitle: "OK")
alert.runModal()
return
}
// check if there is any app associted with `.theme` extension
let userThemeCFURL: CFURL = userThemeURL as CFURL
if LSCopyDefaultApplicationURLForURL(userThemeCFURL, .editor, nil) != nil {
NSWorkspace.shared.open(userThemeURL)
} else {
// otherwise open with TextEdit
NSWorkspace.shared.openFile(userThemeURL.path, withApplication: "TextEdit", andDeactivate: true)
}
}
}
}
| mit | 84fde1e2094916b6193299a4c61eb3a2 | 41.141667 | 219 | 0.632984 | 5.144456 | false | false | false | false |
johnoppenheimer/epiquote-ios | EpiquoteSwift/sections/QuoteSectionController.swift | 1 | 1833 | //
// QuoteSectionController.swift
// EpiquoteSwift
//
// Created by Maxime Cattet on 17/11/2016.
//
//
import UIKit
import IGListKit
class QuoteSectionController: IGListSectionController, IGListSectionType {
var quote: Quote?
var color: UIColor = UIColor.random()
func numberOfItems() -> Int {
return 2
}
func sizeForItem(at index: Int) -> CGSize {
let width = self.collectionContext!.containerSize.width
switch index {
case 0:
let height = Utilities.textHeight(with: self.quote!.context!, width: width, font: UIFont.systemFont(ofSize: 12.0))
return CGSize(width: width, height: height)
default:
let height: CGFloat = Utilities.textHeight(with: self.quote!.content, width: width, insets: UIEdgeInsetsMake(10, 15, 15, 10), font: UIFont.systemFont(ofSize: 14.0))
return CGSize(width: width, height: height + 5)
}
}
func cellForItem(at index: Int) -> UICollectionViewCell {
if index == 0 {
let cell = self.collectionContext?.dequeueReusableCell(of: ContextCollectionViewCell.self, for: self, at: index) as! ContextCollectionViewCell
cell.textLabel.text = self.quote!.context
cell.colorBlockView.backgroundColor = self.color
return cell
}
else {
let cell = self.collectionContext?.dequeueReusableCell(of: ContentCollectionViewCell.self, for: self, at: index) as! ContentCollectionViewCell
cell.textView.text = self.quote!.content
cell.colorBlockView.backgroundColor = self.color
return cell
}
}
func didUpdate(to object: Any) {
self.quote = object as? Quote
}
func didSelectItem(at index: Int) {}
}
| mit | 0f4c859b9d016efa291eba6e084729ea | 32.327273 | 176 | 0.627387 | 4.628788 | false | false | false | false |
kumapo/RxSwiftTestSchedulerExample | RxSwiftTestSchedulerExample/ViewModel.swift | 1 | 781 | //
// Created by kumapo on 2015/10/23.
// Copyright ยฉ 2015ๅนด kumapo. All rights reserved.
//
import RxSwift
enum State: Int {
case Empty = 0
case InProgress
case Success
case Error
}
class ViewModel: NSObject {
var state: Variable<State> = Variable(.Empty)
var disposeBag = DisposeBag()
var client: Fetchable {
return RestfulClient.sharedInstance
}
func load() -> Observable<Int> {
self.state.value = .InProgress
return client
.fetch()
.doOn(
onNext: { [unowned self] (_) in
self.state.value = .Success
},
onError: { [unowned self] (_) in
self.state.value = .Error
})
}
} | mit | 0666467061de019c79b95479f199c63f | 20.638889 | 50 | 0.521851 | 4.39548 | false | false | false | false |
yanagiba/swift-transform | Sources/Transform/Generator.swift | 1 | 15753 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import AST
open class Generator {
let _options: [String: Any]?
let _tokenizer: Tokenizer
let _tokenJoiner: TokenJoiner
public init(
options: [String: Any]? = nil,
tokenizer: Tokenizer = Tokenizer(),
tokenJoiner: TokenJoiner = TokenJoiner())
{
_options = options
_tokenizer = tokenizer
_tokenJoiner = tokenJoiner
}
open func generate(_ topLevelDeclaration: TopLevelDeclaration) -> String {
let tokens = _tokenizer.tokenize(topLevelDeclaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ codeBlock: CodeBlock) -> String {
let tokens = _tokenizer.tokenize(codeBlock)
return _tokenJoiner.join(tokens: tokens)
}
// MARK: Statements
open func generate(_ statement: Statement) -> String { // swift-lint:suppress(high_cyclomatic_complexity)
switch statement {
case let decl as Declaration:
return generate(decl)
case let expr as Expression:
return generate(expr)
case let stmt as BreakStatement:
return generate(stmt)
case let stmt as CompilerControlStatement:
return generate(stmt)
case let stmt as ContinueStatement:
return generate(stmt)
case let stmt as DeferStatement:
return generate(stmt)
case let stmt as DoStatement:
return generate(stmt)
case let stmt as FallthroughStatement:
return generate(stmt)
case let stmt as ForInStatement:
return generate(stmt)
case let stmt as GuardStatement:
return generate(stmt)
case let stmt as IfStatement:
return generate(stmt)
case let stmt as LabeledStatement:
return generate(stmt)
case let stmt as RepeatWhileStatement:
return generate(stmt)
case let stmt as ReturnStatement:
return generate(stmt)
case let stmt as SwitchStatement:
return generate(stmt)
case let stmt as ThrowStatement:
return generate(stmt)
case let stmt as WhileStatement:
return generate(stmt)
default:
return statement.textDescription
}
}
open func generate(_ statement: BreakStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: CompilerControlStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: ContinueStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: DeferStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: DoStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: FallthroughStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: ForInStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: GuardStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: IfStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: LabeledStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: RepeatWhileStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: ReturnStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: SwitchStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: ThrowStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ statement: WhileStatement) -> String {
let tokens = _tokenizer.tokenize(statement)
return _tokenJoiner.join(tokens: tokens)
}
// MARK: Declarations
open func generate(_ declaration: Declaration) -> String { // swift-lint:suppress(high_cyclomatic_complexity)
switch declaration {
case let decl as ClassDeclaration:
return generate(decl)
case let decl as ConstantDeclaration:
return generate(decl)
case let decl as DeinitializerDeclaration:
return generate(decl)
case let decl as EnumDeclaration:
return generate(decl)
case let decl as ExtensionDeclaration:
return generate(decl)
case let decl as FunctionDeclaration:
return generate(decl)
case let decl as ImportDeclaration:
return generate(decl)
case let decl as InitializerDeclaration:
return generate(decl)
case let decl as OperatorDeclaration:
return generate(decl)
case let decl as PrecedenceGroupDeclaration:
return generate(decl)
case let decl as ProtocolDeclaration:
return generate(decl)
case let decl as StructDeclaration:
return generate(decl)
case let decl as SubscriptDeclaration:
return generate(decl)
case let decl as TypealiasDeclaration:
return generate(decl)
case let decl as VariableDeclaration:
return generate(decl)
default:
return declaration.textDescription // no implementation for this declaration, just continue
}
}
open func generate(_ declaration: ClassDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: ConstantDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: DeinitializerDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: EnumDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: ExtensionDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: FunctionDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: ImportDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: InitializerDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: OperatorDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: PrecedenceGroupDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: ProtocolDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: StructDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: SubscriptDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: TypealiasDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ declaration: VariableDeclaration) -> String {
let tokens = _tokenizer.tokenize(declaration)
return _tokenJoiner.join(tokens: tokens)
}
// MARK: Expressions
open func generate(_ expression: Expression) -> String { /*
swift-lint:suppress(high_cyclomatic_complexity, high_ncss) */
switch expression {
case let expr as AssignmentOperatorExpression:
return generate(expr)
case let expr as BinaryOperatorExpression:
return generate(expr)
case let expr as ClosureExpression:
return generate(expr)
case let expr as ExplicitMemberExpression:
return generate(expr)
case let expr as ForcedValueExpression:
return generate(expr)
case let expr as FunctionCallExpression:
return generate(expr)
case let expr as IdentifierExpression:
return generate(expr)
case let expr as ImplicitMemberExpression:
return generate(expr)
case let expr as InOutExpression:
return generate(expr)
case let expr as InitializerExpression:
return generate(expr)
case let expr as KeyPathStringExpression:
return generate(expr)
case let expr as LiteralExpression:
return generate(expr)
case let expr as OptionalChainingExpression:
return generate(expr)
case let expr as ParenthesizedExpression:
return generate(expr)
case let expr as PostfixOperatorExpression:
return generate(expr)
case let expr as PostfixSelfExpression:
return generate(expr)
case let expr as PrefixOperatorExpression:
return generate(expr)
case let expr as SelectorExpression:
return generate(expr)
case let expr as SelfExpression:
return generate(expr)
case let expr as SequenceExpression:
return generate(expr)
case let expr as SubscriptExpression:
return generate(expr)
case let expr as SuperclassExpression:
return generate(expr)
case let expr as TernaryConditionalOperatorExpression:
return generate(expr)
case let expr as TryOperatorExpression:
return generate(expr)
case let expr as TupleExpression:
return generate(expr)
case let expr as TypeCastingOperatorExpression:
return generate(expr)
case let expr as WildcardExpression:
return generate(expr)
default:
return expression.textDescription
}
}
open func generate(_ expression: AssignmentOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: BinaryOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: ClosureExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: ExplicitMemberExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: ForcedValueExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: FunctionCallExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: IdentifierExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: ImplicitMemberExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: InOutExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: InitializerExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: KeyPathStringExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: LiteralExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: OptionalChainingExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: ParenthesizedExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: PostfixOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: PostfixSelfExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: PrefixOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: SelectorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: SelfExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: SequenceExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: SubscriptExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: SuperclassExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: TernaryConditionalOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: TryOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: TupleExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: TypeCastingOperatorExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
open func generate(_ expression: WildcardExpression) -> String {
let tokens = _tokenizer.tokenize(expression)
return _tokenJoiner.join(tokens: tokens)
}
}
| apache-2.0 | 759a7110c751c451eb493b150d9669d4 | 32.234177 | 111 | 0.717006 | 4.712235 | false | false | false | false |
auth0/Auth0.swift | Auth0/BioAuthentication.swift | 1 | 1298 | #if WEB_AUTH_PLATFORM
import Foundation
import LocalAuthentication
struct BioAuthentication {
private let authContext: LAContext
private let evaluationPolicy: LAPolicy
let title: String
var fallbackTitle: String? {
get { return self.authContext.localizedFallbackTitle }
set { self.authContext.localizedFallbackTitle = newValue }
}
var cancelTitle: String? {
get { return self.authContext.localizedCancelTitle }
set { self.authContext.localizedCancelTitle = newValue }
}
var available: Bool {
return self.authContext.canEvaluatePolicy(evaluationPolicy, error: nil)
}
init(authContext: LAContext, evaluationPolicy: LAPolicy, title: String, cancelTitle: String? = nil, fallbackTitle: String? = nil) {
self.authContext = authContext
self.evaluationPolicy = evaluationPolicy
self.title = title
self.cancelTitle = cancelTitle
self.fallbackTitle = fallbackTitle
}
func validateBiometric(callback: @escaping (Error?) -> Void) {
self.authContext.evaluatePolicy(evaluationPolicy, localizedReason: self.title) {
guard $1 == nil else { return callback($1) }
callback($0 ? nil : LAError(LAError.authenticationFailed))
}
}
}
#endif
| mit | 69c8dce028f0edd2183b0a9a7e5583f1 | 30.658537 | 135 | 0.68567 | 4.898113 | false | false | false | false |
smud/TextUserInterface | Sources/TextUserInterface/Protocols/Session.swift | 1 | 1404 | //
// Session.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Smud
public protocol Session: class {
var textUserInterface: TextUserInterface { get }
var context: SessionContext? { get set }
var account: Account? { get set }
var creature: Creature? { get set }
func send(items: [Any], separator: String, terminator: String, isPrompt: Bool)
}
public extension Session {
func send(items: [Any], separator: String = "", terminator: String = "\n") {
send(items: items, separator: separator, terminator: terminator, isPrompt: false)
}
func send(_ items: Any..., separator: String = "", terminator: String = "\n") {
send(items: items, separator: separator, terminator: terminator)
}
func sendPrompt(items: [Any], separator: String = "", terminator: String = "\n") {
var items = items
items.insert("\n", at: 0)
send(items: items, separator: separator, terminator: "", isPrompt: true)
}
func sendPrompt(_ items: Any..., separator: String = "", terminator: String = "\n") {
sendPrompt(items: items, separator: separator, terminator: "")
}
}
| apache-2.0 | 232a935d9ba74914519acc4f7ad45431 | 31.651163 | 89 | 0.650997 | 4.069565 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/HistoryFetcher.swift | 1 | 2106 | //
// HistoryFetcher.swift
// breadwallet
//
// Created by Adrian Corscadden on 2020-07-14.
// Copyright ยฉ 2020 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import CoinGecko
enum PriceHistoryResult {
case success([PriceDataPoint])
case unavailable
}
//Data points used in the chart on the Account Screen
struct PriceDataPoint: Codable, Equatable {
let time: Date
let close: Double
}
class HistoryFetcher {
private let client = CoinGeckoClient()
// Fetches historical prices for a given currency and history period in the user's
// current display currency.
//
// The returned data points are uses to display the chart on the account screen
func fetchHistory(forCode code: String, period: HistoryPeriod, callback: @escaping (PriceHistoryResult) -> Void) {
let chart = Resources.marketChart(currencyId: code, vs: UserDefaults.defaultCurrencyCode, days: period.days) { (result: Result<MarketChart, CoinGeckoError>) in
guard case .success(let data) = result else { return }
let points: [PriceDataPoint] = data.dataPoints.map {
return PriceDataPoint(time: Date(timeIntervalSince1970: Double($0.timestamp)/1000.0), close: $0.price)
}
callback(.success(self.reduceDataSize(array: points, byFactor: period.reductionFactor)))
}
client.load(chart)
}
//Reduces the size of an array by a factor.
// eg. a reduction factor of 6 would reduce an array of size
// 1095 to 1095/6=182
private func reduceDataSize<T: Equatable>(array: [T], byFactor: Int) -> [T] {
guard byFactor > 0 else { return array }
var newArray = array.enumerated().filter({ i, _ in
i % byFactor == 0
}).map { $0.1 }
//If last item was removed, add it back. This makes
//the current price more accurate
if array.last != newArray.last {
newArray.append(array.last!)
}
return newArray
}
}
| mit | 3ef765eaab66ce539c578ee5fe8cedd0 | 33.508197 | 167 | 0.652257 | 4.218437 | false | false | false | false |
Misstime0501/iOS | LearniOS/LearnSwift/Array/main.swift | 1 | 1359 | //
// main.swift
// Array
//
// Created by LiChen on 16/5/22.
// Copyright ยฉ 2016ๅนด LiChen. All rights reserved.
//
import Foundation
/**
* ๆฐ็ปๅฃฐๆๆนๆณ
* ็ฌฌไธ็ง Array<SomeType>
* ็ฌฌไบ็ง [SomeType]
*/
// ๅๅปบๅญ็ฌฆไธฒๅฝขๅผ็็ฉบๆฐ็ป
var myArr = Array<String>()
// ๅๅปบๆดๅฝขๆฐ็ป๏ผ้้ขๅ
ๅซ 3 ไธช 1
var num = Array<Int>(count : 3, repeatedValue: 1)
print(num)
var arr : [Int] = [1, 2, 3]
// ไฝฟ็จๆ้ ๆนๆณๅๅปบๆฐ็ป
var someInts = [Int]()
var threeDoubles = [Double](count : 3, repeatedValue : 0.0)
var food = ["apple", "orange", "banana", "tomato", "potato"]
print(food)
print(food.count)
var shoppingList = ["Eggs", 123, true]
for item in shoppingList
{
print(item)
}
for fruit in food
{
// ้ๅๅบๆฅ็ fruit ๆฏ let ็ฑปๅ
}
// ๆฐ็ป็ๅฏๅๆง
// 1. append() ๆนๆณๆฏๅจๆฐ็ป็ปๅฐพๆทปๅ ๅ
็ด
// food.append๏ผ"Vegetables : mushroom"๏ผ
// 2. ้่ฟๅฎถ่ฎฟๆทปๅ ๆฐ็ป
// food += ["pineappple", "pitaya"]
// 3. food[0...2] = ["a", "b"] // ๆฟๆข
// 4. insert(atIndex:) ๅจๆไธชๅ
ทไฝ็ดขๅผๅผไนๅๆทปๅ ๅ
็ด
food.insert("Meat", atIndex:0)
// removeAtIndex ็งป้คๆไธ้กน
food.removeAtIndex(0)
// removeLast ็งป้คๆฐ็ปๆๅไธไธช
food.removeLast()
// ๅ ้คๆๆๅ
็ด ๏ผๅๆฐไธบๆฏๅฆไฟ็็ผๅฒๅบ๏ผ้ป่ฎคๆฏ false
food.removeAll(keepCapacity : false)
| mit | e6e004de4cbb0d78e3666bfe6de3c67f | 14.408451 | 60 | 0.635283 | 2.681373 | false | false | false | false |
daisukenagata/BLEView | BLEView/Classes/BLEBEaconAuthenticationCall.swift | 1 | 805 | //
// BLEBEaconAuthenticationCall.swift
// Pods
//
// Created by ๆฐธ็ฐๅคง็ฅ on 2017/02/12.
//
//
import UIKit
import CoreLocation
extension BLBeacon {
func aurhnticationCall() {
for i in 0 ..< UUIDList.count {
let uuid = NSUUID(uuidString:UUIDList[i].lowercased())
let identifierStr:String = "identifier" + UUIDList.count.description
blBeaconRegion = CLBeaconRegion(proximityUUID: uuid! as UUID , identifier: identifierStr)
blBeaconRegion.notifyEntryStateOnDisplay = false
blBeaconRegion.notifyOnEntry = true
blBeaconRegion.notifyOnExit = true
beaconRegionArray.append(blBeaconRegion)
blLocationManager.startMonitoring(for: blBeaconRegion)
}
}
}
| mit | 229edc6302881a1b8df285aa79eb3acf | 27.464286 | 102 | 0.638645 | 4.554286 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/CoreAnimation/VC/CircleCoreAnimationVC.swift | 1 | 3625 | //
// CircleCoreAnimationVC.swift
// iOSExample
//
// Created by iCrany on 2018/11/25.
// Copyright ยฉ 2018 iCrany. All rights reserved.
//
import Foundation
import SnapKit
class TestCricleCoreAnimationView: UIView {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
private func setupUI() {
let label: UILabel = UILabel()
label.text = "Test"
label.sizeToFit()
self.addSubview(label)
label.snp.makeConstraints { (make) in
make.center.equalToSuperview()
}
}
}
class CircleCoreAnimationVC: UIViewController {
private var circleView: TestCricleCoreAnimationView = {
let v = TestCricleCoreAnimationView.init(frame: CGRect(origin: CGPoint(x: 0, y: 100), size: CGSize(width: 100, height: 100)))
v.center = CGPoint(x: kScreenWidth * 0.5, y: kScreenHeight * 0.5)
v.layer.cornerRadius = v.frame.size.height * 0.5
v.backgroundColor = UIColor.blue
return v
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
private func setupUI() {
self.view.backgroundColor = UIColor.white
self.view.addSubview(self.circleView)
let circlePoint: CGPoint = self.circleView.center
let alphaGap: CGFloat = 20.0
let keyAnimationPath: CGMutablePath = CGMutablePath()
//ๆ่ฝฌ็นๅจๆญฃๅทฆๆน
// let circleAnimationPoint: CGPoint = CGPoint(x: circlePoint.x - alphaGap, y: circlePoint.y)
// keyAnimationPath.addArc(center: circleAnimationPoint,
// radius: alphaGap,
// startAngle: 0,
// endAngle: 2 * CGFloat.pi,
// clockwise: true)
//ๆ่ฝฌ็นๅจๆญฃไธๆน
let circleAnimationPoint: CGPoint = CGPoint(x: circlePoint.x, y: circlePoint.y + alphaGap)
keyAnimationPath.addArc(center: circleAnimationPoint,
radius: alphaGap,
startAngle: CGFloat.pi * 1.5,
endAngle: (1.5 + 2) * CGFloat.pi,
clockwise: true)
//็ปๅ
let circleLayer: CAShapeLayer = CAShapeLayer()
circleLayer.frame = CGRect(origin: CGPoint(x: circlePoint.x, y: circlePoint.y + 120), size: CGSize(width: 100, height: 100))
let circleLayerPath: CGMutablePath = CGMutablePath()
circleLayer.path = circleLayerPath
circleLayer.lineWidth = 2.0
circleLayer.strokeColor = UIColor.blue.cgColor
self.view.layer.addSublayer(circleLayer)
let keyFrame: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position")
keyFrame.path = keyAnimationPath
keyFrame.duration = 5.0
keyFrame.repeatCount = Float.greatestFiniteMagnitude
let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureAction))
self.circleView.addGestureRecognizer(tapGesture)
self.circleView.layer.add(keyFrame, forKey: "position.key")
}
@objc private func tapGestureAction() {
NSLog("tapGestureAction...")
}
}
| mit | 51eaff2167dba973ea45ea589052f292 | 33.873786 | 133 | 0.597717 | 4.738786 | false | false | false | false |
arciem/Lores | Lores/Lores/CanvasView.swift | 1 | 1563 | //
// CanvasView.swift
// Lores
//
// Created by Robert McNally on 7/30/14.
// Copyright (c) 2014 Arciem LLC. All rights reserved.
//
import WolfCore
import QuartzCore
class CanvasView : ImageView {
var touchBegan: ((point: CGPoint) -> Void)?
var touchMoved: ((point: CGPoint) -> Void)?
var touchEnded: ((point: CGPoint) -> Void)?
var touchCancelled: ((point: CGPoint) -> Void)?
override func setup() {
super.setup()
layer.magnificationFilter = kCAFilterNearest
contentMode = .ScaleAspectFit
userInteractionEnabled = true
}
override func didMoveToSuperview() {
if superview != nil {
constrainToSuperview()
}
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!
let loc = touch.locationInView(self)
touchBegan?(point: loc)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!
let loc = touch.locationInView(self)
touchMoved?(point: loc)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = touches.first!
let loc = touch.locationInView(self)
touchEnded?(point: loc)
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
let touch = touches!.first!
let loc = touch.locationInView(self)
touchCancelled?(point: loc)
}
}
| apache-2.0 | 649289d79d30b0d893d3e203e0aff044 | 27.418182 | 87 | 0.619962 | 4.556851 | false | false | false | false |
rain2540/Play-with-Algorithms-in-Swift | LeetCode/01-Array.playground/Pages/Pascal Triangle.xcplaygroundpage/Contents.swift | 1 | 1040 | //: [Previous](@previous)
import Foundation
//: ## Pascal's Triangle
//:
//: Given numRows, generate the first numRows of Pascal's triangle.
//:
//: For example, given numRows = 5, Return
//:
//: [
//:
//: [1],
//:
//: [1,1],
//:
//: [1,2,1],
//:
//: [1,3,3,1],
//:
//:[1,4,6,4,1]
//:
//: ]
//: ๅๆ
//:
//: ๅธๆฏๅกไธ่งๆๅฆไธ็่งๅพ
//:
//: * ็ฌฌ k ๅฑๆ k ไธชๅ
็ด
//:
//: * ๆฏๅฑ็ฌฌไธไธชไปฅๅๆๅไธไธชๅ
็ด ๅผไธบ 1
//:
//: * ๅฏนไบ็ฌฌ k (k > 2) ๅฑ็ฌฌ n (n > 1 && n < k) ไธชๅ
็ด A[k][n], A[k][n] = A[k - 1][n - 1] + A[k - 1][n]
func generate(numRows: Int) -> Array<[Int]> {
var vals = Array<[Int]>(repeating: [], count: numRows)
for i in 0 ..< numRows {
vals[i] = [Int](repeating: 0, count: i + 1)
vals[i][0] = 1
vals[i][vals[i].count - 1] = 1
if i > 0 {
for j in 1 ..< vals[i].count - 1 {
vals[i][j] = vals[i - 1][j - 1] + vals[i - 1][j]
}
}
}
return vals
}
print(generate(numRows: 5))
//: [Next](@next)
| mit | 254387b41d5676cf3ccc49f1d909724f | 16.381818 | 94 | 0.441423 | 2.549333 | false | false | false | false |
shu223/ARKit-Sampler | ARKit-Sampler/Samples/ARMetal/ARMetalViewController.swift | 1 | 3695 | //
// ARMetalViewController.swift
// ARKit-Sampler
//
// Created by Shuichi Tsutsumi on 2017/09/20.
// Copyright ยฉ 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import ARKit
import Metal
import MetalKit
class ARMetalViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet weak var sceneView: ARSCNView!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var resetBtn: UIButton!
@IBOutlet weak var metalView: ARMetalImageView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.debugOptions = [SCNDebugOptions.showFeaturePoints]
sceneView.scene = SCNScene()
label.text = "Wait..."
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
sceneView.session.run()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
// MARK: - Private
private func reset() {
}
// MARK: - ARSCNViewDelegate
var isRendering = false
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
guard let frame = sceneView.session.currentFrame else {return}
let pixelBuffer = frame.capturedImage
if isRendering {
return
}
isRendering = true
DispatchQueue.main.async(execute: {
let orientation = UIApplication.shared.statusBarOrientation
let viewportSize = self.sceneView.bounds.size
var image = CIImage(cvPixelBuffer: pixelBuffer)
let transform = frame.displayTransform(for: orientation, viewportSize: viewportSize).inverted()
image = image.transformed(by: transform)
let context = CIContext(options:nil)
guard let cameraImage = context.createCGImage(image, from: image.extent) else {return}
guard let snapshotImage = self.sceneView.snapshot().cgImage else {return}
self.metalView.registerTexturesFor(cameraImage: cameraImage, snapshotImage: snapshotImage)
self.metalView.time = Float(time)
self.isRendering = false
})
}
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
// guard let planeAnchor = anchor as? ARPlaneAnchor else {fatalError()}
// print("anchor:\(anchor), node: \(node), node geometry: \(String(describing: node.geometry))")
let virtualNode = VirtualObjectNode()
for child in virtualNode.childNodes {
if let material = child.geometry?.firstMaterial {
material.diffuse.contents = UIColor.black
}
}
virtualNode.scale = SCNVector3Make(2, 2, 2)
DispatchQueue.main.async(execute: {
node.addChildNode(virtualNode)
})
}
func renderer(_ renderer: SCNSceneRenderer, didUpdate node: SCNNode, for anchor: ARAnchor) {
print("\(self.classForCoder)/" + #function)
}
func renderer(_ renderer: SCNSceneRenderer, didRemove node: SCNNode, for anchor: ARAnchor) {
print("\(self.classForCoder)/" + #function)
}
// MARK: - ARSessionObserver
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
print("trackingState: \(camera.trackingState)")
label.text = camera.trackingState.description
}
// MARK: - Actions
@IBAction func resetBtnTapped(_ sender: UIButton) {
reset()
sceneView.session.run()
}
}
| mit | b396577f1ac7fd1a70ca154785378663 | 30.042017 | 107 | 0.63346 | 5.116343 | false | false | false | false |
juliangrosshauser/Countdown | Countdown/Source/NSCalendar+Countdown.swift | 1 | 836 | //
// NSCalendar+Countdown.swift
// Countdown
//
// Created by Julian Grosshauser on 29/10/15.
// Copyright ยฉ 2015 Julian Grosshauser. All rights reserved.
//
import Foundation
public extension NSCalendar {
public func daysInYear(date: NSDate) -> Int {
let dateComponents = components(.Year, fromDate: date)
let monthsInYear = rangeOfUnit(.Month, inUnit: .Year, forDate: date).length
var days = 0
for month in 1...monthsInYear {
dateComponents.month = month
if let monthInYear = dateFromComponents(dateComponents) {
days += rangeOfUnit(.Day, inUnit: .Month, forDate: monthInYear).length
} else {
// In case of an error, simply return 365 days
return 365
}
}
return days
}
}
| mit | 479f6f70c43ae7c9a7150e09f9c9bd3f | 26.833333 | 86 | 0.601198 | 4.538043 | false | false | false | false |
vhart/PPL-iOS | PPL-iOS/PPL-iOS/LogManager+ExerciseUpdateHelpers.swift | 1 | 4264 | //
// LogManager+ExerciseUpdateHelpers.swift
// PPL-iOS
//
// Created by Jovanny Espinal on 2/22/16.
// Copyright ยฉ 2016 Jovanny Espinal. All rights reserved.
//
import Foundation
import CoreData
// MARK: Global Update Helpers
extension LogManager {
func addBaseExercises(inout updatedExercises: NSMutableOrderedSet, baseExercises: [Exercise])
{
updatedExercises.addObjectsFromArray(baseExercises)
}
}
// MARK: Pull Update Helpers
extension LogManager {
func alternatePullExercises(var previousPullExercises: [Exercise], context: NSManagedObjectContext) -> NSOrderedSet?
{
if let previousAlternatePullExercises = previousExercises(fromWorkoutType: .AlternatePull)?.array as? [Exercise] {
return updatedPullTypeExercises(&previousPullExercises, compoundExerciseFrom: previousAlternatePullExercises)
} else {
let workoutTemp = Workout(typeOfWorkout: .AlternatePull, context: context)
return updatedPullTypeExercises(previousPullExercises, workoutTemp: workoutTemp)
}
}
func updatedPullTypeExercises(inout baseExercises: [Exercise], compoundExerciseFrom previousExercise: [Exercise]) -> NSMutableOrderedSet
{
var updatedExercises = NSMutableOrderedSet()
removePreviousPullTypeCompoundExercises(&baseExercises)
addCompoundExerciseFromPullExercise(&updatedExercises, exercises: previousExercise)
addBaseExercises(&updatedExercises, baseExercises: baseExercises)
return updatedExercises
}
func updatedPullTypeExercises(var previousBaseExercises: [Exercise], workoutTemp: Workout) -> NSMutableOrderedSet?
{
if let alternatePullExercises = workoutTemp.exercises.array as? [Exercise] {
return updatedPullTypeExercises(&previousBaseExercises, compoundExerciseFrom: alternatePullExercises)
}
return nil
}
func addCompoundExerciseFromPullExercise(inout updatedExercises: NSMutableOrderedSet, exercises: [Exercise])
{
updatedExercises.addObject(exercises[0])
}
func removePreviousPullTypeCompoundExercises(inout previousExercises: [Exercise])
{
previousExercises.removeFirst()
}
}
// MARK: Push Update Helpers
extension LogManager {
func alternatePushExercises(var previousPushExercises: [Exercise], context: NSManagedObjectContext ) -> NSOrderedSet?
{
if let previousAlternatePushExercises = previousExercises(fromWorkoutType: .AlternatePush)?.array as? [Exercise] {
return updatedPushTypeExercises(&previousPushExercises, compoundExerciseFrom: previousAlternatePushExercises)
} else {
let workoutTemp = Workout(typeOfWorkout: .AlternatePush, context: context)
return updatedPushTypeExercises(previousPushExercises, workoutTemp: workoutTemp)
}
}
func updatedPushTypeExercises(inout baseExercises: [Exercise], compoundExerciseFrom previousAlternatePushExercises: [Exercise]) -> NSMutableOrderedSet
{
var updatedAlternatePushExercises = NSMutableOrderedSet()
removePreviousPushTypeCompoundExercises(&baseExercises)
addCompoundExercisesFromPushExercise(&updatedAlternatePushExercises, exercises: previousAlternatePushExercises)
addBaseExercises(&updatedAlternatePushExercises, baseExercises: baseExercises)
return updatedAlternatePushExercises
}
func updatedPushTypeExercises(var previousBaseExercises: [Exercise], workoutTemp: Workout) -> NSMutableOrderedSet?
{
if let alternatePushExercises = workoutTemp.exercises.array as? [Exercise]{
return updatedPushTypeExercises(&previousBaseExercises, compoundExerciseFrom: alternatePushExercises)
}
return nil
}
func addCompoundExercisesFromPushExercise(inout updatedExercises: NSMutableOrderedSet, exercises: [Exercise])
{
updatedExercises.addObject(exercises[0])
updatedExercises.addObject(exercises[1])
}
func removePreviousPushTypeCompoundExercises(inout previousExercises: [Exercise])
{
previousExercises.removeRange(0...1)
}
} | mit | 7650c9373312ff564d55457dc033bca4 | 37.071429 | 154 | 0.72578 | 6.151515 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01179-swift-declcontext-lookupqualified.swift | 11 | 573 | // 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
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
}
struct c<h : b> : b {
typealias e = a<c<h>, d>
}
struct c<S: Sequence, T where Optional<T> == S.Iterator.Element
| apache-2.0 | 42a398ced79aa6d9e7e12d1807c7c3f1 | 32.705882 | 78 | 0.703316 | 3.312139 | false | false | false | false |
edopelawi/CascadingTableDelegate | Example/CascadingTableDelegate/SectionTableDelegates/DestinationReviewUserSectionDelegate.swift | 1 | 3435 | //
// DestinationReviewUserSectionDelegate.swift
// CascadingTableDelegate
//
// Created by Ricardo Pramana Suranta on 11/2/16.
// Copyright ยฉ 2016 Ricardo Pramana Suranta. All rights reserved.
//
import Foundation
import CascadingTableDelegate
class DestinationReviewUserSectionDelegate: CascadingSectionTableDelegate {
fileprivate var viewModel: DestinationReviewSectionViewModel?
fileprivate var headerView: EmptyContentView
fileprivate var footerView: ReviewSectionFooterView
convenience init(viewModel: DestinationReviewSectionViewModel) {
self.init()
viewModel.add(observer: self)
self.viewModel = viewModel
updateChildDelegates()
self.reloadModeOnChildDelegatesChanged = .section(animation: .automatic)
}
required init(index: Int = 0, childDelegates: [CascadingTableDelegate] = []) {
headerView = EmptyContentView.view()
footerView = ReviewSectionFooterView.view()
super.init(index: index, childDelegates: childDelegates)
configureFooterViewObserver()
}
deinit {
viewModel?.remove(observer: self)
}
override func prepare(tableView: UITableView) {
super.prepare(tableView: tableView)
registerNib(tableView: tableView)
}
// MARK: - Private methods
fileprivate func registerNib(tableView: UITableView) {
let rowIdentifier = DestinationReviewUserRowDelegate.cellIdentifier
let nib = UINib(nibName: rowIdentifier, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: rowIdentifier)
}
fileprivate func updateChildDelegates() {
guard let childViewModels = viewModel?.rowViewModels else {
return
}
childDelegates = childViewModels.map({ DestinationReviewUserRowDelegate(viewModel: $0) })
}
fileprivate func configureFooterViewObserver() {
footerView.onButtonTapped = { [weak self] in
self?.retrieveMoreViewModels()
}
}
fileprivate func retrieveMoreViewModels() {
footerView.startActivityIndicator()
viewModel?.retrieveMoreRowViewModels({ [weak self] in
self?.footerView.stopActivityIndicator()
})
}
}
extension DestinationReviewUserSectionDelegate: DestinationReviewSectionViewModelObserver {
func reviewSectionDataChanged() {
updateChildDelegates()
}
}
extension DestinationReviewUserSectionDelegate {
@objc override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(1.1)
}
@objc override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerView
}
@objc override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if let remainingViewModels = viewModel?.remainingRowViewModels, remainingViewModels > 0 {
return ReviewSectionFooterView.preferredHeight()
}
return CGFloat(1.1)
}
@objc override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if let remainingViewModels = viewModel?.remainingRowViewModels, remainingViewModels > 0 {
return footerView
}
return nil
}
@objc override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard let view = view as? ReviewSectionFooterView else {
return
}
if let remainingViewModels = viewModel?.remainingRowViewModels {
view.buttonText = "\(remainingViewModels) more"
} else {
view.buttonText = nil
}
}
}
| mit | 6bfac9ade62d9d17e0df51ba2dc6d512 | 24.819549 | 119 | 0.759173 | 4.65943 | false | false | false | false |
zyuanming/EffectDesignerX | EffectDesignerX/Extension/NSColorExtension.swift | 1 | 2193 | //
// NSColorExtension.swift
// EffectDesignerX
//
// Created by Zhang Yuanming on 10/11/16.
// Copyright ยฉ 2016 Zhang Yuanming. All rights reserved.
//
import Foundation
extension NSColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
var hexStr = (rgba as NSString).substring(from: 1) as NSString
if hexStr.length == 8 {
let alphaHexStr = hexStr.substring(from: 6)
hexStr = hexStr.substring(to: 6) as NSString
var alphaHexValue: UInt32 = 0
let alphaScanner = Scanner(string: alphaHexStr)
if alphaScanner.scanHexInt32(&alphaHexValue) {
let alphaHex = Int(alphaHexValue)
alpha = CGFloat(alphaHex & 0x000000FF) / 255.0
} else {
print("scan alphaHex error")
}
}
let rgbScanner = Scanner(string: hexStr as String)
var hexValue: UInt32 = 0
if rgbScanner.scanHexInt32(&hexValue) {
if hexStr.length == 6 {
let hex = Int(hexValue)
red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
green = CGFloat((hex & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hex & 0x0000FF) / 255.0
} else {
print("invalid rgb string, length should be 6")
}
} else {
print("scan hex error")
}
} else {
print("invalid rgb string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
func getHexString(withAlpha alpha: CGFloat = 1.0) -> String {
let red = Int(round(redComponent * 0xFF))
let green = Int(round(greenComponent * 0xFF))
let blue = Int(round(blueComponent * 0xFF))
let alpha = Int(alpha * 0xFF)
let hexString = String(format: "#%02X%02X%02X%02X", red, green, blue, alpha)
return hexString
}
}
| mit | cd8259b02c29a52838f652f065f50116 | 33.793651 | 84 | 0.519617 | 4.239845 | false | false | false | false |
googleads/googleads-mobile-ios-examples | Swift/advanced/APIDemo/APIDemo/AdManagerCategoryExclusionsTableViewController.swift | 1 | 2179 | //
// Copyright (C) 2016 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import GoogleMobileAds
import UIKit
class AdManagerCategoryExclusionsTableViewController: UITableViewController {
/// The no exclusions banner view.
@IBOutlet weak var noExclusionsBannerView: GAMBannerView!
/// The exclude dogs banner view.
@IBOutlet weak var excludeDogsBannerView: GAMBannerView!
/// The exclude cats banner view.
@IBOutlet weak var excludeCatsBannerView: GAMBannerView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
noExclusionsBannerView.adUnitID = Constants.AdManagerCategoryExclusionsAdUnitID
noExclusionsBannerView.rootViewController = self
let noExclusionsRequest = GAMRequest()
noExclusionsBannerView.load(noExclusionsRequest)
excludeDogsBannerView.adUnitID = Constants.AdManagerCategoryExclusionsAdUnitID
excludeDogsBannerView.rootViewController = self
let excludeDogsRequest = GAMRequest()
excludeDogsRequest.categoryExclusions = [Constants.CategoryExclusionDogs]
excludeDogsBannerView.load(excludeDogsRequest)
excludeCatsBannerView.adUnitID = Constants.AdManagerCategoryExclusionsAdUnitID
excludeCatsBannerView.rootViewController = self
let excludeCatsRequest = GAMRequest()
excludeCatsRequest.categoryExclusions = [Constants.CategoryExclusionCats]
excludeCatsBannerView.load(excludeCatsRequest)
}
// MARK: - Table View
override func tableView(
_ tableView: UITableView, willDisplayHeaderView view: UIView,
forSection section: Int
) {
view.tintColor = UIColor.clear
}
}
| apache-2.0 | 3dbfd2db17df3557e1d3c051e82c6d6e | 33.587302 | 83 | 0.773291 | 4.896629 | false | false | false | false |
alecgorge/AGAudioPlayer | Pods/Interpolate/Interpolate/Interpolatable.swift | 1 | 6851 | //
// Interpolatable.swift
// Interpolate
//
// Created by Roy Marmelstein on 10/04/2016.
// Copyright ยฉ 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
import QuartzCore
/**
* Interpolatable protocol. Requires implementation of a vectorize function.
*/
public protocol Interpolatable {
/**
Vectorizes the type and returns and IPValue
*/
func vectorize() -> IPValue
}
/**
Supported interpolatable types.
*/
public enum InterpolatableType {
/// CATransform3D type.
case caTransform3D
/// CGAffineTransform type.
case cgAffineTransform
/// CGFloat type.
case cgFloat
/// CGPoint type.
case cgPoint
/// CGRect type.
case cgRect
/// CGSize type.
case cgSize
/// ColorHSB type.
case colorHSB
/// ColorMonochrome type.
case colorMonochrome
/// ColorRGB type.
case colorRGB
/// Double type.
case double
/// Int type.
case int
/// NSNumber type.
case nsNumber
/// UIEdgeInsets type.
case uiEdgeInsets
}
// MARK: Extensions
/// CATransform3D Interpolatable extension.
extension CATransform3D: Interpolatable {
/**
Vectorize CATransform3D.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .caTransform3D, vectors: [m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44])
}
}
/// CGAffineTransform Interpolatable extension.
extension CGAffineTransform: Interpolatable {
/**
Vectorize CGAffineTransform.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .cgAffineTransform, vectors: [a, b, c, d, tx, ty])
}
}
/// CGFloat Interpolatable extension.
extension CGFloat: Interpolatable {
/**
Vectorize CGFloat.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .cgFloat, vectors: [self])
}
}
/// CGPoint Interpolatable extension.
extension CGPoint: Interpolatable {
/**
Vectorize CGPoint.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .cgPoint, vectors: [x, y])
}
}
/// CGRect Interpolatable extension.
extension CGRect: Interpolatable {
/**
Vectorize CGRect.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .cgRect, vectors: [origin.x, origin.y, size.width, size.height])
}
}
/// CGSize Interpolatable extension.
extension CGSize: Interpolatable {
/**
Vectorize CGSize.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .cgSize, vectors: [width, height])
}
}
/// Double Interpolatable extension.
extension Double: Interpolatable {
/**
Vectorize Double.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .double, vectors: [CGFloat(self)])
}
}
/// Int Interpolatable extension.
extension Int: Interpolatable {
/**
Vectorize Int.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .int, vectors: [CGFloat(self)])
}
}
/// NSNumber Interpolatable extension.
extension NSNumber: Interpolatable {
/**
Vectorize NSNumber.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .nsNumber, vectors: [CGFloat(truncating: self)])
}
}
/// UIColor Interpolatable extension.
extension UIColor: Interpolatable {
/**
Vectorize UIColor.
- returns: IPValue
*/
public func vectorize() -> IPValue {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return IPValue(type: .colorRGB, vectors: [red, green, blue, alpha])
}
var white: CGFloat = 0
if getWhite(&white, alpha: &alpha) {
return IPValue(type: .colorMonochrome, vectors: [white, alpha])
}
var hue: CGFloat = 0, saturation: CGFloat = 0, brightness: CGFloat = 0
getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
return IPValue(type: .colorHSB, vectors: [hue, saturation, brightness, alpha])
}
}
/// UIEdgeInsets Interpolatable extension.
extension UIEdgeInsets: Interpolatable {
/**
Vectorize UIEdgeInsets.
- returns: IPValue
*/
public func vectorize() -> IPValue {
return IPValue(type: .uiEdgeInsets, vectors: [top, left, bottom, right])
}
}
/// IPValue class. Contains a vectorized version of an Interpolatable type.
open class IPValue {
let type: InterpolatableType
var vectors: [CGFloat]
init(value: IPValue) {
self.vectors = value.vectors
self.type = value.type
}
init (type: InterpolatableType, vectors: [CGFloat]) {
self.vectors = vectors
self.type = type
}
func toInterpolatable() -> Interpolatable {
switch type {
case .caTransform3D:
return CATransform3D(m11: vectors[0], m12: vectors[1], m13: vectors[2], m14: vectors[3], m21: vectors[4], m22: vectors[5], m23: vectors[6], m24: vectors[7], m31: vectors[8], m32: vectors[9], m33: vectors[10], m34: vectors[11], m41: vectors[12], m42: vectors[13], m43: vectors[14], m44: vectors[15])
case .cgAffineTransform:
return CGAffineTransform(a: vectors[0], b: vectors[1], c: vectors[2], d: vectors[3], tx: vectors[4], ty: vectors[5])
case .cgFloat:
return vectors[0]
case .cgPoint:
return CGPoint(x: vectors[0], y: vectors[1])
case .cgRect:
return CGRect(x: vectors[0], y: vectors[1], width: vectors[2], height: vectors[3])
case .cgSize:
return CGSize(width: vectors[0], height: vectors[1])
case .colorRGB:
return UIColor(red: vectors[0], green: vectors[1], blue: vectors[2], alpha: vectors[3])
case .colorMonochrome:
return UIColor(white: vectors[0], alpha: vectors[1])
case .colorHSB:
return UIColor(hue: vectors[0], saturation: vectors[1], brightness: vectors[2], alpha: vectors[3])
case .double:
return Double(vectors[0])
case .int:
return Int(vectors[0])
case .nsNumber:
return NSNumber(value: Double(vectors[0]))
case .uiEdgeInsets:
return UIEdgeInsets(top: vectors[0], left: vectors[1], bottom: vectors[2], right: vectors[3])
}
}
}
| mit | cf72fa6cfdf2dace4a99c4e1498a0a6e | 25.968504 | 314 | 0.59781 | 4.305468 | false | false | false | false |
idapgroup/IDPCastable | Tests/iOS/iOSTests/IDPCastableTests.swift | 1 | 4965 | //
// IDPCastableTests.swift
// IDPCastableTests
//
// Created by Oleksa 'trimm' Korin on 12/12/16.
// Copyright ยฉ 2016 Oleksa 'trimm' Korin. All rights reserved.
//
import Quick
import Nimble
@testable import IDPCastable
class CastTestClass { }
class ChildCastTestClass : CastTestClass { }
class IDPCastableSpec: QuickSpec {
override func spec() {
describe("func cast<Type, Result>(_ value: Type) -> Result?") {
let value: Any = CastTestClass()
it("should cast to optional .some for types castable from Type to Result") {
let castedValue: CastTestClass? = cast(value)
expect(castedValue).notTo(beNil())
}
it("should not cast to optional .some for types not castable from Type to Result") {
let castedValue: ChildCastTestClass? = cast(value)
expect(castedValue).to(beNil())
}
}
let wrapped: AnyObject = ChildCastTestClass()
describe("Castable") {
let value = Castable<AnyObject>.value(wrapped)
context("when matching") {
it("should call the function with argument type castable to .value") {
var called = false
value.match { (_: CastTestClass) in called = true }
expect(called).to(beTrue())
}
it("should not call the function with argument type not castable to .value") {
var called = false
value.match { (_: CustomStringConvertible) in called = true }
expect(called).to(beFalse())
}
context("when extracting") {
it("should return the value it was created with") {
expect(ObjectIdentifier(value.extract())).to(equal(ObjectIdentifier(wrapped)))
}
}
}
}
describe("func castable<Wrapped>(_ x: Wrapped) -> Castable<Wrapped>") {
it("should return Castable wrapping x") {
let value = castable(wrapped)
expect(ObjectIdentifier(value.extract())).to(equal(ObjectIdentifier(wrapped)))
}
}
describe("func castable<Wrapped, Subject>(_ x: Wrapped, f: (Subject) -> ()) -> Castable<Wrapped>") {
var value = Castable<AnyObject>.value(wrapped)
context("when Wrapped can be cast to Subject") {
it("should apply f to x") {
var called = false
value = castable(wrapped) { (x: CastTestClass) in called = true }
expect(called).to(beTrue())
}
it("should return Castable wrapping x") {
expect(ObjectIdentifier(value.extract())).to(equal(ObjectIdentifier(wrapped)))
}
}
context("when Wrapped can not be cast to Subject") {
it("should not apply f to x") {
var called = false
value = castable(wrapped) { (x: CustomStringConvertible) in called = true }
expect(called).to(beFalse())
}
it("should return Castable wrapping x") {
expect(ObjectIdentifier(value.extract())).to(equal(ObjectIdentifier(wrapped)))
}
}
}
describe("func match<Wrapped, Subject>(_ value: Wrapped, f: (Subject) -> ()) -> Wrapped") {
context("when Wrapped can be cast to Subject") {
it("should apply f to x") {
var called = false
match(wrapped) { (x: CastTestClass) in called = true }
expect(called).to(beTrue())
}
it("should return x") {
expect(ObjectIdentifier(match(wrapped) { (x: CastTestClass) in }))
.to(equal(ObjectIdentifier(wrapped)))
}
}
context("when Wrapped can not be cast to Subject") {
it("should not apply f to x") {
var called = false
match(wrapped) { (x: CustomStringConvertible) in called = true }
expect(called).to(beFalse())
}
it("should return x") {
expect(ObjectIdentifier(match(wrapped) { (x: CustomStringConvertible) in }))
.to(equal(ObjectIdentifier(wrapped)))
}
}
}
}
}
| bsd-3-clause | 28b14e7643e3b8a3436e42a7e426b11b | 37.184615 | 108 | 0.471595 | 5.640909 | false | true | false | false |
iOSDevLog/iOSDevLog | 201. UI Test/Swift/ListerKit/LocalListCoordinator.swift | 1 | 8553 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sampleโs licensing information
Abstract:
The `LocalListCoordinator` class handles querying for and interacting with lists stored as local files.
*/
import Foundation
/**
An object that conforms to the `LocalListCoordinator` protocol and is responsible for implementing
entry points in order to communicate with an `ListCoordinatorDelegate`. In the case of Lister,
this is the `ListsController` instance. The main responsibility of a `LocalListCoordinator` is
to track different `NSURL` instances that are important. The local coordinator is responsible for
making sure that the `ListsController` knows about the current set of documents that are available
in the app's local container.
There are also other responsibilities that an `LocalListCoordinator` must have that are specific
to the underlying storage mechanism of the coordinator. A `CloudListCoordinator` determines whether
or not a new list can be created with a specific name, it removes URLs tied to a specific list, and
it is also responsible for listening for updates to any changes that occur at a specific URL
(e.g. a list document is updated on another device, etc.).
Instances of `LocalListCoordinator` can search for URLs in an asynchronous way. When a new `NSURL`
instance is found, removed, or updated, the `ListCoordinator` instance must make its delegate
aware of the updates. If a failure occured in removing or creating an `NSURL` for a given list,
it must make its delegate aware by calling one of the appropriate error methods defined in the
`ListCoordinatorDelegate` protocol.
*/
public class LocalListCoordinator: ListCoordinator, DirectoryMonitorDelegate {
// MARK: Properties
public weak var delegate: ListCoordinatorDelegate?
/**
A GCD based monitor used to observe changes to the local documents directory.
*/
private var directoryMonitor: DirectoryMonitor
/**
Closure executed after the first update provided by the coordinator regarding tracked
URLs.
*/
private var firstQueryUpdateHandler: (Void -> Void)?
private let predicate: NSPredicate
private var currentLocalContents = [NSURL]()
public var documentsDirectory: NSURL {
return ListUtilities.localDocumentsDirectory
}
// MARK: Initializers
/**
Initializes an `LocalListCoordinator` based on a path extension used to identify files that can be
managed by the app. Also provides a block parameter that can be used to provide actions to be executed
when the coordinator returns its first set of documents. This coordinator monitors the app's local
container.
- parameter pathExtension: The extension that should be used to identify documents of interest to this coordinator.
- parameter firstQueryUpdateHandler: The handler that is executed once the first results are returned.
*/
public init(pathExtension: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
directoryMonitor = DirectoryMonitor(URL: ListUtilities.localDocumentsDirectory)
predicate = NSPredicate(format: "(pathExtension = %@)", argumentArray: [pathExtension])
self.firstQueryUpdateHandler = firstQueryUpdateHandler
directoryMonitor.delegate = self
}
/**
Initializes an `LocalListCoordinator` based on a single document used to identify a file that should
be monitored. Also provides a block parameter that can be used to provide actions to be executed when the
coordinator returns its initial result. This coordinator monitors the app's local container.
- parameter lastPathComponent: The file name that should be monitored by this coordinator.
- parameter firstQueryUpdateHandler: The handler that is executed once the first results are returned.
*/
public init(lastPathComponent: String, firstQueryUpdateHandler: (Void -> Void)? = nil) {
directoryMonitor = DirectoryMonitor(URL: ListUtilities.localDocumentsDirectory)
predicate = NSPredicate(format: "(lastPathComponent = %@)", argumentArray: [lastPathComponent])
self.firstQueryUpdateHandler = firstQueryUpdateHandler
directoryMonitor.delegate = self
}
// MARK: ListCoordinator
public func startQuery() {
processChangeToLocalDocumentsDirectory()
directoryMonitor.startMonitoring()
}
public func stopQuery() {
directoryMonitor.stopMonitoring()
}
public func removeListAtURL(URL: NSURL) {
ListUtilities.removeListAtURL(URL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailRemovingListAtURL(URL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [], removedURLs: [URL], updatedURLs: [])
}
}
}
public func createURLForList(list: List, withName name: String) {
let documentURL = documentURLForName(name)
ListUtilities.createList(list, atURL: documentURL) { error in
if let realError = error {
self.delegate?.listCoordinatorDidFailCreatingListAtURL(documentURL, withError: realError)
}
else {
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: [documentURL], removedURLs: [], updatedURLs: [])
}
}
}
public func canCreateListWithName(name: String) -> Bool {
if name.isEmpty {
return false
}
let documentURL = documentURLForName(name)
return !NSFileManager.defaultManager().fileExistsAtPath(documentURL.path!)
}
public func copyListFromURL(URL: NSURL, toListWithName name: String) {
let documentURL = documentURLForName(name)
ListUtilities.copyFromURL(URL, toURL: documentURL)
}
// MARK: DirectoryMonitorDelegate
func directoryMonitorDidObserveChange(directoryMonitor: DirectoryMonitor) {
processChangeToLocalDocumentsDirectory()
}
// MARK: Convenience
func processChangeToLocalDocumentsDirectory() {
let defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(defaultQueue) {
let fileManager = NSFileManager.defaultManager()
do {
// Fetch the list documents from containerd documents directory.
let localDocumentURLs = try fileManager.contentsOfDirectoryAtURL(ListUtilities.localDocumentsDirectory, includingPropertiesForKeys: nil, options: .SkipsPackageDescendants)
let localListURLs = localDocumentURLs.filter { self.predicate.evaluateWithObject($0) }
if !localListURLs.isEmpty {
let insertedURLs = localListURLs.filter { !self.currentLocalContents.contains($0) }
let removedURLs = self.currentLocalContents.filter { !localListURLs.contains($0) }
self.delegate?.listCoordinatorDidUpdateContents(insertedURLs: insertedURLs, removedURLs: removedURLs, updatedURLs: [])
self.currentLocalContents = localListURLs
}
}
catch let error as NSError {
print("An error occurred accessing the contents of a directory. Domain: \(error.domain) Code: \(error.code)")
}
// Requiring an additional catch to satisfy exhaustivity is a known issue.
catch {}
// Execute the `firstQueryUpdateHandler`, it will contain the closure from initialization on first update.
if let handler = self.firstQueryUpdateHandler {
handler()
// Set `firstQueryUpdateHandler` to an empty closure so that the handler provided is only run on first update.
self.firstQueryUpdateHandler = nil
}
}
}
private func documentURLForName(name: String) -> NSURL {
let documentURLWithoutExtension = documentsDirectory.URLByAppendingPathComponent(name)
return documentURLWithoutExtension.URLByAppendingPathExtension(AppConfiguration.listerFileExtension)
}
}
| mit | 66c89715ff0d30244d907b37981d5256 | 43.305699 | 187 | 0.680037 | 5.83686 | false | false | false | false |
corinnekrych/aerogear-ios-http-1 | AeroGearHttpTests/RequestSerializerTest.swift | 1 | 2505 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import XCTest
import AeroGearHttp
class RequestSerializerTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testGETWithParameters() {
var url = "http://api.icndb.com/jokes/12"
var serialiser = JsonRequestSerializer()
var result = serialiser.request(NSURL(string: url)!, method:.GET, parameters: ["param1": "value1", "array": ["one", "two", "three", "four"], "numeric": 5, "dictionary": ["key_one":"value_one"]])
if let urlString = result.URL!.absoluteString {
println(">>>>" + (NSString(string: urlString) as String))
XCTAssertTrue(NSString(string: urlString).rangeOfString("param1=value1").location != NSNotFound)
XCTAssertTrue(NSString(string: urlString).rangeOfString("numeric=5").location != NSNotFound)
XCTAssertTrue(NSString(string: urlString).rangeOfString("dictionary%5Bkey_one%5D=value_one").location != NSNotFound)
XCTAssertTrue(NSString(string: urlString).rangeOfString("array%5B%5D=one&array%5B%5D=two&array%5B%5D=three&array%5B%5D=four").location != NSNotFound)
} else {
XCTFail("url should not give an empty string")
}
}
func testStringResponseSerializer() {
var url = NSURL(string: "http://api.icndb.com/jokes/12")
var serialiser = StringResponseSerializer()
let result: String? = serialiser.response("some text received".dataUsingEncoding(NSUTF8StringEncoding)!) as? String
XCTAssertTrue(result == "some text received")
}
}
| apache-2.0 | 0ac02438d2891dc990f5524a69a0a791 | 43.732143 | 202 | 0.681836 | 4.304124 | false | true | false | false |
miracl/amcl | version3/swift/rom_nums512e.swift | 1 | 3847 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
*/
//
// rom.swift
//
// Created by Michael Scott on 12/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
public struct ROM{
#if D32
// Base Bits= 29
// nums512 Modulus
static public let Modulus:[Chunk] = [0x1FFFFDC7,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFF]
static let R2modp:[Chunk] = [0xB100000,0x278,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x239
// nums512 Edwards Curve
static let CURVE_Cof_I:Int = 4
static let CURVE_Cof:[Chunk] = [0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = 1
static let CURVE_B_I:Int = -78296
static public let CURVE_B:[Chunk] = [0x1FFECBEF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFF]
static public let CURVE_Order:[Chunk] = [0x1BEED46D,0x1A3467A8,0x1BFB3FD9,0xC0AF0DB,0x86F52A4,0xC64B85B,0x6EA78FF,0xDA5F9F2,0x1FB4F063,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFF]
static public let CURVE_Gx:[Chunk] = [0x19EC57FE,0xDCD594C,0x113C0571,0xA4A84F9,0x104AD0FE,0x4C92B44,0xC3DE2F7,0x9DDC8CE,0x74621C1,0x1139DC0A,0x9E85FAF,0x1B894704,0x1D1E79F4,0x9E29997,0x32DE223,0x16D38F43,0x116D128D,0x6FC71]
static public let CURVE_Gy:[Chunk] = [0x1E2F5E1,0x136EF606,0x1C7407CC,0xDA71537,0xC1FD026,0x3431576,0x15898068,0x1E5D32C6,0x120CA53,0xC84F41A,0xA4ADAE5,0x104B3A45,0x76F726D,0x1512B772,0x3D5DEA0,0x194E3316,0x1FF39D49,0x3684D]
// nums384 Edwards Curve
#endif
#if D64
// Base Bits= 60
// nums512 Modulus
static public let Modulus:[Chunk] = [0xFFFFFFFFFFFFDC7,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFF]
static let R2modp:[Chunk] = [0x100000000000000,0x4F0B,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x239
// nums512 Edwards Curve
static let CURVE_Cof_I:Int = 4
static let CURVE_Cof:[Chunk] = [0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = 1
static let CURVE_B_I:Int = -78296
static let CURVE_B:[Chunk] = [0xFFFFFFFFFFECBEF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFF]
static public let CURVE_Order:[Chunk] = [0x7468CF51BEED46D,0x4605786DEFECFF6,0xFD8C970B686F52A,0x636D2FCF91BA9E3,0xFFFFFFFFFFFB4F0,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFFF,0x3FFFFFFF]
static public let CURVE_Gx:[Chunk] = [0x5B9AB2999EC57FE,0xE525427CC4F015C,0xDC992568904AD0F,0xC14EEE46730F78B,0xEBE273B81474621,0x9F4DC4A38227A17,0x888D3C5332FD1E7,0x128DB69C7A18CB7,0xDF8E316D]
static public let CURVE_Gy:[Chunk] = [0x26DDEC0C1E2F5E1,0x66D38A9BF1D01F3,0xA06862AECC1FD02,0x53F2E9963562601,0xB95909E834120CA,0x26D8259D22A92B6,0x7A82A256EE476F7,0x9D49CA7198B0F57,0x6D09BFF3]
#endif
}
| apache-2.0 | c30c91f938f7c91ad0b80d8fb24b646f | 50.293333 | 232 | 0.81622 | 2.316075 | false | false | false | false |
yonadev/yona-app-ios | Yona/Yona/UIControlCell/NoGoCell.swift | 1 | 2584 | //
// NoGoView.swift
// Yona
//
// Created by Ben Smith on 12/07/16.
// Copyright ยฉ 2016 Yona. All rights reserved.
//
import Foundation
class NoGoCell : UITableViewCell {
@IBOutlet weak var nogoImage: UIImageView!
@IBOutlet weak var nogoType: UILabel!
@IBOutlet weak var nogoMessage: UILabel!
@IBOutlet weak var gradientView: GradientSmooth!
var goalAccomplished: Bool = false
var goalName: String = NSLocalizedString("meday.nogo.message", comment: "")
var goalDate: Date = Date()
var totalMinutesBeyondGoal: Int = 0
override func layoutSubviews() {
contentView.layoutIfNeeded()
setupGradient()
drawTheCell()
}
func setupGradient () {
gradientView.setGradientSmooth(UIColor.yiBgGradientTwoColor(), color2: UIColor.yiBgGradientOneColor())
}
func drawTheCell (){
nogoType.text = goalName
if goalAccomplished {
self.nogoMessage.text = NSLocalizedString("meday.nogo.message", comment: "")
self.nogoImage.image = R.image.adultHappy()
} else {
self.nogoImage.image = R.image.adultSad()
let dateFromat = DateFormatter()
dateFromat.dateFormat = "HH:mm"
let date = dateFromat.string(from: goalDate)
self.nogoMessage.text = "\(totalMinutesBeyondGoal) " + "\(NSLocalizedString("meday.nogo.minutes", comment: ""))"
}
}
func setDataForView(_ activityGoal : ActivitiesGoal) {
goalAccomplished = activityGoal.goalAccomplished
self.goalDate = activityGoal.date as Date
self.totalMinutesBeyondGoal = activityGoal.totalMinutesBeyondGoal
if let goalName = activityGoal.goalName{
self.goalName = goalName
}
}
func setDayActivityDetailForView(_ activityGoal : DaySingleActivityDetail) {
goalAccomplished = activityGoal.goalAccomplished
if let goalDate = activityGoal.date {
self.goalDate = goalDate as Date
}
self.goalName = NSLocalizedString("meweek.message.score", comment: "")
self.totalMinutesBeyondGoal = activityGoal.totalMinutesBeyondGoal
}
func setDataForWeekDetailView(_ activityGoal : WeekSingleActivityDetail) {
if activityGoal.totalMinutesBeyondGoal > 0 {
self.goalAccomplished = false
}
self.goalName = NSLocalizedString("meweek.message.score", comment: "")
self.totalMinutesBeyondGoal = activityGoal.totalMinutesBeyondGoal
}
}
| mpl-2.0 | 381d8b76d4d6c99ab648cf6eee6505f7 | 31.696203 | 125 | 0.648471 | 4.948276 | false | false | false | false |
krummler/SKPhotoBrowser | SKPhotoBrowser/SKLocalPhoto.swift | 1 | 1999 | //
// SKLocalPhoto.swift
// SKPhotoBrowser
//
// Created by Antoine Barrault on 13/04/2016.
// Copyright ยฉ 2016 suzuki_keishi. All rights reserved.
//
import UIKit
// MARK: - SKLocalPhoto
public class SKLocalPhoto: NSObject, SKPhotoProtocol {
public var underlyingImage: UIImage!
public var photoURL: String!
public var contentMode: UIViewContentMode = .ScaleToFill
public var shouldCachePhotoURLImage: Bool = false
public var caption: String!
public var index: Int = 0
override init() {
super.init()
}
convenience init(url: String) {
self.init()
photoURL = url
}
convenience init(url: String, holder: UIImage?) {
self.init()
photoURL = url
underlyingImage = holder
}
public func checkCache() {}
public func loadUnderlyingImageAndNotify() {
if underlyingImage != nil && photoURL == nil {
loadUnderlyingImageComplete()
}
if photoURL != nil {
// Fetch Image
if NSFileManager.defaultManager().fileExistsAtPath(photoURL) {
if let data = NSFileManager.defaultManager().contentsAtPath(photoURL) {
self.loadUnderlyingImageComplete()
if let image = UIImage(data: data) {
self.underlyingImage = image
self.loadUnderlyingImageComplete()
}
}
}
}
}
public func loadUnderlyingImageComplete() {
NSNotificationCenter.defaultCenter().postNotificationName(SKPHOTO_LOADING_DID_END_NOTIFICATION, object: self)
}
// MARK: - class func
public class func photoWithImageURL(url: String) -> SKLocalPhoto {
return SKLocalPhoto(url: url)
}
public class func photoWithImageURL(url: String, holder: UIImage?) -> SKLocalPhoto {
return SKLocalPhoto(url: url, holder: holder)
}
}
| mit | 22cf58cb3621b7ff5ed27efaffc11175 | 27.542857 | 117 | 0.595596 | 5.230366 | false | false | false | false |
mownier/photostream | Photostream/UI/Single Post/SinglePostViewController.swift | 1 | 3150 | //
// SinglePostViewController.swift
// Photostream
//
// Created by Mounir Ybanez on 19/01/2017.
// Copyright ยฉ 2017 Mounir Ybanez. All rights reserved.
//
import UIKit
@objc protocol SinglePostViewControllerAction: class {
func back()
}
class SinglePostViewController: UICollectionViewController, SinglePostViewControllerAction {
lazy var prototype: PostListCollectionCell! = PostListCollectionCell()
lazy var loadingView: UIActivityIndicatorView! = {
let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
view.hidesWhenStopped = true
return view
}()
var listLayout: UICollectionViewFlowLayout!
var presenter: SinglePostModuleInterface!
var isLoadingViewHidden: Bool = false {
didSet {
guard collectionView != nil else {
return
}
if isLoadingViewHidden {
loadingView.stopAnimating()
if collectionView!.backgroundView == loadingView {
collectionView!.backgroundView = nil
}
} else {
loadingView.frame = collectionView!.bounds
loadingView.startAnimating()
collectionView!.backgroundView = loadingView
}
}
}
convenience init() {
let layout = UICollectionViewFlowLayout()
self.init(collectionViewLayout: layout)
self.listLayout = layout
}
override func loadView() {
super.loadView()
guard collectionView != nil else {
return
}
collectionView!.alwaysBounceVertical = true
collectionView!.backgroundColor = UIColor.white
let size = collectionView!.frame.size
listLayout.configure(with: size.width, columnCount: 1)
listLayout.headerReferenceSize = CGSize(width: size.width, height: 48)
listLayout.sectionHeadersPinToVisibleBounds = false
PostListCollectionCell.register(in: collectionView!)
PostListCollectionHeader.register(in: collectionView!)
prototype.bounds.size.width = size.width
setupNavigationItem()
}
override func viewDidLoad() {
super.viewDidLoad()
presenter.viewDidLoad()
}
func setupNavigationItem() {
let barItem = UIBarButtonItem(
image: #imageLiteral(resourceName: "back_nav_icon"),
style: .plain,
target: self,
action: #selector(self.back))
navigationItem.leftBarButtonItem = barItem
navigationItem.title = "Post"
}
func back() {
presenter.exit()
}
}
extension SinglePostViewController: SinglePostScene {
var controller: UIViewController? {
return self
}
func reload() {
collectionView?.reloadData()
}
func didFetch(error: String?) {
}
func didLike(error: String?) {
}
func didUnlike(error: String?) {
}
}
| mit | 5ff8fbd6e97b25ab7c45e8bef37f175f | 24.601626 | 92 | 0.588758 | 6.079151 | false | false | false | false |
Geor9eLau/WorkHelper | Carthage/Checkouts/SwiftCharts/SwiftCharts/ChartCoordsSpace.swift | 1 | 16913 | //
// ChartCoordsSpace.swift
// SwiftCharts
//
// Created by ischuetz on 27/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
/**
A ChartCoordsSpace calculates the chart's inner frame and generates the axis layers based on given axis models, chart size and chart settings. In doing so it's able to calculate the frame for the inner area of the chart where points, bars, lines, etc. are drawn to represent data.
````
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ChartSettings.top โ
โ โโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโ โ
โ โ โ X โ โ โ
โ โ โ high โ โ โ
โ โโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโค โ
โ โ โ โ โ โ
โ โ โ โ โ โ
โ โ โ โ โ โ
โ โ โ โ โ โ
ChartSettings.leading โโโผโถ โ Y โ Chart Inner Frame โ Y โ โโผโโ ChartSettings.trailing
โ โlow โ โhighโ โ
โ โ โ โ โ โ
โ โ โ โ โ โ
โ โโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโค โ
โ โ โ X โ โ โ
โ โ โ low โ โ โ
โ โโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโ โ
โ ChartSettings.bottom โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโ chartSize โโโโโโโโโโโโโโโโโโโ
````
*/
open class ChartCoordsSpace {
public typealias ChartAxisLayerModel = (p1: CGPoint, p2: CGPoint, axisValues: [ChartAxisValue], axisTitleLabels: [ChartAxisLabel], settings: ChartAxisSettings)
public typealias ChartAxisLayerGenerator = (ChartAxisLayerModel) -> ChartAxisLayer
fileprivate let chartSettings: ChartSettings
fileprivate let chartSize: CGSize
open fileprivate(set) var chartInnerFrame: CGRect = CGRect.zero
fileprivate let yLowModels: [ChartAxisModel]
fileprivate let yHighModels: [ChartAxisModel]
fileprivate let xLowModels: [ChartAxisModel]
fileprivate let xHighModels: [ChartAxisModel]
fileprivate let yLowGenerator: ChartAxisLayerGenerator
fileprivate let yHighGenerator: ChartAxisLayerGenerator
fileprivate let xLowGenerator: ChartAxisLayerGenerator
fileprivate let xHighGenerator: ChartAxisLayerGenerator
open fileprivate(set) var yLowAxes: [ChartAxisLayer] = []
open fileprivate(set) var yHighAxes: [ChartAxisLayer] = []
open fileprivate(set) var xLowAxes: [ChartAxisLayer] = []
open fileprivate(set) var xHighAxes: [ChartAxisLayer] = []
/**
A convenience initializer with default axis layer generators
- parameter chartSettings: The chart layout settings
- parameter chartSize: The desired size of the chart
- parameter yLowModels: The chart axis model used to generate the Y low axis
- parameter yHighModels: The chart axis model used to generate the Y high axis
- parameter xLowModels: The chart axis model used to generate the X low axis
- parameter xHighModels: The chart axis model used to generate the X high axis
- returns: The coordinate space with generated axis layers
*/
public convenience init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel] = [], yHighModels: [ChartAxisModel] = [], xLowModels: [ChartAxisModel] = [], xHighModels: [ChartAxisModel] = []) {
let yLowGenerator: ChartAxisLayerGenerator = {model in
ChartAxisYLowLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings)
}
let yHighGenerator: ChartAxisLayerGenerator = {model in
ChartAxisYHighLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings)
}
let xLowGenerator: ChartAxisLayerGenerator = {model in
ChartAxisXLowLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings)
}
let xHighGenerator: ChartAxisLayerGenerator = {model in
ChartAxisXHighLayerDefault(p1: model.p1, p2: model.p2, axisValues: model.axisValues, axisTitleLabels: model.axisTitleLabels, settings: model.settings)
}
self.init(chartSettings: chartSettings, chartSize: chartSize, yLowModels: yLowModels, yHighModels: yHighModels, xLowModels: xLowModels, xHighModels: xHighModels, yLowGenerator: yLowGenerator, yHighGenerator: yHighGenerator, xLowGenerator: xLowGenerator, xHighGenerator: xHighGenerator)
}
public init(chartSettings: ChartSettings, chartSize: CGSize, yLowModels: [ChartAxisModel], yHighModels: [ChartAxisModel], xLowModels: [ChartAxisModel], xHighModels: [ChartAxisModel], yLowGenerator: @escaping ChartAxisLayerGenerator, yHighGenerator: @escaping ChartAxisLayerGenerator, xLowGenerator: @escaping ChartAxisLayerGenerator, xHighGenerator: @escaping ChartAxisLayerGenerator) {
self.chartSettings = chartSettings
self.chartSize = chartSize
self.yLowModels = yLowModels
self.yHighModels = yHighModels
self.xLowModels = xLowModels
self.xHighModels = xHighModels
self.yLowGenerator = yLowGenerator
self.yHighGenerator = yHighGenerator
self.xLowGenerator = xLowGenerator
self.xHighGenerator = xHighGenerator
self.chartInnerFrame = self.calculateChartInnerFrame()
self.yLowAxes = self.generateYLowAxes()
self.yHighAxes = self.generateYHighAxes()
self.xLowAxes = self.generateXLowAxes()
self.xHighAxes = self.generateXHighAxes()
}
fileprivate func generateYLowAxes() -> [ChartAxisLayer] {
return generateYAxisShared(axisModels: self.yLowModels, offset: chartSettings.leading, generator: self.yLowGenerator)
}
fileprivate func generateYHighAxes() -> [ChartAxisLayer] {
let chartFrame = self.chartInnerFrame
return generateYAxisShared(axisModels: self.yHighModels, offset: chartFrame.origin.x + chartFrame.width, generator: self.yHighGenerator)
}
fileprivate func generateXLowAxes() -> [ChartAxisLayer] {
let chartFrame = self.chartInnerFrame
let y = chartFrame.origin.y + chartFrame.height
return self.generateXAxesShared(axisModels: self.xLowModels, offset: y, generator: self.xLowGenerator)
}
fileprivate func generateXHighAxes() -> [ChartAxisLayer] {
return self.generateXAxesShared(axisModels: self.xHighModels, offset: chartSettings.top, generator: self.xHighGenerator)
}
/**
Uses a generator to make X axis layers from axis models. This method is used for both low and high X axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateXAxesShared(axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartFrame = self.chartInnerFrame
let chartSettings = self.chartSettings
let x = chartFrame.origin.x
let length = chartFrame.width
return generateAxisShared(axisModels: axisModels, offset: offset, boundingPointsCreator: { offset in
(p1: CGPoint(x: x, y: offset), p2: CGPoint(x: x + length, y: offset))
}, nextLayerOffset: { layer in
layer.rect.height + chartSettings.spacingBetweenAxesX
}, generator: generator)
}
/**
Uses a generator to make Y axis layers from axis models. This method is used for both low and high Y axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateYAxisShared(axisModels: [ChartAxisModel], offset: CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartFrame = self.chartInnerFrame
let chartSettings = self.chartSettings
let y = chartFrame.origin.y
let length = chartFrame.height
return generateAxisShared(axisModels: axisModels, offset: offset, boundingPointsCreator: { offset in
(p1: CGPoint(x: offset, y: y + length), p2: CGPoint(x: offset, y: y))
}, nextLayerOffset: { layer in
layer.rect.width + chartSettings.spacingBetweenAxesY
}, generator: generator)
}
/**
Uses a generator to make axis layers from axis models. This method is used for all axes.
- parameter axisModels: The models used to generate the axis layers
- parameter offset: The offset in points for the generated layers
- parameter boundingPointsCreator: A closure that creates a tuple containing the location of the smallest and largest values along the axis. For example, boundingPointsCreator for a Y axis might return a value like (p1: CGPoint(x, 0), p2: CGPoint(x, 100)), where x is the offset of the axis layer.
- parameter nextLayerOffset: A closure that returns the offset of the next axis layer relative to the current layer
- parameter generator: The generator used to create the layers
- returns: An array of ChartAxisLayers
*/
fileprivate func generateAxisShared(axisModels: [ChartAxisModel], offset: CGFloat, boundingPointsCreator: (_ offset: CGFloat) -> (p1: CGPoint, p2: CGPoint), nextLayerOffset: (ChartAxisLayer) -> CGFloat, generator: ChartAxisLayerGenerator) -> [ChartAxisLayer] {
let chartSettings = self.chartSettings
return axisModels.reduce((axes: Array<ChartAxisLayer>(), x: offset)) {tuple, chartAxisModel in
let layers = tuple.axes
let x: CGFloat = tuple.x
let axisSettings = ChartAxisSettings(chartSettings)
axisSettings.lineColor = chartAxisModel.lineColor
let points = boundingPointsCreator(x)
let layer = generator(p1: points.p1, p2: points.p2, axisValues: chartAxisModel.axisValues, axisTitleLabels: chartAxisModel.axisTitleLabels, settings: axisSettings)
return (
axes: layers + [layer],
x: x + nextLayerOffset(layer)
)
}.0
}
/**
Calculates the inner frame of the chart, which in short is the area where your points, bars, lines etc. are drawn. In order to calculate this frame the axes will be generated.
- returns: The inner frame as a CGRect
*/
fileprivate func calculateChartInnerFrame() -> CGRect {
let totalDim = {(axisLayers: [ChartAxisLayer], dimPicker: (ChartAxisLayer) -> CGFloat, spacingBetweenAxes: CGFloat) -> CGFloat in
return axisLayers.reduce((CGFloat(0), CGFloat(0))) {tuple, chartAxisLayer in
let totalDim = tuple.0 + tuple.1
return (totalDim + dimPicker(chartAxisLayer), spacingBetweenAxes)
}.0
}
func totalWidth(_ axisLayers: [ChartAxisLayer]) -> CGFloat {
return totalDim(axisLayers, {$0.rect.width}, self.chartSettings.spacingBetweenAxesY)
}
func totalHeight(_ axisLayers: [ChartAxisLayer]) -> CGFloat {
return totalDim(axisLayers, {$0.rect.height}, self.chartSettings.spacingBetweenAxesX)
}
let yLowWidth = totalWidth(self.generateYLowAxes())
let yHighWidth = totalWidth(self.generateYHighAxes())
let xLowHeight = totalHeight(self.generateXLowAxes())
let xHighHeight = totalHeight(self.generateXHighAxes())
let leftWidth = yLowWidth + self.chartSettings.leading
let topHeigth = xHighHeight + self.chartSettings.top
let rightWidth = yHighWidth + self.chartSettings.trailing
let bottomHeight = xLowHeight + self.chartSettings.bottom
return CGRect(
x: leftWidth,
y: topHeigth,
width: self.chartSize.width - leftWidth - rightWidth,
height: self.chartSize.height - topHeigth - bottomHeight
)
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the left and bottom edges
open class ChartCoordsSpaceLeftBottomSingleAxis {
open let yAxis: ChartAxisLayer
open let xAxis: ChartAxisLayer
open let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xLowModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxis = coordsSpaceInitializer.yLowAxes[0]
self.xAxis = coordsSpaceInitializer.xLowAxes[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the left and top edges
open class ChartCoordsSpaceLeftTopSingleAxis {
open let yAxis: ChartAxisLayer
open let xAxis: ChartAxisLayer
open let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yLowModels: [yModel], xHighModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxis = coordsSpaceInitializer.yLowAxes[0]
self.xAxis = coordsSpaceInitializer.xHighAxes[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the right and bottom edges
open class ChartCoordsSpaceRightBottomSingleAxis {
open let yAxis: ChartAxisLayer
open let xAxis: ChartAxisLayer
open let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yHighModels: [yModel], xLowModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxis = coordsSpaceInitializer.yHighAxes[0]
self.xAxis = coordsSpaceInitializer.xLowAxes[0]
}
}
/// A ChartCoordsSpace subclass specifically for a chart with axes along the right and top edges
open class ChartCoordsSpaceRightTopSingleAxis {
open let yAxis: ChartAxisLayer
open let xAxis: ChartAxisLayer
open let chartInnerFrame: CGRect
public init(chartSettings: ChartSettings, chartFrame: CGRect, xModel: ChartAxisModel, yModel: ChartAxisModel) {
let coordsSpaceInitializer = ChartCoordsSpace(chartSettings: chartSettings, chartSize: chartFrame.size, yHighModels: [yModel], xHighModels: [xModel])
self.chartInnerFrame = coordsSpaceInitializer.chartInnerFrame
self.yAxis = coordsSpaceInitializer.yHighAxes[0]
self.xAxis = coordsSpaceInitializer.xHighAxes[0]
}
}
| mit | c794a54a1233f0b764709eb5529d167b | 50.945161 | 390 | 0.643545 | 5.499658 | false | false | false | false |
workshop/struct | examples/tvOS_Application/broadcastUIExtension/BroadcastViewController.swift | 3 | 1457 | //
// BroadcastViewController.swift
// broadcastUIExtension
//
import ReplayKit
class BroadcastViewController: UIViewController {
// Called when the user has finished interacting with the view controller and a broadcast stream can start
func userDidFinishSetup() {
// Broadcast url that will be returned to the application
let broadcastURL = URL(string:"http://broadcastURL_example/stream1")
// Service specific broadcast data example which will be supplied to the process extension during broadcast
let userID = "user1"
let endpointURL = "http://broadcastURL_example/stream1/upload"
let setupInfo: [String: NSCoding & NSObjectProtocol] = [ "userID" : userID as NSString, "endpointURL" : endpointURL as NSString ]
// Set broadcast settings
let broadcastConfiguration = RPBroadcastConfiguration()
broadcastConfiguration.clipDuration = 5
// Tell ReplayKit that the extension is finished setting up and can begin broadcasting
self.extensionContext?.completeRequest(withBroadcast: broadcastURL!, broadcastConfiguration: broadcastConfiguration, setupInfo: setupInfo)
}
func userDidCancelSetup() {
let error = NSError(domain: "YouAppDomain", code: -1, userInfo: nil)
// Tell ReplayKit that the extension was cancelled by the user
self.extensionContext?.cancelRequest(withError: error)
}
}
| mit | 9f976a00d1d6e262295ad8e9fe00c307 | 43.151515 | 146 | 0.707618 | 5.298182 | false | true | false | false |
richeterre/SwiftGoal | Carthage/Checkouts/Argo/ArgoTests/Tests/RawRepresentableTests.swift | 4 | 952 | import XCTest
import Argo
enum TestRawString: String {
case CoolString
case NotCoolStringBro
}
enum TestRawInt: Int {
case Zero
case One
}
extension TestRawString: Decodable { }
extension TestRawInt: Decodable { }
class RawRepresentable: XCTestCase {
func testStringEnum() {
let json = JSON.Object([
"string": JSON.String("CoolString"),
"another": JSON.String("NotCoolStringBro")
])
let string: TestRawString? = (json <| "string").value
let another: TestRawString? = (json <| "another").value
XCTAssert(TestRawString.CoolString == string)
XCTAssert(TestRawString.NotCoolStringBro == another)
}
func testIntEnum() {
let json = JSON.Object([
"zero": JSON.Number(0),
"one": JSON.Number(1)
])
let zero: TestRawInt? = (json <| "zero").value
let one: TestRawInt? = (json <| "one").value
XCTAssert(TestRawInt.Zero == zero)
XCTAssert(TestRawInt.One == one)
}
}
| mit | 9b320b6d295941b4aa752062d2cc7fb6 | 22.219512 | 59 | 0.656513 | 3.777778 | false | true | false | false |
intel-isl/MiDaS | mobile/ios/Midas/Constants.swift | 1 | 1072 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
enum Constants {
// MARK: - Constants related to the image processing
static let bgraPixel = (channels: 4, alphaComponent: 3, lastBgrComponent: 2)
static let rgbPixelChannels = 3
static let maxRGBValue: Float32 = 255.0
// MARK: - Constants related to the model interperter
static let defaultThreadCount = 2
static let defaultDelegate: Delegates = .CPU
}
| mit | ccee0fc01b9a585bd3c850750420e9e9 | 41.88 | 80 | 0.690299 | 4.485356 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.